1 /* *******************************************************************
2 * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
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
10 * PARC initial implementation
11 * ******************************************************************/
13 package org.aspectj.ajdt.internal.compiler.lookup;
15 import java.lang.reflect.Modifier;
18 import org.aspectj.ajdt.internal.compiler.CommonPrinter;
19 import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
20 import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
21 import org.aspectj.asm.AsmManager;
22 import org.aspectj.bridge.IMessage;
23 import org.aspectj.bridge.context.CompilationAndWeavingContext;
24 import org.aspectj.bridge.context.ContextToken;
25 import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
26 import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
27 import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
28 import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
29 import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation;
30 import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
31 import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
32 import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
33 import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
34 import org.aspectj.org.eclipse.jdt.internal.compiler.env.AccessRestriction;
35 import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType;
36 import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
37 import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
38 import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ITypeRequestor;
39 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
40 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
41 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
42 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
43 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
44 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
45 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MissingTypeBinding;
46 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ModuleBinding;
47 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
48 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
49 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding;
50 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
51 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
52 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeCollisionException;
53 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits;
54 import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
55 import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
56 import org.aspectj.weaver.AnnotationAJ;
57 import org.aspectj.weaver.ConcreteTypeMunger;
58 import org.aspectj.weaver.ReferenceType;
59 import org.aspectj.weaver.ReferenceTypeDelegate;
60 import org.aspectj.weaver.ResolvedMember;
61 import org.aspectj.weaver.ResolvedType;
62 import org.aspectj.weaver.ResolvedTypeMunger;
63 import org.aspectj.weaver.UnresolvedType;
64 import org.aspectj.weaver.WeaverMessages;
65 import org.aspectj.weaver.WeaverStateInfo;
66 import org.aspectj.weaver.World;
67 import org.aspectj.weaver.bcel.BcelAnnotation;
68 import org.aspectj.weaver.bcel.BcelObjectType;
69 import org.aspectj.weaver.bcel.FakeAnnotation;
70 import org.aspectj.weaver.bcel.LazyClassGen;
71 import org.aspectj.weaver.patterns.DeclareAnnotation;
72 import org.aspectj.weaver.patterns.DeclareParents;
75 * Overrides the default eclipse LookupEnvironment for two purposes.
77 * 1. To provide some additional phases to <code>completeTypeBindings</code> that weave declare parents and inter-type declarations
78 * at the correct time.
80 * 2. To intercept the loading of new binary types to ensure the they will have declare parents and inter-type declarations woven
85 public class AjLookupEnvironment extends LookupEnvironment implements AnonymousClassCreationListener {
86 public EclipseFactory factory = null;
88 // private boolean builtInterTypesAndPerClauses = false;
89 private final List<SourceTypeBinding> pendingTypesToWeave = new ArrayList<>();
91 // Q: What are dangerousInterfaces?
92 // A: An interface is considered dangerous if an ITD has been made upon it
94 // requires the top most implementors of the interface to be woven *and yet*
96 // responsible for the ITD is not in the 'world'.
97 // Q: Err, how can that happen?
98 // A: When a type is on the inpath, it is 'processed' when completing type
100 // point we look at any type mungers it was affected by previously (stored
102 // state info attribute). Effectively we are working with a type munger and
103 // yet may not have its
104 // originating aspect in the world. This is a problem if, for example, the
106 // a 'body' for a method targetting an interface - since the top most
107 // implementors should
108 // be woven by the munger from the aspect. When this happens we store the
109 // interface name here
110 // in the map - if we later process a type that is the topMostImplementor of
112 // interface then we put out an error message.
115 * interfaces targetted by ITDs that have to be implemented by accessing the topMostImplementor of the interface, yet the aspect
116 * where the ITD originated is not in the world
118 private final Map dangerousInterfaces = new HashMap();
120 public AjLookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter,
121 INameEnvironment nameEnvironment) {
122 super(typeRequestor, options, problemReporter, nameEnvironment);
125 public AjLookupEnvironment(LookupEnvironment env, ModuleBinding moduleBinding) {
126 super(env, moduleBinding);
129 // ??? duplicates some of super's code
131 public void completeTypeBindings() {
132 AsmManager.setCompletingTypeBindings(true);
133 ContextToken completeTypeBindingsToken = CompilationAndWeavingContext.enteringPhase(
134 CompilationAndWeavingContext.COMPLETING_TYPE_BINDINGS, "");
135 // builtInterTypesAndPerClauses = false;
136 // pendingTypesToWeave = new ArrayList();
137 stepCompleted = BUILD_TYPE_HIERARCHY;
139 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
140 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CHECK_AND_SET_IMPORTS,
141 units[i].compilationResult.fileName);
142 units[i].scope.checkAndSetImports();
143 CompilationAndWeavingContext.leavingPhase(tok);
145 stepCompleted = CHECK_AND_SET_IMPORTS;
147 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
148 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CONNECTING_TYPE_HIERARCHY,
149 units[i].compilationResult.fileName);
150 units[i].scope.connectTypeHierarchy();
151 CompilationAndWeavingContext.leavingPhase(tok);
153 stepCompleted = CONNECT_TYPE_HIERARCHY;
155 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
156 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.BUILDING_FIELDS_AND_METHODS,
157 units[i].compilationResult.fileName);
158 // units[i].scope.checkParameterizedTypes(); do this check a little
159 // later, after ITDs applied to stbs
160 units[i].scope.buildFieldsAndMethods();
161 CompilationAndWeavingContext.leavingPhase(tok);
164 // would like to gather up all TypeDeclarations at this point and put
165 // them in the factory
166 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
167 SourceTypeBinding[] b = units[i].scope.topLevelTypes;
168 for (SourceTypeBinding sourceTypeBinding : b) {
169 factory.addSourceTypeBinding(sourceTypeBinding, units[i]);
170 if (sourceTypeBinding.superclass instanceof MissingTypeBinding) {
171 // e37: Undoing the work in ClassScope.connectSuperClass() as it will lead to cascade errors
172 // TODO allow MissingTypeBinding through here and cope with it in all situations later?
173 sourceTypeBinding.superclass = units[i].scope.getJavaLangObject();
178 // We won't find out about anonymous types until later though, so
180 // told about them when they turn up.
181 AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(this);
183 // need to build inter-type declarations for all AspectDeclarations at
185 // this MUST be done in order from super-types to subtypes
186 List<SourceTypeBinding> typesToProcess = new ArrayList<>();
187 List<SourceTypeBinding> aspectsToProcess = new ArrayList<>();
188 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
189 CompilationUnitScope cus = units[i].scope;
190 SourceTypeBinding[] stbs = cus.topLevelTypes;
191 for (SourceTypeBinding stb : stbs) {
192 typesToProcess.add(stb);
193 TypeDeclaration typeDeclaration = stb.scope.referenceContext;
194 if (typeDeclaration instanceof AspectDeclaration) {
195 aspectsToProcess.add(stb);
199 factory.getWorld().getCrosscuttingMembersSet().reset();
201 // Need to do these before the other ITDs
202 for (SourceTypeBinding aspectToProcess : aspectsToProcess) {
203 processInterTypeMemberTypes(aspectToProcess.scope);
206 while (typesToProcess.size() > 0) {
207 // removes types from the list as they are processed...
208 collectAllITDsAndDeclares(typesToProcess.get(0), typesToProcess);
211 factory.finishTypeMungers();
214 final List<ConcreteTypeMunger> typeMungers = factory.getTypeMungers();
216 final List<DeclareParents> declareParents = factory.getDeclareParents();
217 final List<DeclareAnnotation> declareAnnotationOnTypes = factory.getDeclareAnnotationOnTypes();
221 // We now have some list of types to process, and we are about to apply
223 // There can be situations where the order of types passed to the
224 // compiler causes the
225 // output from the compiler to vary - THIS IS BAD. For example, if we
227 // and class B extends A. Also, an aspect that 'declare parents: A+
228 // implements Serializable'
229 // then depending on whether we see A first, we may or may not make B
232 // The fix is to process them in the right order, ensuring that for a
233 // type we process its
234 // supertypes and superinterfaces first. This algorithm may have
236 // - partial hierarchies (e.g. suppose types A,B,C are in a hierarchy
237 // and A and C are to be woven but not B)
238 // - weaving that brings new types in for processing (see
239 // pendingTypesToWeave.add() calls) after we thought
240 // we had the full list.
242 // but these aren't common cases (he bravely said...)
243 boolean typeProcessingOrderIsImportant = declareParents.size() > 0 || declareAnnotationOnTypes.size() > 0; // DECAT
245 if (typeProcessingOrderIsImportant) {
246 typesToProcess = new ArrayList<>();
247 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
248 CompilationUnitScope cus = units[i].scope;
249 SourceTypeBinding[] stbs = cus.topLevelTypes;
250 Collections.addAll(typesToProcess, stbs);
253 List<SourceTypeBinding> stb2 = new ArrayList<>();
254 stb2.addAll(typesToProcess);
256 while (typesToProcess.size() > 0) {
257 // A side effect of weaveIntertypes() is that the processed type is removed from the collection
258 weaveIntertypes(typesToProcess, typesToProcess.get(0), typeMungers, declareParents, declareAnnotationOnTypes, 1);
261 while (stb2.size() > 0) {
262 // A side effect of weaveIntertypes() is that the processed type is removed from the collection
263 weaveIntertypes(stb2, stb2.get(0), typeMungers, declareParents, declareAnnotationOnTypes, 2);
267 // Order isn't important
268 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
269 weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents, declareAnnotationOnTypes);
273 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
274 units[i].scope.checkParameterizedTypes();
277 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
278 SourceTypeBinding[] b = units[i].scope.topLevelTypes;
279 for (SourceTypeBinding sourceTypeBinding : b) {
280 ContextToken tok = CompilationAndWeavingContext.enteringPhase(
281 CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, sourceTypeBinding.sourceName);
282 resolvePointcutDeclarations(sourceTypeBinding.scope);
283 CompilationAndWeavingContext.leavingPhase(tok);
287 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
288 SourceTypeBinding[] b = units[i].scope.topLevelTypes;
289 for (SourceTypeBinding sourceTypeBinding : b) {
290 ContextToken tok = CompilationAndWeavingContext.enteringPhase(
291 CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, sourceTypeBinding.sourceName);
292 addAdviceLikeDeclares(sourceTypeBinding.scope);
293 CompilationAndWeavingContext.leavingPhase(tok);
297 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
298 units[i] = null; // release unnecessary reference to the parsed unit
301 stepCompleted = BUILD_FIELDS_AND_METHODS;
302 lastCompletedUnitIndex = lastUnitIndex;
303 AsmManager.setCompletingTypeBindings(false);
304 factory.getWorld().getCrosscuttingMembersSet().verify();
305 CompilationAndWeavingContext.leavingPhase(completeTypeBindingsToken);
307 if (isProcessingAnnotations) {
308 throw new SourceTypeCollisionException(); // TODO(yushkovskiy): temporary solution; forcing to recompile units to insert mungers into types
313 // * For any given sourcetypebinding, this method checks that if it is a
314 // parameterized aspect that
315 // * the type parameters specified for any supertypes meet the bounds for
319 // private void verifyAnyTypeParametersMeetBounds(SourceTypeBinding
321 // ResolvedType onType = factory.fromEclipse(sourceType);
322 // if (onType.isAspect()) {
323 // ResolvedType superType = factory.fromEclipse(sourceType.superclass);
324 // // Don't need to check if it was used in its RAW form or isnt generic
325 // if (superType.isGenericType() || superType.isParameterizedType()) {
326 // TypeVariable[] typeVariables = superType.getTypeVariables();
327 // UnresolvedType[] typeParams = superType.getTypeParameters();
328 // if (typeVariables!=null && typeParams!=null) {
329 // for (int i = 0; i < typeVariables.length; i++) {
331 // typeVariables[i].canBeBoundTo(typeParams[i].resolve(factory.getWorld()));
332 // if (!ok) { // the supplied parameter violates the bounds
333 // // Type {0} does not meet the specification for type parameter {1} ({2})
334 // in generic type {3}
336 // WeaverMessages.format(
337 // WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS,
340 // typeVariables[i].getDisplayName(),
341 // superType.getGenericType().getName());
342 // factory.getWorld().getMessageHandler().handleMessage(MessageUtil.error(msg
343 // ,onType.getSourceLocation()));
351 public void doSupertypesFirst(ReferenceBinding rb, Collection<? extends ReferenceBinding> yetToProcess) {
352 if (rb instanceof SourceTypeBinding) {
353 if (yetToProcess.contains(rb)) {
354 collectAllITDsAndDeclares((SourceTypeBinding) rb, yetToProcess);
356 } else if (rb instanceof ParameterizedTypeBinding) {
357 // If its a PTB we need to pull the SourceTypeBinding out of it.
358 ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) rb;
359 if (ptb.type instanceof SourceTypeBinding && yetToProcess.contains(ptb.type)) {
360 collectAllITDsAndDeclares((SourceTypeBinding) ptb.type, yetToProcess);
366 * Find all the ITDs and Declares, but it is important we do this from the supertypes down to the subtypes.
369 * @param yetToProcess
371 private void collectAllITDsAndDeclares(SourceTypeBinding sourceType, Collection<? extends ReferenceBinding> yetToProcess) {
372 // Look at the supertype first
373 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.COLLECTING_ITDS_AND_DECLARES,
374 sourceType.sourceName);
376 yetToProcess.remove(sourceType);
377 // look out our direct supertype
378 doSupertypesFirst(sourceType.superclass(), yetToProcess);
380 // now check our membertypes (pr119570)
381 ReferenceBinding[] memberTypes = sourceType.memberTypes;
382 for (ReferenceBinding memberType : memberTypes) {
383 SourceTypeBinding rb = (SourceTypeBinding) memberType;
384 if (!rb.superclass().equals(sourceType)) {
385 doSupertypesFirst(rb.superclass(), yetToProcess);
389 buildInterTypeAndPerClause(sourceType.scope);
390 addCrosscuttingStructures(sourceType.scope);
391 CompilationAndWeavingContext.leavingPhase(tok);
395 * Weave the parents and intertype decls into a given type. This method looks at the supertype and superinterfaces for the
396 * specified type and recurses to weave those first if they are in the full list of types we are going to process during this
397 * compile... it stops recursing the first time it hits a type we aren't going to process during this compile. This could cause
398 * problems if you supply 'pieces' of a hierarchy, i.e. the bottom and the top, but not the middle - but what the hell are you
399 * doing if you do that?
401 * @param mode 0=do everything, 1=do declare parents, 2=do ITDs
403 private void weaveIntertypes(List<SourceTypeBinding> typesToProcess, SourceTypeBinding typeToWeave,
404 List<ConcreteTypeMunger> typeMungers, List<DeclareParents> declareParents,
405 List<DeclareAnnotation> declareAnnotationOnTypes, int mode) {
406 // Look at the supertype first
407 ReferenceBinding superType = typeToWeave.superclass();
408 if (typesToProcess.contains(superType) && superType instanceof SourceTypeBinding) {
409 // System.err.println("Recursing to supertype "+new
410 // String(superType.getFileName()));
411 weaveIntertypes(typesToProcess, (SourceTypeBinding) superType, typeMungers, declareParents, declareAnnotationOnTypes,
414 // Then look at the superinterface list
415 ReferenceBinding[] interfaceTypes = typeToWeave.superInterfaces();
416 for (ReferenceBinding binding : interfaceTypes) {
417 if (typesToProcess.contains(binding) && binding instanceof SourceTypeBinding) {
418 // System.err.println("Recursing to superinterface "+new
419 // String(binding.getFileName()));
420 weaveIntertypes(typesToProcess, (SourceTypeBinding) binding, typeMungers, declareParents, declareAnnotationOnTypes,
422 } else if (binding instanceof ParameterizedTypeBinding && (((ParameterizedTypeBinding) binding).type instanceof SourceTypeBinding) && typesToProcess.contains(((ParameterizedTypeBinding) binding).type)) {
423 weaveIntertypes(typesToProcess, (SourceTypeBinding) ((ParameterizedTypeBinding) binding).type, typeMungers, declareParents, declareAnnotationOnTypes, mode);
426 weaveInterTypeDeclarations(typeToWeave, typeMungers, declareParents, declareAnnotationOnTypes, false, mode);
427 typesToProcess.remove(typeToWeave);
430 private void doPendingWeaves() {
431 for (SourceTypeBinding t: pendingTypesToWeave) {
432 ContextToken tok = CompilationAndWeavingContext.enteringPhase(
433 CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, t.sourceName);
434 weaveInterTypeDeclarations(t);
435 CompilationAndWeavingContext.leavingPhase(tok);
437 pendingTypesToWeave.clear();
440 private void addAdviceLikeDeclares(ClassScope s) {
441 TypeDeclaration dec = s.referenceContext;
443 if (dec instanceof AspectDeclaration) {
444 ResolvedType typeX = factory.fromEclipse(dec.binding);
445 factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX);
448 SourceTypeBinding sourceType = s.referenceContext.binding;
449 ReferenceBinding[] memberTypes = sourceType.memberTypes;
450 for (ReferenceBinding memberType : memberTypes) {
451 addAdviceLikeDeclares(((SourceTypeBinding) memberType).scope);
455 private void addCrosscuttingStructures(ClassScope s) {
456 TypeDeclaration dec = s.referenceContext;
458 if (dec instanceof AspectDeclaration) {
459 ResolvedType typeX = factory.fromEclipse(dec.binding);
460 factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX, false);
462 if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) {
463 factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass(), false);
467 SourceTypeBinding sourceType = s.referenceContext.binding;
468 ReferenceBinding[] memberTypes = sourceType.memberTypes;
469 for (ReferenceBinding memberType : memberTypes) {
470 addCrosscuttingStructures(((SourceTypeBinding) memberType).scope);
474 private void resolvePointcutDeclarations(ClassScope s) {
475 TypeDeclaration dec = s.referenceContext;
476 SourceTypeBinding sourceType = s.referenceContext.binding;
477 boolean hasPointcuts = false;
478 AbstractMethodDeclaration[] methods = dec.methods;
479 boolean initializedMethods = false;
480 if (methods != null) {
481 for (AbstractMethodDeclaration method : methods) {
482 if (method instanceof PointcutDeclaration) {
484 if (!initializedMethods) {
485 sourceType.methods(); // force initialization
486 initializedMethods = true;
488 ((PointcutDeclaration) method).resolvePointcut(s);
493 if (hasPointcuts || dec instanceof AspectDeclaration || couldBeAnnotationStyleAspectDeclaration(dec)) {
494 ReferenceType name = (ReferenceType) factory.fromEclipse(sourceType);
495 EclipseSourceType eclipseSourceType = (EclipseSourceType) name.getDelegate();
496 eclipseSourceType.checkPointcutDeclarations();
499 ReferenceBinding[] memberTypes = sourceType.memberTypes;
500 for (ReferenceBinding memberType : memberTypes) {
501 resolvePointcutDeclarations(((SourceTypeBinding) memberType).scope);
506 * Return true if the declaration has @Aspect annotation. Called 'couldBe' rather than 'is' because someone else may have
507 * defined an annotation called Aspect - we can't verify the full name (including package name) because it may not have been
508 * resolved just yet and rather going through expensive resolution when we dont have to, this gives us a cheap check that tells
509 * us whether to bother.
511 private boolean couldBeAnnotationStyleAspectDeclaration(TypeDeclaration dec) {
512 Annotation[] annotations = dec.annotations;
513 boolean couldBeAtAspect = false;
514 if (annotations != null) {
515 for (int i = 0; i < annotations.length && !couldBeAtAspect; i++) {
516 if (annotations[i].toString().equals("@Aspect")) {
517 couldBeAtAspect = true;
521 return couldBeAtAspect;
525 * Applies any intertype member type declarations up front.
527 private void processInterTypeMemberTypes(ClassScope classScope) {
528 TypeDeclaration dec = classScope.referenceContext;
529 if (dec instanceof AspectDeclaration) {
530 ((AspectDeclaration) dec).processIntertypeMemberTypes(classScope);
532 // if we are going to support nested aspects making itd member types, copy the logic from the end of
533 // buildInterTypeAndPerClause() which walks members
536 private void buildInterTypeAndPerClause(ClassScope s) {
537 TypeDeclaration dec = s.referenceContext;
538 if (dec instanceof AspectDeclaration) {
539 ((AspectDeclaration) dec).buildInterTypeAndPerClause(s);
542 SourceTypeBinding sourceType = s.referenceContext.binding;
543 // test classes don't extend aspects
544 if (sourceType.superclass != null) {
545 ResolvedType parent = factory.fromEclipse(sourceType.superclass);
546 if (parent.isAspect() && !isAspect(dec)) {
547 factory.showMessage(IMessage.ERROR, "class \'" + new String(sourceType.sourceName) + "\' can not extend aspect \'"
548 + parent.getName() + "\'", factory.fromEclipse(sourceType).getSourceLocation(), null);
552 ReferenceBinding[] memberTypes = sourceType.memberTypes;
553 if (memberTypes == null) {
554 System.err.println("Unexpectedly found null for memberTypes of " + sourceType.debugName());
556 if (memberTypes != null) {
557 for (ReferenceBinding memberType : memberTypes) {
558 buildInterTypeAndPerClause(((SourceTypeBinding) memberType).scope);
563 private boolean isAspect(TypeDeclaration decl) {
564 if ((decl instanceof AspectDeclaration)) {
566 } else if (decl.annotations == null) {
569 for (int i = 0; i < decl.annotations.length; i++) {
570 Annotation ann = decl.annotations[i];
571 if (ann.type instanceof SingleTypeReference) {
572 if (CharOperation.equals("Aspect".toCharArray(), ((SingleTypeReference) ann.type).token)) {
575 } else if (ann.type instanceof QualifiedTypeReference) {
576 QualifiedTypeReference qtr = (QualifiedTypeReference) ann.type;
577 if (qtr.tokens.length != 5) {
580 if (!CharOperation.equals("org".toCharArray(), qtr.tokens[0])) {
583 if (!CharOperation.equals("aspectj".toCharArray(), qtr.tokens[1])) {
586 if (!CharOperation.equals("lang".toCharArray(), qtr.tokens[2])) {
589 if (!CharOperation.equals("annotation".toCharArray(), qtr.tokens[3])) {
592 if (!CharOperation.equals("Aspect".toCharArray(), qtr.tokens[4])) {
602 private void weaveInterTypeDeclarations(CompilationUnitScope unit, List<ConcreteTypeMunger> typeMungers,
603 List<DeclareParents> declareParents, List<DeclareAnnotation> declareAnnotationOnTypes) {
604 for (int i = 0, length = unit.topLevelTypes.length; i < length; i++) {
605 weaveInterTypeDeclarations(unit.topLevelTypes[i], typeMungers, declareParents, declareAnnotationOnTypes, false, 0);
609 private void weaveInterTypeDeclarations(SourceTypeBinding sourceType) {
610 if (!factory.areTypeMungersFinished()) {
611 if (!pendingTypesToWeave.contains(sourceType)) {
612 pendingTypesToWeave.add(sourceType);
614 // inner type ITD support - may need this for some incremental cases...
615 // List<ConcreteTypeMunger> ctms = factory.getWorld().getCrosscuttingMembersSet().getTypeMungersOfKind(
616 // ResolvedTypeMunger.InnerClass);
617 // // List<ConcreteTypeMunger> innerTypeMungers = new ArrayList<ConcreteTypeMunger>();
618 // // for (ConcreteTypeMunger ctm : ctms) {
619 // // if (ctm.getMunger() != null && ctm.getMunger().getKind() == ResolvedTypeMunger.InnerClass) {
620 // // innerTypeMungers.add(ctm);
623 // // that includes the innertype one...
624 // // doPendingWeaves at this level is about applying inner class
625 // BinaryTypeBinding t = (BinaryTypeBinding) sourceType;
626 // for (ConcreteTypeMunger ctm : innerTypeMungers) {
627 // NewMemberClassTypeMunger nmctm = (NewMemberClassTypeMunger) ctm.getMunger();
628 // ReferenceBinding[] rbs = t.memberTypes;
629 // UnresolvedType ut = factory.fromBinding(t);
630 // if (ut.equals(nmctm.getTargetType())) {
631 // // got a match here
632 // SourceTypeBinding aspectTypeBinding = (SourceTypeBinding) factory.makeTypeBinding(ctm.getAspectType());
634 // char[] mungerMemberTypeName = ("$" + nmctm.getMemberTypeName()).toCharArray();
635 // ReferenceBinding innerTypeBinding = null;
636 // for (ReferenceBinding innerType : aspectTypeBinding.memberTypes) {
637 // char[] compounded = CharOperation.concatWith(innerType.compoundName, '.');
638 // if (org.aspectj.org.eclipse.jdt.core.compiler.CharOperation.endsWith(compounded, mungerMemberTypeName)) {
639 // innerTypeBinding = innerType;
643 // // may be unresolved if the aspect type binding was a BinaryTypeBinding
644 // if (innerTypeBinding instanceof UnresolvedReferenceBinding) {
645 // innerTypeBinding = BinaryTypeBinding
646 // .resolveType(innerTypeBinding, factory.getLookupEnvironment(), true);
648 // t.memberTypes(); // cause initialization
649 // t.memberTypes = new ReferenceBinding[] { innerTypeBinding };
652 // // The inner type from the aspect should be put into the membertypebindings for this
659 weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(),
660 factory.getDeclareAnnotationOnTypes(), true, 0);
665 * @param mode 0=do everything, 1=do declare parents, 2=do ITDs
667 private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, List<ConcreteTypeMunger> typeMungers,
668 List<DeclareParents> declareParents, List<DeclareAnnotation> declareAnnotationOnTypes, boolean skipInners, int mode) {
670 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS,
671 sourceType.sourceName);
673 ResolvedType onType = factory.fromEclipse(sourceType);
675 // AMC we shouldn't need this when generic sigs are fixed??
676 if (onType.isRawType()) {
677 onType = onType.getGenericType();
680 WeaverStateInfo info = onType.getWeaverState();
683 // this test isnt quite right - there will be a case where we fail to
685 // with a 'dangerous interface' because the type is reweavable when we
687 // because the type wasn't going to be rewoven... if that happens, we
689 // move this test and dangerous interface processing to the end of this
691 // make it conditional on whether any of the typeMungers passed into
693 // matched this type.
694 if (info != null && !info.isOldStyle() && !info.isReweavable()) {
695 processTypeMungersFromExistingWeaverState(sourceType, onType);
696 CompilationAndWeavingContext.leavingPhase(tok);
700 // Check if the type we are looking at is the topMostImplementor of a
701 // dangerous interface -
702 // report a problem if it is.
703 for (Object o : dangerousInterfaces.entrySet()) {
704 Map.Entry entry = (Map.Entry) o;
705 ResolvedType interfaceType = (ResolvedType) entry.getKey();
706 if (onType.isTopmostImplementor(interfaceType)) {
707 factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null);
711 boolean needOldStyleWarning = (info != null && info.isOldStyle());
713 onType.clearInterTypeMungers();
714 onType.ensureConsistent();
716 // FIXME asc perf Could optimize here, after processing the expected set
717 // of types we may bring
718 // binary types that are not exposed to the weaver, there is no need to
719 // attempt declare parents
720 // or declare annotation really - unless we want to report the
721 // not-exposed to weaver
724 List<DeclareParents> decpToRepeat = new ArrayList<>();
725 List<DeclareAnnotation> decaToRepeat = new ArrayList<>();
726 boolean anyNewParents = false;
727 boolean anyNewAnnotations = false;
730 // try and apply all decps - if they match, then great. If they don't
732 // check if they are starred-annotation patterns. If they are not
734 // annotation patterns then they might match later...remember that...
735 for (DeclareParents decp : declareParents) {
736 if (!decp.isMixin()) {
737 boolean didSomething = doDeclareParents(decp, sourceType);
739 if (factory.pushinCollector != null) {
740 factory.pushinCollector.tagAsMunged(sourceType, decp.getParents().get(0));
742 anyNewParents = true;
744 if (!decp.getChild().isStarAnnotation()) {
745 decpToRepeat.add(decp);
751 for (DeclareAnnotation deca : declareAnnotationOnTypes) {
752 boolean didSomething = doDeclareAnnotations(deca, sourceType, true);
754 anyNewAnnotations = true;
756 if (!deca.getTypePattern().isStar()) {
757 decaToRepeat.add(deca);
762 List<Object> forRemoval = new ArrayList<>();
763 // now lets loop over and over until we have done all we can
764 while ((anyNewAnnotations || anyNewParents) && (!decpToRepeat.isEmpty() || !decaToRepeat.isEmpty())) {
765 anyNewParents = anyNewAnnotations = false;
767 for (DeclareParents decp : decpToRepeat) {
768 boolean didSomething = doDeclareParents(decp, sourceType);
770 if (factory.pushinCollector != null) {
771 factory.pushinCollector.tagAsMunged(sourceType, decp.getParents().get(0));
773 anyNewParents = true;
774 forRemoval.add(decp);
777 decpToRepeat.removeAll(forRemoval);
780 for (DeclareAnnotation deca : decaToRepeat) {
781 boolean didSomething = doDeclareAnnotations(deca, sourceType, false);
783 if (factory.pushinCollector != null) {
784 factory.pushinCollector.tagAsMunged(sourceType, deca.getAnnotationString());
786 anyNewAnnotations = true;
787 forRemoval.add(deca);
790 decaToRepeat.removeAll(forRemoval);
793 if (mode == 0 || mode == 2) {
794 for (ConcreteTypeMunger typeMunger : typeMungers) {
795 EclipseTypeMunger munger = (EclipseTypeMunger) typeMunger;
796 if (munger.matches(onType)) {
797 // if (needOldStyleWarning) {
798 // factory.showMessage(IMessage.WARNING, "The class for " + onType
799 // + " should be recompiled with ajc-1.1.1 for best results", onType.getSourceLocation(), null);
800 // needOldStyleWarning = false;
802 onType.addInterTypeMunger(munger, true);
803 if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.InnerClass) {
804 // Must do these right now, because if we do an ITD member afterwards it may attempt to reference the
805 // type being applied (the call above 'addInterTypeMunger' will fail for these ITDs if it needed
806 // it to be in place)
807 if (munger.munge(sourceType, onType)) {
808 if (factory.pushinCollector != null) {
809 factory.pushinCollector.tagAsMunged(sourceType, munger.getSourceMethod());
816 onType.checkInterTypeMungers();
817 for (ConcreteTypeMunger concreteTypeMunger : onType.getInterTypeMungers()) {
818 EclipseTypeMunger munger = (EclipseTypeMunger) concreteTypeMunger;
819 if (munger.getMunger() == null || munger.getMunger().getKind() != ResolvedTypeMunger.InnerClass) {
820 if (munger.munge(sourceType, onType)) {
821 if (factory.pushinCollector != null) {
822 factory.pushinCollector.tagAsMunged(sourceType, munger.getSourceMethod());
829 // Call if you would like to do source weaving of declare
830 // @method/@constructor
831 // at source time... no need to do this as it can't impact anything, but
833 // future generations to enjoy. Method source is commented out at the
834 // end of this module
835 // doDeclareAnnotationOnMethods();
837 // Call if you would like to do source weaving of declare @field
838 // at source time... no need to do this as it can't impact anything, but
840 // future generations to enjoy. Method source is commented out at the
841 // end of this module
842 // doDeclareAnnotationOnFields();
845 CompilationAndWeavingContext.leavingPhase(tok);
849 ReferenceBinding[] memberTypes = sourceType.memberTypes;
850 for (ReferenceBinding memberType : memberTypes) {
851 if (memberType instanceof SourceTypeBinding) {
852 weaveInterTypeDeclarations((SourceTypeBinding) memberType, typeMungers, declareParents,
853 declareAnnotationOnTypes, false, mode);
856 CompilationAndWeavingContext.leavingPhase(tok);
860 * Called when we discover we are weaving intertype declarations on some type that has an existing 'WeaverStateInfo' object -
861 * this is typically some previously woven type that has been passed on the inpath.
863 * sourceType and onType are the 'same type' - the former is the 'Eclipse' version and the latter is the 'Weaver' version.
865 private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType, ResolvedType onType) {
866 List<ConcreteTypeMunger> previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType);
868 for (ConcreteTypeMunger m : previouslyAppliedMungers) {
869 EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m);
870 if (munger.munge(sourceType, onType)) {
871 if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) {
872 if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) {
874 .put(onType, "implementors of " + onType + " must be woven by " + munger.getAspectType());
882 private boolean doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) {
883 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,
884 sourceType.sourceName);
885 ResolvedType resolvedSourceType = factory.fromEclipse(sourceType);
886 List<ResolvedType> newParents = declareParents.findMatchingNewParents(resolvedSourceType, false);
887 if (!newParents.isEmpty()) {
888 for (ResolvedType parent : newParents) {
889 if (dangerousInterfaces.containsKey(parent)) {
890 ResolvedType onType = factory.fromEclipse(sourceType);
891 factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent),
892 onType.getSourceLocation(), null);
894 if (Modifier.isFinal(parent.getModifiers())) {
895 factory.showMessage(IMessage.ERROR, "cannot extend final class " + parent.getClassName(),
896 declareParents.getSourceLocation(), null);
898 // do not actually do it if the type isn't exposed - this
899 // will correctly reported as a problem elsewhere
900 if (!resolvedSourceType.isExposedToWeaver()) {
903 // AsmRelationshipProvider.getDefault().
904 // addDeclareParentsRelationship
905 // (declareParents.getSourceLocation(),
906 // factory.fromEclipse(sourceType), newParents);
907 addParent(sourceType, parent);
910 CompilationAndWeavingContext.leavingPhase(tok);
913 CompilationAndWeavingContext.leavingPhase(tok);
917 private String stringifyTargets(long bits) {
918 if ((bits & TagBits.AnnotationTargetMASK) == 0) {
921 Set<String> s = new HashSet<>();
922 if ((bits & TagBits.AnnotationForAnnotationType) != 0) {
923 s.add("ANNOTATION_TYPE");
925 if ((bits & TagBits.AnnotationForConstructor) != 0) {
926 s.add("CONSTRUCTOR");
928 if ((bits & TagBits.AnnotationForField) != 0) {
931 if ((bits & TagBits.AnnotationForLocalVariable) != 0) {
932 s.add("LOCAL_VARIABLE");
934 if ((bits & TagBits.AnnotationForMethod) != 0) {
937 if ((bits & TagBits.AnnotationForPackage) != 0) {
940 if ((bits & TagBits.AnnotationForParameter) != 0) {
943 if ((bits & TagBits.AnnotationForType) != 0) {
946 StringBuffer sb = new StringBuffer();
948 for (Iterator<String> iter = s.iterator(); iter.hasNext();) {
949 String element = iter.next();
951 if (iter.hasNext()) {
956 return sb.toString();
959 private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) {
960 ResolvedType rtx = factory.fromEclipse(sourceType);
961 if (!decA.matches(rtx)) {
964 if (!rtx.isExposedToWeaver()) {
968 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS,
969 sourceType.sourceName);
971 // Get the annotation specified in the declare
972 UnresolvedType aspectType = decA.getAspect();
973 if (aspectType instanceof ReferenceType) {
974 ReferenceType rt = (ReferenceType) aspectType;
975 if (rt.isParameterizedType() || rt.isRawType()) {
976 aspectType = rt.getGenericType();
979 TypeBinding tb = factory.makeTypeBinding(aspectType);
981 // Hideousness follows:
983 // There are multiple situations to consider here and they relate to the
985 // where the annotation is coming from and where the annotation is going
988 // 1. Straight full build, all from source - the annotation is from a
990 // is being put on some type. Both types are real SourceTypeBindings.
992 // 2. Incremental build, changing the affected type - the annotation is
994 // dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and
996 // affected type is a real SourceTypeBinding. Mostly works (pr128665)
999 SourceTypeBinding stb = (SourceTypeBinding) tb;
1000 Annotation[] toAdd = null;
1003 AbstractMethodDeclaration methodDecl = null;
1004 // Might have to retrieve the annotation through BCEL and construct an
1005 // eclipse one for it.
1006 if (stb instanceof BinaryTypeBinding) {
1007 toAdd = retrieveAnnotationFromBinaryTypeBinding(decA, stb);
1008 if (toAdd != null && toAdd.length > 0 && toAdd[0].resolvedType != null) {
1009 abits = toAdd[0].resolvedType.getAnnotationTagBits();
1011 } else if (stb != null) {
1012 // much nicer, its a real SourceTypeBinding so we can stay in
1014 // if (decA.getAnnotationMethod() != null) {
1015 char[] declareSelector = decA.getAnnotationMethod().toCharArray();
1017 ReferenceBinding rb = stb;
1018 String declaringAspectName = decA.getDeclaringType().getRawName();
1019 while (rb != null && !new String(CharOperation.concatWith(rb.compoundName, '.')).equals(declaringAspectName)) {
1020 rb = rb.superclass();
1022 MethodBinding[] mbs = rb.getMethods(declareSelector);
1024 ReferenceBinding declaringBinding = mbs[0].declaringClass;
1025 if (declaringBinding instanceof ParameterizedTypeBinding) {
1026 // Unwrap - this means we don't allow the type of the annotation to be parameterized, may need to revisit that
1027 declaringBinding = ((ParameterizedTypeBinding) declaringBinding).type;
1029 if (declaringBinding instanceof BinaryTypeBinding) {
1030 toAdd = retrieveAnnotationFromBinaryTypeBinding(decA, declaringBinding);
1031 if (toAdd != null && toAdd.length > 0 && toAdd[0].resolvedType != null) {
1032 abits = toAdd[0].resolvedType.getAnnotationTagBits();
1035 abits = mbs[0].getAnnotationTagBits(); // ensure resolved
1036 TypeDeclaration typeDecl = ((SourceTypeBinding) declaringBinding).scope.referenceContext;
1037 methodDecl = typeDecl.declarationOf(mbs[0]);
1038 toAdd = methodDecl.annotations; // this is what to add
1039 toAdd[0] = createAnnotationCopy(toAdd[0]);
1040 if (toAdd[0].resolvedType != null) {
1041 abits = toAdd[0].resolvedType.getAnnotationTagBits();
1047 // This happens if there is another error in the code - that should be reported separately
1048 if (toAdd == null || toAdd[0] == null || toAdd[0].type == null) {
1049 CompilationAndWeavingContext.leavingPhase(tok);
1052 if (sourceType instanceof BinaryTypeBinding) {
1053 // In this case we can't access the source type binding to add a new
1054 // annotation, so let's put something
1055 // on the weaver type temporarily
1056 ResolvedType theTargetType = factory.fromEclipse(sourceType);
1057 TypeBinding theAnnotationType = toAdd[0].resolvedType;
1058 // The annotation type may be null if it could not be resolved (eg. the relevant import has not been added yet)
1059 // In this case an error will be put out about the annotation but not if we crash here
1060 if (theAnnotationType == null) {
1063 String sig = new String(theAnnotationType.signature());
1064 UnresolvedType bcelAnnotationType = UnresolvedType.forSignature(sig);
1065 String name = bcelAnnotationType.getName();
1066 if (theTargetType.hasAnnotation(bcelAnnotationType)) {
1067 CompilationAndWeavingContext.leavingPhase(tok);
1071 // FIXME asc tidy up this code that duplicates whats below!
1072 // Simple checks on the bits
1073 boolean giveupnow = false;
1074 if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
1075 if (isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) {
1076 // error will have been already reported
1078 } else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
1079 || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
1081 if (reportProblems) {
1082 if (decA.isExactPattern()) {
1083 factory.showMessage(IMessage.ERROR, WeaverMessages.format(
1084 WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
1085 stringifyTargets(abits)), decA.getSourceLocation(), null);
1087 // dont put out the lint - the weaving process will do
1090 // if (factory.getWorld().getLint().
1091 // invalidTargetForAnnotation.isEnabled()) {
1092 // factory.getWorld().getLint().invalidTargetForAnnotation
1094 // String[]{rtx.getName(),toAdd[0].type.toString(),
1096 // (abits)},decA.getSourceLocation(),null);
1104 CompilationAndWeavingContext.leavingPhase(tok);
1108 theTargetType.addAnnotation(new BcelAnnotation(new FakeAnnotation(name, sig,
1109 (abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld()));
1110 CompilationAndWeavingContext.leavingPhase(tok);
1114 Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations;
1115 if (currentAnnotations != null) {
1116 for (Annotation annotation : currentAnnotations) {
1117 String a = CharOperation.toString(annotation.type.getTypeName());
1118 String b = CharOperation.toString(toAdd[0].type.getTypeName());
1119 // FIXME asc we have a lint for attempting to add an annotation
1120 // twice to a method,
1121 // we could put it out here *if* we can resolve the problem of
1122 // errors coming out
1123 // multiple times if we have cause to loop through here
1125 CompilationAndWeavingContext.leavingPhase(tok);
1131 if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
1132 if ((abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0) {
1133 // this means it specifies something other than annotation or
1134 // normal type - error will have been already reported,
1135 // just resolution process above
1136 CompilationAndWeavingContext.leavingPhase(tok);
1139 if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
1140 || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
1142 if (reportProblems) {
1143 if (decA.isExactPattern()) {
1144 factory.showMessage(IMessage.ERROR, WeaverMessages.format(
1145 WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
1146 stringifyTargets(abits)), decA.getSourceLocation(), null);
1148 // dont put out the lint - the weaving process will do that
1151 // (factory.getWorld().getLint().invalidTargetForAnnotation
1153 // factory.getWorld().getLint().invalidTargetForAnnotation.
1155 // String[]{rtx.getName(),toAdd[0].type.toString(),
1156 // stringifyTargets(abits)},decA.getSourceLocation(),null);
1160 CompilationAndWeavingContext.leavingPhase(tok);
1165 // Build a new array of annotations
1167 // remember the current set (rememberAnnotations only does something the
1168 // first time it is called for a type)
1169 sourceType.scope.referenceContext.rememberAnnotations();
1171 // AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(
1172 // decA.getSourceLocation(), rtx.getSourceLocation());
1173 final Annotation[] abefore = sourceType.scope.referenceContext.annotations;
1174 final Annotation[] newset = new Annotation[toAdd.length + (abefore == null ? 0 : abefore.length)];
1175 System.arraycopy(toAdd, 0, newset, 0, toAdd.length);
1176 if (abefore != null) {
1177 System.arraycopy(abefore, 0, newset, toAdd.length, abefore.length);
1179 sourceType.scope.referenceContext.annotations = newset;
1180 if ((sourceType.tagBits & TagBits.AnnotationResolved)!=0) {
1181 sourceType.tagBits = sourceType.tagBits - TagBits.AnnotationResolved;
1183 CompilationAndWeavingContext.leavingPhase(tok);
1184 if (factory.pushinCollector != null) {
1185 factory.pushinCollector.tagAsMunged(sourceType, new CommonPrinter((methodDecl == null ? null : methodDecl.scope))
1186 .printAnnotation(toAdd[0]).toString());
1191 private Annotation[] retrieveAnnotationFromBinaryTypeBinding(DeclareAnnotation decA, ReferenceBinding declaringBinding) {
1192 ReferenceType rt = (ReferenceType) factory.fromEclipse(declaringBinding);
1193 ResolvedMember[] methods = rt.getDeclaredMethods();
1194 ResolvedMember decaMethod = null;
1195 String nameToLookFor = decA.getAnnotationMethod();
1196 for (ResolvedMember method : methods) {
1197 if (method.getName().equals(nameToLookFor)) {
1198 decaMethod = method;
1202 if (decaMethod != null) { // could assert this ...
1203 AnnotationAJ[] axs = decaMethod.getAnnotations();
1204 if (axs != null) { // another error has occurred, dont crash here because of it
1205 Annotation[] toAdd = new Annotation[1];
1206 toAdd[0] = createAnnotationFromBcelAnnotation(axs[0], decaMethod.getSourceLocation().getOffset(), factory);
1207 // BUG BUG BUG - We dont test these abits are correct, in fact
1208 // we'll be very lucky if they are.
1209 // What does that mean? It means on an incremental compile you
1210 // might get away with an
1211 // annotation that isn't allowed on a type being put on a type.
1212 // if (toAdd[0].resolvedType != null) {
1213 // abits = toAdd[0].resolvedType.getAnnotationTagBits();
1222 * Transform an annotation from its AJ form to an eclipse form. We *DONT* care about the values of the annotation. that is
1223 * because it is only being stuck on a type during type completion to allow for other constructs (decps, decas) that might be
1224 * looking for it - when the class actually gets to disk it wont have this new annotation on it and during weave time we will do
1225 * the right thing copying across values too.
1227 private static Annotation createAnnotationFromBcelAnnotation(AnnotationAJ annX, int pos, EclipseFactory factory) {
1228 String name = annX.getTypeName();
1229 TypeBinding tb = factory.makeTypeBinding(annX.getType());
1230 // String theName = annX.getSignature().getBaseName();
1231 char[][] typeName = CharOperation.splitOn('.', name.replace('$', '.').toCharArray()); // pr149293 - not bulletproof...
1232 long[] positions = new long[typeName.length];
1233 for (int i = 0; i < positions.length; i++) {
1236 TypeReference annType = new QualifiedTypeReference(typeName, positions);
1237 NormalAnnotation ann = new NormalAnnotation(annType, pos);
1238 ann.resolvedType = tb; // yuck - is this OK in all cases?
1239 // We don't need membervalues...
1240 // Expression pcExpr = new
1241 // StringLiteral(pointcutExpression.toCharArray(),pos,pos);
1242 // MemberValuePair[] mvps = new MemberValuePair[2];
1243 // mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr);
1244 // Expression argNamesExpr = new
1245 // StringLiteral(argNames.toCharArray(),pos,pos);
1247 // MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
1248 // ann.memberValuePairs = mvps;
1253 * Create a copy of an annotation, not deep but deep enough so we don't copy across fields that will get us into trouble like
1256 private static Annotation createAnnotationCopy(Annotation ann) {
1257 NormalAnnotation ann2 = new NormalAnnotation(ann.type, ann.sourceStart);
1258 ann2.memberValuePairs = ann.memberValuePairs();
1259 ann2.resolvedType = ann.resolvedType;
1260 ann2.bits = ann.bits;
1262 // String name = annX.getTypeName();
1263 // TypeBinding tb = factory.makeTypeBinding(annX.getSignature());
1264 // String theName = annX.getSignature().getBaseName();
1265 // char[][] typeName =
1266 // CharOperation.splitOn('.',name.replace('$','.').toCharArray());
1267 // //pr149293 - not bulletproof...
1268 // long[] positions = new long[typeName.length];
1269 // for (int i = 0; i < positions.length; i++) positions[i]=pos;
1270 // TypeReference annType = new
1271 // QualifiedTypeReference(typeName,positions);
1272 // NormalAnnotation ann = new NormalAnnotation(annType,pos);
1273 // ann.resolvedType=tb; // yuck - is this OK in all cases?
1274 // // We don't need membervalues...
1275 // // Expression pcExpr = new
1276 // StringLiteral(pointcutExpression.toCharArray(),pos,pos);
1277 // // MemberValuePair[] mvps = new MemberValuePair[2];
1279 // MemberValuePair("value".toCharArray(),pos,pos,pcExpr);
1280 // // Expression argNamesExpr = new
1281 // StringLiteral(argNames.toCharArray(),pos,pos);
1283 // MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
1284 // // ann.memberValuePairs = mvps;
1288 private boolean isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(long abits) {
1289 return (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0;
1292 // private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk, SourceTypeBinding sourceType, ResolvedType parent) {
1293 // if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
1294 // String filename = new String(sourceType.getFileName());
1296 // int takefrom = filename.lastIndexOf('/');
1297 // if (takefrom == -1) {
1298 // takefrom = filename.lastIndexOf('\\');
1300 // filename = filename.substring(takefrom + 1);
1302 // factory.getWorld()
1303 // .getMessageHandler()
1305 // WeaveMessage.constructWeavingMessage(wmk,
1306 // new String[] { CharOperation.toString(sourceType.compoundName), filename,
1307 // parent.getClassName(),
1308 // getShortname(parent.getSourceLocation().getSourceFile().getPath()) }));
1312 // private String getShortname(String path) {
1313 // int takefrom = path.lastIndexOf('/');
1314 // if (takefrom == -1) {
1315 // takefrom = path.lastIndexOf('\\');
1317 // return path.substring(takefrom + 1);
1320 private void addParent(SourceTypeBinding sourceType, ResolvedType parent) {
1321 ReferenceBinding parentBinding = (ReferenceBinding) factory.makeTypeBinding(parent);
1322 if (parentBinding == null) {
1323 return; // The parent is missing, it will be reported elsewhere.
1325 // Due to e37 switching to MethodVerifier15 for everything, it is important added types are correctly
1326 // raw or not. For example, if Comparable is used in generic form compareTo(T) will be used to check
1327 // methods against in the verifier rather than compareTo(Object)
1328 if (!factory.getWorld().isInJava5Mode()) {
1329 parentBinding = (ReferenceBinding)convertToRawType(parentBinding, false /*do not force conversion of enclosing types*/);
1330 } else if (sourceType.isGenericType()) {
1331 RawTypeBinding rawTargetType = (RawTypeBinding)convertToRawType(sourceType, false);
1332 if (rawTargetType != null) {
1333 // assert: don't need to 'rememberTypeHierarchy' because the class file is constructed based on the generic type
1334 if (parentBinding.isClass()) {
1335 rawTargetType.superclass = parentBinding;
1337 ReferenceBinding[] oldI = rawTargetType.superInterfaces;
1338 ReferenceBinding[] newI;
1340 newI = new ReferenceBinding[1];
1341 newI[0] = parentBinding;
1343 int n = oldI.length;
1344 newI = new ReferenceBinding[n + 1];
1345 System.arraycopy(oldI, 0, newI, 0, n);
1346 newI[n] = parentBinding;
1348 rawTargetType.superInterfaces = newI;
1351 // TODO what about parameterized types?
1353 sourceType.rememberTypeHierarchy();
1354 if (parentBinding.isClass()) {
1355 sourceType.superclass = parentBinding;
1357 // this used to be true, but I think I've fixed it now, decp is done
1359 // TAG: WeavingMessage DECLARE PARENTS: EXTENDS
1360 // Compiler restriction: Can't do EXTENDS at weave time
1361 // So, only see this message if doing a source compilation
1362 // reportDeclareParentsMessage(WeaveMessage.
1363 // WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent);
1366 ReferenceBinding[] oldI = sourceType.superInterfaces;
1367 ReferenceBinding[] newI;
1369 newI = new ReferenceBinding[1];
1370 newI[0] = parentBinding;
1372 int n = oldI.length;
1373 newI = new ReferenceBinding[n + 1];
1374 System.arraycopy(oldI, 0, newI, 0, n);
1375 newI[n] = parentBinding;
1377 sourceType.superInterfaces = newI;
1378 // warnOnAddedInterface(factory.fromEclipse(sourceType),parent); //
1379 // now reported at weave time...
1381 // this used to be true, but I think I've fixed it now, decp is done
1383 // TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS
1384 // This message will come out of BcelTypeMunger.munge if doing a
1386 // reportDeclareParentsMessage(WeaveMessage.
1387 // WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent);
1391 // also add it to the bcel delegate if there is one
1392 if (sourceType instanceof BinaryTypeBinding) {
1393 ResolvedType onType = factory.fromEclipse(sourceType);
1394 ReferenceType rt = (ReferenceType) onType;
1395 ReferenceTypeDelegate rtd = rt.getDelegate();
1396 if (rtd instanceof BcelObjectType) {
1397 if (rt.isRawType()) {
1398 rt = rt.getGenericType();
1400 rt.addParent(parent);
1401 // ((BcelObjectType) rtd).addParent(parent);
1407 public void warnOnAddedInterface(ResolvedType type, ResolvedType parent) {
1408 World world = factory.getWorld();
1409 ResolvedType serializable = world.getCoreType(UnresolvedType.SERIALIZABLE);
1410 if (serializable.isAssignableFrom(type) && !serializable.isAssignableFrom(parent)
1411 && !LazyClassGen.hasSerialVersionUIDField(type)) {
1412 world.getLint().needsSerialVersionUIDField.signal(new String[] { type.getName().toString(),
1413 "added interface " + parent.getName().toString() }, null, null);
1417 private final List pendingTypesToFinish = new ArrayList();
1418 boolean inBinaryTypeCreationAndWeaving = false;
1419 boolean processingTheQueue = false;
1422 public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding,
1423 boolean needFieldsAndMethods, AccessRestriction accessRestriction) {
1425 if (inBinaryTypeCreationAndWeaving) {
1426 BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction);
1427 pendingTypesToFinish.add(ret);
1431 inBinaryTypeCreationAndWeaving = true;
1433 BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction);
1434 factory.getWorld().validateType(factory.fromBinding(ret));
1435 // if you need the bytes to pass to validate, here they
1436 // are:((ClassFileReader)binaryType).getReferenceBytes()
1437 weaveInterTypeDeclarations(ret);
1440 inBinaryTypeCreationAndWeaving = false;
1442 // Start processing the list...
1443 if (pendingTypesToFinish.size() > 0) {
1444 processingTheQueue = true;
1445 while (!pendingTypesToFinish.isEmpty()) {
1446 BinaryTypeBinding nextVictim = (BinaryTypeBinding) pendingTypesToFinish.remove(0);
1447 // During this call we may recurse into this method and add
1448 // more entries to the pendingTypesToFinish list.
1449 weaveInterTypeDeclarations(nextVictim);
1451 processingTheQueue = false;
1457 * Callback driven when the compiler detects an anonymous type during block resolution. We need to add it to the weaver so that
1458 * we don't trip up later.
1463 public void anonymousTypeBindingCreated(LocalTypeBinding aBinding) {
1464 factory.addSourceTypeBinding(aBinding, null);
1468 public void buildTypeBindings(CompilationUnitDeclaration unit, AccessRestriction accessRestriction) {
1469 if (this.isProcessingAnnotations && hasAspectDeclarations(unit)) {
1470 throw new SourceTypeCollisionException();
1472 super.buildTypeBindings(unit, accessRestriction);
1475 private static boolean hasAspectDeclarations(CompilationUnitDeclaration unit) {
1476 for (int j = 0; j < unit.types.length; j++) {
1477 if (unit.types[j] instanceof AspectDeclaration) {
1485 public void reset() {
1486 this.factory.cleanup();
1491 public LookupEnvironment wrapInModuleEnvironment(ModuleBinding moduleBinding) {
1492 AjLookupEnvironment newAjLookupEnvironment = new AjLookupEnvironment(this, moduleBinding);
1493 newAjLookupEnvironment.factory = this.factory;
1494 return newAjLookupEnvironment;
1498 // commented out, supplied as info on how to manipulate annotations in an
1501 // public void doDeclareAnnotationOnMethods() {
1502 // Do the declare annotation on fields/methods/ctors
1503 // Collection daoms = factory.getDeclareAnnotationOnMethods();
1504 // if (daoms!=null && daoms.size()>0 && !(sourceType instanceof
1505 // BinaryTypeBinding)) {
1506 // System.err.println("Going through the methods on "+sourceType.debugName()+
1507 // " looking for DECA matches");
1508 // // We better take a look through them...
1509 // for (Iterator iter = daoms.iterator(); iter.hasNext();) {
1510 // DeclareAnnotation element = (DeclareAnnotation) iter.next();
1511 // System.err.println("Looking for anything that might match "+element+" on "+
1512 // sourceType.debugName()+" "+getType(sourceType.
1513 // compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding));
1515 // ReferenceBinding rbb = getType(sourceType.compoundName);
1516 // // fix me if we ever uncomment this code... should iterate the other way
1517 // round, over the methods then over the decas
1518 // sourceType.methods();
1519 // MethodBinding sourceMbs[] = sourceType.methods;
1520 // for (int i = 0; i < sourceMbs.length; i++) {
1521 // MethodBinding sourceMb = sourceMbs[i];
1522 // MethodBinding mbbbb =
1523 // ((SourceTypeBinding)rbb).getExactMethod(sourceMb.selector
1524 // ,sourceMb.parameters);
1525 // boolean isCtor = sourceMb.selector[0]=='<';
1527 // if ((element.isDeclareAtConstuctor() ^ !isCtor)) {
1528 // System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb.
1529 // declaringClass.debugName()+" rbb="+rbb.debugName()+" "+
1530 // sourceMb.declaringClass.equals(rbb));
1532 // ResolvedMember rm = null;
1533 // rm = EclipseFactory.makeResolvedMember(mbbbb);
1534 // if (element.matches(rm,factory.getWorld())) {
1535 // System.err.println("MATCH");
1537 // // Determine the set of annotations that are currently on the method
1538 // ReferenceBinding rb = getType(sourceType.compoundName);
1539 // // TypeBinding tb = factory.makeTypeBinding(decA.getAspect());
1540 // MethodBinding mb =
1541 // ((SourceTypeBinding)rb).getExactMethod(sourceMb.selector,sourceMb
1543 // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved
1544 // TypeDeclaration typeDecl =
1545 // ((SourceTypeBinding)sourceMb.declaringClass).scope.referenceContext;
1546 // AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb);
1547 // Annotation[] currentlyHas = methodDecl.annotations; // this is what to add
1548 // //abits = toAdd[0].resolvedType.getAnnotationTagBits();
1550 // // Determine the annotations to add to that method
1551 // TypeBinding tb = factory.makeTypeBinding(element.getAspect());
1552 // MethodBinding[] aspectMbs =
1553 // ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod
1554 // ().toCharArray());
1555 // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved
1556 // TypeDeclaration typeDecl2 =
1557 // ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext;
1558 // AbstractMethodDeclaration methodDecl2 =
1559 // typeDecl2.declarationOf(aspectMbs[0]);
1560 // Annotation[] toAdd = methodDecl2.annotations; // this is what to add
1561 // // abits = toAdd[0].resolvedType.getAnnotationTagBits();
1562 // System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd);
1564 // // fix me? should check if it already has the annotation
1565 // //Annotation abefore[] = sourceType.scope.referenceContext.annotations;
1566 // Annotation[] newset = new
1567 // Annotation[(currentlyHas==null?0:currentlyHas.length)+1];
1568 // System.arraycopy(toAdd,0,newset,0,toAdd.length);
1569 // if (currentlyHas!=null) {
1570 // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length);
1572 // methodDecl.annotations = newset;
1573 // System.err.println("New set on "+CharOperation.charToString(sourceMb.selector)
1576 // System.err.println("NO MATCH");
1583 // commented out, supplied as info on how to manipulate annotations in an
1586 // public void doDeclareAnnotationOnFields() {
1587 // Collection daofs = factory.getDeclareAnnotationOnFields();
1588 // if (daofs!=null && daofs.size()>0 && !(sourceType instanceof
1589 // BinaryTypeBinding)) {
1590 // System.err.println("Going through the fields on "+sourceType.debugName()+
1591 // " looking for DECA matches");
1592 // // We better take a look through them...
1593 // for (Iterator iter = daofs.iterator(); iter.hasNext();) {
1594 // DeclareAnnotation element = (DeclareAnnotation) iter.next();
1595 // System.err.println("Processing deca "+element+" on "+sourceType.debugName()+
1596 // " "+getType(sourceType.compoundName).debugName()+" "
1597 // +(sourceType instanceof BinaryTypeBinding));
1599 // ReferenceBinding rbb = getType(sourceType.compoundName);
1600 // // fix me? should iterate the other way round, over the methods then over the
1602 // sourceType.fields(); // resolve the bloody things
1603 // FieldBinding sourceFbs[] = sourceType.fields;
1604 // for (int i = 0; i < sourceFbs.length; i++) {
1605 // FieldBinding sourceFb = sourceFbs[i];
1606 // //FieldBinding fbbbb =
1607 // ((SourceTypeBinding)rbb).getgetExactMethod(sourceMb.selector
1608 // ,sourceMb.parameters);
1610 // System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb.
1611 // declaringClass.debugName()+" rbb="+rbb.debugName());
1613 // ResolvedMember rm = null;
1614 // rm = EclipseFactory.makeResolvedMember(sourceFb);
1615 // if (element.matches(rm,factory.getWorld())) {
1616 // System.err.println("MATCH");
1618 // // Determine the set of annotations that are currently on the field
1619 // ReferenceBinding rb = getType(sourceType.compoundName);
1620 // // TypeBinding tb = factory.makeTypeBinding(decA.getAspect());
1621 // FieldBinding fb = ((SourceTypeBinding)rb).getField(sourceFb.name,true);
1622 // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved
1623 // TypeDeclaration typeDecl =
1624 // ((SourceTypeBinding)sourceFb.declaringClass).scope.referenceContext;
1625 // FieldDeclaration fd = typeDecl.declarationOf(sourceFb);
1626 // //AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb);
1627 // Annotation[] currentlyHas = fd.annotations; // this is what to add
1628 // //abits = toAdd[0].resolvedType.getAnnotationTagBits();
1630 // // Determine the annotations to add to that method
1631 // TypeBinding tb = factory.makeTypeBinding(element.getAspect());
1632 // MethodBinding[] aspectMbs =
1633 // ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod
1634 // ().toCharArray());
1635 // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved
1636 // TypeDeclaration typeDecl2 =
1637 // ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext;
1638 // AbstractMethodDeclaration methodDecl2 =
1639 // typeDecl2.declarationOf(aspectMbs[0]);
1640 // Annotation[] toAdd = methodDecl2.annotations; // this is what to add
1641 // // abits = toAdd[0].resolvedType.getAnnotationTagBits();
1642 // System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd);
1644 // // fix me? check if it already has the annotation
1647 // //Annotation abefore[] = sourceType.scope.referenceContext.annotations;
1648 // Annotation[] newset = new
1649 // Annotation[(currentlyHas==null?0:currentlyHas.length)+1];
1650 // System.arraycopy(toAdd,0,newset,0,toAdd.length);
1651 // if (currentlyHas!=null) {
1652 // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length);
1654 // fd.annotations = newset;
1655 // System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+
1658 // System.err.println("NO MATCH");