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 v 2.0
6 * which accompanies this distribution and is available at
7 * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt
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.Declare;
72 import org.aspectj.weaver.patterns.DeclareAnnotation;
73 import org.aspectj.weaver.patterns.DeclareParents;
76 * Overrides the default eclipse LookupEnvironment for two purposes.
78 * 1. To provide some additional phases to <code>completeTypeBindings</code> that weave declare parents and inter-type declarations
79 * at the correct time.
81 * 2. To intercept the loading of new binary types to ensure the they will have declare parents and inter-type declarations woven
86 public class AjLookupEnvironment extends LookupEnvironment implements AnonymousClassCreationListener {
87 public EclipseFactory factory = null;
89 // private boolean builtInterTypesAndPerClauses = false;
90 private final List<SourceTypeBinding> pendingTypesToWeave = new ArrayList<>();
92 // Q: What are dangerousInterfaces?
93 // A: An interface is considered dangerous if an ITD has been made upon it
95 // requires the top most implementors of the interface to be woven *and yet*
97 // responsible for the ITD is not in the 'world'.
98 // Q: Err, how can that happen?
99 // A: When a type is on the inpath, it is 'processed' when completing type
101 // point we look at any type mungers it was affected by previously (stored
103 // state info attribute). Effectively we are working with a type munger and
104 // yet may not have its
105 // originating aspect in the world. This is a problem if, for example, the
107 // a 'body' for a method targetting an interface - since the top most
108 // implementors should
109 // be woven by the munger from the aspect. When this happens we store the
110 // interface name here
111 // in the map - if we later process a type that is the topMostImplementor of
113 // interface then we put out an error message.
116 * interfaces targetted by ITDs that have to be implemented by accessing the topMostImplementor of the interface, yet the aspect
117 * where the ITD originated is not in the world
119 private final Map<ResolvedType, String> dangerousInterfaces = new HashMap<>();
121 public AjLookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter,
122 INameEnvironment nameEnvironment) {
123 super(typeRequestor, options, problemReporter, nameEnvironment);
126 public AjLookupEnvironment(LookupEnvironment env, ModuleBinding moduleBinding) {
127 super(env, moduleBinding);
130 // ??? duplicates some of super's code
132 public void completeTypeBindings() {
133 AsmManager.setCompletingTypeBindings(true);
134 ContextToken completeTypeBindingsToken = CompilationAndWeavingContext.enteringPhase(
135 CompilationAndWeavingContext.COMPLETING_TYPE_BINDINGS, "");
136 // builtInterTypesAndPerClauses = false;
137 // pendingTypesToWeave = new ArrayList();
138 stepCompleted = BUILD_TYPE_HIERARCHY;
140 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
141 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CHECK_AND_SET_IMPORTS,
142 units[i].compilationResult.fileName);
143 units[i].scope.checkAndSetImports();
144 CompilationAndWeavingContext.leavingPhase(tok);
146 stepCompleted = CHECK_AND_SET_IMPORTS;
148 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
149 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CONNECTING_TYPE_HIERARCHY,
150 units[i].compilationResult.fileName);
151 units[i].scope.connectTypeHierarchy();
152 CompilationAndWeavingContext.leavingPhase(tok);
154 stepCompleted = CONNECT_TYPE_HIERARCHY;
156 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
157 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.BUILDING_FIELDS_AND_METHODS,
158 units[i].compilationResult.fileName);
159 // units[i].scope.checkParameterizedTypes(); do this check a little
160 // later, after ITDs applied to stbs
161 units[i].scope.buildFieldsAndMethods();
162 CompilationAndWeavingContext.leavingPhase(tok);
165 // would like to gather up all TypeDeclarations at this point and put
166 // them in the factory
167 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
168 SourceTypeBinding[] b = units[i].scope.topLevelTypes;
169 for (SourceTypeBinding sourceTypeBinding : b) {
170 factory.addSourceTypeBinding(sourceTypeBinding, units[i]);
171 if (sourceTypeBinding.superclass instanceof MissingTypeBinding) {
172 // e37: Undoing the work in ClassScope.connectSuperClass() as it will lead to cascade errors
173 // TODO allow MissingTypeBinding through here and cope with it in all situations later?
174 sourceTypeBinding.superclass = units[i].scope.getJavaLangObject();
179 // We won't find out about anonymous types until later though, so
181 // told about them when they turn up.
182 AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(this);
184 // need to build inter-type declarations for all AspectDeclarations at
186 // this MUST be done in order from super-types to subtypes
187 List<SourceTypeBinding> typesToProcess = new ArrayList<>();
188 List<SourceTypeBinding> aspectsToProcess = new ArrayList<>();
189 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
190 CompilationUnitScope cus = units[i].scope;
191 SourceTypeBinding[] stbs = cus.topLevelTypes;
192 for (SourceTypeBinding stb : stbs) {
193 typesToProcess.add(stb);
194 TypeDeclaration typeDeclaration = stb.scope.referenceContext;
195 if (typeDeclaration instanceof AspectDeclaration) {
196 aspectsToProcess.add(stb);
200 factory.getWorld().getCrosscuttingMembersSet().reset();
202 // Need to do these before the other ITDs
203 for (SourceTypeBinding aspectToProcess : aspectsToProcess) {
204 processInterTypeMemberTypes(aspectToProcess.scope);
207 while (typesToProcess.size() > 0) {
208 // removes types from the list as they are processed...
209 collectAllITDsAndDeclares(typesToProcess.get(0), typesToProcess);
212 factory.finishTypeMungers();
215 final List<ConcreteTypeMunger> typeMungers = factory.getTypeMungers();
217 final List<DeclareParents> declareParents = factory.getDeclareParents();
218 final List<DeclareAnnotation> declareAnnotationOnTypes = factory.getDeclareAnnotationOnTypes();
222 // We now have some list of types to process, and we are about to apply
224 // There can be situations where the order of types passed to the
225 // compiler causes the
226 // output from the compiler to vary - THIS IS BAD. For example, if we
228 // and class B extends A. Also, an aspect that 'declare parents: A+
229 // implements Serializable'
230 // then depending on whether we see A first, we may or may not make B
233 // The fix is to process them in the right order, ensuring that for a
234 // type we process its
235 // supertypes and superinterfaces first. This algorithm may have
237 // - partial hierarchies (e.g. suppose types A,B,C are in a hierarchy
238 // and A and C are to be woven but not B)
239 // - weaving that brings new types in for processing (see
240 // pendingTypesToWeave.add() calls) after we thought
241 // we had the full list.
243 // but these aren't common cases (he bravely said...)
244 boolean typeProcessingOrderIsImportant = declareParents.size() > 0 || declareAnnotationOnTypes.size() > 0; // DECAT
246 if (typeProcessingOrderIsImportant) {
247 typesToProcess = new ArrayList<>();
248 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
249 CompilationUnitScope cus = units[i].scope;
250 SourceTypeBinding[] stbs = cus.topLevelTypes;
251 Collections.addAll(typesToProcess, stbs);
254 List<SourceTypeBinding> stb2 = new ArrayList<>(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 (Map.Entry<ResolvedType, String> entry : dangerousInterfaces.entrySet()) {
704 ResolvedType interfaceType = entry.getKey();
705 if (onType.isTopmostImplementor(interfaceType)) {
706 factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null);
710 boolean needOldStyleWarning = (info != null && info.isOldStyle());
712 onType.clearInterTypeMungers();
713 onType.ensureConsistent();
715 // FIXME asc perf Could optimize here, after processing the expected set
716 // of types we may bring
717 // binary types that are not exposed to the weaver, there is no need to
718 // attempt declare parents
719 // or declare annotation really - unless we want to report the
720 // not-exposed to weaver
723 List<DeclareParents> decpToRepeat = new ArrayList<>();
724 List<DeclareAnnotation> decaToRepeat = new ArrayList<>();
725 boolean anyNewParents = false;
726 boolean anyNewAnnotations = false;
729 // try and apply all decps - if they match, then great. If they don't
731 // check if they are starred-annotation patterns. If they are not
733 // annotation patterns then they might match later...remember that...
734 for (DeclareParents decp : declareParents) {
735 if (!decp.isMixin()) {
736 boolean didSomething = doDeclareParents(decp, sourceType);
738 if (factory.pushinCollector != null) {
739 factory.pushinCollector.tagAsMunged(sourceType, decp.getParents().get(0));
741 anyNewParents = true;
743 if (!decp.getChild().isStarAnnotation()) {
744 decpToRepeat.add(decp);
750 for (DeclareAnnotation deca : declareAnnotationOnTypes) {
751 boolean didSomething = doDeclareAnnotations(deca, sourceType, true);
753 anyNewAnnotations = true;
755 if (!deca.getTypePattern().isStar()) {
756 decaToRepeat.add(deca);
761 List<Declare> forRemoval = new ArrayList<>();
762 // now lets loop over and over until we have done all we can
763 while ((anyNewAnnotations || anyNewParents) && (!decpToRepeat.isEmpty() || !decaToRepeat.isEmpty())) {
764 anyNewParents = anyNewAnnotations = false;
766 for (DeclareParents decp : decpToRepeat) {
767 boolean didSomething = doDeclareParents(decp, sourceType);
769 if (factory.pushinCollector != null) {
770 factory.pushinCollector.tagAsMunged(sourceType, decp.getParents().get(0));
772 anyNewParents = true;
773 forRemoval.add(decp);
776 decpToRepeat.removeAll(forRemoval);
779 for (DeclareAnnotation deca : decaToRepeat) {
780 boolean didSomething = doDeclareAnnotations(deca, sourceType, false);
782 if (factory.pushinCollector != null) {
783 factory.pushinCollector.tagAsMunged(sourceType, deca.getAnnotationString());
785 anyNewAnnotations = true;
786 forRemoval.add(deca);
789 decaToRepeat.removeAll(forRemoval);
792 if (mode == 0 || mode == 2) {
793 for (ConcreteTypeMunger typeMunger : typeMungers) {
794 EclipseTypeMunger munger = (EclipseTypeMunger) typeMunger;
795 if (munger.matches(onType)) {
796 // if (needOldStyleWarning) {
797 // factory.showMessage(IMessage.WARNING, "The class for " + onType
798 // + " should be recompiled with ajc-1.1.1 for best results", onType.getSourceLocation(), null);
799 // needOldStyleWarning = false;
801 onType.addInterTypeMunger(munger, true);
802 if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.InnerClass) {
803 // Must do these right now, because if we do an ITD member afterwards it may attempt to reference the
804 // type being applied (the call above 'addInterTypeMunger' will fail for these ITDs if it needed
805 // it to be in place)
806 if (munger.munge(sourceType, onType)) {
807 if (factory.pushinCollector != null) {
808 factory.pushinCollector.tagAsMunged(sourceType, munger.getSourceMethod());
815 onType.checkInterTypeMungers();
816 for (ConcreteTypeMunger concreteTypeMunger : onType.getInterTypeMungers()) {
817 EclipseTypeMunger munger = (EclipseTypeMunger) concreteTypeMunger;
818 if (munger.getMunger() == null || munger.getMunger().getKind() != ResolvedTypeMunger.InnerClass) {
819 if (munger.munge(sourceType, onType)) {
820 if (factory.pushinCollector != null) {
821 factory.pushinCollector.tagAsMunged(sourceType, munger.getSourceMethod());
828 // Call if you would like to do source weaving of declare
829 // @method/@constructor
830 // at source time... no need to do this as it can't impact anything, but
832 // future generations to enjoy. Method source is commented out at the
833 // end of this module
834 // doDeclareAnnotationOnMethods();
836 // Call if you would like to do source weaving of declare @field
837 // at source time... no need to do this as it can't impact anything, but
839 // future generations to enjoy. Method source is commented out at the
840 // end of this module
841 // doDeclareAnnotationOnFields();
844 CompilationAndWeavingContext.leavingPhase(tok);
848 ReferenceBinding[] memberTypes = sourceType.memberTypes;
849 for (ReferenceBinding memberType : memberTypes) {
850 if (memberType instanceof SourceTypeBinding) {
851 weaveInterTypeDeclarations((SourceTypeBinding) memberType, typeMungers, declareParents,
852 declareAnnotationOnTypes, false, mode);
855 CompilationAndWeavingContext.leavingPhase(tok);
859 * Called when we discover we are weaving intertype declarations on some type that has an existing 'WeaverStateInfo' object -
860 * this is typically some previously woven type that has been passed on the inpath.
862 * sourceType and onType are the 'same type' - the former is the 'Eclipse' version and the latter is the 'Weaver' version.
864 private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType, ResolvedType onType) {
865 List<ConcreteTypeMunger> previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType);
867 for (ConcreteTypeMunger m : previouslyAppliedMungers) {
868 EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m);
869 if (munger.munge(sourceType, onType)) {
870 if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) {
871 if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) {
873 .put(onType, "implementors of " + onType + " must be woven by " + munger.getAspectType());
881 private boolean doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) {
882 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,
883 sourceType.sourceName);
884 ResolvedType resolvedSourceType = factory.fromEclipse(sourceType);
885 List<ResolvedType> newParents = declareParents.findMatchingNewParents(resolvedSourceType, false);
886 if (!newParents.isEmpty()) {
887 for (ResolvedType parent : newParents) {
888 if (dangerousInterfaces.containsKey(parent)) {
889 ResolvedType onType = factory.fromEclipse(sourceType);
890 factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent),
891 onType.getSourceLocation(), null);
893 if (Modifier.isFinal(parent.getModifiers())) {
894 factory.showMessage(IMessage.ERROR, "cannot extend final class " + parent.getClassName(),
895 declareParents.getSourceLocation(), null);
897 // do not actually do it if the type isn't exposed - this
898 // will correctly reported as a problem elsewhere
899 if (!resolvedSourceType.isExposedToWeaver()) {
902 // AsmRelationshipProvider.getDefault().
903 // addDeclareParentsRelationship
904 // (declareParents.getSourceLocation(),
905 // factory.fromEclipse(sourceType), newParents);
906 addParent(sourceType, parent);
909 CompilationAndWeavingContext.leavingPhase(tok);
912 CompilationAndWeavingContext.leavingPhase(tok);
916 private String stringifyTargets(long bits) {
917 if ((bits & TagBits.AnnotationTargetMASK) == 0) {
920 Set<String> s = new HashSet<>();
921 if ((bits & TagBits.AnnotationForAnnotationType) != 0) {
922 s.add("ANNOTATION_TYPE");
924 if ((bits & TagBits.AnnotationForConstructor) != 0) {
925 s.add("CONSTRUCTOR");
927 if ((bits & TagBits.AnnotationForField) != 0) {
930 if ((bits & TagBits.AnnotationForLocalVariable) != 0) {
931 s.add("LOCAL_VARIABLE");
933 if ((bits & TagBits.AnnotationForMethod) != 0) {
936 if ((bits & TagBits.AnnotationForPackage) != 0) {
939 if ((bits & TagBits.AnnotationForParameter) != 0) {
942 if ((bits & TagBits.AnnotationForType) != 0) {
945 StringBuilder sb = new StringBuilder();
947 for (Iterator<String> iter = s.iterator(); iter.hasNext();) {
948 String element = iter.next();
950 if (iter.hasNext()) {
955 return sb.toString();
958 private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) {
959 ResolvedType rtx = factory.fromEclipse(sourceType);
960 if (!decA.matches(rtx)) {
963 if (!rtx.isExposedToWeaver()) {
967 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS,
968 sourceType.sourceName);
970 // Get the annotation specified in the declare
971 UnresolvedType aspectType = decA.getAspect();
972 if (aspectType instanceof ReferenceType) {
973 ReferenceType rt = (ReferenceType) aspectType;
974 if (rt.isParameterizedType() || rt.isRawType()) {
975 aspectType = rt.getGenericType();
978 TypeBinding tb = factory.makeTypeBinding(aspectType);
980 // Hideousness follows:
982 // There are multiple situations to consider here and they relate to the
984 // where the annotation is coming from and where the annotation is going
987 // 1. Straight full build, all from source - the annotation is from a
989 // is being put on some type. Both types are real SourceTypeBindings.
991 // 2. Incremental build, changing the affected type - the annotation is
993 // dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and
995 // affected type is a real SourceTypeBinding. Mostly works (pr128665)
998 SourceTypeBinding stb = (SourceTypeBinding) tb;
999 Annotation[] toAdd = null;
1002 AbstractMethodDeclaration methodDecl = null;
1003 // Might have to retrieve the annotation through BCEL and construct an
1004 // eclipse one for it.
1005 if (stb instanceof BinaryTypeBinding) {
1006 toAdd = retrieveAnnotationFromBinaryTypeBinding(decA, stb);
1007 if (toAdd != null && toAdd.length > 0 && toAdd[0].resolvedType != null) {
1008 abits = toAdd[0].resolvedType.getAnnotationTagBits();
1010 } else if (stb != null) {
1011 // much nicer, its a real SourceTypeBinding so we can stay in
1013 // if (decA.getAnnotationMethod() != null) {
1014 char[] declareSelector = decA.getAnnotationMethod().toCharArray();
1016 ReferenceBinding rb = stb;
1017 String declaringAspectName = decA.getDeclaringType().getRawName();
1018 while (rb != null && !new String(CharOperation.concatWith(rb.compoundName, '.')).equals(declaringAspectName)) {
1019 rb = rb.superclass();
1021 MethodBinding[] mbs = rb.getMethods(declareSelector);
1023 ReferenceBinding declaringBinding = mbs[0].declaringClass;
1024 if (declaringBinding instanceof ParameterizedTypeBinding) {
1025 // Unwrap - this means we don't allow the type of the annotation to be parameterized, may need to revisit that
1026 declaringBinding = ((ParameterizedTypeBinding) declaringBinding).type;
1028 if (declaringBinding instanceof BinaryTypeBinding) {
1029 toAdd = retrieveAnnotationFromBinaryTypeBinding(decA, declaringBinding);
1030 if (toAdd != null && toAdd.length > 0 && toAdd[0].resolvedType != null) {
1031 abits = toAdd[0].resolvedType.getAnnotationTagBits();
1034 abits = mbs[0].getAnnotationTagBits(); // ensure resolved
1035 TypeDeclaration typeDecl = ((SourceTypeBinding) declaringBinding).scope.referenceContext;
1036 methodDecl = typeDecl.declarationOf(mbs[0]);
1037 toAdd = methodDecl.annotations; // this is what to add
1038 toAdd[0] = createAnnotationCopy(toAdd[0]);
1039 if (toAdd[0].resolvedType != null) {
1040 abits = toAdd[0].resolvedType.getAnnotationTagBits();
1046 // This happens if there is another error in the code - that should be reported separately
1047 if (toAdd == null || toAdd[0] == null || toAdd[0].type == null) {
1048 CompilationAndWeavingContext.leavingPhase(tok);
1051 if (sourceType instanceof BinaryTypeBinding) {
1052 // In this case we can't access the source type binding to add a new
1053 // annotation, so let's put something
1054 // on the weaver type temporarily
1055 ResolvedType theTargetType = factory.fromEclipse(sourceType);
1056 TypeBinding theAnnotationType = toAdd[0].resolvedType;
1057 // The annotation type may be null if it could not be resolved (eg. the relevant import has not been added yet)
1058 // In this case an error will be put out about the annotation but not if we crash here
1059 if (theAnnotationType == null) {
1062 String sig = new String(theAnnotationType.signature());
1063 UnresolvedType bcelAnnotationType = UnresolvedType.forSignature(sig);
1064 String name = bcelAnnotationType.getName();
1065 if (theTargetType.hasAnnotation(bcelAnnotationType)) {
1066 CompilationAndWeavingContext.leavingPhase(tok);
1070 // FIXME asc tidy up this code that duplicates whats below!
1071 // Simple checks on the bits
1072 boolean giveupnow = false;
1073 if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
1074 if (isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) {
1075 // error will have been already reported
1077 } else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
1078 || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
1080 if (reportProblems) {
1081 if (decA.isExactPattern()) {
1082 factory.showMessage(IMessage.ERROR, WeaverMessages.format(
1083 WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
1084 stringifyTargets(abits)), decA.getSourceLocation(), null);
1086 // dont put out the lint - the weaving process will do
1089 // if (factory.getWorld().getLint().
1090 // invalidTargetForAnnotation.isEnabled()) {
1091 // factory.getWorld().getLint().invalidTargetForAnnotation
1093 // String[]{rtx.getName(),toAdd[0].type.toString(),
1095 // (abits)},decA.getSourceLocation(),null);
1103 CompilationAndWeavingContext.leavingPhase(tok);
1107 theTargetType.addAnnotation(new BcelAnnotation(new FakeAnnotation(name, sig,
1108 (abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld()));
1109 CompilationAndWeavingContext.leavingPhase(tok);
1113 Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations;
1114 if (currentAnnotations != null) {
1115 for (Annotation annotation : currentAnnotations) {
1116 String a = CharOperation.toString(annotation.type.getTypeName());
1117 String b = CharOperation.toString(toAdd[0].type.getTypeName());
1118 // FIXME asc we have a lint for attempting to add an annotation
1119 // twice to a method,
1120 // we could put it out here *if* we can resolve the problem of
1121 // errors coming out
1122 // multiple times if we have cause to loop through here
1124 CompilationAndWeavingContext.leavingPhase(tok);
1130 if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
1131 if ((abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0) {
1132 // this means it specifies something other than annotation or
1133 // normal type - error will have been already reported,
1134 // just resolution process above
1135 CompilationAndWeavingContext.leavingPhase(tok);
1138 if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
1139 || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
1141 if (reportProblems) {
1142 if (decA.isExactPattern()) {
1143 factory.showMessage(IMessage.ERROR, WeaverMessages.format(
1144 WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
1145 stringifyTargets(abits)), decA.getSourceLocation(), null);
1147 // dont put out the lint - the weaving process will do that
1150 // (factory.getWorld().getLint().invalidTargetForAnnotation
1152 // factory.getWorld().getLint().invalidTargetForAnnotation.
1154 // String[]{rtx.getName(),toAdd[0].type.toString(),
1155 // stringifyTargets(abits)},decA.getSourceLocation(),null);
1159 CompilationAndWeavingContext.leavingPhase(tok);
1164 // Build a new array of annotations
1166 // remember the current set (rememberAnnotations only does something the
1167 // first time it is called for a type)
1168 sourceType.scope.referenceContext.rememberAnnotations();
1170 // AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(
1171 // decA.getSourceLocation(), rtx.getSourceLocation());
1172 final Annotation[] abefore = sourceType.scope.referenceContext.annotations;
1173 final Annotation[] newset = new Annotation[toAdd.length + (abefore == null ? 0 : abefore.length)];
1174 System.arraycopy(toAdd, 0, newset, 0, toAdd.length);
1175 if (abefore != null) {
1176 System.arraycopy(abefore, 0, newset, toAdd.length, abefore.length);
1178 sourceType.scope.referenceContext.annotations = newset;
1179 if ((sourceType.tagBits & TagBits.AnnotationResolved)!=0) {
1180 sourceType.tagBits = sourceType.tagBits - TagBits.AnnotationResolved;
1182 CompilationAndWeavingContext.leavingPhase(tok);
1183 if (factory.pushinCollector != null) {
1184 factory.pushinCollector.tagAsMunged(sourceType, new CommonPrinter((methodDecl == null ? null : methodDecl.scope))
1185 .printAnnotation(toAdd[0]).toString());
1190 private Annotation[] retrieveAnnotationFromBinaryTypeBinding(DeclareAnnotation decA, ReferenceBinding declaringBinding) {
1191 ReferenceType rt = (ReferenceType) factory.fromEclipse(declaringBinding);
1192 ResolvedMember[] methods = rt.getDeclaredMethods();
1193 ResolvedMember decaMethod = null;
1194 String nameToLookFor = decA.getAnnotationMethod();
1195 for (ResolvedMember method : methods) {
1196 if (method.getName().equals(nameToLookFor)) {
1197 decaMethod = method;
1201 if (decaMethod != null) { // could assert this ...
1202 AnnotationAJ[] axs = decaMethod.getAnnotations();
1203 if (axs != null) { // another error has occurred, dont crash here because of it
1204 Annotation[] toAdd = new Annotation[1];
1205 toAdd[0] = createAnnotationFromBcelAnnotation(axs[0], decaMethod.getSourceLocation().getOffset(), factory);
1206 // BUG BUG BUG - We dont test these abits are correct, in fact
1207 // we'll be very lucky if they are.
1208 // What does that mean? It means on an incremental compile you
1209 // might get away with an
1210 // annotation that isn't allowed on a type being put on a type.
1211 // if (toAdd[0].resolvedType != null) {
1212 // abits = toAdd[0].resolvedType.getAnnotationTagBits();
1221 * Transform an annotation from its AJ form to an eclipse form. We *DONT* care about the values of the annotation. that is
1222 * because it is only being stuck on a type during type completion to allow for other constructs (decps, decas) that might be
1223 * 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
1224 * the right thing copying across values too.
1226 private static Annotation createAnnotationFromBcelAnnotation(AnnotationAJ annX, int pos, EclipseFactory factory) {
1227 String name = annX.getTypeName();
1228 TypeBinding tb = factory.makeTypeBinding(annX.getType());
1229 // String theName = annX.getSignature().getBaseName();
1230 char[][] typeName = CharOperation.splitOn('.', name.replace('$', '.').toCharArray()); // pr149293 - not bulletproof...
1231 long[] positions = new long[typeName.length];
1232 for (int i = 0; i < positions.length; i++) {
1235 TypeReference annType = new QualifiedTypeReference(typeName, positions);
1236 NormalAnnotation ann = new NormalAnnotation(annType, pos);
1237 ann.resolvedType = tb; // yuck - is this OK in all cases?
1238 // We don't need membervalues...
1239 // Expression pcExpr = new
1240 // StringLiteral(pointcutExpression.toCharArray(),pos,pos);
1241 // MemberValuePair[] mvps = new MemberValuePair[2];
1242 // mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr);
1243 // Expression argNamesExpr = new
1244 // StringLiteral(argNames.toCharArray(),pos,pos);
1246 // MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
1247 // ann.memberValuePairs = mvps;
1252 * 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
1255 private static Annotation createAnnotationCopy(Annotation ann) {
1256 NormalAnnotation ann2 = new NormalAnnotation(ann.type, ann.sourceStart);
1257 ann2.memberValuePairs = ann.memberValuePairs();
1258 ann2.resolvedType = ann.resolvedType;
1259 ann2.bits = ann.bits;
1261 // String name = annX.getTypeName();
1262 // TypeBinding tb = factory.makeTypeBinding(annX.getSignature());
1263 // String theName = annX.getSignature().getBaseName();
1264 // char[][] typeName =
1265 // CharOperation.splitOn('.',name.replace('$','.').toCharArray());
1266 // //pr149293 - not bulletproof...
1267 // long[] positions = new long[typeName.length];
1268 // for (int i = 0; i < positions.length; i++) positions[i]=pos;
1269 // TypeReference annType = new
1270 // QualifiedTypeReference(typeName,positions);
1271 // NormalAnnotation ann = new NormalAnnotation(annType,pos);
1272 // ann.resolvedType=tb; // yuck - is this OK in all cases?
1273 // // We don't need membervalues...
1274 // // Expression pcExpr = new
1275 // StringLiteral(pointcutExpression.toCharArray(),pos,pos);
1276 // // MemberValuePair[] mvps = new MemberValuePair[2];
1278 // MemberValuePair("value".toCharArray(),pos,pos,pcExpr);
1279 // // Expression argNamesExpr = new
1280 // StringLiteral(argNames.toCharArray(),pos,pos);
1282 // MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
1283 // // ann.memberValuePairs = mvps;
1287 private boolean isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(long abits) {
1288 return (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0;
1291 // private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk, SourceTypeBinding sourceType, ResolvedType parent) {
1292 // if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
1293 // String filename = new String(sourceType.getFileName());
1295 // int takefrom = filename.lastIndexOf('/');
1296 // if (takefrom == -1) {
1297 // takefrom = filename.lastIndexOf('\\');
1299 // filename = filename.substring(takefrom + 1);
1301 // factory.getWorld()
1302 // .getMessageHandler()
1304 // WeaveMessage.constructWeavingMessage(wmk,
1305 // new String[] { CharOperation.toString(sourceType.compoundName), filename,
1306 // parent.getClassName(),
1307 // getShortname(parent.getSourceLocation().getSourceFile().getPath()) }));
1311 // private String getShortname(String path) {
1312 // int takefrom = path.lastIndexOf('/');
1313 // if (takefrom == -1) {
1314 // takefrom = path.lastIndexOf('\\');
1316 // return path.substring(takefrom + 1);
1319 private void addParent(SourceTypeBinding sourceType, ResolvedType parent) {
1320 ReferenceBinding parentBinding = (ReferenceBinding) factory.makeTypeBinding(parent);
1321 if (parentBinding == null) {
1322 return; // The parent is missing, it will be reported elsewhere.
1324 // Due to e37 switching to MethodVerifier15 for everything, it is important added types are correctly
1325 // raw or not. For example, if Comparable is used in generic form compareTo(T) will be used to check
1326 // methods against in the verifier rather than compareTo(Object)
1327 if (!factory.getWorld().isInJava5Mode()) {
1328 parentBinding = (ReferenceBinding)convertToRawType(parentBinding, false /*do not force conversion of enclosing types*/);
1329 } else if (sourceType.isGenericType()) {
1330 RawTypeBinding rawTargetType = (RawTypeBinding)convertToRawType(sourceType, false);
1331 if (rawTargetType != null) {
1332 // assert: don't need to 'rememberTypeHierarchy' because the class file is constructed based on the generic type
1333 if (parentBinding.isClass()) {
1334 rawTargetType.superclass = parentBinding;
1336 ReferenceBinding[] oldI = rawTargetType.superInterfaces;
1337 ReferenceBinding[] newI;
1339 newI = new ReferenceBinding[1];
1340 newI[0] = parentBinding;
1342 int n = oldI.length;
1343 newI = new ReferenceBinding[n + 1];
1344 System.arraycopy(oldI, 0, newI, 0, n);
1345 newI[n] = parentBinding;
1347 rawTargetType.superInterfaces = newI;
1350 // TODO what about parameterized types?
1352 sourceType.rememberTypeHierarchy();
1353 if (parentBinding.isClass()) {
1354 sourceType.superclass = parentBinding;
1356 // this used to be true, but I think I've fixed it now, decp is done
1358 // TAG: WeavingMessage DECLARE PARENTS: EXTENDS
1359 // Compiler restriction: Can't do EXTENDS at weave time
1360 // So, only see this message if doing a source compilation
1361 // reportDeclareParentsMessage(WeaveMessage.
1362 // WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent);
1365 ReferenceBinding[] oldI = sourceType.superInterfaces;
1366 ReferenceBinding[] newI;
1368 newI = new ReferenceBinding[1];
1369 newI[0] = parentBinding;
1371 int n = oldI.length;
1372 newI = new ReferenceBinding[n + 1];
1373 System.arraycopy(oldI, 0, newI, 0, n);
1374 newI[n] = parentBinding;
1376 sourceType.superInterfaces = newI;
1377 // warnOnAddedInterface(factory.fromEclipse(sourceType),parent); //
1378 // now reported at weave time...
1380 // this used to be true, but I think I've fixed it now, decp is done
1382 // TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS
1383 // This message will come out of BcelTypeMunger.munge if doing a
1385 // reportDeclareParentsMessage(WeaveMessage.
1386 // WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent);
1390 // also add it to the bcel delegate if there is one
1391 if (sourceType instanceof BinaryTypeBinding) {
1392 ResolvedType onType = factory.fromEclipse(sourceType);
1393 ReferenceType rt = (ReferenceType) onType;
1394 ReferenceTypeDelegate rtd = rt.getDelegate();
1395 if (rtd instanceof BcelObjectType) {
1396 if (rt.isRawType()) {
1397 rt = rt.getGenericType();
1399 rt.addParent(parent);
1400 // ((BcelObjectType) rtd).addParent(parent);
1406 public void warnOnAddedInterface(ResolvedType type, ResolvedType parent) {
1407 World world = factory.getWorld();
1408 ResolvedType serializable = world.getCoreType(UnresolvedType.SERIALIZABLE);
1409 if (serializable.isAssignableFrom(type) && !serializable.isAssignableFrom(parent)
1410 && !LazyClassGen.hasSerialVersionUIDField(type)) {
1411 world.getLint().needsSerialVersionUIDField.signal(new String[] { type.getName().toString(),
1412 "added interface " + parent.getName().toString() }, null, null);
1416 private final List<BinaryTypeBinding> pendingTypesToFinish = new ArrayList<>();
1417 boolean inBinaryTypeCreationAndWeaving = false;
1418 boolean processingTheQueue = false;
1421 public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding,
1422 boolean needFieldsAndMethods, AccessRestriction accessRestriction) {
1424 if (inBinaryTypeCreationAndWeaving) {
1425 BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction);
1426 pendingTypesToFinish.add(ret);
1430 inBinaryTypeCreationAndWeaving = true;
1432 BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction);
1433 factory.getWorld().validateType(factory.fromBinding(ret));
1434 // if you need the bytes to pass to validate, here they
1435 // are:((ClassFileReader)binaryType).getReferenceBytes()
1436 weaveInterTypeDeclarations(ret);
1439 inBinaryTypeCreationAndWeaving = false;
1441 // Start processing the list...
1442 if (pendingTypesToFinish.size() > 0) {
1443 processingTheQueue = true;
1444 while (!pendingTypesToFinish.isEmpty()) {
1445 BinaryTypeBinding nextVictim = pendingTypesToFinish.remove(0);
1446 // During this call we may recurse into this method and add
1447 // more entries to the pendingTypesToFinish list.
1448 weaveInterTypeDeclarations(nextVictim);
1450 processingTheQueue = false;
1456 * Callback driven when the compiler detects an anonymous type during block resolution. We need to add it to the weaver so that
1457 * we don't trip up later.
1462 public void anonymousTypeBindingCreated(LocalTypeBinding aBinding) {
1463 factory.addSourceTypeBinding(aBinding, null);
1467 public void buildTypeBindings(CompilationUnitDeclaration unit, AccessRestriction accessRestriction) {
1468 if (this.isProcessingAnnotations && hasAspectDeclarations(unit)) {
1469 throw new SourceTypeCollisionException();
1471 super.buildTypeBindings(unit, accessRestriction);
1474 private static boolean hasAspectDeclarations(CompilationUnitDeclaration unit) {
1475 for (int j = 0; j < unit.types.length; j++) {
1476 if (unit.types[j] instanceof AspectDeclaration) {
1484 public void reset() {
1485 this.factory.cleanup();
1490 public LookupEnvironment wrapInModuleEnvironment(ModuleBinding moduleBinding) {
1491 AjLookupEnvironment newAjLookupEnvironment = new AjLookupEnvironment(this, moduleBinding);
1492 newAjLookupEnvironment.factory = this.factory;
1493 return newAjLookupEnvironment;
1497 // commented out, supplied as info on how to manipulate annotations in an
1500 // public void doDeclareAnnotationOnMethods() {
1501 // Do the declare annotation on fields/methods/ctors
1502 // Collection daoms = factory.getDeclareAnnotationOnMethods();
1503 // if (daoms!=null && daoms.size()>0 && !(sourceType instanceof
1504 // BinaryTypeBinding)) {
1505 // System.err.println("Going through the methods on "+sourceType.debugName()+
1506 // " looking for DECA matches");
1507 // // We better take a look through them...
1508 // for (Iterator iter = daoms.iterator(); iter.hasNext();) {
1509 // DeclareAnnotation element = (DeclareAnnotation) iter.next();
1510 // System.err.println("Looking for anything that might match "+element+" on "+
1511 // sourceType.debugName()+" "+getType(sourceType.
1512 // compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding));
1514 // ReferenceBinding rbb = getType(sourceType.compoundName);
1515 // // fix me if we ever uncomment this code... should iterate the other way
1516 // round, over the methods then over the decas
1517 // sourceType.methods();
1518 // MethodBinding sourceMbs[] = sourceType.methods;
1519 // for (int i = 0; i < sourceMbs.length; i++) {
1520 // MethodBinding sourceMb = sourceMbs[i];
1521 // MethodBinding mbbbb =
1522 // ((SourceTypeBinding)rbb).getExactMethod(sourceMb.selector
1523 // ,sourceMb.parameters);
1524 // boolean isCtor = sourceMb.selector[0]=='<';
1526 // if ((element.isDeclareAtConstuctor() ^ !isCtor)) {
1527 // System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb.
1528 // declaringClass.debugName()+" rbb="+rbb.debugName()+" "+
1529 // sourceMb.declaringClass.equals(rbb));
1531 // ResolvedMember rm = null;
1532 // rm = EclipseFactory.makeResolvedMember(mbbbb);
1533 // if (element.matches(rm,factory.getWorld())) {
1534 // System.err.println("MATCH");
1536 // // Determine the set of annotations that are currently on the method
1537 // ReferenceBinding rb = getType(sourceType.compoundName);
1538 // // TypeBinding tb = factory.makeTypeBinding(decA.getAspect());
1539 // MethodBinding mb =
1540 // ((SourceTypeBinding)rb).getExactMethod(sourceMb.selector,sourceMb
1542 // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved
1543 // TypeDeclaration typeDecl =
1544 // ((SourceTypeBinding)sourceMb.declaringClass).scope.referenceContext;
1545 // AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb);
1546 // Annotation[] currentlyHas = methodDecl.annotations; // this is what to add
1547 // //abits = toAdd[0].resolvedType.getAnnotationTagBits();
1549 // // Determine the annotations to add to that method
1550 // TypeBinding tb = factory.makeTypeBinding(element.getAspect());
1551 // MethodBinding[] aspectMbs =
1552 // ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod
1553 // ().toCharArray());
1554 // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved
1555 // TypeDeclaration typeDecl2 =
1556 // ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext;
1557 // AbstractMethodDeclaration methodDecl2 =
1558 // typeDecl2.declarationOf(aspectMbs[0]);
1559 // Annotation[] toAdd = methodDecl2.annotations; // this is what to add
1560 // // abits = toAdd[0].resolvedType.getAnnotationTagBits();
1561 // System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd);
1563 // // fix me? should check if it already has the annotation
1564 // //Annotation abefore[] = sourceType.scope.referenceContext.annotations;
1565 // Annotation[] newset = new
1566 // Annotation[(currentlyHas==null?0:currentlyHas.length)+1];
1567 // System.arraycopy(toAdd,0,newset,0,toAdd.length);
1568 // if (currentlyHas!=null) {
1569 // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length);
1571 // methodDecl.annotations = newset;
1572 // System.err.println("New set on "+CharOperation.charToString(sourceMb.selector)
1575 // System.err.println("NO MATCH");
1582 // commented out, supplied as info on how to manipulate annotations in an
1585 // public void doDeclareAnnotationOnFields() {
1586 // Collection daofs = factory.getDeclareAnnotationOnFields();
1587 // if (daofs!=null && daofs.size()>0 && !(sourceType instanceof
1588 // BinaryTypeBinding)) {
1589 // System.err.println("Going through the fields on "+sourceType.debugName()+
1590 // " looking for DECA matches");
1591 // // We better take a look through them...
1592 // for (Iterator iter = daofs.iterator(); iter.hasNext();) {
1593 // DeclareAnnotation element = (DeclareAnnotation) iter.next();
1594 // System.err.println("Processing deca "+element+" on "+sourceType.debugName()+
1595 // " "+getType(sourceType.compoundName).debugName()+" "
1596 // +(sourceType instanceof BinaryTypeBinding));
1598 // ReferenceBinding rbb = getType(sourceType.compoundName);
1599 // // fix me? should iterate the other way round, over the methods then over the
1601 // sourceType.fields(); // resolve the bloody things
1602 // FieldBinding sourceFbs[] = sourceType.fields;
1603 // for (int i = 0; i < sourceFbs.length; i++) {
1604 // FieldBinding sourceFb = sourceFbs[i];
1605 // //FieldBinding fbbbb =
1606 // ((SourceTypeBinding)rbb).getgetExactMethod(sourceMb.selector
1607 // ,sourceMb.parameters);
1609 // System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb.
1610 // declaringClass.debugName()+" rbb="+rbb.debugName());
1612 // ResolvedMember rm = null;
1613 // rm = EclipseFactory.makeResolvedMember(sourceFb);
1614 // if (element.matches(rm,factory.getWorld())) {
1615 // System.err.println("MATCH");
1617 // // Determine the set of annotations that are currently on the field
1618 // ReferenceBinding rb = getType(sourceType.compoundName);
1619 // // TypeBinding tb = factory.makeTypeBinding(decA.getAspect());
1620 // FieldBinding fb = ((SourceTypeBinding)rb).getField(sourceFb.name,true);
1621 // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved
1622 // TypeDeclaration typeDecl =
1623 // ((SourceTypeBinding)sourceFb.declaringClass).scope.referenceContext;
1624 // FieldDeclaration fd = typeDecl.declarationOf(sourceFb);
1625 // //AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb);
1626 // Annotation[] currentlyHas = fd.annotations; // this is what to add
1627 // //abits = toAdd[0].resolvedType.getAnnotationTagBits();
1629 // // Determine the annotations to add to that method
1630 // TypeBinding tb = factory.makeTypeBinding(element.getAspect());
1631 // MethodBinding[] aspectMbs =
1632 // ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod
1633 // ().toCharArray());
1634 // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved
1635 // TypeDeclaration typeDecl2 =
1636 // ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext;
1637 // AbstractMethodDeclaration methodDecl2 =
1638 // typeDecl2.declarationOf(aspectMbs[0]);
1639 // Annotation[] toAdd = methodDecl2.annotations; // this is what to add
1640 // // abits = toAdd[0].resolvedType.getAnnotationTagBits();
1641 // System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd);
1643 // // fix me? check if it already has the annotation
1646 // //Annotation abefore[] = sourceType.scope.referenceContext.annotations;
1647 // Annotation[] newset = new
1648 // Annotation[(currentlyHas==null?0:currentlyHas.length)+1];
1649 // System.arraycopy(toAdd,0,newset,0,toAdd.length);
1650 // if (currentlyHas!=null) {
1651 // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length);
1653 // fd.annotations = newset;
1654 // System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+
1657 // System.err.println("NO MATCH");