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.

InterTypeDeclaration.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.ajdt.internal.compiler.ast;
  13. import java.lang.reflect.Modifier;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
  17. import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger;
  18. import org.aspectj.ajdt.internal.compiler.lookup.InterTypeScope;
  19. import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
  20. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  21. import org.aspectj.bridge.context.ContextToken;
  22. import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
  23. import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
  24. import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
  25. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
  26. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference;
  27. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference;
  28. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
  29. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
  30. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
  31. import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
  32. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
  33. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodScope;
  34. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
  35. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ProblemReferenceBinding;
  36. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding;
  37. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
  38. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
  39. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
  40. import org.aspectj.weaver.AjAttribute;
  41. import org.aspectj.weaver.ResolvedMember;
  42. import org.aspectj.weaver.ResolvedTypeMunger;
  43. import org.aspectj.weaver.Shadow;
  44. /**
  45. * Base type for all inter-type declarations including methods, fields and constructors.
  46. *
  47. * @author Jim Hugunin
  48. */
  49. public abstract class InterTypeDeclaration extends AjMethodDeclaration {
  50. protected TypeReference onType;
  51. protected ReferenceBinding onTypeBinding;
  52. protected ResolvedTypeMunger munger;
  53. public int declaredModifiers; // so others can see (these differ from the modifiers in the superclass)
  54. protected char[] declaredSelector;
  55. /**
  56. * If targetting a generic type and wanting to use its type variables, an ITD can use an alternative name for
  57. * them. This is a list of strings representing the alternative names - the position in the list is used to
  58. * match it to the real type variable in the target generic type.
  59. */
  60. protected List<String> typeVariableAliases;
  61. protected InterTypeScope interTypeScope;
  62. /**
  63. * When set to true, the scope hierarchy for the field/method declaration has been correctly modified to
  64. * include an intertypescope which resolves things relative to the targetted type.
  65. */
  66. private boolean scopeSetup = false;
  67. // XXXAJ5 - When the compiler is changed, these will exist somewhere in it...
  68. private final static short ACC_ANNOTATION = 0x2000;
  69. private final static short ACC_ENUM = 0x4000;
  70. public InterTypeDeclaration(CompilationResult result, TypeReference onType) {
  71. super(result);
  72. setOnType(onType);
  73. modifiers = ClassFileConstants.AccPublic | ClassFileConstants.AccStatic;
  74. }
  75. public void setOnType(TypeReference onType) {
  76. this.onType = onType;
  77. determineTypeVariableAliases();
  78. }
  79. public void setDeclaredModifiers(int modifiers) {
  80. this.declaredModifiers = modifiers;
  81. }
  82. public void setSelector(char[] selector) {
  83. declaredSelector = selector;
  84. this.selector = CharOperation.concat(selector, Integer.toHexString(sourceStart).toCharArray());
  85. this.selector = CharOperation.concat(getPrefix(),this.selector);
  86. }
  87. // return the selector prefix for this itd that is to be used before resolution replaces it with a "proper" name
  88. protected abstract char[] getPrefix();
  89. public void addAtAspectJAnnotations() {
  90. if (munger == null) return;
  91. Annotation ann = AtAspectJAnnotationFactory.createITDAnnotation(
  92. munger.getSignature().getDeclaringType().getName().toCharArray(),
  93. declaredModifiers,declaredSelector,declarationSourceStart);
  94. AtAspectJAnnotationFactory.addAnnotation(this,ann,this.scope);
  95. }
  96. /**
  97. * Checks that the target for the ITD is not an annotation. If it is, an error message
  98. * is signaled. We return true if it is annotation so the caller knows to stop processing.
  99. * kind is 'constructor', 'field', 'method'
  100. */
  101. public boolean isTargetAnnotation(ClassScope classScope,String kind) {
  102. if ((onTypeBinding.getAccessFlags() & ACC_ANNOTATION)!=0) {
  103. classScope.problemReporter().signalError(sourceStart,sourceEnd,
  104. "can't make inter-type "+kind+" declarations on annotation types.");
  105. ignoreFurtherInvestigation = true;
  106. return true;
  107. }
  108. return false;
  109. }
  110. /**
  111. * Checks that the target for the ITD is not an enum. If it is, an error message
  112. * is signaled. We return true if it is enum so the caller knows to stop processing.
  113. */
  114. public boolean isTargetEnum(ClassScope classScope,String kind) {
  115. if ((onTypeBinding.getAccessFlags() & ACC_ENUM)!=0) {
  116. classScope.problemReporter().signalError(sourceStart,sourceEnd,
  117. "can't make inter-type "+kind+" declarations on enum types.");
  118. ignoreFurtherInvestigation = true;
  119. return true;
  120. }
  121. return false;
  122. }
  123. @Override
  124. public void resolve(ClassScope upperScope) {
  125. if (ignoreFurtherInvestigation) return;
  126. if (!scopeSetup) {
  127. interTypeScope = new InterTypeScope(upperScope, onTypeBinding,typeVariableAliases);
  128. scope.parent = interTypeScope;
  129. this.scope.isStatic = Modifier.isStatic(declaredModifiers);
  130. scopeSetup = true;
  131. }
  132. fixSuperCallsForInterfaceContext(upperScope);
  133. if (ignoreFurtherInvestigation) return;
  134. super.resolve((ClassScope)scope.parent);//newParent);
  135. fixSuperCallsInBody();
  136. }
  137. private void fixSuperCallsForInterfaceContext(ClassScope scope) {
  138. if (onTypeBinding.isInterface()) {
  139. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.FIXING_SUPER_CALLS, selector);
  140. InterSuperFixerVisitor v =
  141. new InterSuperFixerVisitor(this,
  142. EclipseFactory.fromScopeLookupEnvironment(scope), scope);
  143. this.traverse(v, scope);
  144. CompilationAndWeavingContext.leavingPhase(tok);
  145. }
  146. }
  147. /**
  148. * Called from AspectDeclarations.buildInterTypeAndPerClause
  149. */
  150. public abstract EclipseTypeMunger build(ClassScope classScope);
  151. public void fixSuperCallsInBody() {
  152. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.FIXING_SUPER_CALLS_IN_ITDS, selector);
  153. SuperFixerVisitor v = new SuperFixerVisitor(this, onTypeBinding);
  154. this.traverse(v, (ClassScope)null);
  155. munger.setSuperMethodsCalled(v.superMethodsCalled);
  156. CompilationAndWeavingContext.leavingPhase(tok);
  157. }
  158. protected void resolveOnType(ClassScope classScope) {
  159. checkSpec();
  160. if (onType==null) return; // error reported elsewhere.
  161. // If they did supply a parameterized single type reference, we need to do
  162. // some extra checks...
  163. if (onType instanceof ParameterizedSingleTypeReference || onType instanceof ParameterizedQualifiedTypeReference) {
  164. resolveTypeParametersForITDOnGenericType(classScope);
  165. } else {
  166. onTypeBinding = (ReferenceBinding)onType.getTypeBindingPublic(classScope);
  167. if (!onTypeBinding.isValidBinding()) {
  168. classScope.problemReporter().invalidType(onType, onTypeBinding);
  169. ignoreFurtherInvestigation = true;
  170. }
  171. if (onTypeBinding.isParameterizedType()) {
  172. // might be OK... pr132349
  173. ParameterizedTypeBinding ptb = (ParameterizedTypeBinding)onTypeBinding;
  174. if (ptb.isNestedType()) {
  175. if (ptb.typeVariables()==null || ptb.typeVariables().length==0) {
  176. if (ptb.enclosingType().isRawType()) onTypeBinding = ptb.type;
  177. }
  178. }
  179. }
  180. }
  181. }
  182. /**
  183. * Transform the parameterized type binding (e.g. SomeType<A,B,C>) to a
  184. * real type (e.g. SomeType). The only kind of parameterization allowed
  185. * is with type variables and those are references to type variables on
  186. * the target type. Once we have worked out the base generic type intended
  187. * then we do lots of checks to verify the declaration was well formed.
  188. */
  189. private void resolveTypeParametersForITDOnGenericType(ClassScope classScope) {
  190. // Collapse the parameterized reference to its generic type
  191. if (onType instanceof ParameterizedSingleTypeReference) {
  192. ParameterizedSingleTypeReference pref = (ParameterizedSingleTypeReference) onType;
  193. long pos = (((long)pref.sourceStart) << 32) | pref.sourceEnd;
  194. onType = new SingleTypeReference(pref.token,pos);
  195. } else {
  196. ParameterizedQualifiedTypeReference pref = (ParameterizedQualifiedTypeReference) onType;
  197. long pos = (((long)pref.sourceStart) << 32) | pref.sourceEnd;
  198. onType = new QualifiedTypeReference(pref.tokens,new long[]{pos});
  199. }
  200. onTypeBinding = (ReferenceBinding)onType.getTypeBindingPublic(classScope);
  201. if (!onTypeBinding.isValidBinding()) {
  202. classScope.problemReporter().invalidType(onType, onTypeBinding);
  203. ignoreFurtherInvestigation = true;
  204. }
  205. if (onTypeBinding.isRawType()) {
  206. onTypeBinding = ((RawTypeBinding)onTypeBinding).type;
  207. }
  208. int aliasCount = (typeVariableAliases==null?0:typeVariableAliases.size());
  209. // Cannot specify a parameterized target type for the ITD if the target
  210. // type is not generic.
  211. if (aliasCount!=0 && !onTypeBinding.isGenericType()) {
  212. scope.problemReporter().signalError(sourceStart,sourceEnd,
  213. "Type parameters can not be specified in the ITD target type - the target type "+onTypeBinding.debugName()+" is not generic.");
  214. ignoreFurtherInvestigation = true;
  215. return;
  216. }
  217. // Check they have supplied the right number of type parameters on the ITD target type
  218. if (aliasCount>0) {
  219. if (onTypeBinding.typeVariables().length != aliasCount) { // typeParameters.length) { phantom contains the fake ones from the ontype, typeparameters will also include extra things if it is a generic method
  220. scope.problemReporter().signalError(sourceStart, sourceEnd,
  221. "Incorrect number of type parameters supplied. The generic type "+onTypeBinding.debugName()+" has "+
  222. onTypeBinding.typeVariables().length+" type parameters, not "+aliasCount+".");
  223. ignoreFurtherInvestigation = true;
  224. return;
  225. }
  226. }
  227. // check if they used stupid names for type variables
  228. if (aliasCount>0) {
  229. for (int i = 0; i < aliasCount; i++) {
  230. String array_element = typeVariableAliases.get(i);
  231. SingleTypeReference str = new SingleTypeReference(array_element.toCharArray(),0);
  232. TypeBinding tb = str.getTypeBindingPublic(classScope);
  233. if (tb!=null && !(tb instanceof ProblemReferenceBinding)) {// && !(tb instanceof TypeVariableBinding)) {
  234. scope.problemReporter().signalError(sourceStart,sourceEnd,
  235. "Intertype declarations can only be made on the generic type, not on a parameterized type. The name '"+
  236. array_element+"' cannot be used as a type parameter, since it refers to a real type.");
  237. ignoreFurtherInvestigation = true;
  238. return;
  239. }
  240. }
  241. }
  242. // TypeVariableBinding[] tVarsInGenericType = onTypeBinding.typeVariables();
  243. // typeVariableAliases = new ArrayList(); /* Name>GenericTypeVariablePosition */ // FIXME ASC DONT THINK WE NEED TO BUILD IT HERE AS WELL...
  244. // TypeReference[] targs = pref.typeArguments;
  245. // if (targs!=null) {
  246. // for (int i = 0; i < targs.length; i++) {
  247. // TypeReference tref = targs[i];
  248. // typeVariableAliases.add(CharOperation.toString(tref.getTypeName()));//tVarsInGenericType[i]);
  249. // }
  250. // }
  251. }
  252. protected void checkSpec() {
  253. if (Modifier.isProtected(declaredModifiers)) {
  254. scope.problemReporter().signalError(sourceStart, sourceEnd,
  255. "protected inter-type declarations are not allowed");
  256. ignoreFurtherInvestigation = true;
  257. }
  258. }
  259. protected List makeEffectiveSignatureAttribute(
  260. ResolvedMember sig,
  261. Shadow.Kind kind,
  262. boolean weaveBody)
  263. {
  264. List l = new ArrayList(1);
  265. l.add(new EclipseAttributeAdapter(
  266. new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody)));
  267. return l;
  268. }
  269. protected void setMunger(ResolvedTypeMunger munger) {
  270. munger.getSignature().setPosition(sourceStart, sourceEnd);
  271. munger.getSignature().setSourceContext(new EclipseSourceContext(compilationResult));
  272. this.munger = munger;
  273. }
  274. @Override
  275. protected int generateInfoAttributes(ClassFile classFile) {
  276. List l;
  277. Shadow.Kind kind = getShadowKindForBody();
  278. if (kind != null) {
  279. l = makeEffectiveSignatureAttribute(munger.getSignature(), kind, true);
  280. } else {
  281. l = new ArrayList(0);
  282. }
  283. addDeclarationStartLineAttribute(l,classFile);
  284. return classFile.generateMethodInfoAttributes(binding, l);
  285. }
  286. protected abstract Shadow.Kind getShadowKindForBody();
  287. public ResolvedMember getSignature() {
  288. if (munger==null) return null; // Can be null in an erroneous program I think
  289. return munger.getSignature();
  290. }
  291. public char[] getDeclaredSelector() {
  292. return declaredSelector;
  293. }
  294. public TypeReference getOnType() {
  295. return onType;
  296. }
  297. /**
  298. * Create the list of aliases based on what was supplied as parameters for the ontype.
  299. * For example, if the declaration is 'List&lt;N&gt; SomeType&lt;N&gt;.foo' then the alias list
  300. * will simply contain 'N' and 'N' will mean 'the first type variable declared for
  301. * type SomeType'
  302. */
  303. public void determineTypeVariableAliases() {
  304. if (onType!=null) {
  305. // TODO loses distinction about which level the type variables are at... is that a problem?
  306. if (onType instanceof ParameterizedSingleTypeReference) {
  307. ParameterizedSingleTypeReference paramRef = (ParameterizedSingleTypeReference) onType;
  308. TypeReference[] rb = paramRef.typeArguments;
  309. typeVariableAliases = new ArrayList();
  310. for (TypeReference typeReference : rb) {
  311. typeVariableAliases.add(CharOperation.toString(typeReference.getTypeName()));
  312. }
  313. } else if (onType instanceof ParameterizedQualifiedTypeReference) {
  314. ParameterizedQualifiedTypeReference paramRef = (ParameterizedQualifiedTypeReference) onType;
  315. typeVariableAliases = new ArrayList();
  316. for (int j = 0; j < paramRef.typeArguments.length; j++) {
  317. TypeReference[] rb = paramRef.typeArguments[j];
  318. for (int i = 0; rb!=null && i < rb.length; i++) {
  319. typeVariableAliases.add(CharOperation.toString(rb[i].getTypeName()));
  320. }
  321. }
  322. }
  323. }
  324. }
  325. /**
  326. * Called just before the compiler is going to start resolving elements of a declaration, this method
  327. * adds an intertypescope between the methodscope and classscope so that elements of the type targetted
  328. * by the ITD can be resolved. For example, if type variables are referred to in the ontype for the ITD,
  329. * they have to be resolved against the ontype, not the aspect containing the ITD.
  330. */
  331. @Override
  332. public void ensureScopeSetup() {
  333. if (scopeSetup) return; // don't do it again
  334. MethodScope scope = this.scope;
  335. TypeReference ot = onType;
  336. ReferenceBinding rb = null;
  337. if (ot instanceof ParameterizedQualifiedTypeReference) { // pr132349
  338. ParameterizedQualifiedTypeReference pref = (ParameterizedQualifiedTypeReference) ot;
  339. if (pref.typeArguments!=null && pref.typeArguments.length!=0) {
  340. boolean usingNonTypeVariableInITD = false;
  341. // Check if any of them are not type variables
  342. for (int i = 0; i < pref.typeArguments.length; i++) {
  343. TypeReference[] refs = pref.typeArguments[i];
  344. for (int j = 0; refs!=null && j < refs.length; j++) {
  345. TypeBinding tb = refs[j].getTypeBindingPublic(scope.parent);
  346. if (!tb.isTypeVariable() && !(tb instanceof ProblemReferenceBinding)) {
  347. usingNonTypeVariableInITD = true;
  348. }
  349. }
  350. }
  351. if (usingNonTypeVariableInITD) {
  352. scope.problemReporter().signalError(sourceStart,sourceEnd,
  353. "Cannot make inter-type declarations on parameterized types");
  354. // to prevent disgusting cascading errors after this problem - lets null out what leads to them (pr105038)
  355. this.arguments=null;
  356. this.returnType=new SingleTypeReference(TypeReference.VOID,0L);
  357. this.ignoreFurtherInvestigation=true;
  358. ReferenceBinding closestMatch = null;
  359. rb = new ProblemReferenceBinding(ot.getParameterizedTypeName(),closestMatch,0);
  360. onType=null;
  361. }
  362. }
  363. }
  364. // Work out the real base type
  365. if (ot instanceof ParameterizedSingleTypeReference) {
  366. ParameterizedSingleTypeReference pref = (ParameterizedSingleTypeReference) ot;
  367. long pos = (((long)pref.sourceStart) << 32) | pref.sourceEnd;
  368. ot = new SingleTypeReference(pref.token,pos);
  369. } else if (ot instanceof ParameterizedQualifiedTypeReference) {
  370. ParameterizedQualifiedTypeReference pref = (ParameterizedQualifiedTypeReference) ot;
  371. long pos = (((long)pref.sourceStart) << 32) | pref.sourceEnd;
  372. ot = new QualifiedTypeReference(pref.tokens,new long[]{pos});//SingleTypeReference(pref.Quatoken,pos);
  373. }
  374. // resolve it
  375. if (rb==null) {
  376. rb = (ReferenceBinding)ot.getTypeBindingPublic(scope.parent);
  377. }
  378. // pr203646 - if we have ended up with the raw type, get back to the underlying generic one.
  379. if (rb.isRawType() && rb.isMemberType()) {
  380. // if the real target type used a type variable alias then we can do this OK, but need to switch things around, we want the generic type
  381. rb = ((RawTypeBinding)rb).type;
  382. }
  383. if (rb instanceof TypeVariableBinding) {
  384. scope.problemReporter().signalError(sourceStart,sourceEnd,
  385. "Cannot make inter-type declarations on type variables, use an interface and declare parents");
  386. // to prevent disgusting cascading errors after this problem - lets null out what leads to them (pr105038)
  387. this.arguments=null;
  388. this.returnType=new SingleTypeReference(TypeReference.VOID,0L);
  389. this.ignoreFurtherInvestigation=true;
  390. ReferenceBinding closestMatch = null;
  391. if (((TypeVariableBinding)rb).firstBound!=null) {
  392. closestMatch = ((TypeVariableBinding)rb).firstBound.enclosingType();
  393. }
  394. rb = new ProblemReferenceBinding(rb.compoundName,closestMatch,0);
  395. }
  396. // if resolution failed, give up - someone else is going to report an error
  397. if (rb instanceof ProblemReferenceBinding) return;
  398. interTypeScope = new InterTypeScope(scope.parent, rb, typeVariableAliases);
  399. // FIXME asc verify the choice of lines here...
  400. // Two versions of this next line.
  401. // First one tricks the JDT variable processing code so that it won't complain if
  402. // you refer to a type variable from a static ITD - it *is* a problem and it *will* be caught, but later and
  403. // by the AJDT code so we can put out a much nicer message.
  404. scope.isStatic = (typeVariableAliases!=null?false:Modifier.isStatic(declaredModifiers));
  405. // this is the original version in case tricking the JDT causes grief (if you reinstate this variant, you
  406. // will need to change the expected messages output for some of the generic ITD tests)
  407. // scope.isStatic = Modifier.isStatic(declaredModifiers);
  408. scope.parent = interTypeScope;
  409. scopeSetup = true;
  410. }
  411. }