]> source.dussan.org Git - aspectj.git/blob
6542ac8285377badfd4770e3817d7e1f46871a61
[aspectj.git] /
1 /* *******************************************************************
2  * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
3  * All rights reserved.
4  * This program and the accompanying materials are made available
5  * under the terms of the Eclipse Public License 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
8  *
9  * Contributors:
10  *     PARC     initial implementation
11  * ******************************************************************/
12
13 package org.aspectj.ajdt.internal.compiler.lookup;
14
15 import java.lang.reflect.Modifier;
16 import java.util.*;
17
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;
74
75 /**
76  * Overrides the default eclipse LookupEnvironment for two purposes.
77  *
78  * 1. To provide some additional phases to <code>completeTypeBindings</code> that weave declare parents and inter-type declarations
79  * at the correct time.
80  *
81  * 2. To intercept the loading of new binary types to ensure the they will have declare parents and inter-type declarations woven
82  * when appropriate.
83  *
84  * @author Jim Hugunin
85  */
86 public class AjLookupEnvironment extends LookupEnvironment implements AnonymousClassCreationListener {
87         public EclipseFactory factory = null;
88
89         // private boolean builtInterTypesAndPerClauses = false;
90         private final List<SourceTypeBinding> pendingTypesToWeave = new ArrayList<>();
91
92         // Q: What are dangerousInterfaces?
93         // A: An interface is considered dangerous if an ITD has been made upon it
94         // and that ITD
95         // requires the top most implementors of the interface to be woven *and yet*
96         // the aspect
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
100         // bindings. At this
101         // point we look at any type mungers it was affected by previously (stored
102         // in the weaver
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
106         // aspect supplied
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
112         // a dangerous
113         // interface then we put out an error message.
114
115         /**
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
118          */
119         private final Map<ResolvedType, String> dangerousInterfaces = new HashMap<>();
120
121         public AjLookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter,
122                         INameEnvironment nameEnvironment) {
123                 super(typeRequestor, options, problemReporter, nameEnvironment);
124         }
125
126         public AjLookupEnvironment(LookupEnvironment env, ModuleBinding moduleBinding) {
127                 super(env, moduleBinding);
128         }
129
130         // ??? duplicates some of super's code
131         @Override
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;
139
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);
145                 }
146                 stepCompleted = CHECK_AND_SET_IMPORTS;
147
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);
153                 }
154                 stepCompleted = CONNECT_TYPE_HIERARCHY;
155
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);
163                 }
164
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();
175                                 }
176                         }
177                 }
178
179                 // We won't find out about anonymous types until later though, so
180                 // register to be
181                 // told about them when they turn up.
182                 AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(this);
183
184                 // need to build inter-type declarations for all AspectDeclarations at
185                 // this point
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);
197                                 }
198                         }
199                 }
200                 factory.getWorld().getCrosscuttingMembersSet().reset();
201
202                 // Need to do these before the other ITDs
203                 for (SourceTypeBinding aspectToProcess : aspectsToProcess) {
204                         processInterTypeMemberTypes(aspectToProcess.scope);
205                 }
206
207                 while (typesToProcess.size() > 0) {
208                         // removes types from the list as they are processed...
209                         collectAllITDsAndDeclares(typesToProcess.get(0), typesToProcess);
210                 }
211
212                 factory.finishTypeMungers();
213
214                 // now do weaving
215                 final List<ConcreteTypeMunger> typeMungers = factory.getTypeMungers();
216
217                 final List<DeclareParents> declareParents = factory.getDeclareParents();
218                 final List<DeclareAnnotation> declareAnnotationOnTypes = factory.getDeclareAnnotationOnTypes();
219
220                 doPendingWeaves();
221
222                 // We now have some list of types to process, and we are about to apply
223                 // the type mungers.
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
227                 // have class A
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
231                 // serializable.
232
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
236                 // problems with:
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.
242                 //
243                 // but these aren't common cases (he bravely said...)
244                 boolean typeProcessingOrderIsImportant = declareParents.size() > 0 || declareAnnotationOnTypes.size() > 0; // DECAT
245
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);
252                         }
253
254                         List<SourceTypeBinding> stb2 = new ArrayList<>(typesToProcess);
255
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);
259                         }
260
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);
264                         }
265
266                 } else {
267                         // Order isn't important
268                         for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
269                                 weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents, declareAnnotationOnTypes);
270                         }
271                 }
272
273                 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
274                         units[i].scope.checkParameterizedTypes();
275                 }
276
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);
284                         }
285                 }
286
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);
294                         }
295                 }
296
297                 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
298                         units[i] = null; // release unnecessary reference to the parsed unit
299                 }
300
301                 stepCompleted = BUILD_FIELDS_AND_METHODS;
302                 lastCompletedUnitIndex = lastUnitIndex;
303                 AsmManager.setCompletingTypeBindings(false);
304                 factory.getWorld().getCrosscuttingMembersSet().verify();
305                 CompilationAndWeavingContext.leavingPhase(completeTypeBindingsToken);
306
307                 if (isProcessingAnnotations) {
308                         throw new SourceTypeCollisionException(); // TODO(yushkovskiy): temporary solution; forcing to recompile units to insert mungers into types
309                 }
310         }
311
312         // /**
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
316         // the generic type
317         // * variables.
318         // */
319         // private void verifyAnyTypeParametersMeetBounds(SourceTypeBinding
320         // sourceType) {
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++) {
330         // boolean ok =
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}
335         // String msg =
336         // WeaverMessages.format(
337         // WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS,
338         // typeParams[i],
339         // new Integer(i+1),
340         // typeVariables[i].getDisplayName(),
341         // superType.getGenericType().getName());
342         // factory.getWorld().getMessageHandler().handleMessage(MessageUtil.error(msg
343         // ,onType.getSourceLocation()));
344         // }
345         // }
346         // }
347         // }
348         // }
349         // }
350
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);
355                         }
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);
361                         }
362                 }
363         }
364
365         /**
366          * Find all the ITDs and Declares, but it is important we do this from the supertypes down to the subtypes.
367          *
368          * @param sourceType
369          * @param yetToProcess
370          */
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);
375
376                 yetToProcess.remove(sourceType);
377                 // look out our direct supertype
378                 doSupertypesFirst(sourceType.superclass(), yetToProcess);
379
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);
386                         }
387                 }
388
389                 buildInterTypeAndPerClause(sourceType.scope);
390                 addCrosscuttingStructures(sourceType.scope);
391                 CompilationAndWeavingContext.leavingPhase(tok);
392         }
393
394         /**
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?
400          *
401          * @param mode 0=do everything, 1=do declare parents, 2=do ITDs
402          */
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,
412                                         mode);
413                 }
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,
421                                                 mode);
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);
424                         }
425                 }
426                 weaveInterTypeDeclarations(typeToWeave, typeMungers, declareParents, declareAnnotationOnTypes, false, mode);
427                 typesToProcess.remove(typeToWeave);
428         }
429
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);
436                 }
437                 pendingTypesToWeave.clear();
438         }
439
440         private void addAdviceLikeDeclares(ClassScope s) {
441                 TypeDeclaration dec = s.referenceContext;
442
443                 if (dec instanceof AspectDeclaration) {
444                         ResolvedType typeX = factory.fromEclipse(dec.binding);
445                         factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX);
446                 }
447
448                 SourceTypeBinding sourceType = s.referenceContext.binding;
449                 ReferenceBinding[] memberTypes = sourceType.memberTypes;
450                 for (ReferenceBinding memberType : memberTypes) {
451                         addAdviceLikeDeclares(((SourceTypeBinding) memberType).scope);
452                 }
453         }
454
455         private void addCrosscuttingStructures(ClassScope s) {
456                 TypeDeclaration dec = s.referenceContext;
457
458                 if (dec instanceof AspectDeclaration) {
459                         ResolvedType typeX = factory.fromEclipse(dec.binding);
460                         factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX, false);
461
462                         if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) {
463                                 factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass(), false);
464                         }
465                 }
466
467                 SourceTypeBinding sourceType = s.referenceContext.binding;
468                 ReferenceBinding[] memberTypes = sourceType.memberTypes;
469                 for (ReferenceBinding memberType : memberTypes) {
470                         addCrosscuttingStructures(((SourceTypeBinding) memberType).scope);
471                 }
472         }
473
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) {
483                                         hasPointcuts = true;
484                                         if (!initializedMethods) {
485                                                 sourceType.methods(); // force initialization
486                                                 initializedMethods = true;
487                                         }
488                                         ((PointcutDeclaration) method).resolvePointcut(s);
489                                 }
490                         }
491                 }
492
493                 if (hasPointcuts || dec instanceof AspectDeclaration || couldBeAnnotationStyleAspectDeclaration(dec)) {
494                         ReferenceType name = (ReferenceType) factory.fromEclipse(sourceType);
495                         EclipseSourceType eclipseSourceType = (EclipseSourceType) name.getDelegate();
496                         eclipseSourceType.checkPointcutDeclarations();
497                 }
498
499                 ReferenceBinding[] memberTypes = sourceType.memberTypes;
500                 for (ReferenceBinding memberType : memberTypes) {
501                         resolvePointcutDeclarations(((SourceTypeBinding) memberType).scope);
502                 }
503         }
504
505         /**
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.
510          */
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;
518                                 }
519                         }
520                 }
521                 return couldBeAtAspect;
522         }
523
524         /**
525          * Applies any intertype member type declarations up front.
526          */
527         private void processInterTypeMemberTypes(ClassScope classScope) {
528                 TypeDeclaration dec = classScope.referenceContext;
529                 if (dec instanceof AspectDeclaration) {
530                         ((AspectDeclaration) dec).processIntertypeMemberTypes(classScope);
531                 }
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
534         }
535
536         private void buildInterTypeAndPerClause(ClassScope s) {
537                 TypeDeclaration dec = s.referenceContext;
538                 if (dec instanceof AspectDeclaration) {
539                         ((AspectDeclaration) dec).buildInterTypeAndPerClause(s);
540                 }
541
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);
549                         }
550                 }
551
552                 ReferenceBinding[] memberTypes = sourceType.memberTypes;
553                 if (memberTypes == null) {
554                         System.err.println("Unexpectedly found null for memberTypes of " + sourceType.debugName());
555                 }
556                 if (memberTypes != null) {
557                         for (ReferenceBinding memberType : memberTypes) {
558                                 buildInterTypeAndPerClause(((SourceTypeBinding) memberType).scope);
559                         }
560                 }
561         }
562
563         private boolean isAspect(TypeDeclaration decl) {
564                 if ((decl instanceof AspectDeclaration)) {
565                         return true;
566                 } else if (decl.annotations == null) {
567                         return false;
568                 } else {
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)) {
573                                                 return true;
574                                         }
575                                 } else if (ann.type instanceof QualifiedTypeReference) {
576                                         QualifiedTypeReference qtr = (QualifiedTypeReference) ann.type;
577                                         if (qtr.tokens.length != 5) {
578                                                 return false;
579                                         }
580                                         if (!CharOperation.equals("org".toCharArray(), qtr.tokens[0])) {
581                                                 return false;
582                                         }
583                                         if (!CharOperation.equals("aspectj".toCharArray(), qtr.tokens[1])) {
584                                                 return false;
585                                         }
586                                         if (!CharOperation.equals("lang".toCharArray(), qtr.tokens[2])) {
587                                                 return false;
588                                         }
589                                         if (!CharOperation.equals("annotation".toCharArray(), qtr.tokens[3])) {
590                                                 return false;
591                                         }
592                                         if (!CharOperation.equals("Aspect".toCharArray(), qtr.tokens[4])) {
593                                                 return false;
594                                         }
595                                         return true;
596                                 }
597                         }
598                 }
599                 return false;
600         }
601
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);
606                 }
607         }
608
609         private void weaveInterTypeDeclarations(SourceTypeBinding sourceType) {
610                 if (!factory.areTypeMungersFinished()) {
611                         if (!pendingTypesToWeave.contains(sourceType)) {
612                                 pendingTypesToWeave.add(sourceType);
613
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);
621                                 // // }
622                                 // // }
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());
633                                 //
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;
640                                 // break;
641                                 // }
642                                 // }
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);
647                                 // }
648                                 // t.memberTypes(); // cause initialization
649                                 // t.memberTypes = new ReferenceBinding[] { innerTypeBinding };
650                                 //
651                                 // int stop = 1;
652                                 // // The inner type from the aspect should be put into the membertypebindings for this
653                                 //
654                                 // }
655                                 // }
656
657                         }
658                 } else {
659                         weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(),
660                                         factory.getDeclareAnnotationOnTypes(), true, 0);
661                 }
662         }
663
664         /**
665          * @param mode 0=do everything, 1=do declare parents, 2=do ITDs
666          */
667         private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, List<ConcreteTypeMunger> typeMungers,
668                         List<DeclareParents> declareParents, List<DeclareAnnotation> declareAnnotationOnTypes, boolean skipInners, int mode) {
669
670                 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS,
671                                 sourceType.sourceName);
672
673                 ResolvedType onType = factory.fromEclipse(sourceType);
674
675                 // AMC we shouldn't need this when generic sigs are fixed??
676                 if (onType.isRawType()) {
677                         onType = onType.getGenericType();
678                 }
679
680                 WeaverStateInfo info = onType.getWeaverState();
681
682                 if (mode < 2) {
683                         // this test isnt quite right - there will be a case where we fail to
684                         // flag a problem
685                         // with a 'dangerous interface' because the type is reweavable when we
686                         // should have
687                         // because the type wasn't going to be rewoven... if that happens, we
688                         // should perhaps
689                         // move this test and dangerous interface processing to the end of this
690                         // method and
691                         // make it conditional on whether any of the typeMungers passed into
692                         // here actually
693                         // matched this type.
694                         if (info != null && !info.isOldStyle() && !info.isReweavable()) {
695                                 processTypeMungersFromExistingWeaverState(sourceType, onType);
696                                 CompilationAndWeavingContext.leavingPhase(tok);
697                                 return;
698                         }
699
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);
707                                 }
708                         }
709
710                         boolean needOldStyleWarning = (info != null && info.isOldStyle());
711
712                         onType.clearInterTypeMungers();
713                         onType.ensureConsistent();
714
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
721                         // messages...
722
723                         List<DeclareParents> decpToRepeat = new ArrayList<>();
724                         List<DeclareAnnotation> decaToRepeat = new ArrayList<>();
725                         boolean anyNewParents = false;
726                         boolean anyNewAnnotations = false;
727
728                         // first pass
729                         // try and apply all decps - if they match, then great. If they don't
730                         // then
731                         // check if they are starred-annotation patterns. If they are not
732                         // starred
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);
737                                         if (didSomething) {
738                                                 if (factory.pushinCollector != null) {
739                                                         factory.pushinCollector.tagAsMunged(sourceType, decp.getParents().get(0));
740                                                 }
741                                                 anyNewParents = true;
742                                         } else {
743                                                 if (!decp.getChild().isStarAnnotation()) {
744                                                         decpToRepeat.add(decp);
745                                                 }
746                                         }
747                                 }
748                         }
749
750                         for (DeclareAnnotation deca : declareAnnotationOnTypes) {
751                                 boolean didSomething = doDeclareAnnotations(deca, sourceType, true);
752                                 if (didSomething) {
753                                         anyNewAnnotations = true;
754                                 } else {
755                                         if (!deca.getTypePattern().isStar()) {
756                                                 decaToRepeat.add(deca);
757                                         }
758                                 }
759                         }
760
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;
765                                 forRemoval.clear();
766                                 for (DeclareParents decp : decpToRepeat) {
767                                         boolean didSomething = doDeclareParents(decp, sourceType);
768                                         if (didSomething) {
769                                                 if (factory.pushinCollector != null) {
770                                                         factory.pushinCollector.tagAsMunged(sourceType, decp.getParents().get(0));
771                                                 }
772                                                 anyNewParents = true;
773                                                 forRemoval.add(decp);
774                                         }
775                                 }
776                                 decpToRepeat.removeAll(forRemoval);
777
778                                 forRemoval.clear();
779                                 for (DeclareAnnotation deca : decaToRepeat) {
780                                         boolean didSomething = doDeclareAnnotations(deca, sourceType, false);
781                                         if (didSomething) {
782                                                 if (factory.pushinCollector != null) {
783                                                         factory.pushinCollector.tagAsMunged(sourceType, deca.getAnnotationString());
784                                                 }
785                                                 anyNewAnnotations = true;
786                                                 forRemoval.add(deca);
787                                         }
788                                 }
789                                 decaToRepeat.removeAll(forRemoval);
790                         }
791                 }
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;
800                                         // }
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());
809                                                         }
810                                                 }
811                                         }
812                                 }
813                         }
814
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());
822                                                 }
823                                         }
824                                 }
825                         }
826                 }
827
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
831                 // left here for
832                 // future generations to enjoy. Method source is commented out at the
833                 // end of this module
834                 // doDeclareAnnotationOnMethods();
835
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
838                 // left here for
839                 // future generations to enjoy. Method source is commented out at the
840                 // end of this module
841                 // doDeclareAnnotationOnFields();
842
843                 if (skipInners) {
844                         CompilationAndWeavingContext.leavingPhase(tok);
845                         return;
846                 }
847
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);
853                         }
854                 }
855                 CompilationAndWeavingContext.leavingPhase(tok);
856         }
857
858         /**
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.
861          *
862          * sourceType and onType are the 'same type' - the former is the 'Eclipse' version and the latter is the 'Weaver' version.
863          */
864         private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType, ResolvedType onType) {
865                 List<ConcreteTypeMunger> previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType);
866
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())) {
872                                                 dangerousInterfaces
873                                                                 .put(onType, "implementors of " + onType + " must be woven by " + munger.getAspectType());
874                                         }
875                                 }
876                         }
877
878                 }
879         }
880
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);
892                                 }
893                                 if (Modifier.isFinal(parent.getModifiers())) {
894                                         factory.showMessage(IMessage.ERROR, "cannot extend final class " + parent.getClassName(),
895                                                         declareParents.getSourceLocation(), null);
896                                 } else {
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()) {
900                                                 return false;
901                                         }
902                                         // AsmRelationshipProvider.getDefault().
903                                         // addDeclareParentsRelationship
904                                         // (declareParents.getSourceLocation(),
905                                         // factory.fromEclipse(sourceType), newParents);
906                                         addParent(sourceType, parent);
907                                 }
908                         }
909                         CompilationAndWeavingContext.leavingPhase(tok);
910                         return true;
911                 }
912                 CompilationAndWeavingContext.leavingPhase(tok);
913                 return false;
914         }
915
916         private String stringifyTargets(long bits) {
917                 if ((bits & TagBits.AnnotationTargetMASK) == 0) {
918                         return "";
919                 }
920                 Set<String> s = new HashSet<>();
921                 if ((bits & TagBits.AnnotationForAnnotationType) != 0) {
922                         s.add("ANNOTATION_TYPE");
923                 }
924                 if ((bits & TagBits.AnnotationForConstructor) != 0) {
925                         s.add("CONSTRUCTOR");
926                 }
927                 if ((bits & TagBits.AnnotationForField) != 0) {
928                         s.add("FIELD");
929                 }
930                 if ((bits & TagBits.AnnotationForLocalVariable) != 0) {
931                         s.add("LOCAL_VARIABLE");
932                 }
933                 if ((bits & TagBits.AnnotationForMethod) != 0) {
934                         s.add("METHOD");
935                 }
936                 if ((bits & TagBits.AnnotationForPackage) != 0) {
937                         s.add("PACKAGE");
938                 }
939                 if ((bits & TagBits.AnnotationForParameter) != 0) {
940                         s.add("PARAMETER");
941                 }
942                 if ((bits & TagBits.AnnotationForType) != 0) {
943                         s.add("TYPE");
944                 }
945                 StringBuilder sb = new StringBuilder();
946                 sb.append("{");
947                 for (Iterator<String> iter = s.iterator(); iter.hasNext();) {
948                         String element = iter.next();
949                         sb.append(element);
950                         if (iter.hasNext()) {
951                                 sb.append(",");
952                         }
953                 }
954                 sb.append("}");
955                 return sb.toString();
956         }
957
958         private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) {
959                 ResolvedType rtx = factory.fromEclipse(sourceType);
960                 if (!decA.matches(rtx)) {
961                         return false;
962                 }
963                 if (!rtx.isExposedToWeaver()) {
964                         return false;
965                 }
966
967                 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS,
968                                 sourceType.sourceName);
969
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();
976                         }
977                 }
978                 TypeBinding tb = factory.makeTypeBinding(aspectType);
979
980                 // Hideousness follows:
981
982                 // There are multiple situations to consider here and they relate to the
983                 // combinations of
984                 // where the annotation is coming from and where the annotation is going
985                 // to be put:
986                 //
987                 // 1. Straight full build, all from source - the annotation is from a
988                 // dec@type and
989                 // is being put on some type. Both types are real SourceTypeBindings.
990                 // WORKS
991                 // 2. Incremental build, changing the affected type - the annotation is
992                 // from a
993                 // dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and
994                 // the
995                 // affected type is a real SourceTypeBinding. Mostly works (pr128665)
996                 // 3. ?
997
998                 SourceTypeBinding stb = (SourceTypeBinding) tb;
999                 Annotation[] toAdd = null;
1000                 long abits = 0;
1001
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();
1009                         }
1010                 } else if (stb != null) {
1011                         // much nicer, its a real SourceTypeBinding so we can stay in
1012                         // eclipse land
1013                         // if (decA.getAnnotationMethod() != null) {
1014                         char[] declareSelector = decA.getAnnotationMethod().toCharArray();
1015
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();
1020                         }
1021                         MethodBinding[] mbs = rb.getMethods(declareSelector);
1022
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;
1027                         }
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();
1032                                 }
1033                         } else {
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();
1041                                         // }
1042                                 }
1043                         }
1044                 }
1045
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);
1049                         return false;
1050                 }
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) {
1060                                 return false;
1061                         }
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);
1067                                 return false;
1068                         }
1069
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
1076                                         giveupnow = true;
1077                                 } else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
1078                                                 || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
1079
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);
1085                                                 }
1086                                                 // dont put out the lint - the weaving process will do
1087                                                 // that
1088                                                 // else {
1089                                                 // if (factory.getWorld().getLint().
1090                                                 // invalidTargetForAnnotation.isEnabled()) {
1091                                                 // factory.getWorld().getLint().invalidTargetForAnnotation
1092                                                 // .signal(new
1093                                                 // String[]{rtx.getName(),toAdd[0].type.toString(),
1094                                                 // stringifyTargets
1095                                                 // (abits)},decA.getSourceLocation(),null);
1096                                                 // }
1097                                                 // }
1098                                         }
1099                                         giveupnow = true;
1100                                 }
1101                         }
1102                         if (giveupnow) {
1103                                 CompilationAndWeavingContext.leavingPhase(tok);
1104                                 return false;
1105                         }
1106
1107                         theTargetType.addAnnotation(new BcelAnnotation(new FakeAnnotation(name, sig,
1108                                         (abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld()));
1109                         CompilationAndWeavingContext.leavingPhase(tok);
1110                         return true;
1111                 }
1112
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
1123                                 if (a.equals(b)) {
1124                                         CompilationAndWeavingContext.leavingPhase(tok);
1125                                         return false;
1126                                 }
1127                         }
1128                 }
1129
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);
1136                                 return false;
1137                         }
1138                         if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
1139                                         || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
1140
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);
1146                                         }
1147                                         // dont put out the lint - the weaving process will do that
1148                                         // else {
1149                                         // if
1150                                         // (factory.getWorld().getLint().invalidTargetForAnnotation
1151                                         // .isEnabled()) {
1152                                         // factory.getWorld().getLint().invalidTargetForAnnotation.
1153                                         // signal(new
1154                                         // String[]{rtx.getName(),toAdd[0].type.toString(),
1155                                         // stringifyTargets(abits)},decA.getSourceLocation(),null);
1156                                         // }
1157                                         // }
1158                                 }
1159                                 CompilationAndWeavingContext.leavingPhase(tok);
1160                                 return false;
1161                         }
1162                 }
1163
1164                 // Build a new array of annotations
1165
1166                 // remember the current set (rememberAnnotations only does something the
1167                 // first time it is called for a type)
1168                 sourceType.scope.referenceContext.rememberAnnotations();
1169
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);
1177                 }
1178                 sourceType.scope.referenceContext.annotations = newset;
1179                 if ((sourceType.tagBits & TagBits.AnnotationResolved)!=0) {
1180                         sourceType.tagBits = sourceType.tagBits - TagBits.AnnotationResolved;
1181                 }
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());
1186                 }
1187                 return true;
1188         }
1189
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;
1198                                 break;
1199                         }
1200                 }
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();
1213                                 // }
1214                                 return toAdd;
1215                         }
1216                 }
1217                 return null;
1218         }
1219
1220         /**
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.
1225          */
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++) {
1233                         positions[i] = pos;
1234                 }
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);
1245                 // mvps[1] = new
1246                 // MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
1247                 // ann.memberValuePairs = mvps;
1248                 return ann;
1249         }
1250
1251         /**
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
1253          * 'recipient'
1254          */
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;
1260                 return ann2;
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];
1277                 // // mvps[0] = new
1278                 // MemberValuePair("value".toCharArray(),pos,pos,pcExpr);
1279                 // // Expression argNamesExpr = new
1280                 // StringLiteral(argNames.toCharArray(),pos,pos);
1281                 // // mvps[1] = new
1282                 // MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
1283                 // // ann.memberValuePairs = mvps;
1284                 // return ann;
1285         }
1286
1287         private boolean isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(long abits) {
1288                 return (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0;
1289         }
1290
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());
1294 //
1295 //                      int takefrom = filename.lastIndexOf('/');
1296 //                      if (takefrom == -1) {
1297 //                              takefrom = filename.lastIndexOf('\\');
1298 //                      }
1299 //                      filename = filename.substring(takefrom + 1);
1300 //
1301 //                      factory.getWorld()
1302 //                                      .getMessageHandler()
1303 //                                      .handleMessage(
1304 //                                                      WeaveMessage.constructWeavingMessage(wmk,
1305 //                                                                      new String[] { CharOperation.toString(sourceType.compoundName), filename,
1306 //                                                                                      parent.getClassName(),
1307 //                                                                                      getShortname(parent.getSourceLocation().getSourceFile().getPath()) }));
1308 //              }
1309 //      }
1310
1311 //      private String getShortname(String path) {
1312 //              int takefrom = path.lastIndexOf('/');
1313 //              if (takefrom == -1) {
1314 //                      takefrom = path.lastIndexOf('\\');
1315 //              }
1316 //              return path.substring(takefrom + 1);
1317 //      }
1318
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.
1323                 }
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;
1335                                 } else {
1336                                         ReferenceBinding[] oldI = rawTargetType.superInterfaces;
1337                                         ReferenceBinding[] newI;
1338                                         if (oldI == null) {
1339                                                 newI = new ReferenceBinding[1];
1340                                                 newI[0] = parentBinding;
1341                                         } else {
1342                                                 int n = oldI.length;
1343                                                 newI = new ReferenceBinding[n + 1];
1344                                                 System.arraycopy(oldI, 0, newI, 0, n);
1345                                                 newI[n] = parentBinding;
1346                                         }
1347                                         rawTargetType.superInterfaces = newI;
1348                                 }
1349                         }
1350                         // TODO what about parameterized types?
1351                 }
1352                 sourceType.rememberTypeHierarchy();
1353                 if (parentBinding.isClass()) {
1354                         sourceType.superclass = parentBinding;
1355
1356                         // this used to be true, but I think I've fixed it now, decp is done
1357                         // at weave time!
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);
1363
1364                 } else {
1365                         ReferenceBinding[] oldI = sourceType.superInterfaces;
1366                         ReferenceBinding[] newI;
1367                         if (oldI == null) {
1368                                 newI = new ReferenceBinding[1];
1369                                 newI[0] = parentBinding;
1370                         } else {
1371                                 int n = oldI.length;
1372                                 newI = new ReferenceBinding[n + 1];
1373                                 System.arraycopy(oldI, 0, newI, 0, n);
1374                                 newI[n] = parentBinding;
1375                         }
1376                         sourceType.superInterfaces = newI;
1377                         // warnOnAddedInterface(factory.fromEclipse(sourceType),parent); //
1378                         // now reported at weave time...
1379
1380                         // this used to be true, but I think I've fixed it now, decp is done
1381                         // at weave time!
1382                         // TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS
1383                         // This message will come out of BcelTypeMunger.munge if doing a
1384                         // binary weave
1385                         // reportDeclareParentsMessage(WeaveMessage.
1386                         // WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent);
1387
1388                 }
1389
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();
1398                                 }
1399                                 rt.addParent(parent);
1400                                 // ((BcelObjectType) rtd).addParent(parent);
1401                         }
1402                 }
1403
1404         }
1405
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);
1413                 }
1414         }
1415
1416         private final List<BinaryTypeBinding> pendingTypesToFinish = new ArrayList<>();
1417         boolean inBinaryTypeCreationAndWeaving = false;
1418         boolean processingTheQueue = false;
1419
1420         @Override
1421         public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding,
1422                         boolean needFieldsAndMethods, AccessRestriction accessRestriction) {
1423
1424                 if (inBinaryTypeCreationAndWeaving) {
1425                         BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction);
1426                         pendingTypesToFinish.add(ret);
1427                         return ret;
1428                 }
1429
1430                 inBinaryTypeCreationAndWeaving = true;
1431                 try {
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);
1437                         return ret;
1438                 } finally {
1439                         inBinaryTypeCreationAndWeaving = false;
1440
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);
1449                                 }
1450                                 processingTheQueue = false;
1451                         }
1452                 }
1453         }
1454
1455         /**
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.
1458          *
1459          * @param aBinding
1460          */
1461         @Override
1462         public void anonymousTypeBindingCreated(LocalTypeBinding aBinding) {
1463                 factory.addSourceTypeBinding(aBinding, null);
1464         }
1465
1466   @Override
1467   public void buildTypeBindings(CompilationUnitDeclaration unit, AccessRestriction accessRestriction) {
1468     if (this.isProcessingAnnotations && hasAspectDeclarations(unit)) {
1469       throw new SourceTypeCollisionException();
1470     }
1471     super.buildTypeBindings(unit, accessRestriction);
1472   }
1473
1474   private static boolean hasAspectDeclarations(CompilationUnitDeclaration unit) {
1475     for (int j = 0; j < unit.types.length; j++) {
1476       if (unit.types[j] instanceof AspectDeclaration) {
1477         return true;
1478       }
1479     }
1480     return false;
1481   }
1482
1483   @Override
1484   public void reset() {
1485     this.factory.cleanup();
1486     super.reset();
1487   }
1488
1489   @Override
1490 public LookupEnvironment wrapInModuleEnvironment(ModuleBinding moduleBinding) {
1491           AjLookupEnvironment newAjLookupEnvironment = new AjLookupEnvironment(this, moduleBinding);
1492           newAjLookupEnvironment.factory = this.factory;
1493           return newAjLookupEnvironment;
1494   }
1495 }
1496
1497 // commented out, supplied as info on how to manipulate annotations in an
1498 // eclipse world
1499 //
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));
1513 //
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]=='<';
1525 //
1526 // if ((element.isDeclareAtConstuctor() ^ !isCtor)) {
1527 // System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb.
1528 // declaringClass.debugName()+" rbb="+rbb.debugName()+"  "+
1529 // sourceMb.declaringClass.equals(rbb));
1530 //
1531 // ResolvedMember rm = null;
1532 // rm = EclipseFactory.makeResolvedMember(mbbbb);
1533 // if (element.matches(rm,factory.getWorld())) {
1534 // System.err.println("MATCH");
1535 //
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
1541 // .parameters);
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();
1548 //
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);
1562 //
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);
1570 // }
1571 // methodDecl.annotations = newset;
1572 // System.err.println("New set on "+CharOperation.charToString(sourceMb.selector)
1573 // +" is "+newset);
1574 // } else
1575 // System.err.println("NO MATCH");
1576 // }
1577 // }
1578 // }
1579 // }
1580 // }
1581
1582 // commented out, supplied as info on how to manipulate annotations in an
1583 // eclipse world
1584 //
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));
1597 //
1598 // ReferenceBinding rbb = getType(sourceType.compoundName);
1599 // // fix me? should iterate the other way round, over the methods then over the
1600 // decas
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);
1608 //
1609 // System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb.
1610 // declaringClass.debugName()+" rbb="+rbb.debugName());
1611 //
1612 // ResolvedMember rm = null;
1613 // rm = EclipseFactory.makeResolvedMember(sourceFb);
1614 // if (element.matches(rm,factory.getWorld())) {
1615 // System.err.println("MATCH");
1616 //
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();
1628 //
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);
1642 //
1643 // // fix me? check if it already has the annotation
1644 //
1645 //
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);
1652 // }
1653 // fd.annotations = newset;
1654 // System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+
1655 // " is "+newset);
1656 // } else
1657 // System.err.println("NO MATCH");
1658 // }
1659 //
1660 // }
1661 // }