]> source.dussan.org Git - aspectj.git/blob
809a73af82ce0496edd294fa86167d1a8b37fe0b
[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 v1.0 
6  * which accompanies this distribution and is available at 
7  * http://www.eclipse.org/legal/epl-v10.html 
8  *  
9  * Contributors: 
10  *     PARC     initial implementation 
11  * ******************************************************************/
12
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.DeclareAnnotation;
72 import org.aspectj.weaver.patterns.DeclareParents;
73
74 /**
75  * Overrides the default eclipse LookupEnvironment for two purposes.
76  *
77  * 1. To provide some additional phases to <code>completeTypeBindings</code> that weave declare parents and inter-type declarations
78  * at the correct time.
79  *
80  * 2. To intercept the loading of new binary types to ensure the they will have declare parents and inter-type declarations woven
81  * when appropriate.
82  *
83  * @author Jim Hugunin
84  */
85 public class AjLookupEnvironment extends LookupEnvironment implements AnonymousClassCreationListener {
86         public EclipseFactory factory = null;
87
88         // private boolean builtInterTypesAndPerClauses = false;
89         private final List<SourceTypeBinding> pendingTypesToWeave = new ArrayList<>();
90
91         // Q: What are dangerousInterfaces?
92         // A: An interface is considered dangerous if an ITD has been made upon it
93         // and that ITD
94         // requires the top most implementors of the interface to be woven *and yet*
95         // the aspect
96         // responsible for the ITD is not in the 'world'.
97         // Q: Err, how can that happen?
98         // A: When a type is on the inpath, it is 'processed' when completing type
99         // bindings. At this
100         // point we look at any type mungers it was affected by previously (stored
101         // in the weaver
102         // state info attribute). Effectively we are working with a type munger and
103         // yet may not have its
104         // originating aspect in the world. This is a problem if, for example, the
105         // aspect supplied
106         // a 'body' for a method targetting an interface - since the top most
107         // implementors should
108         // be woven by the munger from the aspect. When this happens we store the
109         // interface name here
110         // in the map - if we later process a type that is the topMostImplementor of
111         // a dangerous
112         // interface then we put out an error message.
113
114         /**
115          * interfaces targetted by ITDs that have to be implemented by accessing the topMostImplementor of the interface, yet the aspect
116          * where the ITD originated is not in the world
117          */
118         private final Map dangerousInterfaces = new HashMap();
119
120         public AjLookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter,
121                         INameEnvironment nameEnvironment) {
122                 super(typeRequestor, options, problemReporter, nameEnvironment);
123         }
124         
125         public AjLookupEnvironment(LookupEnvironment env, ModuleBinding moduleBinding) {
126                 super(env, moduleBinding);
127         }
128
129         // ??? duplicates some of super's code
130         @Override
131         public void completeTypeBindings() {
132                 AsmManager.setCompletingTypeBindings(true);
133                 ContextToken completeTypeBindingsToken = CompilationAndWeavingContext.enteringPhase(
134                                 CompilationAndWeavingContext.COMPLETING_TYPE_BINDINGS, "");
135                 // builtInterTypesAndPerClauses = false;
136                 // pendingTypesToWeave = new ArrayList();
137                 stepCompleted = BUILD_TYPE_HIERARCHY;
138
139                 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
140                         ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CHECK_AND_SET_IMPORTS,
141                                         units[i].compilationResult.fileName);
142                         units[i].scope.checkAndSetImports();
143                         CompilationAndWeavingContext.leavingPhase(tok);
144                 }
145                 stepCompleted = CHECK_AND_SET_IMPORTS;
146
147                 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
148                         ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CONNECTING_TYPE_HIERARCHY,
149                                         units[i].compilationResult.fileName);
150                         units[i].scope.connectTypeHierarchy();
151                         CompilationAndWeavingContext.leavingPhase(tok);
152                 }
153                 stepCompleted = CONNECT_TYPE_HIERARCHY;
154
155                 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
156                         ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.BUILDING_FIELDS_AND_METHODS,
157                                         units[i].compilationResult.fileName);
158                         // units[i].scope.checkParameterizedTypes(); do this check a little
159                         // later, after ITDs applied to stbs
160                         units[i].scope.buildFieldsAndMethods();
161                         CompilationAndWeavingContext.leavingPhase(tok);
162                 }
163
164                 // would like to gather up all TypeDeclarations at this point and put
165                 // them in the factory
166                 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
167                         SourceTypeBinding[] b = units[i].scope.topLevelTypes;
168                         for (SourceTypeBinding sourceTypeBinding : b) {
169                                 factory.addSourceTypeBinding(sourceTypeBinding, units[i]);
170                                 if (sourceTypeBinding.superclass instanceof MissingTypeBinding) {
171                                         // e37: Undoing the work in ClassScope.connectSuperClass() as it will lead to cascade errors
172                                         // TODO allow MissingTypeBinding through here and cope with it in all situations later?
173                                         sourceTypeBinding.superclass = units[i].scope.getJavaLangObject();
174                                 }
175                         }
176                 }
177
178                 // We won't find out about anonymous types until later though, so
179                 // register to be
180                 // told about them when they turn up.
181                 AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(this);
182
183                 // need to build inter-type declarations for all AspectDeclarations at
184                 // this point
185                 // this MUST be done in order from super-types to subtypes
186                 List<SourceTypeBinding> typesToProcess = new ArrayList<>();
187                 List<SourceTypeBinding> aspectsToProcess = new ArrayList<>();
188                 for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
189                         CompilationUnitScope cus = units[i].scope;
190                         SourceTypeBinding[] stbs = cus.topLevelTypes;
191                         for (SourceTypeBinding stb : stbs) {
192                                 typesToProcess.add(stb);
193                                 TypeDeclaration typeDeclaration = stb.scope.referenceContext;
194                                 if (typeDeclaration instanceof AspectDeclaration) {
195                                         aspectsToProcess.add(stb);
196                                 }
197                         }
198                 }
199                 factory.getWorld().getCrosscuttingMembersSet().reset();
200
201                 // Need to do these before the other ITDs
202                 for (SourceTypeBinding aspectToProcess : aspectsToProcess) {
203                         processInterTypeMemberTypes(aspectToProcess.scope);
204                 }
205
206                 while (typesToProcess.size() > 0) {
207                         // removes types from the list as they are processed...
208                         collectAllITDsAndDeclares(typesToProcess.get(0), typesToProcess);
209                 }
210
211                 factory.finishTypeMungers();
212
213                 // now do weaving
214                 final List<ConcreteTypeMunger> typeMungers = factory.getTypeMungers();
215
216                 final List<DeclareParents> declareParents = factory.getDeclareParents();
217                 final List<DeclareAnnotation> declareAnnotationOnTypes = factory.getDeclareAnnotationOnTypes();
218
219                 doPendingWeaves();
220
221                 // We now have some list of types to process, and we are about to apply
222                 // the type mungers.
223                 // There can be situations where the order of types passed to the
224                 // compiler causes the
225                 // output from the compiler to vary - THIS IS BAD. For example, if we
226                 // have class A
227                 // and class B extends A. Also, an aspect that 'declare parents: A+
228                 // implements Serializable'
229                 // then depending on whether we see A first, we may or may not make B
230                 // serializable.
231
232                 // The fix is to process them in the right order, ensuring that for a
233                 // type we process its
234                 // supertypes and superinterfaces first. This algorithm may have
235                 // problems with:
236                 // - partial hierarchies (e.g. suppose types A,B,C are in a hierarchy
237                 // and A and C are to be woven but not B)
238                 // - weaving that brings new types in for processing (see
239                 // pendingTypesToWeave.add() calls) after we thought
240                 // we had the full list.
241                 //
242                 // but these aren't common cases (he bravely said...)
243                 boolean typeProcessingOrderIsImportant = declareParents.size() > 0 || declareAnnotationOnTypes.size() > 0; // DECAT
244
245                 if (typeProcessingOrderIsImportant) {
246                         typesToProcess = new ArrayList<>();
247                         for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
248                                 CompilationUnitScope cus = units[i].scope;
249                                 SourceTypeBinding[] stbs = cus.topLevelTypes;
250                                 Collections.addAll(typesToProcess, stbs);
251                         }
252
253                         List<SourceTypeBinding> stb2 = new ArrayList<>();
254                         stb2.addAll(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 (Object o : dangerousInterfaces.entrySet()) {
704                                 Map.Entry entry = (Map.Entry) o;
705                                 ResolvedType interfaceType = (ResolvedType) entry.getKey();
706                                 if (onType.isTopmostImplementor(interfaceType)) {
707                                         factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null);
708                                 }
709                         }
710
711                         boolean needOldStyleWarning = (info != null && info.isOldStyle());
712
713                         onType.clearInterTypeMungers();
714                         onType.ensureConsistent();
715
716                         // FIXME asc perf Could optimize here, after processing the expected set
717                         // of types we may bring
718                         // binary types that are not exposed to the weaver, there is no need to
719                         // attempt declare parents
720                         // or declare annotation really - unless we want to report the
721                         // not-exposed to weaver
722                         // messages...
723
724                         List<DeclareParents> decpToRepeat = new ArrayList<>();
725                         List<DeclareAnnotation> decaToRepeat = new ArrayList<>();
726                         boolean anyNewParents = false;
727                         boolean anyNewAnnotations = false;
728
729                         // first pass
730                         // try and apply all decps - if they match, then great. If they don't
731                         // then
732                         // check if they are starred-annotation patterns. If they are not
733                         // starred
734                         // annotation patterns then they might match later...remember that...
735                         for (DeclareParents decp : declareParents) {
736                                 if (!decp.isMixin()) {
737                                         boolean didSomething = doDeclareParents(decp, sourceType);
738                                         if (didSomething) {
739                                                 if (factory.pushinCollector != null) {
740                                                         factory.pushinCollector.tagAsMunged(sourceType, decp.getParents().get(0));
741                                                 }
742                                                 anyNewParents = true;
743                                         } else {
744                                                 if (!decp.getChild().isStarAnnotation()) {
745                                                         decpToRepeat.add(decp);
746                                                 }
747                                         }
748                                 }
749                         }
750
751                         for (DeclareAnnotation deca : declareAnnotationOnTypes) {
752                                 boolean didSomething = doDeclareAnnotations(deca, sourceType, true);
753                                 if (didSomething) {
754                                         anyNewAnnotations = true;
755                                 } else {
756                                         if (!deca.getTypePattern().isStar()) {
757                                                 decaToRepeat.add(deca);
758                                         }
759                                 }
760                         }
761
762                         List<Object> forRemoval = new ArrayList<>();
763                         // now lets loop over and over until we have done all we can
764                         while ((anyNewAnnotations || anyNewParents) && (!decpToRepeat.isEmpty() || !decaToRepeat.isEmpty())) {
765                                 anyNewParents = anyNewAnnotations = false;
766                                 forRemoval.clear();
767                                 for (DeclareParents decp : decpToRepeat) {
768                                         boolean didSomething = doDeclareParents(decp, sourceType);
769                                         if (didSomething) {
770                                                 if (factory.pushinCollector != null) {
771                                                         factory.pushinCollector.tagAsMunged(sourceType, decp.getParents().get(0));
772                                                 }
773                                                 anyNewParents = true;
774                                                 forRemoval.add(decp);
775                                         }
776                                 }
777                                 decpToRepeat.removeAll(forRemoval);
778
779                                 forRemoval.clear();
780                                 for (DeclareAnnotation deca : decaToRepeat) {
781                                         boolean didSomething = doDeclareAnnotations(deca, sourceType, false);
782                                         if (didSomething) {
783                                                 if (factory.pushinCollector != null) {
784                                                         factory.pushinCollector.tagAsMunged(sourceType, deca.getAnnotationString());
785                                                 }
786                                                 anyNewAnnotations = true;
787                                                 forRemoval.add(deca);
788                                         }
789                                 }
790                                 decaToRepeat.removeAll(forRemoval);
791                         }
792                 }
793                 if (mode == 0 || mode == 2) {
794                         for (ConcreteTypeMunger typeMunger : typeMungers) {
795                                 EclipseTypeMunger munger = (EclipseTypeMunger) typeMunger;
796                                 if (munger.matches(onType)) {
797                                         // if (needOldStyleWarning) {
798                                         // factory.showMessage(IMessage.WARNING, "The class for " + onType
799                                         // + " should be recompiled with ajc-1.1.1 for best results", onType.getSourceLocation(), null);
800                                         // needOldStyleWarning = false;
801                                         // }
802                                         onType.addInterTypeMunger(munger, true);
803                                         if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.InnerClass) {
804                                                 // Must do these right now, because if we do an ITD member afterwards it may attempt to reference the
805                                                 // type being applied (the call above 'addInterTypeMunger' will fail for these ITDs if it needed
806                                                 // it to be in place)
807                                                 if (munger.munge(sourceType, onType)) {
808                                                         if (factory.pushinCollector != null) {
809                                                                 factory.pushinCollector.tagAsMunged(sourceType, munger.getSourceMethod());
810                                                         }
811                                                 }
812                                         }
813                                 }
814                         }
815
816                         onType.checkInterTypeMungers();
817                         for (ConcreteTypeMunger concreteTypeMunger : onType.getInterTypeMungers()) {
818                                 EclipseTypeMunger munger = (EclipseTypeMunger) concreteTypeMunger;
819                                 if (munger.getMunger() == null || munger.getMunger().getKind() != ResolvedTypeMunger.InnerClass) {
820                                         if (munger.munge(sourceType, onType)) {
821                                                 if (factory.pushinCollector != null) {
822                                                         factory.pushinCollector.tagAsMunged(sourceType, munger.getSourceMethod());
823                                                 }
824                                         }
825                                 }
826                         }
827                 }
828
829                 // Call if you would like to do source weaving of declare
830                 // @method/@constructor
831                 // at source time... no need to do this as it can't impact anything, but
832                 // left here for
833                 // future generations to enjoy. Method source is commented out at the
834                 // end of this module
835                 // doDeclareAnnotationOnMethods();
836
837                 // Call if you would like to do source weaving of declare @field
838                 // at source time... no need to do this as it can't impact anything, but
839                 // left here for
840                 // future generations to enjoy. Method source is commented out at the
841                 // end of this module
842                 // doDeclareAnnotationOnFields();
843
844                 if (skipInners) {
845                         CompilationAndWeavingContext.leavingPhase(tok);
846                         return;
847                 }
848
849                 ReferenceBinding[] memberTypes = sourceType.memberTypes;
850                 for (ReferenceBinding memberType : memberTypes) {
851                         if (memberType instanceof SourceTypeBinding) {
852                                 weaveInterTypeDeclarations((SourceTypeBinding) memberType, typeMungers, declareParents,
853                                                 declareAnnotationOnTypes, false, mode);
854                         }
855                 }
856                 CompilationAndWeavingContext.leavingPhase(tok);
857         }
858
859         /**
860          * Called when we discover we are weaving intertype declarations on some type that has an existing 'WeaverStateInfo' object -
861          * this is typically some previously woven type that has been passed on the inpath.
862          *
863          * sourceType and onType are the 'same type' - the former is the 'Eclipse' version and the latter is the 'Weaver' version.
864          */
865         private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType, ResolvedType onType) {
866                 List<ConcreteTypeMunger> previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType);
867
868                 for (ConcreteTypeMunger m : previouslyAppliedMungers) {
869                         EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m);
870                         if (munger.munge(sourceType, onType)) {
871                                 if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) {
872                                         if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) {
873                                                 dangerousInterfaces
874                                                                 .put(onType, "implementors of " + onType + " must be woven by " + munger.getAspectType());
875                                         }
876                                 }
877                         }
878
879                 }
880         }
881
882         private boolean doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) {
883                 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,
884                                 sourceType.sourceName);
885                 ResolvedType resolvedSourceType = factory.fromEclipse(sourceType);
886                 List<ResolvedType> newParents = declareParents.findMatchingNewParents(resolvedSourceType, false);
887                 if (!newParents.isEmpty()) {
888                         for (ResolvedType parent : newParents) {
889                                 if (dangerousInterfaces.containsKey(parent)) {
890                                         ResolvedType onType = factory.fromEclipse(sourceType);
891                                         factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent),
892                                                         onType.getSourceLocation(), null);
893                                 }
894                                 if (Modifier.isFinal(parent.getModifiers())) {
895                                         factory.showMessage(IMessage.ERROR, "cannot extend final class " + parent.getClassName(),
896                                                         declareParents.getSourceLocation(), null);
897                                 } else {
898                                         // do not actually do it if the type isn't exposed - this
899                                         // will correctly reported as a problem elsewhere
900                                         if (!resolvedSourceType.isExposedToWeaver()) {
901                                                 return false;
902                                         }
903                                         // AsmRelationshipProvider.getDefault().
904                                         // addDeclareParentsRelationship
905                                         // (declareParents.getSourceLocation(),
906                                         // factory.fromEclipse(sourceType), newParents);
907                                         addParent(sourceType, parent);
908                                 }
909                         }
910                         CompilationAndWeavingContext.leavingPhase(tok);
911                         return true;
912                 }
913                 CompilationAndWeavingContext.leavingPhase(tok);
914                 return false;
915         }
916
917         private String stringifyTargets(long bits) {
918                 if ((bits & TagBits.AnnotationTargetMASK) == 0) {
919                         return "";
920                 }
921                 Set<String> s = new HashSet<>();
922                 if ((bits & TagBits.AnnotationForAnnotationType) != 0) {
923                         s.add("ANNOTATION_TYPE");
924                 }
925                 if ((bits & TagBits.AnnotationForConstructor) != 0) {
926                         s.add("CONSTRUCTOR");
927                 }
928                 if ((bits & TagBits.AnnotationForField) != 0) {
929                         s.add("FIELD");
930                 }
931                 if ((bits & TagBits.AnnotationForLocalVariable) != 0) {
932                         s.add("LOCAL_VARIABLE");
933                 }
934                 if ((bits & TagBits.AnnotationForMethod) != 0) {
935                         s.add("METHOD");
936                 }
937                 if ((bits & TagBits.AnnotationForPackage) != 0) {
938                         s.add("PACKAGE");
939                 }
940                 if ((bits & TagBits.AnnotationForParameter) != 0) {
941                         s.add("PARAMETER");
942                 }
943                 if ((bits & TagBits.AnnotationForType) != 0) {
944                         s.add("TYPE");
945                 }
946                 StringBuffer sb = new StringBuffer();
947                 sb.append("{");
948                 for (Iterator<String> iter = s.iterator(); iter.hasNext();) {
949                         String element = iter.next();
950                         sb.append(element);
951                         if (iter.hasNext()) {
952                                 sb.append(",");
953                         }
954                 }
955                 sb.append("}");
956                 return sb.toString();
957         }
958
959         private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) {
960                 ResolvedType rtx = factory.fromEclipse(sourceType);
961                 if (!decA.matches(rtx)) {
962                         return false;
963                 }
964                 if (!rtx.isExposedToWeaver()) {
965                         return false;
966                 }
967
968                 ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS,
969                                 sourceType.sourceName);
970
971                 // Get the annotation specified in the declare
972                 UnresolvedType aspectType = decA.getAspect();
973                 if (aspectType instanceof ReferenceType) {
974                         ReferenceType rt = (ReferenceType) aspectType;
975                         if (rt.isParameterizedType() || rt.isRawType()) {
976                                 aspectType = rt.getGenericType();
977                         }
978                 }
979                 TypeBinding tb = factory.makeTypeBinding(aspectType);
980
981                 // Hideousness follows:
982
983                 // There are multiple situations to consider here and they relate to the
984                 // combinations of
985                 // where the annotation is coming from and where the annotation is going
986                 // to be put:
987                 //
988                 // 1. Straight full build, all from source - the annotation is from a
989                 // dec@type and
990                 // is being put on some type. Both types are real SourceTypeBindings.
991                 // WORKS
992                 // 2. Incremental build, changing the affected type - the annotation is
993                 // from a
994                 // dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and
995                 // the
996                 // affected type is a real SourceTypeBinding. Mostly works (pr128665)
997                 // 3. ?
998
999                 SourceTypeBinding stb = (SourceTypeBinding) tb;
1000                 Annotation[] toAdd = null;
1001                 long abits = 0;
1002
1003                 AbstractMethodDeclaration methodDecl = null;
1004                 // Might have to retrieve the annotation through BCEL and construct an
1005                 // eclipse one for it.
1006                 if (stb instanceof BinaryTypeBinding) {
1007                         toAdd = retrieveAnnotationFromBinaryTypeBinding(decA, stb);
1008                         if (toAdd != null && toAdd.length > 0 && toAdd[0].resolvedType != null) {
1009                                 abits = toAdd[0].resolvedType.getAnnotationTagBits();
1010                         }
1011                 } else if (stb != null) {
1012                         // much nicer, its a real SourceTypeBinding so we can stay in
1013                         // eclipse land
1014                         // if (decA.getAnnotationMethod() != null) {
1015                         char[] declareSelector = decA.getAnnotationMethod().toCharArray();
1016
1017                         ReferenceBinding rb = stb;
1018                         String declaringAspectName = decA.getDeclaringType().getRawName();
1019                         while (rb != null && !new String(CharOperation.concatWith(rb.compoundName, '.')).equals(declaringAspectName)) {
1020                                 rb = rb.superclass();
1021                         }
1022                         MethodBinding[] mbs = rb.getMethods(declareSelector);
1023
1024                         ReferenceBinding declaringBinding = mbs[0].declaringClass;
1025                         if (declaringBinding instanceof ParameterizedTypeBinding) {
1026                                 // Unwrap - this means we don't allow the type of the annotation to be parameterized, may need to revisit that
1027                                 declaringBinding = ((ParameterizedTypeBinding) declaringBinding).type;
1028                         }
1029                         if (declaringBinding instanceof BinaryTypeBinding) {
1030                                 toAdd = retrieveAnnotationFromBinaryTypeBinding(decA, declaringBinding);
1031                                 if (toAdd != null && toAdd.length > 0 && toAdd[0].resolvedType != null) {
1032                                         abits = toAdd[0].resolvedType.getAnnotationTagBits();
1033                                 }
1034                         } else {
1035                                 abits = mbs[0].getAnnotationTagBits(); // ensure resolved
1036                                 TypeDeclaration typeDecl = ((SourceTypeBinding) declaringBinding).scope.referenceContext;
1037                                 methodDecl = typeDecl.declarationOf(mbs[0]);
1038                                 toAdd = methodDecl.annotations; // this is what to add
1039                                 toAdd[0] = createAnnotationCopy(toAdd[0]);
1040                                 if (toAdd[0].resolvedType != null) {
1041                                         abits = toAdd[0].resolvedType.getAnnotationTagBits();
1042                                         // }
1043                                 }
1044                         }
1045                 }
1046
1047                 // This happens if there is another error in the code - that should be reported separately
1048                 if (toAdd == null || toAdd[0] == null || toAdd[0].type == null) {
1049                         CompilationAndWeavingContext.leavingPhase(tok);
1050                         return false;
1051                 }
1052                 if (sourceType instanceof BinaryTypeBinding) {
1053                         // In this case we can't access the source type binding to add a new
1054                         // annotation, so let's put something
1055                         // on the weaver type temporarily
1056                         ResolvedType theTargetType = factory.fromEclipse(sourceType);
1057                         TypeBinding theAnnotationType = toAdd[0].resolvedType;
1058                         // The annotation type may be null if it could not be resolved (eg. the relevant import has not been added yet)
1059                         // In this case an error will be put out about the annotation but not if we crash here
1060                         if (theAnnotationType == null) {
1061                                 return false;
1062                         }
1063                         String sig = new String(theAnnotationType.signature());
1064                         UnresolvedType bcelAnnotationType = UnresolvedType.forSignature(sig);
1065                         String name = bcelAnnotationType.getName();
1066                         if (theTargetType.hasAnnotation(bcelAnnotationType)) {
1067                                 CompilationAndWeavingContext.leavingPhase(tok);
1068                                 return false;
1069                         }
1070
1071                         // FIXME asc tidy up this code that duplicates whats below!
1072                         // Simple checks on the bits
1073                         boolean giveupnow = false;
1074                         if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
1075                                 if (isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) {
1076                                         // error will have been already reported
1077                                         giveupnow = true;
1078                                 } else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
1079                                                 || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
1080
1081                                         if (reportProblems) {
1082                                                 if (decA.isExactPattern()) {
1083                                                         factory.showMessage(IMessage.ERROR, WeaverMessages.format(
1084                                                                         WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
1085                                                                         stringifyTargets(abits)), decA.getSourceLocation(), null);
1086                                                 }
1087                                                 // dont put out the lint - the weaving process will do
1088                                                 // that
1089                                                 // else {
1090                                                 // if (factory.getWorld().getLint().
1091                                                 // invalidTargetForAnnotation.isEnabled()) {
1092                                                 // factory.getWorld().getLint().invalidTargetForAnnotation
1093                                                 // .signal(new
1094                                                 // String[]{rtx.getName(),toAdd[0].type.toString(),
1095                                                 // stringifyTargets
1096                                                 // (abits)},decA.getSourceLocation(),null);
1097                                                 // }
1098                                                 // }
1099                                         }
1100                                         giveupnow = true;
1101                                 }
1102                         }
1103                         if (giveupnow) {
1104                                 CompilationAndWeavingContext.leavingPhase(tok);
1105                                 return false;
1106                         }
1107
1108                         theTargetType.addAnnotation(new BcelAnnotation(new FakeAnnotation(name, sig,
1109                                         (abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld()));
1110                         CompilationAndWeavingContext.leavingPhase(tok);
1111                         return true;
1112                 }
1113
1114                 Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations;
1115                 if (currentAnnotations != null) {
1116                         for (Annotation annotation : currentAnnotations) {
1117                                 String a = CharOperation.toString(annotation.type.getTypeName());
1118                                 String b = CharOperation.toString(toAdd[0].type.getTypeName());
1119                                 // FIXME asc we have a lint for attempting to add an annotation
1120                                 // twice to a method,
1121                                 // we could put it out here *if* we can resolve the problem of
1122                                 // errors coming out
1123                                 // multiple times if we have cause to loop through here
1124                                 if (a.equals(b)) {
1125                                         CompilationAndWeavingContext.leavingPhase(tok);
1126                                         return false;
1127                                 }
1128                         }
1129                 }
1130
1131                 if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
1132                         if ((abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0) {
1133                                 // this means it specifies something other than annotation or
1134                                 // normal type - error will have been already reported,
1135                                 // just resolution process above
1136                                 CompilationAndWeavingContext.leavingPhase(tok);
1137                                 return false;
1138                         }
1139                         if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
1140                                         || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
1141
1142                                 if (reportProblems) {
1143                                         if (decA.isExactPattern()) {
1144                                                 factory.showMessage(IMessage.ERROR, WeaverMessages.format(
1145                                                                 WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
1146                                                                 stringifyTargets(abits)), decA.getSourceLocation(), null);
1147                                         }
1148                                         // dont put out the lint - the weaving process will do that
1149                                         // else {
1150                                         // if
1151                                         // (factory.getWorld().getLint().invalidTargetForAnnotation
1152                                         // .isEnabled()) {
1153                                         // factory.getWorld().getLint().invalidTargetForAnnotation.
1154                                         // signal(new
1155                                         // String[]{rtx.getName(),toAdd[0].type.toString(),
1156                                         // stringifyTargets(abits)},decA.getSourceLocation(),null);
1157                                         // }
1158                                         // }
1159                                 }
1160                                 CompilationAndWeavingContext.leavingPhase(tok);
1161                                 return false;
1162                         }
1163                 }
1164
1165                 // Build a new array of annotations
1166
1167                 // remember the current set (rememberAnnotations only does something the
1168                 // first time it is called for a type)
1169                 sourceType.scope.referenceContext.rememberAnnotations();
1170
1171                 // AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(
1172                 // decA.getSourceLocation(), rtx.getSourceLocation());
1173                 final Annotation[] abefore = sourceType.scope.referenceContext.annotations;
1174                 final Annotation[] newset = new Annotation[toAdd.length + (abefore == null ? 0 : abefore.length)];
1175                 System.arraycopy(toAdd, 0, newset, 0, toAdd.length);
1176                 if (abefore != null) {
1177                         System.arraycopy(abefore, 0, newset, toAdd.length, abefore.length);
1178                 }
1179                 sourceType.scope.referenceContext.annotations = newset;
1180                 if ((sourceType.tagBits & TagBits.AnnotationResolved)!=0) {
1181                         sourceType.tagBits = sourceType.tagBits - TagBits.AnnotationResolved;
1182                 }
1183                 CompilationAndWeavingContext.leavingPhase(tok);
1184                 if (factory.pushinCollector != null) {
1185                         factory.pushinCollector.tagAsMunged(sourceType, new CommonPrinter((methodDecl == null ? null : methodDecl.scope))
1186                                         .printAnnotation(toAdd[0]).toString());
1187                 }
1188                 return true;
1189         }
1190
1191         private Annotation[] retrieveAnnotationFromBinaryTypeBinding(DeclareAnnotation decA, ReferenceBinding declaringBinding) {
1192                 ReferenceType rt = (ReferenceType) factory.fromEclipse(declaringBinding);
1193                 ResolvedMember[] methods = rt.getDeclaredMethods();
1194                 ResolvedMember decaMethod = null;
1195                 String nameToLookFor = decA.getAnnotationMethod();
1196                 for (ResolvedMember method : methods) {
1197                         if (method.getName().equals(nameToLookFor)) {
1198                                 decaMethod = method;
1199                                 break;
1200                         }
1201                 }
1202                 if (decaMethod != null) { // could assert this ...
1203                         AnnotationAJ[] axs = decaMethod.getAnnotations();
1204                         if (axs != null) { // another error has occurred, dont crash here because of it
1205                                 Annotation[] toAdd = new Annotation[1];
1206                                 toAdd[0] = createAnnotationFromBcelAnnotation(axs[0], decaMethod.getSourceLocation().getOffset(), factory);
1207                                 // BUG BUG BUG - We dont test these abits are correct, in fact
1208                                 // we'll be very lucky if they are.
1209                                 // What does that mean? It means on an incremental compile you
1210                                 // might get away with an
1211                                 // annotation that isn't allowed on a type being put on a type.
1212                                 // if (toAdd[0].resolvedType != null) {
1213                                 // abits = toAdd[0].resolvedType.getAnnotationTagBits();
1214                                 // }
1215                                 return toAdd;
1216                         }
1217                 }
1218                 return null;
1219         }
1220
1221         /**
1222          * Transform an annotation from its AJ form to an eclipse form. We *DONT* care about the values of the annotation. that is
1223          * because it is only being stuck on a type during type completion to allow for other constructs (decps, decas) that might be
1224          * looking for it - when the class actually gets to disk it wont have this new annotation on it and during weave time we will do
1225          * the right thing copying across values too.
1226          */
1227         private static Annotation createAnnotationFromBcelAnnotation(AnnotationAJ annX, int pos, EclipseFactory factory) {
1228                 String name = annX.getTypeName();
1229                 TypeBinding tb = factory.makeTypeBinding(annX.getType());
1230                 // String theName = annX.getSignature().getBaseName();
1231                 char[][] typeName = CharOperation.splitOn('.', name.replace('$', '.').toCharArray()); // pr149293 - not bulletproof...
1232                 long[] positions = new long[typeName.length];
1233                 for (int i = 0; i < positions.length; i++) {
1234                         positions[i] = pos;
1235                 }
1236                 TypeReference annType = new QualifiedTypeReference(typeName, positions);
1237                 NormalAnnotation ann = new NormalAnnotation(annType, pos);
1238                 ann.resolvedType = tb; // yuck - is this OK in all cases?
1239                 // We don't need membervalues...
1240                 // Expression pcExpr = new
1241                 // StringLiteral(pointcutExpression.toCharArray(),pos,pos);
1242                 // MemberValuePair[] mvps = new MemberValuePair[2];
1243                 // mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr);
1244                 // Expression argNamesExpr = new
1245                 // StringLiteral(argNames.toCharArray(),pos,pos);
1246                 // mvps[1] = new
1247                 // MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
1248                 // ann.memberValuePairs = mvps;
1249                 return ann;
1250         }
1251
1252         /**
1253          * Create a copy of an annotation, not deep but deep enough so we don't copy across fields that will get us into trouble like
1254          * 'recipient'
1255          */
1256         private static Annotation createAnnotationCopy(Annotation ann) {
1257                 NormalAnnotation ann2 = new NormalAnnotation(ann.type, ann.sourceStart);
1258                 ann2.memberValuePairs = ann.memberValuePairs();
1259                 ann2.resolvedType = ann.resolvedType;
1260                 ann2.bits = ann.bits;
1261                 return ann2;
1262                 // String name = annX.getTypeName();
1263                 // TypeBinding tb = factory.makeTypeBinding(annX.getSignature());
1264                 // String theName = annX.getSignature().getBaseName();
1265                 // char[][] typeName =
1266                 // CharOperation.splitOn('.',name.replace('$','.').toCharArray());
1267                 // //pr149293 - not bulletproof...
1268                 // long[] positions = new long[typeName.length];
1269                 // for (int i = 0; i < positions.length; i++) positions[i]=pos;
1270                 // TypeReference annType = new
1271                 // QualifiedTypeReference(typeName,positions);
1272                 // NormalAnnotation ann = new NormalAnnotation(annType,pos);
1273                 // ann.resolvedType=tb; // yuck - is this OK in all cases?
1274                 // // We don't need membervalues...
1275                 // // Expression pcExpr = new
1276                 // StringLiteral(pointcutExpression.toCharArray(),pos,pos);
1277                 // // MemberValuePair[] mvps = new MemberValuePair[2];
1278                 // // mvps[0] = new
1279                 // MemberValuePair("value".toCharArray(),pos,pos,pcExpr);
1280                 // // Expression argNamesExpr = new
1281                 // StringLiteral(argNames.toCharArray(),pos,pos);
1282                 // // mvps[1] = new
1283                 // MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
1284                 // // ann.memberValuePairs = mvps;
1285                 // return ann;
1286         }
1287
1288         private boolean isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(long abits) {
1289                 return (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0;
1290         }
1291
1292 //      private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk, SourceTypeBinding sourceType, ResolvedType parent) {
1293 //              if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
1294 //                      String filename = new String(sourceType.getFileName());
1295 //
1296 //                      int takefrom = filename.lastIndexOf('/');
1297 //                      if (takefrom == -1) {
1298 //                              takefrom = filename.lastIndexOf('\\');
1299 //                      }
1300 //                      filename = filename.substring(takefrom + 1);
1301 //
1302 //                      factory.getWorld()
1303 //                                      .getMessageHandler()
1304 //                                      .handleMessage(
1305 //                                                      WeaveMessage.constructWeavingMessage(wmk,
1306 //                                                                      new String[] { CharOperation.toString(sourceType.compoundName), filename,
1307 //                                                                                      parent.getClassName(),
1308 //                                                                                      getShortname(parent.getSourceLocation().getSourceFile().getPath()) }));
1309 //              }
1310 //      }
1311
1312 //      private String getShortname(String path) {
1313 //              int takefrom = path.lastIndexOf('/');
1314 //              if (takefrom == -1) {
1315 //                      takefrom = path.lastIndexOf('\\');
1316 //              }
1317 //              return path.substring(takefrom + 1);
1318 //      }
1319
1320         private void addParent(SourceTypeBinding sourceType, ResolvedType parent) {
1321                 ReferenceBinding parentBinding = (ReferenceBinding) factory.makeTypeBinding(parent);
1322                 if (parentBinding == null) {
1323                         return; // The parent is missing, it will be reported elsewhere.
1324                 }
1325                 // Due to e37 switching to MethodVerifier15 for everything, it is important added types are correctly
1326                 // raw or not.  For example, if Comparable is used in generic form compareTo(T) will be used to check
1327                 // methods against in the verifier rather than compareTo(Object)
1328                 if (!factory.getWorld().isInJava5Mode()) {
1329                         parentBinding = (ReferenceBinding)convertToRawType(parentBinding, false /*do not force conversion of enclosing types*/);
1330                 } else if (sourceType.isGenericType()) {
1331                         RawTypeBinding rawTargetType = (RawTypeBinding)convertToRawType(sourceType, false);
1332                         if (rawTargetType != null) {
1333                                 // assert: don't need to 'rememberTypeHierarchy' because the class file is constructed based on the generic type
1334                                 if (parentBinding.isClass()) {
1335                                         rawTargetType.superclass = parentBinding;
1336                                 } else {
1337                                         ReferenceBinding[] oldI = rawTargetType.superInterfaces;
1338                                         ReferenceBinding[] newI;
1339                                         if (oldI == null) {
1340                                                 newI = new ReferenceBinding[1];
1341                                                 newI[0] = parentBinding;
1342                                         } else {
1343                                                 int n = oldI.length;
1344                                                 newI = new ReferenceBinding[n + 1];
1345                                                 System.arraycopy(oldI, 0, newI, 0, n);
1346                                                 newI[n] = parentBinding;
1347                                         }
1348                                         rawTargetType.superInterfaces = newI;
1349                                 }
1350                         }
1351                         // TODO what about parameterized types?
1352                 }
1353                 sourceType.rememberTypeHierarchy();
1354                 if (parentBinding.isClass()) {
1355                         sourceType.superclass = parentBinding;
1356
1357                         // this used to be true, but I think I've fixed it now, decp is done
1358                         // at weave time!
1359                         // TAG: WeavingMessage DECLARE PARENTS: EXTENDS
1360                         // Compiler restriction: Can't do EXTENDS at weave time
1361                         // So, only see this message if doing a source compilation
1362                         // reportDeclareParentsMessage(WeaveMessage.
1363                         // WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent);
1364
1365                 } else {
1366                         ReferenceBinding[] oldI = sourceType.superInterfaces;
1367                         ReferenceBinding[] newI;
1368                         if (oldI == null) {
1369                                 newI = new ReferenceBinding[1];
1370                                 newI[0] = parentBinding;
1371                         } else {
1372                                 int n = oldI.length;
1373                                 newI = new ReferenceBinding[n + 1];
1374                                 System.arraycopy(oldI, 0, newI, 0, n);
1375                                 newI[n] = parentBinding;
1376                         }
1377                         sourceType.superInterfaces = newI;
1378                         // warnOnAddedInterface(factory.fromEclipse(sourceType),parent); //
1379                         // now reported at weave time...
1380
1381                         // this used to be true, but I think I've fixed it now, decp is done
1382                         // at weave time!
1383                         // TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS
1384                         // This message will come out of BcelTypeMunger.munge if doing a
1385                         // binary weave
1386                         // reportDeclareParentsMessage(WeaveMessage.
1387                         // WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent);
1388
1389                 }
1390
1391                 // also add it to the bcel delegate if there is one
1392                 if (sourceType instanceof BinaryTypeBinding) {
1393                         ResolvedType onType = factory.fromEclipse(sourceType);
1394                         ReferenceType rt = (ReferenceType) onType;
1395                         ReferenceTypeDelegate rtd = rt.getDelegate();
1396                         if (rtd instanceof BcelObjectType) {
1397                                 if (rt.isRawType()) {
1398                                         rt = rt.getGenericType();
1399                                 }
1400                                 rt.addParent(parent);
1401                                 // ((BcelObjectType) rtd).addParent(parent);
1402                         }
1403                 }
1404
1405         }
1406
1407         public void warnOnAddedInterface(ResolvedType type, ResolvedType parent) {
1408                 World world = factory.getWorld();
1409                 ResolvedType serializable = world.getCoreType(UnresolvedType.SERIALIZABLE);
1410                 if (serializable.isAssignableFrom(type) && !serializable.isAssignableFrom(parent)
1411                                 && !LazyClassGen.hasSerialVersionUIDField(type)) {
1412                         world.getLint().needsSerialVersionUIDField.signal(new String[] { type.getName().toString(),
1413                                         "added interface " + parent.getName().toString() }, null, null);
1414                 }
1415         }
1416
1417         private final List pendingTypesToFinish = new ArrayList();
1418         boolean inBinaryTypeCreationAndWeaving = false;
1419         boolean processingTheQueue = false;
1420
1421         @Override
1422         public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding,
1423                         boolean needFieldsAndMethods, AccessRestriction accessRestriction) {
1424
1425                 if (inBinaryTypeCreationAndWeaving) {
1426                         BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction);
1427                         pendingTypesToFinish.add(ret);
1428                         return ret;
1429                 }
1430
1431                 inBinaryTypeCreationAndWeaving = true;
1432                 try {
1433                         BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction);
1434                         factory.getWorld().validateType(factory.fromBinding(ret));
1435                         // if you need the bytes to pass to validate, here they
1436                         // are:((ClassFileReader)binaryType).getReferenceBytes()
1437                         weaveInterTypeDeclarations(ret);
1438                         return ret;
1439                 } finally {
1440                         inBinaryTypeCreationAndWeaving = false;
1441
1442                         // Start processing the list...
1443                         if (pendingTypesToFinish.size() > 0) {
1444                                 processingTheQueue = true;
1445                                 while (!pendingTypesToFinish.isEmpty()) {
1446                                         BinaryTypeBinding nextVictim = (BinaryTypeBinding) pendingTypesToFinish.remove(0);
1447                                         // During this call we may recurse into this method and add
1448                                         // more entries to the pendingTypesToFinish list.
1449                                         weaveInterTypeDeclarations(nextVictim);
1450                                 }
1451                                 processingTheQueue = false;
1452                         }
1453                 }
1454         }
1455
1456         /**
1457          * Callback driven when the compiler detects an anonymous type during block resolution. We need to add it to the weaver so that
1458          * we don't trip up later.
1459          *
1460          * @param aBinding
1461          */
1462         @Override
1463         public void anonymousTypeBindingCreated(LocalTypeBinding aBinding) {
1464                 factory.addSourceTypeBinding(aBinding, null);
1465         }
1466
1467   @Override
1468   public void buildTypeBindings(CompilationUnitDeclaration unit, AccessRestriction accessRestriction) {
1469     if (this.isProcessingAnnotations && hasAspectDeclarations(unit)) {
1470       throw new SourceTypeCollisionException();
1471     }
1472     super.buildTypeBindings(unit, accessRestriction);
1473   }
1474
1475   private static boolean hasAspectDeclarations(CompilationUnitDeclaration unit) {
1476     for (int j = 0; j < unit.types.length; j++) {
1477       if (unit.types[j] instanceof AspectDeclaration) {
1478         return true;
1479       }
1480     }
1481     return false;
1482   }
1483
1484   @Override
1485   public void reset() {
1486     this.factory.cleanup();
1487     super.reset();
1488   }
1489   
1490   @Override
1491 public LookupEnvironment wrapInModuleEnvironment(ModuleBinding moduleBinding) {
1492           AjLookupEnvironment newAjLookupEnvironment = new AjLookupEnvironment(this, moduleBinding);
1493           newAjLookupEnvironment.factory = this.factory;
1494           return newAjLookupEnvironment;
1495   }
1496 }
1497
1498 // commented out, supplied as info on how to manipulate annotations in an
1499 // eclipse world
1500 //
1501 // public void doDeclareAnnotationOnMethods() {
1502 // Do the declare annotation on fields/methods/ctors
1503 // Collection daoms = factory.getDeclareAnnotationOnMethods();
1504 // if (daoms!=null && daoms.size()>0 && !(sourceType instanceof
1505 // BinaryTypeBinding)) {
1506 // System.err.println("Going through the methods on "+sourceType.debugName()+
1507 // " looking for DECA matches");
1508 // // We better take a look through them...
1509 // for (Iterator iter = daoms.iterator(); iter.hasNext();) {
1510 // DeclareAnnotation element = (DeclareAnnotation) iter.next();
1511 // System.err.println("Looking for anything that might match "+element+" on "+
1512 // sourceType.debugName()+"  "+getType(sourceType.
1513 // compoundName).debugName()+"  "+(sourceType instanceof BinaryTypeBinding));
1514 //
1515 // ReferenceBinding rbb = getType(sourceType.compoundName);
1516 // // fix me if we ever uncomment this code... should iterate the other way
1517 // round, over the methods then over the decas
1518 // sourceType.methods();
1519 // MethodBinding sourceMbs[] = sourceType.methods;
1520 // for (int i = 0; i < sourceMbs.length; i++) {
1521 // MethodBinding sourceMb = sourceMbs[i];
1522 // MethodBinding mbbbb =
1523 // ((SourceTypeBinding)rbb).getExactMethod(sourceMb.selector
1524 // ,sourceMb.parameters);
1525 // boolean isCtor = sourceMb.selector[0]=='<';
1526 //
1527 // if ((element.isDeclareAtConstuctor() ^ !isCtor)) {
1528 // System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb.
1529 // declaringClass.debugName()+" rbb="+rbb.debugName()+"  "+
1530 // sourceMb.declaringClass.equals(rbb));
1531 //
1532 // ResolvedMember rm = null;
1533 // rm = EclipseFactory.makeResolvedMember(mbbbb);
1534 // if (element.matches(rm,factory.getWorld())) {
1535 // System.err.println("MATCH");
1536 //
1537 // // Determine the set of annotations that are currently on the method
1538 // ReferenceBinding rb = getType(sourceType.compoundName);
1539 // // TypeBinding tb = factory.makeTypeBinding(decA.getAspect());
1540 // MethodBinding mb =
1541 // ((SourceTypeBinding)rb).getExactMethod(sourceMb.selector,sourceMb
1542 // .parameters);
1543 // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved
1544 // TypeDeclaration typeDecl =
1545 // ((SourceTypeBinding)sourceMb.declaringClass).scope.referenceContext;
1546 // AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb);
1547 // Annotation[] currentlyHas = methodDecl.annotations; // this is what to add
1548 // //abits = toAdd[0].resolvedType.getAnnotationTagBits();
1549 //
1550 // // Determine the annotations to add to that method
1551 // TypeBinding tb = factory.makeTypeBinding(element.getAspect());
1552 // MethodBinding[] aspectMbs =
1553 // ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod
1554 // ().toCharArray());
1555 // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved
1556 // TypeDeclaration typeDecl2 =
1557 // ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext;
1558 // AbstractMethodDeclaration methodDecl2 =
1559 // typeDecl2.declarationOf(aspectMbs[0]);
1560 // Annotation[] toAdd = methodDecl2.annotations; // this is what to add
1561 // // abits = toAdd[0].resolvedType.getAnnotationTagBits();
1562 // System.err.println("Has: "+currentlyHas+"    toAdd: "+toAdd);
1563 //
1564 // // fix me? should check if it already has the annotation
1565 // //Annotation abefore[] = sourceType.scope.referenceContext.annotations;
1566 // Annotation[] newset = new
1567 // Annotation[(currentlyHas==null?0:currentlyHas.length)+1];
1568 // System.arraycopy(toAdd,0,newset,0,toAdd.length);
1569 // if (currentlyHas!=null) {
1570 // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length);
1571 // }
1572 // methodDecl.annotations = newset;
1573 // System.err.println("New set on "+CharOperation.charToString(sourceMb.selector)
1574 // +" is "+newset);
1575 // } else
1576 // System.err.println("NO MATCH");
1577 // }
1578 // }
1579 // }
1580 // }
1581 // }
1582
1583 // commented out, supplied as info on how to manipulate annotations in an
1584 // eclipse world
1585 //
1586 // public void doDeclareAnnotationOnFields() {
1587 // Collection daofs = factory.getDeclareAnnotationOnFields();
1588 // if (daofs!=null && daofs.size()>0 && !(sourceType instanceof
1589 // BinaryTypeBinding)) {
1590 // System.err.println("Going through the fields on "+sourceType.debugName()+
1591 // " looking for DECA matches");
1592 // // We better take a look through them...
1593 // for (Iterator iter = daofs.iterator(); iter.hasNext();) {
1594 // DeclareAnnotation element = (DeclareAnnotation) iter.next();
1595 // System.err.println("Processing deca "+element+" on "+sourceType.debugName()+
1596 // "  "+getType(sourceType.compoundName).debugName()+"  "
1597 // +(sourceType instanceof BinaryTypeBinding));
1598 //
1599 // ReferenceBinding rbb = getType(sourceType.compoundName);
1600 // // fix me? should iterate the other way round, over the methods then over the
1601 // decas
1602 // sourceType.fields(); // resolve the bloody things
1603 // FieldBinding sourceFbs[] = sourceType.fields;
1604 // for (int i = 0; i < sourceFbs.length; i++) {
1605 // FieldBinding sourceFb = sourceFbs[i];
1606 // //FieldBinding fbbbb =
1607 // ((SourceTypeBinding)rbb).getgetExactMethod(sourceMb.selector
1608 // ,sourceMb.parameters);
1609 //
1610 // System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb.
1611 // declaringClass.debugName()+" rbb="+rbb.debugName());
1612 //
1613 // ResolvedMember rm = null;
1614 // rm = EclipseFactory.makeResolvedMember(sourceFb);
1615 // if (element.matches(rm,factory.getWorld())) {
1616 // System.err.println("MATCH");
1617 //
1618 // // Determine the set of annotations that are currently on the field
1619 // ReferenceBinding rb = getType(sourceType.compoundName);
1620 // // TypeBinding tb = factory.makeTypeBinding(decA.getAspect());
1621 // FieldBinding fb = ((SourceTypeBinding)rb).getField(sourceFb.name,true);
1622 // //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved
1623 // TypeDeclaration typeDecl =
1624 // ((SourceTypeBinding)sourceFb.declaringClass).scope.referenceContext;
1625 // FieldDeclaration fd = typeDecl.declarationOf(sourceFb);
1626 // //AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb);
1627 // Annotation[] currentlyHas = fd.annotations; // this is what to add
1628 // //abits = toAdd[0].resolvedType.getAnnotationTagBits();
1629 //
1630 // // Determine the annotations to add to that method
1631 // TypeBinding tb = factory.makeTypeBinding(element.getAspect());
1632 // MethodBinding[] aspectMbs =
1633 // ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod
1634 // ().toCharArray());
1635 // long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved
1636 // TypeDeclaration typeDecl2 =
1637 // ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext;
1638 // AbstractMethodDeclaration methodDecl2 =
1639 // typeDecl2.declarationOf(aspectMbs[0]);
1640 // Annotation[] toAdd = methodDecl2.annotations; // this is what to add
1641 // // abits = toAdd[0].resolvedType.getAnnotationTagBits();
1642 // System.err.println("Has: "+currentlyHas+"    toAdd: "+toAdd);
1643 //
1644 // // fix me? check if it already has the annotation
1645 //
1646 //
1647 // //Annotation abefore[] = sourceType.scope.referenceContext.annotations;
1648 // Annotation[] newset = new
1649 // Annotation[(currentlyHas==null?0:currentlyHas.length)+1];
1650 // System.arraycopy(toAdd,0,newset,0,toAdd.length);
1651 // if (currentlyHas!=null) {
1652 // System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length);
1653 // }
1654 // fd.annotations = newset;
1655 // System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+
1656 // " is "+newset);
1657 // } else
1658 // System.err.println("NO MATCH");
1659 // }
1660 //
1661 // }
1662 // }