You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WildTypePattern.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Common Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/cpl-v10.html
  8. *
  9. * Contributors:
  10. * Xerox/PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.weaver.patterns;
  13. import java.io.*;
  14. import java.util.*;
  15. import org.aspectj.weaver.*;
  16. import org.aspectj.bridge.*;
  17. import org.aspectj.bridge.IMessage;
  18. import org.aspectj.util.*;
  19. //XXX need to use dim in matching
  20. public class WildTypePattern extends TypePattern {
  21. NamePattern[] namePatterns;
  22. int ellipsisCount;
  23. String[] importedPrefixes;
  24. String[] knownMatches;
  25. int dim;
  26. WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim) {
  27. super(includeSubtypes);
  28. this.namePatterns = namePatterns;
  29. this.ellipsisCount = ellipsisCount;
  30. this.dim = dim;
  31. ellipsisCount = 0;
  32. for (int i=0; i<namePatterns.length; i++) {
  33. if (namePatterns[i] == NamePattern.ELLIPSIS) ellipsisCount++;
  34. }
  35. setLocation(namePatterns[0].getSourceContext(), namePatterns[0].getStart(), namePatterns[namePatterns.length-1].getEnd());
  36. }
  37. public WildTypePattern(List names, boolean includeSubtypes, int dim) {
  38. this((NamePattern[])names.toArray(new NamePattern[names.size()]), includeSubtypes, dim);
  39. }
  40. public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) {
  41. this(names, includeSubtypes, dim);
  42. this.end = endPos;
  43. }
  44. //XXX inefficient implementation
  45. public static char[][] splitNames(String s) {
  46. List ret = new ArrayList();
  47. int startIndex = 0;
  48. while (true) {
  49. int breakIndex = s.indexOf('.', startIndex); // what about /
  50. if (breakIndex == -1) breakIndex = s.indexOf('$', startIndex); // we treat $ like . here
  51. if (breakIndex == -1) break;
  52. char[] name = s.substring(startIndex, breakIndex).toCharArray();
  53. ret.add(name);
  54. startIndex = breakIndex+1;
  55. }
  56. ret.add(s.substring(startIndex).toCharArray());
  57. return (char[][])ret.toArray(new char[ret.size()][]);
  58. }
  59. /**
  60. * @see org.aspectj.weaver.TypePattern#matchesExactly(IType)
  61. */
  62. protected boolean matchesExactly(ResolvedTypeX type) {
  63. String targetTypeName = type.getName();
  64. //XXX hack
  65. if (knownMatches == null) {
  66. return innerMatchesExactly(targetTypeName);
  67. }
  68. // if our pattern is length 1, then known matches are exact matches
  69. // if it's longer than that, then known matches are prefixes of a sort
  70. if (namePatterns.length == 1) {
  71. for (int i=0, len=knownMatches.length; i < len; i++) {
  72. if (knownMatches[i].equals(targetTypeName)) return true;
  73. }
  74. } else {
  75. for (int i=0, len=knownMatches.length; i < len; i++) {
  76. String knownPrefix = knownMatches[i] + "$";
  77. if (targetTypeName.startsWith(knownPrefix)) {
  78. int pos = lastIndexOfDotOrDollar(knownMatches[i]);
  79. if (innerMatchesExactly(targetTypeName.substring(pos+1))) {
  80. return true;
  81. }
  82. }
  83. }
  84. }
  85. // if any prefixes match, strip the prefix and check that the rest matches
  86. // assumes that prefixes have a dot at the end
  87. for (int i=0, len=importedPrefixes.length; i < len; i++) {
  88. String prefix = importedPrefixes[i];
  89. if (targetTypeName.startsWith(prefix)) {
  90. if (innerMatchesExactly(targetTypeName.substring(prefix.length()))) {
  91. return true;
  92. }
  93. }
  94. }
  95. return innerMatchesExactly(targetTypeName);
  96. }
  97. private int lastIndexOfDotOrDollar(String string) {
  98. int dot = string.lastIndexOf('.');
  99. int dollar = string.lastIndexOf('$');
  100. return Math.max(dot, dollar);
  101. }
  102. private boolean innerMatchesExactly(String targetTypeName) {
  103. //??? doing this everytime is not very efficient
  104. char[][] names = splitNames(targetTypeName);
  105. return innerMatchesExactly(names);
  106. }
  107. private boolean innerMatchesExactly(char[][] names) {
  108. int namesLength = names.length;
  109. int patternsLength = namePatterns.length;
  110. int namesIndex = 0;
  111. int patternsIndex = 0;
  112. if (ellipsisCount == 0) {
  113. if (namesLength != patternsLength) return false;
  114. while (patternsIndex < patternsLength) {
  115. if (!namePatterns[patternsIndex++].matches(names[namesIndex++])) {
  116. return false;
  117. }
  118. }
  119. return true;
  120. } else if (ellipsisCount == 1) {
  121. if (namesLength < patternsLength-1) return false;
  122. while (patternsIndex < patternsLength) {
  123. NamePattern p = namePatterns[patternsIndex++];
  124. if (p == NamePattern.ELLIPSIS) {
  125. namesIndex = namesLength - (patternsLength-patternsIndex);
  126. } else {
  127. if (!p.matches(names[namesIndex++])) {
  128. return false;
  129. }
  130. }
  131. }
  132. return true;
  133. } else {
  134. // System.err.print("match(\"" + Arrays.asList(namePatterns) + "\", \"" + Arrays.asList(names) + "\") -> ");
  135. boolean b = outOfStar(namePatterns, names, 0, 0, patternsLength - ellipsisCount, namesLength, ellipsisCount);
  136. // System.err.println(b);
  137. return b;
  138. }
  139. }
  140. private static boolean outOfStar(final NamePattern[] pattern, final char[][] target,
  141. int pi, int ti,
  142. int pLeft, int tLeft,
  143. final int starsLeft) {
  144. if (pLeft > tLeft) return false;
  145. while (true) {
  146. // invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length)
  147. if (tLeft == 0) return true;
  148. if (pLeft == 0) {
  149. return (starsLeft > 0);
  150. }
  151. if (pattern[pi] == NamePattern.ELLIPSIS) {
  152. return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1);
  153. }
  154. if (! pattern[pi].matches(target[ti])) {
  155. return false;
  156. }
  157. pi++; ti++; pLeft--; tLeft--;
  158. }
  159. }
  160. private static boolean inStar(final NamePattern[] pattern, final char[][] target,
  161. int pi, int ti,
  162. final int pLeft, int tLeft,
  163. int starsLeft) {
  164. // invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern
  165. // of course, we probably can't parse multiple ..'s in a row, but this keeps the algorithm
  166. // exactly parallel with that in NamePattern
  167. NamePattern patternChar = pattern[pi];
  168. while (patternChar == NamePattern.ELLIPSIS) {
  169. starsLeft--;
  170. patternChar = pattern[++pi];
  171. }
  172. while (true) {
  173. // invariant: if (tLeft > 0) then (ti < target.length)
  174. if (pLeft > tLeft) return false;
  175. if (patternChar.matches(target[ti])) {
  176. if (outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft)) return true;
  177. }
  178. ti++; tLeft--;
  179. }
  180. }
  181. /**
  182. * @see org.aspectj.weaver.TypePattern#matchesInstanceof(IType)
  183. */
  184. public FuzzyBoolean matchesInstanceof(ResolvedTypeX type) {
  185. //XXX hack to let unmatched types just silently remain so
  186. if (maybeGetSimpleName() != null) return FuzzyBoolean.NO;
  187. type.getWorld().getMessageHandler().handleMessage(
  188. new Message("can't do instanceof matching on patterns with wildcards",
  189. IMessage.ERROR, null, getSourceLocation()));
  190. return FuzzyBoolean.NO;
  191. }
  192. public NamePattern extractName() {
  193. //System.err.println("extract from : " + Arrays.asList(namePatterns));
  194. int len = namePatterns.length;
  195. NamePattern ret = namePatterns[len-1];
  196. NamePattern[] newNames = new NamePattern[len-1];
  197. System.arraycopy(namePatterns, 0, newNames, 0, len-1);
  198. namePatterns = newNames;
  199. //System.err.println(" left : " + Arrays.asList(namePatterns));
  200. return ret;
  201. }
  202. /**
  203. * Method maybeExtractName.
  204. * @param string
  205. * @return boolean
  206. */
  207. public boolean maybeExtractName(String string) {
  208. int len = namePatterns.length;
  209. NamePattern ret = namePatterns[len-1];
  210. String simple = ret.maybeGetSimpleName();
  211. if (simple != null && simple.equals(string)) {
  212. extractName();
  213. return true;
  214. }
  215. return false;
  216. }
  217. /**
  218. * If this type pattern has no '.' or '*' in it, then
  219. * return a simple string
  220. *
  221. * otherwise, this will return null;
  222. */
  223. public String maybeGetSimpleName() {
  224. if (namePatterns.length == 1) {
  225. return namePatterns[0].maybeGetSimpleName();
  226. }
  227. return null;
  228. }
  229. /**
  230. * If this type pattern has no '*' or '..' in it
  231. */
  232. public String maybeGetCleanName() {
  233. if (namePatterns.length == 0) {
  234. throw new RuntimeException("bad name: " + namePatterns);
  235. }
  236. //System.out.println("get clean: " + this);
  237. StringBuffer buf = new StringBuffer();
  238. for (int i=0, len=namePatterns.length; i < len; i++) {
  239. NamePattern p = namePatterns[i];
  240. String simpleName = p.maybeGetSimpleName();
  241. if (simpleName == null) return null;
  242. if (i > 0) buf.append(".");
  243. buf.append(simpleName);
  244. }
  245. //System.out.println(buf);
  246. return buf.toString();
  247. }
  248. /**
  249. * Need to determine if I'm really a pattern or a reference to a formal
  250. *
  251. * We may wish to further optimize the case of pattern vs. non-pattern
  252. *
  253. * We will be replaced by what we return
  254. */
  255. public TypePattern resolveBindings(IScope scope, Bindings bindings,
  256. boolean allowBinding, boolean requireExactType)
  257. {
  258. if (isStar()) {
  259. return TypePattern.ANY; //??? loses source location
  260. }
  261. String simpleName = maybeGetSimpleName();
  262. if (simpleName != null) {
  263. FormalBinding formalBinding = scope.lookupFormal(simpleName);
  264. if (formalBinding != null) {
  265. if (!allowBinding || bindings == null) {
  266. scope.message(IMessage.ERROR, this, "negation doesn't allow binding");
  267. return this;
  268. }
  269. BindingTypePattern binding = new BindingTypePattern(formalBinding);
  270. binding.copyLocationFrom(this);
  271. bindings.register(binding, scope);
  272. return binding;
  273. }
  274. }
  275. String cleanName = maybeGetCleanName();
  276. if (cleanName != null) {
  277. TypeX type;
  278. //System.out.println("resolve: " + cleanName);
  279. //??? this loop has too many inefficiencies to count
  280. while ((type = scope.lookupType(cleanName, this)) == ResolvedTypeX.MISSING) {
  281. int lastDot = cleanName.lastIndexOf('.');
  282. if (lastDot == -1) break;
  283. cleanName = cleanName.substring(0, lastDot) + '$' + cleanName.substring(lastDot+1);
  284. }
  285. if (type == ResolvedTypeX.MISSING) {
  286. if (requireExactType) {
  287. if (!allowBinding) {
  288. scope.getWorld().getMessageHandler().handleMessage(
  289. MessageUtil.error("can't bind type name '" + cleanName + "'",
  290. getSourceLocation()));
  291. } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) {
  292. scope.getWorld().getLint().invalidAbsoluteTypeName.signal(cleanName, getSourceLocation());
  293. }
  294. return NO;
  295. } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) {
  296. scope.getWorld().getLint().invalidAbsoluteTypeName.signal(cleanName, getSourceLocation());
  297. }
  298. } else {
  299. if (dim != 0) type = TypeX.makeArray(type, dim);
  300. TypePattern ret = new ExactTypePattern(type, includeSubtypes);
  301. ret.copyLocationFrom(this);
  302. return ret;
  303. }
  304. } else {
  305. if (requireExactType) {
  306. scope.getWorld().getMessageHandler().handleMessage(
  307. MessageUtil.error("wildcard type pattern not allowed, must use type name",
  308. getSourceLocation()));
  309. return NO;
  310. }
  311. //XXX need to implement behavior for Lint.invalidWildcardTypeName
  312. }
  313. importedPrefixes = scope.getImportedPrefixes();
  314. knownMatches = preMatch(scope.getImportedNames());
  315. return this;
  316. }
  317. public boolean isStar() {
  318. return namePatterns.length == 1 && namePatterns[0].isAny();
  319. }
  320. /**
  321. * returns those possible matches which I match exactly the last element of
  322. */
  323. private String[] preMatch(String[] possibleMatches) {
  324. //if (namePatterns.length != 1) return CollectionUtil.NO_STRINGS;
  325. List ret = new ArrayList();
  326. for (int i=0, len=possibleMatches.length; i < len; i++) {
  327. char[][] names = splitNames(possibleMatches[i]); //??? not most efficient
  328. if (namePatterns[0].matches(names[names.length-1])) {
  329. ret.add(possibleMatches[i]);
  330. }
  331. }
  332. return (String[])ret.toArray(new String[ret.size()]);
  333. }
  334. // public void postRead(ResolvedTypeX enclosingType) {
  335. // this.importedPrefixes = enclosingType.getImportedPrefixes();
  336. // this.knownNames = prematch(enclosingType.getImportedNames());
  337. // }
  338. public String toString() {
  339. StringBuffer buf = new StringBuffer();
  340. for (int i=0, len=namePatterns.length; i < len; i++) {
  341. NamePattern name = namePatterns[i];
  342. if (name == null) {
  343. buf.append(".");
  344. } else {
  345. if (i > 0) buf.append(".");
  346. buf.append(name.toString());
  347. }
  348. }
  349. return buf.toString();
  350. }
  351. public boolean equals(Object other) {
  352. if (!(other instanceof WildTypePattern)) return false;
  353. WildTypePattern o = (WildTypePattern)other;
  354. int len = o.namePatterns.length;
  355. if (len != this.namePatterns.length) return false;
  356. for (int i=0; i < len; i++) {
  357. if (!o.namePatterns[i].equals(this.namePatterns[i])) return false;
  358. }
  359. return true;
  360. }
  361. public int hashCode() {
  362. int result = 17;
  363. for (int i = 0, len = namePatterns.length; i < len; i++) {
  364. result = 37*result + namePatterns[i].hashCode();
  365. }
  366. return result;
  367. }
  368. /**
  369. * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream)
  370. */
  371. public void write(DataOutputStream s) throws IOException {
  372. s.writeByte(TypePattern.WILD);
  373. s.writeShort(namePatterns.length);
  374. for (int i = 0; i < namePatterns.length; i++) {
  375. namePatterns[i].write(s);
  376. }
  377. s.writeBoolean(includeSubtypes);
  378. s.writeInt(dim);
  379. writeLocation(s);
  380. }
  381. public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException {
  382. int len = s.readShort();
  383. NamePattern[] namePatterns = new NamePattern[len];
  384. for (int i=0; i < len; i++) {
  385. namePatterns[i] = NamePattern.read(s);
  386. }
  387. boolean includeSubtypes = s.readBoolean();
  388. int dim = s.readInt();
  389. TypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim);
  390. ret.readLocation(context, s);
  391. return ret;
  392. }
  393. }