From 5fd25b258cce531b2f08c8ad39d062a9e51552f9 Mon Sep 17 00:00:00 2001 From: aclement Date: Thu, 28 Aug 2008 03:08:39 +0000 Subject: [PATCH] fixed eclipse warnings --- .../ast/AddAtAspectJAnnotationsVisitor.java | 38 +- .../compiler/ast/AspectDeclaration.java | 1226 +++++++-------- .../ValidateAtAspectJAnnotationsVisitor.java | 559 ++++--- .../compiler/lookup/AjLookupEnvironment.java | 1393 +++++++++-------- .../lookup/EclipseAnnotationConvertor.java | 131 +- .../compiler/lookup/EclipseFactory.java | 879 +++++------ .../compiler/lookup/EclipseSourceType.java | 830 +++++----- .../lookup/InterTypeMethodBinding.java | 153 +- .../ajdt/internal/core/builder/AjState.java | 60 +- .../core/builder/AsmElementFormatter.java | 332 ++-- .../core/builder/AsmHierarchyBuilder.java | 20 +- .../eclipse/jdt/core/dom/AjASTMatcher.java | 107 +- .../compiler/batch/DeclareParents.java | 127 +- .../org/aspectj/tools/ajc/AjASTTest.java | 12 +- 14 files changed, 2885 insertions(+), 2982 deletions(-) diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AddAtAspectJAnnotationsVisitor.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AddAtAspectJAnnotationsVisitor.java index bc709cc2b..7606ed446 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AddAtAspectJAnnotationsVisitor.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AddAtAspectJAnnotationsVisitor.java @@ -20,58 +20,52 @@ import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; /** - * Adds runtime visible annotations to code-style aspect declarations so that the - * MAP can provide aspect information at runtime. + * Adds runtime visible annotations to code-style aspect declarations so that the MAP can provide aspect information at runtime. * - * Done: - * - AspectDeclaration - * - AdviceDeclaration - * - PointcutDeclaration - * - * To Do: - * - DeclareDeclaration - * - Inter-Type Declaration + * Done: - AspectDeclaration - AdviceDeclaration - PointcutDeclaration + * + * To Do: - DeclareDeclaration - Inter-Type Declaration */ public class AddAtAspectJAnnotationsVisitor extends ASTVisitor { - private CompilationUnitDeclaration unit; - + // private CompilationUnitDeclaration unit; + public AddAtAspectJAnnotationsVisitor(CompilationUnitDeclaration unit) { - this.unit = unit; + // this.unit = unit; } - + public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) { if (localTypeDeclaration instanceof AspectDeclaration) { ((AspectDeclaration) localTypeDeclaration).addAtAspectJAnnotations(); } return true; } - - public boolean visit(TypeDeclaration memberTypeDeclaration,ClassScope scope) { + + public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { if (memberTypeDeclaration instanceof AspectDeclaration) { ((AspectDeclaration) memberTypeDeclaration).addAtAspectJAnnotations(); } return true; } - + public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { if (typeDeclaration instanceof AspectDeclaration) { ((AspectDeclaration) typeDeclaration).addAtAspectJAnnotations(); } return true; } + public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { if (methodDeclaration instanceof AdviceDeclaration) { - ((AdviceDeclaration)methodDeclaration).addAtAspectJAnnotations(); + ((AdviceDeclaration) methodDeclaration).addAtAspectJAnnotations(); } else if (methodDeclaration instanceof PointcutDeclaration) { - ((PointcutDeclaration)methodDeclaration).addAtAspectJAnnotations(); + ((PointcutDeclaration) methodDeclaration).addAtAspectJAnnotations(); } else if (methodDeclaration instanceof DeclareDeclaration) { - ((DeclareDeclaration)methodDeclaration).addAtAspectJAnnotations(); + ((DeclareDeclaration) methodDeclaration).addAtAspectJAnnotations(); } else if (methodDeclaration instanceof InterTypeDeclaration) { - ((InterTypeDeclaration)methodDeclaration).addAtAspectJAnnotations(); + ((InterTypeDeclaration) methodDeclaration).addAtAspectJAnnotations(); } return false; } - } diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java index 3f3eb4a98..7719e213c 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java @@ -10,7 +10,6 @@ * PARC initial implementation * ******************************************************************/ - package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; @@ -64,291 +63,279 @@ import org.aspectj.weaver.patterns.PerFromSuper; import org.aspectj.weaver.patterns.PerSingleton; import org.aspectj.weaver.patterns.TypePattern; - // (we used to...) making all aspects member types avoids a nasty hierarchy pain // switched from MemberTypeDeclaration to TypeDeclaration public class AspectDeclaration extends TypeDeclaration { - //public IAjDeclaration[] ajDeclarations; - - private AjAttribute.Aspect aspectAttribute; + // public IAjDeclaration[] ajDeclarations; + + // private AjAttribute.Aspect aspectAttribute; public PerClause perClause; public ResolvedMember aspectOfMethod; public ResolvedMember ptwGetWithinTypeNameMethod; public ResolvedMember hasAspectMethod; - public Map accessForInline = new HashMap(); public Map superAccessForInline = new HashMap(); - + public boolean isPrivileged; private int declaredModifiers; - + public EclipseSourceType concreteName; - + public ReferenceType typeX; - - public EclipseFactory factory; //??? should use this consistently - public int adviceCounter = 1; // Used as a part of the generated name for advice methods - public int declareCounter= 1; // Used as a part of the generated name for methods representing declares - + public EclipseFactory factory; // ??? should use this consistently + + public int adviceCounter = 1; // Used as a part of the generated name for advice methods + public int declareCounter = 1; // Used as a part of the generated name for methods representing declares + // for better error messages in 1.0 to 1.1 transition public TypePattern dominatesPattern; public AspectDeclaration(CompilationResult compilationResult) { super(compilationResult); - //perClause = new PerSingleton(); + // perClause = new PerSingleton(); } - + public boolean isAbstract() { return (modifiers & ClassFileConstants.AccAbstract) != 0; } - + public void resolve() { declaredModifiers = modifiers; // remember our modifiers, we're going to be public in generateCode if (binding == null) { ignoreFurtherInvestigation = true; return; } - + super.resolve(); } - - + public void checkSpec(ClassScope scope) { - if (ignoreFurtherInvestigation) return; + if (ignoreFurtherInvestigation) + return; if (dominatesPattern != null) { scope.problemReporter().signalError( - dominatesPattern.getStart(), dominatesPattern.getEnd(), - "dominates has changed for 1.1, use 'declare precedence: " + - new String(this.name) + ", " + dominatesPattern.toString() + ";' " + - "in the body of the aspect instead"); + dominatesPattern.getStart(), + dominatesPattern.getEnd(), + "dominates has changed for 1.1, use 'declare precedence: " + new String(this.name) + ", " + + dominatesPattern.toString() + ";' " + "in the body of the aspect instead"); } - + if (!isAbstract()) { MethodBinding[] methods = binding.methods(); - for (int i=0, len = methods.length; i < len; i++) { + for (int i = 0, len = methods.length; i < len; i++) { MethodBinding m = methods[i]; if (m.isConstructor()) { // this make all constructors in aspects invisible and thus uncallable - //XXX this only works for aspects that come from source + // XXX this only works for aspects that come from source methods[i] = new MethodBinding(m, binding) { - public boolean canBeSeenBy( - InvocationSite invocationSite, - Scope scope) { + public boolean canBeSeenBy(InvocationSite invocationSite, Scope scope) { return false; } }; - + if (m.parameters != null && m.parameters.length != 0) { scope.problemReporter().signalError(m.sourceStart(), m.sourceEnd(), "only zero-argument constructors allowed in concrete aspect"); } } } - + // check the aspect was not declared generic, only abstract aspects can have type params if (typeParameters != null && typeParameters.length > 0) { - scope.problemReporter().signalError(sourceStart(), sourceEnd(), - "only abstract aspects can have type parameters"); + scope.problemReporter().signalError(sourceStart(), sourceEnd(), "only abstract aspects can have type parameters"); } } - + if (this.enclosingType != null) { if (!Modifier.isStatic(modifiers)) { - scope.problemReporter().signalError(sourceStart, sourceEnd, - "inner aspects must be static"); + scope.problemReporter().signalError(sourceStart, sourceEnd, "inner aspects must be static"); ignoreFurtherInvestigation = true; - return; + return; } } - - + EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); ResolvedType myType = typeX; - //if (myType == null) System.err.println("bad myType for: " + this); - ResolvedType superType = myType.getSuperclass(); - + // if (myType == null) System.err.println("bad myType for: " + this); + ResolvedType superType = myType.getSuperclass(); + // can't be Serializable/Cloneable unless -XserializableAspects if (!world.isXSerializableAspects()) { if (world.getWorld().getCoreType(UnresolvedType.SERIALIZABLE).isAssignableFrom(myType)) { - scope.problemReporter().signalError(sourceStart, sourceEnd, - "aspects may not implement Serializable"); + scope.problemReporter().signalError(sourceStart, sourceEnd, "aspects may not implement Serializable"); ignoreFurtherInvestigation = true; - return; + return; } if (world.getWorld().getCoreType(UnresolvedType.CLONEABLE).isAssignableFrom(myType)) { - scope.problemReporter().signalError(sourceStart, sourceEnd, - "aspects may not implement Cloneable"); + scope.problemReporter().signalError(sourceStart, sourceEnd, "aspects may not implement Cloneable"); ignoreFurtherInvestigation = true; - return; + return; } } if (superType.isAspect()) { if (!superType.isAbstract()) { - scope.problemReporter().signalError(sourceStart, sourceEnd, - "can not extend a concrete aspect"); + scope.problemReporter().signalError(sourceStart, sourceEnd, "can not extend a concrete aspect"); ignoreFurtherInvestigation = true; return; } - + // if super type is generic, check that we have fully parameterized it if (superType.isRawType()) { scope.problemReporter().signalError(sourceStart, sourceEnd, - "a generic super-aspect must be fully parameterized in an extends clause"); + "a generic super-aspect must be fully parameterized in an extends clause"); ignoreFurtherInvestigation = true; return; } } } - - private FieldBinding initFailureField= null; - + + private FieldBinding initFailureField = null; + /** - * AMC - this method is called by the AtAspectJVisitor during beforeCompilation processing in - * the AjCompiler adapter. We use this hook to add in the @AspectJ annotations. + * AMC - this method is called by the AtAspectJVisitor during beforeCompilation processing in the AjCompiler adapter. We use + * this hook to add in the @AspectJ annotations. */ - public void addAtAspectJAnnotations() { - Annotation atAspectAnnotation = AtAspectJAnnotationFactory.createAspectAnnotation(perClause.toDeclarationString(), declarationSourceStart); + public void addAtAspectJAnnotations() { + Annotation atAspectAnnotation = AtAspectJAnnotationFactory.createAspectAnnotation(perClause.toDeclarationString(), + declarationSourceStart); Annotation privilegedAnnotation = null; - if (isPrivileged) privilegedAnnotation = AtAspectJAnnotationFactory.createPrivilegedAnnotation(declarationSourceStart); + if (isPrivileged) + privilegedAnnotation = AtAspectJAnnotationFactory.createPrivilegedAnnotation(declarationSourceStart); Annotation[] toAdd = new Annotation[isPrivileged ? 2 : 1]; toAdd[0] = atAspectAnnotation; - if (isPrivileged) toAdd[1] = privilegedAnnotation; + if (isPrivileged) + toAdd[1] = privilegedAnnotation; if (annotations == null) { annotations = toAdd; } else { Annotation[] old = annotations; annotations = new Annotation[annotations.length + toAdd.length]; - System.arraycopy(old,0,annotations,0,old.length); - System.arraycopy(toAdd,0,annotations,old.length,toAdd.length); - } + System.arraycopy(old, 0, annotations, 0, old.length); + System.arraycopy(toAdd, 0, annotations, old.length, toAdd.length); + } } - - + public void generateCode(ClassFile enclosingClassFile) { if (ignoreFurtherInvestigation) { if (binding == null) return; - ClassFile.createProblemType( - this, - scope.referenceCompilationUnit().compilationResult); + ClassFile.createProblemType(this, scope.referenceCompilationUnit().compilationResult); return; } - - + // make me and my binding public this.modifiers = AstUtil.makePublic(this.modifiers); this.binding.modifiers = AstUtil.makePublic(this.binding.modifiers); - - + if (!isAbstract()) { - if (perClause!=null && perClause.getKind()==PerClause.SINGLETON) { - initFailureField = factory.createSyntheticFieldBinding(binding,AjcMemberMaker.initFailureCauseField(typeX)); + if (perClause != null && perClause.getKind() == PerClause.SINGLETON) { + initFailureField = factory.createSyntheticFieldBinding(binding, AjcMemberMaker.initFailureCauseField(typeX)); } -// binding.addSyntheticField((SyntheticFieldBinding)initFailureField); - //initFailureField = factory.makeFieldBinding(AjcMemberMaker.initFailureCauseField(typeX)); - //binding.addField(initFailureField); - + // binding.addSyntheticField((SyntheticFieldBinding)initFailureField); + // initFailureField = factory.makeFieldBinding(AjcMemberMaker.initFailureCauseField(typeX)); + // binding.addField(initFailureField); + if (perClause == null) { // we've already produced an error for this } else if (perClause.getKind() == PerClause.SINGLETON) { factory.createSyntheticFieldBinding(binding, AjcMemberMaker.perSingletonField(typeX)); -//CUSTARD binding.addField(factory.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX))); - -//CUSTARD - methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, false, true, initFailureField); + // CUSTARD binding.addField(factory.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX))); + + // CUSTARD + methods[0] = new AspectClinit((Clinit) methods[0], compilationResult, false, true, initFailureField); } else if (perClause.getKind() == PerClause.PERCFLOW) { factory.createSyntheticFieldBinding(binding, AjcMemberMaker.perCflowField(typeX)); -//CUSTARD binding.addField(factory.makeFieldBinding(AjcMemberMaker.perCflowField(typeX))); - methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false, null); + // CUSTARD binding.addField(factory.makeFieldBinding(AjcMemberMaker.perCflowField(typeX))); + methods[0] = new AspectClinit((Clinit) methods[0], compilationResult, true, false, null); } else if (perClause.getKind() == PerClause.PEROBJECT) { -// binding.addField( -// world.makeFieldBinding( -// AjcMemberMaker.perCflowField( -// typeX))); + // binding.addField( + // world.makeFieldBinding( + // AjcMemberMaker.perCflowField( + // typeX))); } else if (perClause.getKind() == PerClause.PERTYPEWITHIN) { - factory.createSyntheticFieldBinding(binding, AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)); - //PTWIMPL Add field for storing typename in aspect for which the aspect instance exists -// binding.addField(factory.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX))); + factory.createSyntheticFieldBinding(binding, AjcMemberMaker.perTypeWithinWithinTypeField(typeX, typeX)); + // PTWIMPL Add field for storing typename in aspect for which the aspect instance exists + // binding.addField(factory.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX))); } else { throw new RuntimeException("unimplemented"); } } - if (EclipseFactory.DEBUG) System.out.println(toString()); - + if (EclipseFactory.DEBUG) + System.out.println(toString()); + super.generateCode(enclosingClassFile); } - + public boolean needClassInitMethod() { return true; } - - - protected void generateAttributes(ClassFile classFile) { - if (!isAbstract()) generatePerSupportMembers(classFile); - + + protected void generateAttributes(ClassFile classFile) { + if (!isAbstract()) + generatePerSupportMembers(classFile); + generateInlineAccessMembers(classFile); addVersionAttributeIfNecessary(classFile); - - classFile.extraAttributes.add( - new EclipseAttributeAdapter(new AjAttribute.Aspect(perClause))); - + + classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.Aspect(perClause))); + if (binding.privilegedHandler != null) { - ResolvedMember[] members = ((PrivilegedHandler)binding.privilegedHandler).getMembers(); - classFile.extraAttributes.add( - new EclipseAttributeAdapter(new AjAttribute.PrivilegedAttribute(members))); + ResolvedMember[] members = ((PrivilegedHandler) binding.privilegedHandler).getMembers(); + classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.PrivilegedAttribute(members))); } - - //XXX need to get this attribute on anyone with a pointcut for good errors - classFile.extraAttributes.add( - new EclipseAttributeAdapter(new AjAttribute.SourceContextAttribute( - new String(compilationResult().getFileName()), - compilationResult().lineSeparatorPositions))); - - super.generateAttributes(classFile); + + // XXX need to get this attribute on anyone with a pointcut for good errors + classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.SourceContextAttribute(new String( + compilationResult().getFileName()), compilationResult().lineSeparatorPositions))); + + super.generateAttributes(classFile); } - + /** * A pointcut might have already added the attribute, let's not add it again. */ private void addVersionAttributeIfNecessary(ClassFile classFile) { for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) { EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next(); - if (CharOperation.equals(element.getNameChars(),weaverVersionChars)) return; + if (CharOperation.equals(element.getNameChars(), weaverVersionChars)) + return; } classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.WeaverVersionInfo())); } + private static char[] weaverVersionChars = "org.aspectj.weaver.WeaverVersion".toCharArray(); - + private void generateInlineAccessMembers(ClassFile classFile) { - for (Iterator i = superAccessForInline.values().iterator(); i.hasNext(); ) { - AccessForInlineVisitor.SuperAccessMethodPair pair = (AccessForInlineVisitor.SuperAccessMethodPair)i.next(); + for (Iterator i = superAccessForInline.values().iterator(); i.hasNext();) { + AccessForInlineVisitor.SuperAccessMethodPair pair = (AccessForInlineVisitor.SuperAccessMethodPair) i.next(); generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod); } - for (Iterator i = accessForInline.entrySet().iterator(); i.hasNext(); ) { - Map.Entry e = (Map.Entry)i.next(); - generateInlineAccessMethod(classFile, (Binding)e.getValue(), (ResolvedMember)e.getKey()); + for (Iterator i = accessForInline.entrySet().iterator(); i.hasNext();) { + Map.Entry e = (Map.Entry) i.next(); + generateInlineAccessMethod(classFile, (Binding) e.getValue(), (ResolvedMember) e.getKey()); } } - private void generatePerSupportMembers(ClassFile classFile) { - if (isAbstract()) return; - - //XXX otherwise we need to have this (error handling?) - if (aspectOfMethod == null) return; + if (isAbstract()) + return; + + // XXX otherwise we need to have this (error handling?) + if (aspectOfMethod == null) + return; if (perClause == null) { System.err.println("has null perClause: " + this); return; } - + EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - + if (perClause.getKind() == PerClause.SINGLETON) { generatePerSingletonAspectOfMethod(classFile); generatePerSingletonHasAspectMethod(classFile); @@ -359,59 +346,60 @@ public class AspectDeclaration extends TypeDeclaration { generatePerCflowPushMethod(classFile); generatePerCflowAjcClinitMethod(classFile); } else if (perClause.getKind() == PerClause.PEROBJECT) { - TypeBinding interfaceType = - generatePerObjectInterface(classFile); + TypeBinding interfaceType = generatePerObjectInterface(classFile); generatePerObjectAspectOfMethod(classFile, interfaceType); generatePerObjectHasAspectMethod(classFile, interfaceType); generatePerObjectBindMethod(classFile, interfaceType); - } else if (perClause.getKind() == PerClause.PERTYPEWITHIN) { - //PTWIMPL Generate the methods required *in the aspect* - generatePerTypeWithinAspectOfMethod(classFile); // public static aspectOf(java.lang.Class) - generatePerTypeWithinGetInstanceMethod(classFile); // private static ajc$getInstance(Class c) throws Exception + } else if (perClause.getKind() == PerClause.PERTYPEWITHIN) { + // PTWIMPL Generate the methods required *in the aspect* + generatePerTypeWithinAspectOfMethod(classFile); // public static aspectOf(java.lang.Class) + generatePerTypeWithinGetInstanceMethod(classFile); // private static ajc$getInstance(Class c) throws + // Exception generatePerTypeWithinHasAspectMethod(classFile); - generatePerTypeWithinCreateAspectInstanceMethod(classFile); // generate public static X ajc$createAspectInstance(Class forClass) { + generatePerTypeWithinCreateAspectInstanceMethod(classFile); // generate public static X ajc$createAspectInstance(Class + // forClass) { generatePerTypeWithinGetWithinTypeNameMethod(classFile); } else { throw new RuntimeException("unimplemented"); } } - private static interface BodyGenerator { public void generate(CodeStream codeStream); } - - + private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(member), gen); } - + private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) { - generateMethod(classFile,methodBinding,null,gen); + generateMethod(classFile, methodBinding, null, gen); } - - protected List makeEffectiveSignatureAttribute(ResolvedMember sig,Shadow.Kind kind,boolean weaveBody) { + + protected List makeEffectiveSignatureAttribute(ResolvedMember sig, Shadow.Kind kind, boolean weaveBody) { List l = new ArrayList(1); - l.add(new EclipseAttributeAdapter( - new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody))); + l.add(new EclipseAttributeAdapter(new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody))); return l; } - + /* - * additionalAttributes allows us to pass some optional attributes we want to attach to the method we generate. - * Currently this is used for inline accessor methods that have been generated to allow private field references or - * private method calls to be inlined (PR71377). In these cases the optional attribute is an effective signature - * attribute which means calls to these methods are able to masquerade as any join point (a field set, field get or - * method call). The effective signature attribute is 'unwrapped' in BcelClassWeaver.matchInvokeInstruction() + * additionalAttributes allows us to pass some optional attributes we want to attach to the method we generate. Currently this + * is used for inline accessor methods that have been generated to allow private field references or private method calls to be + * inlined (PR71377). In these cases the optional attribute is an effective signature attribute which means calls to these + * methods are able to masquerade as any join point (a field set, field get or method call). The effective signature attribute + * is 'unwrapped' in BcelClassWeaver.matchInvokeInstruction() */ - private void generateMethod(ClassFile classFile, MethodBinding methodBinding, List additionalAttributes/*ResolvedMember realMember*/, BodyGenerator gen) { -// EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); + private void generateMethod(ClassFile classFile, MethodBinding methodBinding, List additionalAttributes/* + * ResolvedMember + * realMember + */, BodyGenerator gen) { + // EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); classFile.generateMethodInfoHeader(methodBinding); int methodAttributeOffset = classFile.contentsOffset; - + int attributeNumber; - if (additionalAttributes!=null) { // mini optimization + if (additionalAttributes != null) { // mini optimization List attrs = new ArrayList(); attrs.addAll(AstUtil.getAjSyntheticAttribute()); attrs.addAll(additionalAttributes); @@ -423,195 +411,162 @@ public class AspectDeclaration extends TypeDeclaration { int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; - + // Use reset() rather than init() // XXX We need a scope to keep reset happy, initializerScope is *not* the right one, but it works ! -// codeStream.init(classFile); -// codeStream.initializeMaxLocals(methodBinding); + // codeStream.init(classFile); + // codeStream.initializeMaxLocals(methodBinding); MethodDeclaration md = AstUtil.makeMethodDeclaration(methodBinding); md.scope = initializerScope; - codeStream.reset(md,classFile); + codeStream.reset(md, classFile); // body starts here gen.generate(codeStream); // body ends here - if (codeStream.pcToSourceMapSize==0) codeStream.recordPositionsFrom(0,1); - boolean b = ((codeStream.generateAttributes & ClassFileConstants.ATTR_VARS)!=0?true:false); // pr148693 - if (codeStream.maxLocals==0) { + if (codeStream.pcToSourceMapSize == 0) + codeStream.recordPositionsFrom(0, 1); + boolean b = ((codeStream.generateAttributes & ClassFileConstants.ATTR_VARS) != 0 ? true : false); // pr148693 + if (codeStream.maxLocals == 0) { codeStream.generateAttributes &= ~ClassFileConstants.ATTR_VARS; } classFile.completeCodeAttribute(codeAttributeOffset); - if (b) codeStream.generateAttributes |= ClassFileConstants.ATTR_VARS; - + if (b) + codeStream.generateAttributes |= ClassFileConstants.ATTR_VARS; + attributeNumber++; classFile.completeMethodInfo(methodAttributeOffset, attributeNumber); - } - + } - private void generatePerCflowAspectOfMethod( - ClassFile classFile) - { + private void generatePerCflowAspectOfMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here - codeStream.getstatic( - world.makeFieldBinding( - AjcMemberMaker.perCflowField( - typeX))); - codeStream.invokevirtual(world.makeMethodBindingForCall( - AjcMemberMaker.cflowStackPeekInstance())); + codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perCflowField(typeX))); + codeStream.invokevirtual(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackPeekInstance())); codeStream.checkcast(binding); codeStream.areturn(); // body ends here - }}); + } + }); } - private void generatePerCflowHasAspectMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here - codeStream.getstatic( - world.makeFieldBinding( - AjcMemberMaker.perCflowField( - typeX))); - codeStream.invokevirtual(world.makeMethodBindingForCall( - AjcMemberMaker.cflowStackIsValid())); + codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perCflowField(typeX))); + codeStream.invokevirtual(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackIsValid())); codeStream.ireturn(); // body ends here - }}); + } + }); } - - private void generatePerCflowPushMethod( - ClassFile classFile) - { + + private void generatePerCflowPushMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush( - factory.fromBinding(binding))), - new BodyGenerator() { - public void generate(CodeStream codeStream) { - // body starts here - codeStream.getstatic( - world.makeFieldBinding( - AjcMemberMaker.perCflowField( - typeX))); - codeStream.new_(binding); - codeStream.dup(); - codeStream.invokespecial( - new MethodBinding(0, "".toCharArray(), - TypeBinding.VOID, new TypeBinding[0], - new ReferenceBinding[0], binding)); - + generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush(factory.fromBinding(binding))), + new BodyGenerator() { + public void generate(CodeStream codeStream) { + // body starts here + codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perCflowField(typeX))); + codeStream.new_(binding); + codeStream.dup(); + codeStream.invokespecial(new MethodBinding(0, "".toCharArray(), TypeBinding.VOID, new TypeBinding[0], + new ReferenceBinding[0], binding)); - codeStream.invokevirtual(world.makeMethodBindingForCall( - AjcMemberMaker.cflowStackPushInstance())); - codeStream.return_(); - // body ends here - }}); + codeStream.invokevirtual(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackPushInstance())); + codeStream.return_(); + // body ends here + } + }); } - - - - private void generatePerCflowAjcClinitMethod( - ClassFile classFile) - { + private void generatePerCflowAjcClinitMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod( - world.fromBinding(binding))), - new BodyGenerator() { - public void generate(CodeStream codeStream) { - // body starts here - codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE)); - codeStream.dup(); - codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit())); - codeStream.putstatic( - world.makeFieldBinding( - AjcMemberMaker.perCflowField( - typeX))); - codeStream.return_(); - // body ends here - }}); + generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod(world.fromBinding(binding))), + new BodyGenerator() { + public void generate(CodeStream codeStream) { + // body starts here + codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE)); + codeStream.dup(); + codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit())); + codeStream.putstatic(world.makeFieldBinding(AjcMemberMaker.perCflowField(typeX))); + codeStream.return_(); + // body ends here + } + }); } - - - private TypeBinding generatePerObjectInterface( - ClassFile classFile) - { + + private TypeBinding generatePerObjectInterface(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - UnresolvedType interfaceTypeX = - AjcMemberMaker.perObjectInterfaceType(typeX); - HelperInterfaceBinding interfaceType = - new HelperInterfaceBinding(this.binding, interfaceTypeX); + UnresolvedType interfaceTypeX = AjcMemberMaker.perObjectInterfaceType(typeX); + HelperInterfaceBinding interfaceType = new HelperInterfaceBinding(this.binding, interfaceTypeX); world.addTypeBindingAndStoreInWorld(interfaceType); interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX)); interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX)); interfaceType.generateClass(compilationResult, classFile); return interfaceType; } - - /*private void generatePerTypeWithinGetWithinTypeMethod(ClassFile classFile) { + + /* + * private void generatePerTypeWithinGetWithinTypeMethod(ClassFile classFile) { final EclipseFactory world = + * EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile,ptwGetWithinTypeMethod,new BodyGenerator() { + * public void generate(CodeStream codeStream) { codeStream.aload_0(); + * codeStream.getfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX))); codeStream.areturn(); + * }}); } + */ + + // PTWIMPL Generate aspectOf() method + private void generatePerTypeWithinAspectOfMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - generateMethod(classFile,ptwGetWithinTypeMethod,new BodyGenerator() { + generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { + BranchLabel instanceFound = new BranchLabel(codeStream); + + ExceptionLabel anythingGoesWrong = new ExceptionLabel(codeStream, world + .makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); + anythingGoesWrong.placeStart(); codeStream.aload_0(); - codeStream.getfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX))); + codeStream.invokestatic(world.makeMethodBindingForCall(AjcMemberMaker.perTypeWithinGetInstance(typeX))); + codeStream.astore_1(); + codeStream.aload_1(); + codeStream.ifnonnull(instanceFound); + codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); + codeStream.dup(); + + codeStream.ldc(typeX.getName()); + codeStream.aconst_null(); + + codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit2())); + codeStream.athrow(); + instanceFound.place(); + codeStream.aload_1(); + codeStream.areturn(); - }}); - }*/ - - // PTWIMPL Generate aspectOf() method - private void generatePerTypeWithinAspectOfMethod(ClassFile classFile) { - final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - generateMethod(classFile, aspectOfMethod, new BodyGenerator() { - public void generate(CodeStream codeStream) { - BranchLabel instanceFound = new BranchLabel(codeStream); - - ExceptionLabel anythingGoesWrong = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); - anythingGoesWrong.placeStart(); - codeStream.aload_0(); - codeStream.invokestatic(world.makeMethodBindingForCall(AjcMemberMaker.perTypeWithinGetInstance(typeX))); - codeStream.astore_1(); - codeStream.aload_1(); - codeStream.ifnonnull(instanceFound); - codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); - codeStream.dup(); - - codeStream.ldc(typeX.getName()); - codeStream.aconst_null(); - - codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit2())); - codeStream.athrow(); - instanceFound.place(); - codeStream.aload_1(); - - codeStream.areturn(); - anythingGoesWrong.placeEnd(); - anythingGoesWrong.place(); - - codeStream.astore_1(); - codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); - - codeStream.dup(); - - // Run the simple ctor for NABE - codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit())); - codeStream.athrow(); - }}); - } - - private void generatePerObjectAspectOfMethod( - ClassFile classFile, - final TypeBinding interfaceType) - { + anythingGoesWrong.placeEnd(); + anythingGoesWrong.place(); + + codeStream.astore_1(); + codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); + + codeStream.dup(); + + // Run the simple ctor for NABE + codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit())); + codeStream.athrow(); + } + }); + } + + private void generatePerObjectAspectOfMethod(ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { - // body starts here + // body starts here BranchLabel wrongType = new BranchLabel(codeStream); BranchLabel popWrongType = new BranchLabel(codeStream); codeStream.aload_0(); @@ -619,31 +574,27 @@ public class AspectDeclaration extends TypeDeclaration { codeStream.ifeq(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); - codeStream.invokeinterface(world.makeMethodBindingForCall( - AjcMemberMaker.perObjectInterfaceGet(typeX))); - + codeStream.invokeinterface(world.makeMethodBindingForCall(AjcMemberMaker.perObjectInterfaceGet(typeX))); + codeStream.dup(); codeStream.ifnull(popWrongType); codeStream.areturn(); - + popWrongType.place(); codeStream.pop(); - + wrongType.place(); codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); codeStream.dup(); - codeStream.invokespecial(world.makeMethodBindingForCall( - AjcMemberMaker.noAspectBoundExceptionInit() - )); + codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit())); codeStream.athrow(); // body ends here - }}); + } + }); } - - private void generatePerObjectHasAspectMethod(ClassFile classFile, - final TypeBinding interfaceType) { + private void generatePerObjectHasAspectMethod(ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { @@ -654,227 +605,208 @@ public class AspectDeclaration extends TypeDeclaration { codeStream.ifeq(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); - codeStream.invokeinterface(world.makeMethodBindingForCall( - AjcMemberMaker.perObjectInterfaceGet(typeX))); + codeStream.invokeinterface(world.makeMethodBindingForCall(AjcMemberMaker.perObjectInterfaceGet(typeX))); codeStream.ifnull(wrongType); codeStream.iconst_1(); codeStream.ireturn(); - + wrongType.place(); codeStream.iconst_0(); codeStream.ireturn(); // body ends here - }}); + } + }); } - + // PTWIMPL Generate hasAspect() method private void generatePerTypeWithinHasAspectMethod(ClassFile classFile) { - final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - generateMethod(classFile, hasAspectMethod, new BodyGenerator() { - public void generate(CodeStream codeStream) { - ExceptionLabel goneBang = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); - BranchLabel noInstanceExists = new BranchLabel(codeStream); - BranchLabel leave = new BranchLabel(codeStream); - goneBang.placeStart(); - codeStream.aload_0(); - codeStream.invokestatic(world.makeMethodBinding(AjcMemberMaker.perTypeWithinGetInstance(typeX))); - codeStream.ifnull(noInstanceExists); - codeStream.iconst_1(); - codeStream.goto_(leave); - noInstanceExists.place(); - codeStream.iconst_0(); - leave.place(); - goneBang.placeEnd(); - codeStream.ireturn(); - goneBang.place(); - codeStream.astore_1(); - codeStream.iconst_0(); - codeStream.ireturn(); - }}); - } - - private void generatePerObjectBindMethod( - ClassFile classFile, - final TypeBinding interfaceType) - { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - generateMethod(classFile, AjcMemberMaker.perObjectBind(world.fromBinding(binding)), - new BodyGenerator() { + generateMethod(classFile, hasAspectMethod, new BodyGenerator() { + public void generate(CodeStream codeStream) { + ExceptionLabel goneBang = new ExceptionLabel(codeStream, world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); + BranchLabel noInstanceExists = new BranchLabel(codeStream); + BranchLabel leave = new BranchLabel(codeStream); + goneBang.placeStart(); + codeStream.aload_0(); + codeStream.invokestatic(world.makeMethodBinding(AjcMemberMaker.perTypeWithinGetInstance(typeX))); + codeStream.ifnull(noInstanceExists); + codeStream.iconst_1(); + codeStream.goto_(leave); + noInstanceExists.place(); + codeStream.iconst_0(); + leave.place(); + goneBang.placeEnd(); + codeStream.ireturn(); + goneBang.place(); + codeStream.astore_1(); + codeStream.iconst_0(); + codeStream.ireturn(); + } + }); + } + + private void generatePerObjectBindMethod(ClassFile classFile, final TypeBinding interfaceType) { + final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); + generateMethod(classFile, AjcMemberMaker.perObjectBind(world.fromBinding(binding)), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here BranchLabel wrongType = new BranchLabel(codeStream); codeStream.aload_0(); codeStream.instance_of(interfaceType); - codeStream.ifeq(wrongType); //XXX this case might call for screaming + codeStream.ifeq(wrongType); // XXX this case might call for screaming codeStream.aload_0(); codeStream.checkcast(interfaceType); - codeStream.invokeinterface(world.makeMethodBindingForCall( - AjcMemberMaker.perObjectInterfaceGet(typeX))); - //XXX should do a check for null here and throw a NoAspectBound + codeStream.invokeinterface(world.makeMethodBindingForCall(AjcMemberMaker.perObjectInterfaceGet(typeX))); + // XXX should do a check for null here and throw a NoAspectBound codeStream.ifnonnull(wrongType); - + codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.new_(binding); codeStream.dup(); - codeStream.invokespecial( - new MethodBinding(0, "".toCharArray(), - TypeBinding.VOID, new TypeBinding[0], + codeStream.invokespecial(new MethodBinding(0, "".toCharArray(), TypeBinding.VOID, new TypeBinding[0], new ReferenceBinding[0], binding)); - codeStream.invokeinterface(world.makeMethodBindingForCall( - AjcMemberMaker.perObjectInterfaceSet(typeX))); - + codeStream.invokeinterface(world.makeMethodBindingForCall(AjcMemberMaker.perObjectInterfaceSet(typeX))); + wrongType.place(); codeStream.return_(); // body ends here - }}); + } + }); } - + private void generatePerTypeWithinGetWithinTypeNameMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); // Code: /* - Code: - Stack=1, Locals=1, Args_size=1 - 0: aload_0 - 1: getfield #14; //Field ajc$withinType:Ljava/lang/String; - 4: areturn + * Code: Stack=1, Locals=1, Args_size=1 0: aload_0 1: getfield #14; //Field ajc$withinType:Ljava/lang/String; 4: areturn */ - generateMethod(classFile, AjcMemberMaker.perTypeWithinGetWithinTypeNameMethod(world.fromBinding(binding),world.getWorld().isInJava5Mode()), - new BodyGenerator() { + generateMethod(classFile, AjcMemberMaker.perTypeWithinGetWithinTypeNameMethod(world.fromBinding(binding), world.getWorld() + .isInJava5Mode()), new BodyGenerator() { public void generate(CodeStream codeStream) { - ExceptionLabel exc = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); + ExceptionLabel exc = new ExceptionLabel(codeStream, world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); exc.placeStart(); codeStream.aload_0(); - codeStream.getfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX))); + codeStream.getfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX, typeX))); codeStream.areturn(); - }}); + } + }); } - // PTWIMPL Generate getInstance method + + // PTWIMPL Generate getInstance method private void generatePerTypeWithinGetInstanceMethod(ClassFile classFile) { - final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - generateMethod(classFile, AjcMemberMaker.perTypeWithinGetInstance(world.fromBinding(binding)), - new BodyGenerator() { - public void generate(CodeStream codeStream) { - ExceptionLabel exc = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); - exc.placeStart(); - codeStream.aload_0(); - codeStream.ldc(NameMangler.perTypeWithinLocalAspectOf(typeX)); - codeStream.aconst_null(); - codeStream.invokevirtual( - new MethodBinding( - 0, - "getDeclaredMethod".toCharArray(), - world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/reflect/Method;")), // return type - new TypeBinding[]{world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/String;")), - world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Class;"))}, - new ReferenceBinding[0], - (ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_CLASS))); - codeStream.astore_1(); - codeStream.aload_1(); - codeStream.aconst_null(); - codeStream.aconst_null(); - codeStream.invokevirtual( - new MethodBinding( - 0, - "invoke".toCharArray(), - world.makeTypeBinding(UnresolvedType.OBJECT), - new TypeBinding[]{world.makeTypeBinding(UnresolvedType.OBJECT),world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Object;"))}, - new ReferenceBinding[0], - (ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_REFLECT_METHOD))); - codeStream.checkcast(world.makeTypeBinding(typeX)); - codeStream.astore_2(); - codeStream.aload_2(); - exc.placeEnd(); - codeStream.areturn(); - exc.place(); - codeStream.astore_1(); - // this just returns null now - the old version used to throw the caught exception! - codeStream.aconst_null(); - codeStream.areturn(); - }}); - } - - private void generatePerTypeWithinCreateAspectInstanceMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - generateMethod(classFile, AjcMemberMaker.perTypeWithinCreateAspectInstance(world.fromBinding(binding)), - new BodyGenerator() { + generateMethod(classFile, AjcMemberMaker.perTypeWithinGetInstance(world.fromBinding(binding)), new BodyGenerator() { public void generate(CodeStream codeStream) { - - codeStream.new_(world.makeTypeBinding(typeX)); - codeStream.dup(); - codeStream.invokespecial(new MethodBinding(0, "".toCharArray(), - TypeBinding.VOID, new TypeBinding[0], - new ReferenceBinding[0], binding)); - codeStream.astore_1(); - codeStream.aload_1(); + ExceptionLabel exc = new ExceptionLabel(codeStream, world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); + exc.placeStart(); codeStream.aload_0(); - codeStream.putfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX))); + codeStream.ldc(NameMangler.perTypeWithinLocalAspectOf(typeX)); + codeStream.aconst_null(); + codeStream.invokevirtual(new MethodBinding(0, "getDeclaredMethod".toCharArray(), + world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/reflect/Method;")), // return type + new TypeBinding[] { world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/String;")), + world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Class;")) }, + new ReferenceBinding[0], (ReferenceBinding) world.makeTypeBinding(UnresolvedType.JAVA_LANG_CLASS))); + codeStream.astore_1(); codeStream.aload_1(); + codeStream.aconst_null(); + codeStream.aconst_null(); + codeStream + .invokevirtual(new MethodBinding(0, "invoke".toCharArray(), world.makeTypeBinding(UnresolvedType.OBJECT), + new TypeBinding[] { world.makeTypeBinding(UnresolvedType.OBJECT), + world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Object;")) }, + new ReferenceBinding[0], (ReferenceBinding) world + .makeTypeBinding(UnresolvedType.JAVA_LANG_REFLECT_METHOD))); + codeStream.checkcast(world.makeTypeBinding(typeX)); + codeStream.astore_2(); + codeStream.aload_2(); + exc.placeEnd(); + codeStream.areturn(); + exc.place(); + codeStream.astore_1(); + // this just returns null now - the old version used to throw the caught exception! + codeStream.aconst_null(); codeStream.areturn(); - }}); + } + }); + } + + private void generatePerTypeWithinCreateAspectInstanceMethod(ClassFile classFile) { + final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); + generateMethod(classFile, AjcMemberMaker.perTypeWithinCreateAspectInstance(world.fromBinding(binding)), + new BodyGenerator() { + public void generate(CodeStream codeStream) { + + codeStream.new_(world.makeTypeBinding(typeX)); + codeStream.dup(); + codeStream.invokespecial(new MethodBinding(0, "".toCharArray(), TypeBinding.VOID, new TypeBinding[0], + new ReferenceBinding[0], binding)); + codeStream.astore_1(); + codeStream.aload_1(); + codeStream.aload_0(); + codeStream.putfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX, typeX))); + codeStream.aload_1(); + codeStream.areturn(); + } + }); } - - private void generatePerSingletonAspectOfMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // Old style aspectOf() method which confused decompilers -// // body starts here -// codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField( -// typeX))); -// Label isNull = new Label(codeStream); -// codeStream.dup(); -// codeStream.ifnull(isNull); -// codeStream.areturn(); -// isNull.place(); -// -// codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter -// codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); -// codeStream.dup(); -// codeStream.ldc(typeX.getNameAsIdentifier()); -// codeStream.getstatic(initFailureField); -// codeStream.invokespecial(world.makeMethodBindingForCall( -// AjcMemberMaker.noAspectBoundExceptionInitWithCause() -// )); -// codeStream.athrow(); -// // body ends here + // // body starts here + // codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField( + // typeX))); + // Label isNull = new Label(codeStream); + // codeStream.dup(); + // codeStream.ifnull(isNull); + // codeStream.areturn(); + // isNull.place(); + // + // codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter + // codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); + // codeStream.dup(); + // codeStream.ldc(typeX.getNameAsIdentifier()); + // codeStream.getstatic(initFailureField); + // codeStream.invokespecial(world.makeMethodBindingForCall( + // AjcMemberMaker.noAspectBoundExceptionInitWithCause() + // )); + // codeStream.athrow(); + // // body ends here // The stuff below generates code that looks like this: /* - * if (ajc$perSingletonInstance == null) - * throw new NoAspectBoundException("A", ajc$initFailureCause); - * else - * return ajc$perSingletonInstance; + * if (ajc$perSingletonInstance == null) throw new NoAspectBoundException("A", ajc$initFailureCause); else return + * ajc$perSingletonInstance; */ - // body starts here (see end of each line for what it is doing!) + // body starts here (see end of each line for what it is doing!) FieldBinding fb = world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX)); - codeStream.getstatic(fb); // GETSTATIC + codeStream.getstatic(fb); // GETSTATIC BranchLabel isNonNull = new BranchLabel(codeStream); - codeStream.ifnonnull(isNonNull); // IFNONNULL - codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW - codeStream.dup(); // DUP - codeStream.ldc(typeX.getNameAsIdentifier()); // LDC - codeStream.getstatic(initFailureField); // GETSTATIC - codeStream.invokespecial(world.makeMethodBindingForCall( - AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL - codeStream.athrow(); // ATHROW + codeStream.ifnonnull(isNonNull); // IFNONNULL + codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW + codeStream.dup(); // DUP + codeStream.ldc(typeX.getNameAsIdentifier()); // LDC + codeStream.getstatic(initFailureField); // GETSTATIC + codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL + codeStream.athrow(); // ATHROW isNonNull.place(); - codeStream.getstatic(fb); // GETSTATIC - codeStream.areturn(); // ARETURN + codeStream.getstatic(fb); // GETSTATIC + codeStream.areturn(); // ARETURN // body ends here - }}); + } + }); } - + private void generatePerSingletonHasAspectMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here - codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField( - typeX))); + codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX))); BranchLabel isNull = new BranchLabel(codeStream); codeStream.ifnull(isNull); codeStream.iconst_1(); @@ -883,161 +815,148 @@ public class AspectDeclaration extends TypeDeclaration { codeStream.iconst_0(); codeStream.ireturn(); // body ends here - }}); + } + }); } - - - private void generatePerSingletonAjcClinitMethod( - ClassFile classFile) - { + + private void generatePerSingletonAjcClinitMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); - generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod( - world.fromBinding(binding))), - new BodyGenerator() { - public void generate(CodeStream codeStream) { - // body starts here - codeStream.new_(binding); - codeStream.dup(); - codeStream.invokespecial( - new MethodBinding(0, "".toCharArray(), - TypeBinding.VOID, new TypeBinding[0], - new ReferenceBinding[0], binding)); - - codeStream.putstatic( - world.makeFieldBinding( - AjcMemberMaker.perSingletonField( - typeX))); - codeStream.return_(); - // body ends here - }}); + generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod(world.fromBinding(binding))), + new BodyGenerator() { + public void generate(CodeStream codeStream) { + // body starts here + codeStream.new_(binding); + codeStream.dup(); + codeStream.invokespecial(new MethodBinding(0, "".toCharArray(), TypeBinding.VOID, new TypeBinding[0], + new ReferenceBinding[0], binding)); + + codeStream.putstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX))); + codeStream.return_(); + // body ends here + } + }); } - + private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) { - generateMethod(classFile, accessMethod, - new BodyGenerator() { + generateMethod(classFile, accessMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.aload_0(); AstUtil.generateParameterLoads(accessMethod.parameters, codeStream); - codeStream.invokespecial( - factory.makeMethodBinding(method)); + codeStream.invokespecial(factory.makeMethodBinding(method)); AstUtil.generateReturn(accessMethod.returnType, codeStream); // body ends here - }}); + } + }); } - private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) { if (binding instanceof InlineAccessFieldBinding) { - generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member); + generateInlineAccessors(classFile, (InlineAccessFieldBinding) binding, member); } else { - generateInlineAccessMethod(classFile, (MethodBinding)binding, member); + generateInlineAccessMethod(classFile, (MethodBinding) binding, member); } } - + private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) { - final FieldBinding fieldBinding = factory.makeFieldBinding(field); - - generateMethod(classFile, accessField.reader, - makeEffectiveSignatureAttribute(field,Shadow.FieldGet,false), - new BodyGenerator() { - public void generate(CodeStream codeStream) { - // body starts here - if (field.isStatic()) { - codeStream.getstatic(fieldBinding); - } else { - codeStream.aload_0(); - codeStream.getfield(fieldBinding); - } - - AstUtil.generateReturn(accessField.reader.returnType, codeStream); - // body ends here - }}); - - generateMethod(classFile, accessField.writer, - makeEffectiveSignatureAttribute(field,Shadow.FieldSet,false), - new BodyGenerator() { - public void generate(CodeStream codeStream) { - // body starts here - if (field.isStatic()) { - codeStream.load(fieldBinding.type, 0); - codeStream.putstatic(fieldBinding); - } else { - codeStream.aload_0(); - codeStream.load(fieldBinding.type, 1); - codeStream.putfield(fieldBinding); - } - - codeStream.return_(); - // body ends here - }}); + final FieldBinding fieldBinding = factory.makeFieldBinding(field); + + generateMethod(classFile, accessField.reader, makeEffectiveSignatureAttribute(field, Shadow.FieldGet, false), + new BodyGenerator() { + public void generate(CodeStream codeStream) { + // body starts here + if (field.isStatic()) { + codeStream.getstatic(fieldBinding); + } else { + codeStream.aload_0(); + codeStream.getfield(fieldBinding); + } + + AstUtil.generateReturn(accessField.reader.returnType, codeStream); + // body ends here + } + }); + + generateMethod(classFile, accessField.writer, makeEffectiveSignatureAttribute(field, Shadow.FieldSet, false), + new BodyGenerator() { + public void generate(CodeStream codeStream) { + // body starts here + if (field.isStatic()) { + codeStream.load(fieldBinding.type, 0); + codeStream.putstatic(fieldBinding); + } else { + codeStream.aload_0(); + codeStream.load(fieldBinding.type, 1); + codeStream.putfield(fieldBinding); + } + + codeStream.return_(); + // body ends here + } + }); } - private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) { - generateMethod(classFile, accessMethod, - makeEffectiveSignatureAttribute(method, Shadow.MethodCall, false), - new BodyGenerator() { - public void generate(CodeStream codeStream) { - // body starts here - - AstUtil.generateParameterLoads(accessMethod.parameters, codeStream); - - if (method.isStatic()) { - codeStream.invokestatic(factory.makeMethodBinding(method)); - } else { - codeStream.invokevirtual(factory.makeMethodBinding(method)); - } - - AstUtil.generateReturn(accessMethod.returnType, codeStream); - // body ends here - }}); + generateMethod(classFile, accessMethod, makeEffectiveSignatureAttribute(method, Shadow.MethodCall, false), + new BodyGenerator() { + public void generate(CodeStream codeStream) { + // body starts here + + AstUtil.generateParameterLoads(accessMethod.parameters, codeStream); + + if (method.isStatic()) { + codeStream.invokestatic(factory.makeMethodBinding(method)); + } else { + codeStream.invokevirtual(factory.makeMethodBinding(method)); + } + + AstUtil.generateReturn(accessMethod.returnType, codeStream); + // body ends here + } + }); } - - private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) { - PerClause perClause; - if (binding instanceof BinaryTypeBinding) { - ResolvedType superTypeX = factory.fromEclipse(binding); - perClause = superTypeX.getPerClause(); - } else if (binding instanceof SourceTypeBinding ) { - SourceTypeBinding sourceSc = (SourceTypeBinding)binding; + PerClause perClause; + if (binding instanceof BinaryTypeBinding) { + ResolvedType superTypeX = factory.fromEclipse(binding); + perClause = superTypeX.getPerClause(); + } else if (binding instanceof SourceTypeBinding) { + SourceTypeBinding sourceSc = (SourceTypeBinding) binding; if (sourceSc.scope.referenceContext instanceof AspectDeclaration) { - perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause; + perClause = ((AspectDeclaration) sourceSc.scope.referenceContext).perClause; } else { return null; } - } else if (binding instanceof ParameterizedTypeBinding) { - ParameterizedTypeBinding pBinding = (ParameterizedTypeBinding)binding; - if (pBinding.type instanceof SourceTypeBinding) { - SourceTypeBinding sourceSc = (SourceTypeBinding)pBinding.type; - if (sourceSc.scope != null && sourceSc.scope.referenceContext instanceof AspectDeclaration) { - perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause; + } else if (binding instanceof ParameterizedTypeBinding) { + ParameterizedTypeBinding pBinding = (ParameterizedTypeBinding) binding; + if (pBinding.type instanceof SourceTypeBinding) { + SourceTypeBinding sourceSc = (SourceTypeBinding) pBinding.type; + if (sourceSc.scope != null && sourceSc.scope.referenceContext instanceof AspectDeclaration) { + perClause = ((AspectDeclaration) sourceSc.scope.referenceContext).perClause; } else { return null; } - } else { - perClause=null; - } + } else { + perClause = null; + } } else { - //XXX need to handle this too + // XXX need to handle this too return null; } - if (perClause == null) { - return lookupPerClauseKind(binding.superclass()); - } else { - return perClause.getKind(); - } - } - + if (perClause == null) { + return lookupPerClauseKind(binding.superclass()); + } else { + return perClause.getKind(); + } + } private void buildPerClause(ClassScope scope) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); - + if (perClause == null) { PerClause.Kind kind = lookupPerClauseKind(binding.superclass); if (kind == null) { @@ -1046,139 +965,138 @@ public class AspectDeclaration extends TypeDeclaration { perClause = new PerFromSuper(kind); } } - - aspectAttribute = new AjAttribute.Aspect(perClause); - - if (ignoreFurtherInvestigation) return; //??? - - + + // aspectAttribute = new AjAttribute.Aspect(perClause); + + if (ignoreFurtherInvestigation) + return; // ??? + if (!isAbstract()) { if (perClause.getKind() == PerClause.SINGLETON) { aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX); - hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX); + hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX); } else if (perClause.getKind() == PerClause.PERCFLOW) { aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX); - hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX); + hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX); } else if (perClause.getKind() == PerClause.PEROBJECT) { aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX); } else if (perClause.getKind() == PerClause.PERTYPEWITHIN) { - // PTWIMPL Use these variants of aspectOf()/hasAspect() - aspectOfMethod = AjcMemberMaker.perTypeWithinAspectOfMethod(typeX,world.getWorld().isInJava5Mode()); - hasAspectMethod = AjcMemberMaker.perTypeWithinHasAspectMethod(typeX,world.getWorld().isInJava5Mode()); - ptwGetWithinTypeNameMethod = AjcMemberMaker.perTypeWithinGetWithinTypeNameMethod(typeX,world.getWorld().isInJava5Mode()); + // PTWIMPL Use these variants of aspectOf()/hasAspect() + aspectOfMethod = AjcMemberMaker.perTypeWithinAspectOfMethod(typeX, world.getWorld().isInJava5Mode()); + hasAspectMethod = AjcMemberMaker.perTypeWithinHasAspectMethod(typeX, world.getWorld().isInJava5Mode()); + ptwGetWithinTypeNameMethod = AjcMemberMaker.perTypeWithinGetWithinTypeNameMethod(typeX, world.getWorld() + .isInJava5Mode()); binding.addMethod(world.makeMethodBinding(ptwGetWithinTypeNameMethod)); } else { - throw new RuntimeException("bad per clause: " + perClause); + throw new RuntimeException("bad per clause: " + perClause); } - + binding.addMethod(world.makeMethodBinding(aspectOfMethod)); binding.addMethod(world.makeMethodBinding(hasAspectMethod)); } - resolvePerClause(); //XXX might be too soon for some error checking + resolvePerClause(); // XXX might be too soon for some error checking } - - private PerClause resolvePerClause() { - EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope); + private PerClause resolvePerClause() { + EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope); perClause.resolve(iscope); return perClause; } - - public void buildInterTypeAndPerClause(ClassScope classScope) { factory = EclipseFactory.fromScopeLookupEnvironment(scope); if (isPrivileged) { binding.privilegedHandler = new PrivilegedHandler(this); } - + checkSpec(classScope); - if (ignoreFurtherInvestigation) return; + if (ignoreFurtherInvestigation) + return; buildPerClause(scope); - + if (methods != null) { for (int i = 0; i < methods.length; i++) { if (methods[i] instanceof InterTypeDeclaration) { - EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope); - if (m != null) concreteName.typeMungers.add(m); + EclipseTypeMunger m = ((InterTypeDeclaration) methods[i]).build(classScope); + if (m != null) + concreteName.typeMungers.add(m); } else if (methods[i] instanceof DeclareDeclaration) { - Declare d = ((DeclareDeclaration)methods[i]).build(classScope); - if (d != null) concreteName.declares.add(d); + Declare d = ((DeclareDeclaration) methods[i]).build(classScope); + if (d != null) + concreteName.declares.add(d); } } } - - concreteName.getDeclaredPointcuts(); - } + concreteName.getDeclaredPointcuts(); + } -// public String toString(int tab) { -// return tabString(tab) + toStringHeader() + toStringBody(tab); -// } -// -// public String toStringBody(int tab) { -// -// String s = " {"; //$NON-NLS-1$ -// -// -// if (memberTypes != null) { -// for (int i = 0; i < memberTypes.length; i++) { -// if (memberTypes[i] != null) { -// s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$ -// } -// } -// } -// if (fields != null) { -// for (int fieldI = 0; fieldI < fields.length; fieldI++) { -// if (fields[fieldI] != null) { -// s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$ -// if (fields[fieldI].isField()) -// s += ";"; //$NON-NLS-1$ -// } -// } -// } -// if (methods != null) { -// for (int i = 0; i < methods.length; i++) { -// if (methods[i] != null) { -// s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$ -// } -// } -// } -// s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$ -// return s; -// } + // public String toString(int tab) { + // return tabString(tab) + toStringHeader() + toStringBody(tab); + // } + // + // public String toStringBody(int tab) { + // + // String s = " {"; //$NON-NLS-1$ + // + // + // if (memberTypes != null) { + // for (int i = 0; i < memberTypes.length; i++) { + // if (memberTypes[i] != null) { + // s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$ + // } + // } + // } + // if (fields != null) { + // for (int fieldI = 0; fieldI < fields.length; fieldI++) { + // if (fields[fieldI] != null) { + // s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$ + // if (fields[fieldI].isField()) + // s += ";"; //$NON-NLS-1$ + // } + // } + // } + // if (methods != null) { + // for (int i = 0; i < methods.length; i++) { + // if (methods[i] != null) { + // s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$ + // } + // } + // } + // s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$ + // return s; + // } public StringBuffer printHeader(int indent, StringBuffer output) { // since all aspects are made public we want to print the // modifiers that were supplied in the original source code - printModifiers(this.declaredModifiers,output); - output.append("aspect " ); + printModifiers(this.declaredModifiers, output); + output.append("aspect "); output.append(name); if (superclass != null) { - output.append(" extends "); //$NON-NLS-1$ + output.append(" extends "); //$NON-NLS-1$ superclass.print(0, output); } if (superInterfaces != null && superInterfaces.length > 0) { output.append((TypeDeclaration.kind(this.modifiers) == TypeDeclaration.INTERFACE_DECL) ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$ for (int i = 0; i < superInterfaces.length; i++) { - if (i > 0) output.append( ", "); //$NON-NLS-1$ + if (i > 0) + output.append(", "); //$NON-NLS-1$ superInterfaces[i].print(0, output); } } - return output; - //XXX we should append the per-clause + return output; + // XXX we should append the per-clause } - + /** - * All aspects are made public after type checking etc. and before generating code - * (so that the advice can be called!). - * This method returns the modifiers as specified in the original source code declaration - * so that the structure model sees the right thing. + * All aspects are made public after type checking etc. and before generating code (so that the advice can be called!). This + * method returns the modifiers as specified in the original source code declaration so that the structure model sees the right + * thing. */ public int getDeclaredModifiers() { return declaredModifiers; } } - diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java index 31e82f378..14c37c316 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java @@ -68,59 +68,60 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray(); private static final char[] declareParentsSig = "Lorg/aspectj/lang/annotation/DeclareParents;".toCharArray(); private static final char[] adviceNameSig = "Lorg/aspectj/lang/annotation/AdviceName;".toCharArray(); - private static final char[] orgAspectJLangAnnotation = "org/aspectj/lang/annotation/".toCharArray(); + // private static final char[] orgAspectJLangAnnotation = "org/aspectj/lang/annotation/".toCharArray(); private static final char[] voidType = "void".toCharArray(); private static final char[] booleanType = "boolean".toCharArray(); private static final char[] joinPoint = "Lorg/aspectj/lang/JoinPoint;".toCharArray(); private static final char[] joinPointStaticPart = "Lorg/aspectj/lang/JoinPoint$StaticPart;".toCharArray(); private static final char[] joinPointEnclosingStaticPart = "Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".toCharArray(); private static final char[] proceedingJoinPoint = "Lorg/aspectj/lang/ProceedingJoinPoint;".toCharArray(); - private static final char[][] adviceSigs = new char[][] {beforeAdviceSig,afterAdviceSig,afterReturningAdviceSig,afterThrowingAdviceSig,aroundAdviceSig}; - - + // private static final char[][] adviceSigs = new char[][] { beforeAdviceSig, afterAdviceSig, afterReturningAdviceSig, + // afterThrowingAdviceSig, aroundAdviceSig }; + private CompilationUnitDeclaration unit; private Stack typeStack = new Stack(); private AspectJAnnotations ajAnnotations; - + public ValidateAtAspectJAnnotationsVisitor(CompilationUnitDeclaration unit) { this.unit = unit; } - + public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) { typeStack.push(localTypeDeclaration); ajAnnotations = new AspectJAnnotations(localTypeDeclaration.annotations); checkTypeDeclaration(localTypeDeclaration); return true; } - - public void endVisit(TypeDeclaration localTypeDeclaration,BlockScope scope) { + + public void endVisit(TypeDeclaration localTypeDeclaration, BlockScope scope) { typeStack.pop(); } - - public boolean visit(TypeDeclaration memberTypeDeclaration,ClassScope scope) { + + public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { typeStack.push(memberTypeDeclaration); ajAnnotations = new AspectJAnnotations(memberTypeDeclaration.annotations); checkTypeDeclaration(memberTypeDeclaration); return true; } - - public void endVisit(TypeDeclaration memberTypeDeclaration,ClassScope scope) { + + public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { typeStack.pop(); } - + public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { typeStack.push(typeDeclaration); ajAnnotations = new AspectJAnnotations(typeDeclaration.annotations); checkTypeDeclaration(typeDeclaration); return true; } - - public void endVisit(TypeDeclaration typeDeclaration,CompilationUnitScope scope) { + + public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { typeStack.pop(); } - + private void checkTypeDeclaration(TypeDeclaration typeDecl) { - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, typeDecl.name); + ContextToken tok = CompilationAndWeavingContext.enteringPhase( + CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, typeDecl.name); if (!(typeDecl instanceof AspectDeclaration)) { if (ajAnnotations.hasAspectAnnotation) { validateAspectDeclaration(typeDecl); @@ -134,7 +135,8 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { if (parentSTB.scope != null) { TypeDeclaration parentDecl = parentSTB.scope.referenceContext; if (isAspect(parentDecl)) { - typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"a class cannot extend an aspect"); + typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, + "a class cannot extend an aspect"); } } } @@ -143,11 +145,8 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { } else { // check that aspect doesn't have @Aspect annotation, we've already added on ourselves. if (ajAnnotations.hasMultipleAspectAnnotations) { - typeDecl.scope.problemReporter().signalError( - typeDecl.sourceStart, - typeDecl.sourceEnd, - "aspects cannot have @Aspect annotation" - ); + typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, + "aspects cannot have @Aspect annotation"); } } CompilationAndWeavingContext.leavingPhase(tok); @@ -156,114 +155,109 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { ajAnnotations = new AspectJAnnotations(fieldDeclaration.annotations); if (ajAnnotations.hasDeclareParents && !insideAspect()) { - scope.problemReporter().signalError(fieldDeclaration.sourceStart, - fieldDeclaration.sourceEnd, - "DeclareParents can only be used inside an aspect type"); + scope.problemReporter().signalError(fieldDeclaration.sourceStart, fieldDeclaration.sourceEnd, + "DeclareParents can only be used inside an aspect type"); } return true; } + public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { if (methodDeclaration.hasErrors()) { return false; } - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, methodDeclaration.selector); + ContextToken tok = CompilationAndWeavingContext.enteringPhase( + CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, methodDeclaration.selector); ajAnnotations = new AspectJAnnotations(methodDeclaration.annotations); if (!methodDeclaration.getClass().equals(AjMethodDeclaration.class)) { // simply test for innapropriate use of annotations on code-style members if (methodDeclaration instanceof PointcutDeclaration) { - if (ajAnnotations.hasMultiplePointcutAnnotations || - ajAnnotations.hasAdviceAnnotation || - ajAnnotations.hasAspectAnnotation || - ajAnnotations.hasAdviceNameAnnotation) { - methodDeclaration.scope.problemReporter().signalError( - methodDeclaration.sourceStart, - methodDeclaration.sourceEnd, - "@AspectJ annotations cannot be declared on this aspect member"); + if (ajAnnotations.hasMultiplePointcutAnnotations || ajAnnotations.hasAdviceAnnotation + || ajAnnotations.hasAspectAnnotation || ajAnnotations.hasAdviceNameAnnotation) { + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, + methodDeclaration.sourceEnd, "@AspectJ annotations cannot be declared on this aspect member"); } } else if (methodDeclaration instanceof AdviceDeclaration) { - if (ajAnnotations.hasMultipleAdviceAnnotations || - ajAnnotations.hasAspectAnnotation || - ajAnnotations.hasPointcutAnnotation) { - methodDeclaration.scope.problemReporter().signalError( - methodDeclaration.sourceStart, - methodDeclaration.sourceEnd, - "Only @AdviceName AspectJ annotation allowed on advice"); - } + if (ajAnnotations.hasMultipleAdviceAnnotations || ajAnnotations.hasAspectAnnotation + || ajAnnotations.hasPointcutAnnotation) { + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, + methodDeclaration.sourceEnd, "Only @AdviceName AspectJ annotation allowed on advice"); + } } else { if (ajAnnotations.hasAspectJAnnotations()) { - methodDeclaration.scope.problemReporter().signalError( - methodDeclaration.sourceStart, - methodDeclaration.sourceEnd, - "@AspectJ annotations cannot be declared on this aspect member"); + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, + methodDeclaration.sourceEnd, "@AspectJ annotations cannot be declared on this aspect member"); } } CompilationAndWeavingContext.leavingPhase(tok); return false; } - + if (ajAnnotations.hasAdviceAnnotation) { validateAdvice(methodDeclaration); } else if (ajAnnotations.hasPointcutAnnotation) { - convertToPointcutDeclaration(methodDeclaration,scope); + convertToPointcutDeclaration(methodDeclaration, scope); } CompilationAndWeavingContext.leavingPhase(tok); return false; } - - private boolean isAspectJAnnotation(Annotation ann) { - if (ann.resolvedType == null) return false; - char[] sig = ann.resolvedType.signature(); - return CharOperation.contains(orgAspectJLangAnnotation, sig); - } - + + // private boolean isAspectJAnnotation(Annotation ann) { + // if (ann.resolvedType == null) return false; + // char[] sig = ann.resolvedType.signature(); + // return CharOperation.contains(orgAspectJLangAnnotation, sig); + // } + private boolean insideAspect() { - if (typeStack.empty()) return false; + if (typeStack.empty()) + return false; TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek(); return isAspect(typeDecl); } - + private boolean isAspect(TypeDeclaration typeDecl) { - if (typeDecl instanceof AspectDeclaration) return true; + if (typeDecl instanceof AspectDeclaration) + return true; return new AspectJAnnotations(typeDecl.annotations).hasAspectAnnotation; } - + /** - * aspect must be public - * nested aspect must be static - * cannot extend a concrete aspect - * pointcut in perclause must be good. + * aspect must be public nested aspect must be static cannot extend a concrete aspect pointcut in perclause must be good. */ private void validateAspectDeclaration(TypeDeclaration typeDecl) { if (typeStack.size() > 1) { // it's a nested aspect if (!Modifier.isStatic(typeDecl.modifiers)) { - typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, "inner aspects must be static"); + typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, + "inner aspects must be static"); return; } } - + SourceTypeBinding binding = typeDecl.binding; if (binding != null) { if (binding.isEnum() || binding.isInterface() || binding.isAnnotationType()) { - typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"only classes can have an @Aspect annotation"); + typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, + "only classes can have an @Aspect annotation"); } } - //FIXME AV - do we really want that -// if (!Modifier.isPublic(typeDecl.modifiers)) { -// typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"@Aspect class must be public"); -// } + // FIXME AV - do we really want that + // if (!Modifier.isPublic(typeDecl.modifiers)) { + // typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"@Aspect class must be public"); + // } - TypeReference parentRef = typeDecl.superclass; + TypeReference parentRef = typeDecl.superclass; if (parentRef != null) { TypeBinding parentBinding = parentRef.resolvedType; if (parentBinding instanceof SourceTypeBinding) { SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding; - if (parentSTB.scope!=null) { // scope is null if its a binarytypebinding (in AJ world, thats a subclass of SourceTypeBinding) - TypeDeclaration parentDecl = parentSTB.scope.referenceContext; + if (parentSTB.scope != null) { // scope is null if its a binarytypebinding (in AJ world, thats a subclass of + // SourceTypeBinding) + TypeDeclaration parentDecl = parentSTB.scope.referenceContext; if (isAspect(parentDecl) && !Modifier.isAbstract(parentDecl.modifiers)) { - typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"cannot extend a concrete aspect"); - } + typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, + "cannot extend a concrete aspect"); + } } } } @@ -276,140 +270,128 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { try { if (perClause != null && !perClause.equals("")) { - ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLoc[0]); - Pointcut pc = new PatternParser(perClause,context).maybeParsePerClause(); - FormalBinding[] bindings = new FormalBinding[0]; - if (pc != null) pc.resolve(new EclipseScope(bindings,typeDecl.scope)); + ISourceContext context = new EclipseSourceContext(unit.compilationResult, pcLoc[0]); + Pointcut pc = new PatternParser(perClause, context).maybeParsePerClause(); + FormalBinding[] bindings = new FormalBinding[0]; + if (pc != null) + pc.resolve(new EclipseScope(bindings, typeDecl.scope)); } - } catch(ParserException pEx) { - typeDecl.scope.problemReporter().parseError( - pcLoc[0] + pEx.getLocation().getStart(), - pcLoc[0] + pEx.getLocation().getEnd() , - -1, - perClause.toCharArray(), - perClause, - new String[] {pEx.getMessage()}); + } catch (ParserException pEx) { + typeDecl.scope.problemReporter().parseError(pcLoc[0] + pEx.getLocation().getStart(), + pcLoc[0] + pEx.getLocation().getEnd(), -1, perClause.toCharArray(), perClause, + new String[] { pEx.getMessage() }); } } - + /** - * 1) Advice must be public - * 2) Advice must have a void return type if not around advice - * 3) Advice must not have any other @AspectJ annotations - * 4) After throwing advice must declare the thrown formal - * 5) After returning advice must declare the returning formal - * 6) Advice must not be static + * 1) Advice must be public 2) Advice must have a void return type if not around advice 3) Advice must not have any other @AspectJ + * annotations 4) After throwing advice must declare the thrown formal 5) After returning advice must declare the returning + * formal 6) Advice must not be static */ private void validateAdvice(MethodDeclaration methodDeclaration) { - + if (!insideAspect()) { - methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, - methodDeclaration.sourceEnd, - "Advice must be declared inside an aspect type"); + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, + "Advice must be declared inside an aspect type"); } - + if (!Modifier.isPublic(methodDeclaration.modifiers)) { - methodDeclaration.scope.problemReporter() - .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"advice must be public"); + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, + "advice must be public"); } if (Modifier.isStatic(methodDeclaration.modifiers)) { - methodDeclaration.scope.problemReporter() - .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"advice can not be declared static"); + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, + "advice can not be declared static"); } - + if (ajAnnotations.hasMultipleAdviceAnnotations) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.duplicateAdviceAnnotation); } if (ajAnnotations.hasPointcutAnnotation) { - methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.pointcutAnnotation); + methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.pointcutAnnotation); } if (ajAnnotations.hasAspectAnnotation) { - methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation); + methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation); } if (ajAnnotations.hasAdviceNameAnnotation) { - methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation); + methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation); } if (ajAnnotations.adviceKind != AdviceKind.Around) { ensureVoidReturnType(methodDeclaration); - } - + } + if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) { int[] throwingLocation = new int[2]; - String thrownFormal = getStringLiteralFor("throwing",ajAnnotations.adviceAnnotation,throwingLocation); + String thrownFormal = getStringLiteralFor("throwing", ajAnnotations.adviceAnnotation, throwingLocation); if (thrownFormal != null) { Argument[] arguments = methodDeclaration.arguments; if (!toArgumentNames(methodDeclaration.arguments).contains(thrownFormal)) { - methodDeclaration.scope.problemReporter() - .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"throwing formal '" + thrownFormal + "' must be declared as a parameter in the advice signature"); + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, + methodDeclaration.sourceEnd, + "throwing formal '" + thrownFormal + "' must be declared as a parameter in the advice signature"); } } } - + if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) { int[] throwingLocation = new int[2]; - String returningFormal = getStringLiteralFor("returning",ajAnnotations.adviceAnnotation,throwingLocation); + String returningFormal = getStringLiteralFor("returning", ajAnnotations.adviceAnnotation, throwingLocation); if (returningFormal != null) { if (!toArgumentNames(methodDeclaration.arguments).contains(returningFormal)) { - methodDeclaration.scope.problemReporter() - .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"returning formal '" + returningFormal + "' must be declared as a parameter in the advice signature"); + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, + methodDeclaration.sourceEnd, + "returning formal '" + returningFormal + "' must be declared as a parameter in the advice signature"); } } } resolveAndSetPointcut(methodDeclaration, ajAnnotations.adviceAnnotation); - + + } + + /** + * Get the argument names as a string list + * + * @param arguments + * @return argument names (possibly empty) + */ + private List toArgumentNames(Argument[] arguments) { + List names = new ArrayList(); + if (arguments == null) { + return names; + } else { + for (int i = 0; i < arguments.length; i++) { + names.add(new String(arguments[i].name)); + } + return names; + } } - /** - * Get the argument names as a string list - * @param arguments - * @return argument names (possibly empty) - */ - private List toArgumentNames(Argument[] arguments) { - List names = new ArrayList(); - if (arguments == null) { - return names; - } else { - for (int i = 0; i < arguments.length; i++) { - names.add(new String(arguments[i].name)); - } - return names; - } - } - - private void resolveAndSetPointcut(MethodDeclaration methodDeclaration, Annotation adviceAnn) { + private void resolveAndSetPointcut(MethodDeclaration methodDeclaration, Annotation adviceAnn) { int[] pcLocation = new int[2]; - String pointcutExpression = getStringLiteralFor("pointcut",adviceAnn,pcLocation); - if (pointcutExpression == null) pointcutExpression = getStringLiteralFor("value",adviceAnn,pcLocation); + String pointcutExpression = getStringLiteralFor("pointcut", adviceAnn, pcLocation); + if (pointcutExpression == null) + pointcutExpression = getStringLiteralFor("value", adviceAnn, pcLocation); try { - ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLocation[0]); - Pointcut pc = new PatternParser(pointcutExpression,context).parsePointcut(); + ISourceContext context = new EclipseSourceContext(unit.compilationResult, pcLocation[0]); + Pointcut pc = new PatternParser(pointcutExpression, context).parsePointcut(); FormalBinding[] bindings = buildFormalAdviceBindingsFrom(methodDeclaration); - pc.resolve(new EclipseScope(bindings,methodDeclaration.scope)); + pc.resolve(new EclipseScope(bindings, methodDeclaration.scope)); EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(methodDeclaration.scope); // now create a ResolvedPointcutDefinition,make an attribute out of it, and add it to the method UnresolvedType[] paramTypes = new UnresolvedType[bindings.length]; - for (int i = 0; i < paramTypes.length; i++) paramTypes[i] = bindings[i].getType(); - ResolvedPointcutDefinition resPcutDef = - new ResolvedPointcutDefinition( - factory.fromBinding(((TypeDeclaration)typeStack.peek()).binding), - methodDeclaration.modifiers, - "anonymous", - paramTypes, - pc - ); + for (int i = 0; i < paramTypes.length; i++) + paramTypes[i] = bindings[i].getType(); + ResolvedPointcutDefinition resPcutDef = new ResolvedPointcutDefinition(factory.fromBinding(((TypeDeclaration) typeStack + .peek()).binding), methodDeclaration.modifiers, "anonymous", paramTypes, pc); AjAttribute attr = new AjAttribute.PointcutDeclarationAttribute(resPcutDef); - ((AjMethodDeclaration)methodDeclaration).addAttribute(new EclipseAttributeAdapter(attr)); - } catch(ParserException pEx) { - methodDeclaration.scope.problemReporter().parseError( - pcLocation[0] + pEx.getLocation().getStart(), - pcLocation[0] + pEx.getLocation().getEnd() , - -1, - pointcutExpression.toCharArray(), - pointcutExpression, - new String[] {pEx.getMessage()}); + ((AjMethodDeclaration) methodDeclaration).addAttribute(new EclipseAttributeAdapter(attr)); + } catch (ParserException pEx) { + methodDeclaration.scope.problemReporter().parseError(pcLocation[0] + pEx.getLocation().getStart(), + pcLocation[0] + pEx.getLocation().getEnd(), -1, pointcutExpression.toCharArray(), pointcutExpression, + new String[] { pEx.getMessage() }); } } @@ -417,7 +399,7 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { boolean returnsVoid = true; if ((methodDeclaration.returnType instanceof SingleTypeReference)) { SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType; - if (!CharOperation.equals(voidType,retType.token)) { + if (!CharOperation.equals(voidType, retType.token)) { returnsVoid = false; } } else { @@ -425,42 +407,43 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { } if (!returnsVoid) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, - methodDeclaration.returnType.sourceEnd, - "This advice must return void"); + methodDeclaration.returnType.sourceEnd, "This advice must return void"); } } - + private FormalBinding[] buildFormalAdviceBindingsFrom(MethodDeclaration mDecl) { - if (mDecl.arguments == null) return new FormalBinding[0]; - if (mDecl.binding == null) return new FormalBinding[0]; + if (mDecl.arguments == null) + return new FormalBinding[0]; + if (mDecl.binding == null) + return new FormalBinding[0]; EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(mDecl.scope); String extraArgName = maybeGetExtraArgName(); - if (extraArgName == null) extraArgName = ""; + if (extraArgName == null) + extraArgName = ""; FormalBinding[] ret = new FormalBinding[mDecl.arguments.length]; for (int i = 0; i < mDecl.arguments.length; i++) { - Argument arg = mDecl.arguments[i]; - String name = new String(arg.name); - TypeBinding argTypeBinding = mDecl.binding.parameters[i]; - UnresolvedType type = factory.fromBinding(argTypeBinding); - if (CharOperation.equals(joinPoint,argTypeBinding.signature()) || - CharOperation.equals(joinPointStaticPart,argTypeBinding.signature()) || - CharOperation.equals(joinPointEnclosingStaticPart,argTypeBinding.signature()) || - CharOperation.equals(proceedingJoinPoint,argTypeBinding.signature()) || - name.equals(extraArgName)) { - ret[i] = new FormalBinding.ImplicitFormalBinding(type,name,i); + Argument arg = mDecl.arguments[i]; + String name = new String(arg.name); + TypeBinding argTypeBinding = mDecl.binding.parameters[i]; + UnresolvedType type = factory.fromBinding(argTypeBinding); + if (CharOperation.equals(joinPoint, argTypeBinding.signature()) + || CharOperation.equals(joinPointStaticPart, argTypeBinding.signature()) + || CharOperation.equals(joinPointEnclosingStaticPart, argTypeBinding.signature()) + || CharOperation.equals(proceedingJoinPoint, argTypeBinding.signature()) || name.equals(extraArgName)) { + ret[i] = new FormalBinding.ImplicitFormalBinding(type, name, i); } else { - ret[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown"); + ret[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown"); } } return ret; } - + private String maybeGetExtraArgName() { String argName = null; if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) { - argName = getStringLiteralFor("returning",ajAnnotations.adviceAnnotation,new int[2]); + argName = getStringLiteralFor("returning", ajAnnotations.adviceAnnotation, new int[2]); } else if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) { - argName = getStringLiteralFor("throwing",ajAnnotations.adviceAnnotation,new int[2]); + argName = getStringLiteralFor("throwing", ajAnnotations.adviceAnnotation, new int[2]); } return argName; } @@ -473,18 +456,21 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { location[0] = sv.sourceStart; location[1] = sv.sourceEnd; return new String(sv.source()); - } else if (sma.memberValue instanceof NameReference && (((NameReference)sma.memberValue).binding instanceof FieldBinding)) { - Binding b = ((NameReference)sma.memberValue).binding; - Constant c = ((FieldBinding)b).constant; + } else if (sma.memberValue instanceof NameReference + && (((NameReference) sma.memberValue).binding instanceof FieldBinding)) { + Binding b = ((NameReference) sma.memberValue).binding; + Constant c = ((FieldBinding) b).constant; return c.stringValue(); } } - if (! (inAnnotation instanceof NormalAnnotation)) return null; + if (!(inAnnotation instanceof NormalAnnotation)) + return null; NormalAnnotation ann = (NormalAnnotation) inAnnotation; MemberValuePair[] mvps = ann.memberValuePairs; - if (mvps == null) return null; + if (mvps == null) + return null; for (int i = 0; i < mvps.length; i++) { - if (CharOperation.equals(memberName.toCharArray(),mvps[i].name)) { + if (CharOperation.equals(memberName.toCharArray(), mvps[i].name)) { if (mvps[i].value instanceof StringLiteral) { StringLiteral sv = (StringLiteral) mvps[i].value; location[0] = sv.sourceStart; @@ -495,123 +481,120 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { } return null; } - + private void convertToPointcutDeclaration(MethodDeclaration methodDeclaration, ClassScope scope) { TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek(); if (typeDecl.binding != null) { if (!typeDecl.binding.isClass()) { - methodDeclaration.scope.problemReporter() - .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"pointcuts can only be declared in a class or an aspect"); + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, + "pointcuts can only be declared in a class or an aspect"); } } - + if (methodDeclaration.thrownExceptions != null && methodDeclaration.thrownExceptions.length > 0) { - methodDeclaration.scope.problemReporter() - .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"pointcuts cannot throw exceptions!"); + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, + "pointcuts cannot throw exceptions!"); } - + PointcutDeclaration pcDecl = new PointcutDeclaration(unit.compilationResult); - copyAllFields(methodDeclaration,pcDecl); + copyAllFields(methodDeclaration, pcDecl); if (ajAnnotations.hasAdviceAnnotation) { - methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceAnnotation); + methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceAnnotation); } if (ajAnnotations.hasAspectAnnotation) { - methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation); + methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation); } if (ajAnnotations.hasAdviceNameAnnotation) { - methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation); + methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation); } - - boolean noValueSupplied=true; + + boolean noValueSupplied = true; boolean containsIfPcd = false; int[] pcLocation = new int[2]; - String pointcutExpression = getStringLiteralFor("value",ajAnnotations.pointcutAnnotation,pcLocation); + String pointcutExpression = getStringLiteralFor("value", ajAnnotations.pointcutAnnotation, pcLocation); try { - ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLocation[0]); - Pointcut pc = null;//abstract - if (pointcutExpression == null || pointcutExpression.length() == 0) { - noValueSupplied=true; // matches nothing pointcut - } else { - noValueSupplied=false; - pc = new PatternParser(pointcutExpression,context).parsePointcut(); - } - pcDecl.pointcutDesignator = (pc==null)?null:new PointcutDesignator(pc); + ISourceContext context = new EclipseSourceContext(unit.compilationResult, pcLocation[0]); + Pointcut pc = null;// abstract + if (pointcutExpression == null || pointcutExpression.length() == 0) { + noValueSupplied = true; // matches nothing pointcut + } else { + noValueSupplied = false; + pc = new PatternParser(pointcutExpression, context).parsePointcut(); + } + pcDecl.pointcutDesignator = (pc == null) ? null : new PointcutDesignator(pc); pcDecl.setGenerateSyntheticPointcutMethod(); TypeDeclaration onType = (TypeDeclaration) typeStack.peek(); pcDecl.postParse(onType); -// EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(methodDeclaration.scope); -// int argsLength = methodDeclaration.arguments == null ? 0 : methodDeclaration.arguments.length; + // EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(methodDeclaration.scope); + // int argsLength = methodDeclaration.arguments == null ? 0 : methodDeclaration.arguments.length; FormalBinding[] bindings = buildFormalAdviceBindingsFrom(methodDeclaration); -// FormalBinding[] bindings = new FormalBinding[argsLength]; -// for (int i = 0, len = bindings.length; i < len; i++) { -// Argument arg = methodDeclaration.arguments[i]; -// String name = new String(arg.name); -// UnresolvedType type = factory.fromBinding(methodDeclaration.binding.parameters[i]); -// bindings[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown"); -// } - swap(onType,methodDeclaration,pcDecl); + // FormalBinding[] bindings = new FormalBinding[argsLength]; + // for (int i = 0, len = bindings.length; i < len; i++) { + // Argument arg = methodDeclaration.arguments[i]; + // String name = new String(arg.name); + // UnresolvedType type = factory.fromBinding(methodDeclaration.binding.parameters[i]); + // bindings[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown"); + // } + swap(onType, methodDeclaration, pcDecl); if (pc != null) { - // has an expression - pc.resolve(new EclipseScope(bindings,methodDeclaration.scope)); - HasIfPCDVisitor ifFinder = new HasIfPCDVisitor(); - pc.traverse(ifFinder, null); - containsIfPcd = ifFinder.containsIfPcd; - } - } catch(ParserException pEx) { - methodDeclaration.scope.problemReporter().parseError( - pcLocation[0] + pEx.getLocation().getStart(), - pcLocation[0] + pEx.getLocation().getEnd() , - -1, - pointcutExpression.toCharArray(), - pointcutExpression, - new String[] {pEx.getMessage()}); - } - + // has an expression + pc.resolve(new EclipseScope(bindings, methodDeclaration.scope)); + HasIfPCDVisitor ifFinder = new HasIfPCDVisitor(); + pc.traverse(ifFinder, null); + containsIfPcd = ifFinder.containsIfPcd; + } + } catch (ParserException pEx) { + methodDeclaration.scope.problemReporter().parseError(pcLocation[0] + pEx.getLocation().getStart(), + pcLocation[0] + pEx.getLocation().getEnd(), -1, pointcutExpression.toCharArray(), pointcutExpression, + new String[] { pEx.getMessage() }); + } + boolean returnsVoid = false; boolean returnsBoolean = false; if ((methodDeclaration.returnType instanceof SingleTypeReference)) { SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType; - if (CharOperation.equals(voidType,retType.token)) returnsVoid = true; - if (CharOperation.equals(booleanType,retType.token)) returnsBoolean = true; - } + if (CharOperation.equals(voidType, retType.token)) + returnsVoid = true; + if (CharOperation.equals(booleanType, retType.token)) + returnsBoolean = true; + } if (!returnsVoid && !containsIfPcd) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, - methodDeclaration.returnType.sourceEnd, - "Methods annotated with @Pointcut must return void unless the pointcut contains an if() expression"); + methodDeclaration.returnType.sourceEnd, + "Methods annotated with @Pointcut must return void unless the pointcut contains an if() expression"); } if (!returnsBoolean && containsIfPcd) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, - methodDeclaration.returnType.sourceEnd, - "Methods annotated with @Pointcut must return boolean when the pointcut contains an if() expression"); + methodDeclaration.returnType.sourceEnd, + "Methods annotated with @Pointcut must return boolean when the pointcut contains an if() expression"); } - + if (methodDeclaration.statements != null && methodDeclaration.statements.length > 0 && !containsIfPcd) { + methodDeclaration.scope.problemReporter() + .signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, + "Pointcuts without an if() expression should have an empty method body"); + } + + if (pcDecl.pointcutDesignator == null) { + if (Modifier.isAbstract(methodDeclaration.modifiers) || noValueSupplied // this is a matches nothing pointcut + // those 2 checks makes sense for aop.xml concretization but NOT for regular abstraction of pointcut + // && returnsVoid + // && (methodDeclaration.arguments == null || methodDeclaration.arguments.length == 0)) { + ) { + ;// fine + } else { + methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, + methodDeclaration.returnType.sourceEnd, + "Method annotated with @Pointcut() for abstract pointcut must be abstract"); + } + } else if (Modifier.isAbstract(methodDeclaration.modifiers)) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, - methodDeclaration.returnType.sourceEnd, - "Pointcuts without an if() expression should have an empty method body"); - } - - if (pcDecl.pointcutDesignator == null) { - if (Modifier.isAbstract(methodDeclaration.modifiers) - || noValueSupplied // this is a matches nothing pointcut - //those 2 checks makes sense for aop.xml concretization but NOT for regular abstraction of pointcut - //&& returnsVoid - //&& (methodDeclaration.arguments == null || methodDeclaration.arguments.length == 0)) { - ) { - ;//fine - } else { - methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, - methodDeclaration.returnType.sourceEnd, - "Method annotated with @Pointcut() for abstract pointcut must be abstract"); - } - } else if (Modifier.isAbstract(methodDeclaration.modifiers)) { - methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, - methodDeclaration.returnType.sourceEnd, - "Method annotated with non abstract @Pointcut(\""+pointcutExpression+"\") is abstract"); - } - } - + methodDeclaration.returnType.sourceEnd, + "Method annotated with non abstract @Pointcut(\"" + pointcutExpression + "\") is abstract"); + } + } + private void copyAllFields(MethodDeclaration from, MethodDeclaration to) { to.annotations = from.annotations; to.arguments = from.arguments; @@ -635,16 +618,16 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { to.thrownExceptions = from.thrownExceptions; to.typeParameters = from.typeParameters; } - + private void swap(TypeDeclaration inType, MethodDeclaration thisDeclaration, MethodDeclaration forThatDeclaration) { for (int i = 0; i < inType.methods.length; i++) { - if (inType.methods[i] == thisDeclaration) { + if (inType.methods[i] == thisDeclaration) { inType.methods[i] = forThatDeclaration; break; } } } - + private static class AspectJAnnotations { boolean hasAdviceAnnotation = false; boolean hasPointcutAnnotation = false; @@ -654,7 +637,7 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { boolean hasMultipleAdviceAnnotations = false; boolean hasMultiplePointcutAnnotations = false; boolean hasMultipleAspectAnnotations = false; - + AdviceKind adviceKind = null; Annotation adviceAnnotation = null; Annotation pointcutAnnotation = null; @@ -664,33 +647,35 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { Annotation duplicateAdviceAnnotation = null; Annotation duplicatePointcutAnnotation = null; Annotation duplicateAspectAnnotation = null; - + public AspectJAnnotations(Annotation[] annotations) { - if (annotations == null) return; + if (annotations == null) + return; for (int i = 0; i < annotations.length; i++) { - if (annotations[i].resolvedType == null) continue; // user messed up annotation declaration + if (annotations[i].resolvedType == null) + continue; // user messed up annotation declaration char[] sig = annotations[i].resolvedType.signature(); - if (CharOperation.equals(afterAdviceSig,sig)) { + if (CharOperation.equals(afterAdviceSig, sig)) { adviceKind = AdviceKind.After; addAdviceAnnotation(annotations[i]); - } else if (CharOperation.equals(afterReturningAdviceSig,sig)) { + } else if (CharOperation.equals(afterReturningAdviceSig, sig)) { adviceKind = AdviceKind.AfterReturning; addAdviceAnnotation(annotations[i]); - } else if (CharOperation.equals(afterThrowingAdviceSig,sig)) { + } else if (CharOperation.equals(afterThrowingAdviceSig, sig)) { adviceKind = AdviceKind.AfterThrowing; addAdviceAnnotation(annotations[i]); - } else if (CharOperation.equals(beforeAdviceSig,sig)) { + } else if (CharOperation.equals(beforeAdviceSig, sig)) { adviceKind = AdviceKind.Before; addAdviceAnnotation(annotations[i]); - } else if (CharOperation.equals(aroundAdviceSig,sig)) { + } else if (CharOperation.equals(aroundAdviceSig, sig)) { adviceKind = AdviceKind.Around; addAdviceAnnotation(annotations[i]); - } else if (CharOperation.equals(adviceNameSig,sig)) { + } else if (CharOperation.equals(adviceNameSig, sig)) { hasAdviceNameAnnotation = true; adviceNameAnnotation = annotations[i]; - } else if (CharOperation.equals(declareParentsSig,sig)) { + } else if (CharOperation.equals(declareParentsSig, sig)) { hasDeclareParents = true; - } else if (CharOperation.equals(aspectSig,sig)) { + } else if (CharOperation.equals(aspectSig, sig)) { if (hasAspectAnnotation) { hasMultipleAspectAnnotations = true; duplicateAspectAnnotation = annotations[i]; @@ -698,7 +683,7 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { hasAspectAnnotation = true; aspectAnnotation = annotations[i]; } - } else if (CharOperation.equals(pointcutSig,sig)) { + } else if (CharOperation.equals(pointcutSig, sig)) { if (hasPointcutAnnotation) { hasMultiplePointcutAnnotations = true; duplicatePointcutAnnotation = annotations[i]; @@ -706,11 +691,11 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { hasPointcutAnnotation = true; pointcutAnnotation = annotations[i]; } - + } } } - + public boolean hasAspectJAnnotations() { return hasAdviceAnnotation || hasPointcutAnnotation || hasAdviceNameAnnotation || hasAspectAnnotation; } @@ -725,10 +710,10 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { } } } - + private static class HasIfPCDVisitor extends AbstractPatternNodeVisitor { public boolean containsIfPcd = false; - + public Object visit(IfPointcut node, Object data) { containsIfPcd = true; return data; diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java index ac2613c97..48123a750 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java @@ -10,7 +10,6 @@ * PARC initial implementation * ******************************************************************/ - package org.aspectj.ajdt.internal.compiler.lookup; import java.lang.reflect.Modifier; @@ -27,7 +26,6 @@ import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.asm.AsmManager; import org.aspectj.bridge.IMessage; -import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; @@ -65,7 +63,6 @@ import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; -import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; @@ -78,399 +75,402 @@ import org.aspectj.weaver.patterns.DeclareParents; /** * Overrides the default eclipse LookupEnvironment for two purposes. * - * 1. To provide some additional phases to completeTypeBindings - * that weave declare parents and inter-type declarations at the correct time. + * 1. To provide some additional phases to completeTypeBindings that weave declare parents and inter-type declarations + * at the correct time. * - * 2. To intercept the loading of new binary types to ensure the they will have - * declare parents and inter-type declarations woven when appropriate. + * 2. To intercept the loading of new binary types to ensure the they will have declare parents and inter-type declarations woven + * when appropriate. * * @author Jim Hugunin */ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousClassCreationListener { - public EclipseFactory factory = null; - -// private boolean builtInterTypesAndPerClauses = false; + public EclipseFactory factory = null; + + // private boolean builtInterTypesAndPerClauses = false; private List pendingTypesToWeave = new ArrayList(); - + // Q: What are dangerousInterfaces? // A: An interface is considered dangerous if an ITD has been made upon it and that ITD - // requires the top most implementors of the interface to be woven *and yet* the aspect - // responsible for the ITD is not in the 'world'. + // requires the top most implementors of the interface to be woven *and yet* the aspect + // responsible for the ITD is not in the 'world'. // Q: Err, how can that happen? - // A: When a type is on the inpath, it is 'processed' when completing type bindings. At this - // point we look at any type mungers it was affected by previously (stored in the weaver - // state info attribute). Effectively we are working with a type munger and yet may not have its - // originating aspect in the world. This is a problem if, for example, the aspect supplied - // a 'body' for a method targetting an interface - since the top most implementors should - // be woven by the munger from the aspect. When this happens we store the interface name here - // in the map - if we later process a type that is the topMostImplementor of a dangerous - // interface then we put out an error message. - - /** interfaces targetted by ITDs that have to be implemented by accessing the topMostImplementor - * of the interface, yet the aspect where the ITD originated is not in the world */ + // A: When a type is on the inpath, it is 'processed' when completing type bindings. At this + // point we look at any type mungers it was affected by previously (stored in the weaver + // state info attribute). Effectively we are working with a type munger and yet may not have its + // originating aspect in the world. This is a problem if, for example, the aspect supplied + // a 'body' for a method targetting an interface - since the top most implementors should + // be woven by the munger from the aspect. When this happens we store the interface name here + // in the map - if we later process a type that is the topMostImplementor of a dangerous + // interface then we put out an error message. + + /** + * interfaces targetted by ITDs that have to be implemented by accessing the topMostImplementor of the interface, yet the aspect + * where the ITD originated is not in the world + */ private Map dangerousInterfaces = new HashMap(); - - public AjLookupEnvironment( - ITypeRequestor typeRequestor, - CompilerOptions options, - ProblemReporter problemReporter, - INameEnvironment nameEnvironment) { + + public AjLookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter, + INameEnvironment nameEnvironment) { super(typeRequestor, options, problemReporter, nameEnvironment); } - - //??? duplicates some of super's code + + // ??? duplicates some of super's code public void completeTypeBindings() { AsmManager.setCompletingTypeBindings(true); - ContextToken completeTypeBindingsToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.COMPLETING_TYPE_BINDINGS, ""); -// builtInterTypesAndPerClauses = false; - //pendingTypesToWeave = new ArrayList(); + ContextToken completeTypeBindingsToken = CompilationAndWeavingContext.enteringPhase( + CompilationAndWeavingContext.COMPLETING_TYPE_BINDINGS, ""); + // builtInterTypesAndPerClauses = false; + // pendingTypesToWeave = new ArrayList(); stepCompleted = BUILD_TYPE_HIERARCHY; - + for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CHECK_AND_SET_IMPORTS, units[i].compilationResult.fileName); + ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CHECK_AND_SET_IMPORTS, + units[i].compilationResult.fileName); units[i].scope.checkAndSetImports(); CompilationAndWeavingContext.leavingPhase(tok); } stepCompleted = CHECK_AND_SET_IMPORTS; - + for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CONNECTING_TYPE_HIERARCHY, units[i].compilationResult.fileName); + ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CONNECTING_TYPE_HIERARCHY, + units[i].compilationResult.fileName); units[i].scope.connectTypeHierarchy(); CompilationAndWeavingContext.leavingPhase(tok); } stepCompleted = CONNECT_TYPE_HIERARCHY; - + for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.BUILDING_FIELDS_AND_METHODS, units[i].compilationResult.fileName); -// units[i].scope.checkParameterizedTypes(); do this check a little later, after ITDs applied to stbs + ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.BUILDING_FIELDS_AND_METHODS, + units[i].compilationResult.fileName); + // units[i].scope.checkParameterizedTypes(); do this check a little later, after ITDs applied to stbs units[i].scope.buildFieldsAndMethods(); CompilationAndWeavingContext.leavingPhase(tok); } - + // would like to gather up all TypeDeclarations at this point and put them in the factory for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; for (int j = 0; j < b.length; j++) { - factory.addSourceTypeBinding(b[j],units[i]); + factory.addSourceTypeBinding(b[j], units[i]); } } - + // We won't find out about anonymous types until later though, so register to be // told about them when they turn up. AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(this); - + // need to build inter-type declarations for all AspectDeclarations at this point // this MUST be done in order from super-types to subtypes List typesToProcess = new ArrayList(); - for (int i=lastCompletedUnitIndex+1; i<=lastUnitIndex; i++) { + for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { CompilationUnitScope cus = units[i].scope; SourceTypeBinding[] stbs = cus.topLevelTypes; - for (int j=0; j0) { + while (typesToProcess.size() > 0) { // removes types from the list as they are processed... - collectAllITDsAndDeclares((SourceTypeBinding)typesToProcess.get(0),typesToProcess); - } - + collectAllITDsAndDeclares((SourceTypeBinding) typesToProcess.get(0), typesToProcess); + } + factory.finishTypeMungers(); - + // now do weaving Collection typeMungers = factory.getTypeMungers(); - + Collection declareParents = factory.getDeclareParents(); Collection declareAnnotationOnTypes = factory.getDeclareAnnotationOnTypes(); doPendingWeaves(); - + // We now have some list of types to process, and we are about to apply the type mungers. // There can be situations where the order of types passed to the compiler causes the - // output from the compiler to vary - THIS IS BAD. For example, if we have class A - // and class B extends A. Also, an aspect that 'declare parents: A+ implements Serializable' + // output from the compiler to vary - THIS IS BAD. For example, if we have class A + // and class B extends A. Also, an aspect that 'declare parents: A+ implements Serializable' // then depending on whether we see A first, we may or may not make B serializable. - - // The fix is to process them in the right order, ensuring that for a type we process its - // supertypes and superinterfaces first. This algorithm may have problems with: + + // The fix is to process them in the right order, ensuring that for a type we process its + // supertypes and superinterfaces first. This algorithm may have problems with: // - partial hierarchies (e.g. suppose types A,B,C are in a hierarchy and A and C are to be woven but not B) // - weaving that brings new types in for processing (see pendingTypesToWeave.add() calls) after we thought - // we had the full list. + // we had the full list. // // but these aren't common cases (he bravely said...) - boolean typeProcessingOrderIsImportant = declareParents.size()>0 || declareAnnotationOnTypes.size()>0; //DECAT - + boolean typeProcessingOrderIsImportant = declareParents.size() > 0 || declareAnnotationOnTypes.size() > 0; // DECAT + if (typeProcessingOrderIsImportant) { typesToProcess = new ArrayList(); - for (int i=lastCompletedUnitIndex+1; i<=lastUnitIndex; i++) { + for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { CompilationUnitScope cus = units[i].scope; SourceTypeBinding[] stbs = cus.topLevelTypes; - for (int j=0; j0) { + while (typesToProcess.size() > 0) { // A side effect of weaveIntertypes() is that the processed type is removed from the collection - weaveIntertypes(typesToProcess,(SourceTypeBinding)typesToProcess.get(0),typeMungers,declareParents,declareAnnotationOnTypes); + weaveIntertypes(typesToProcess, (SourceTypeBinding) typesToProcess.get(0), typeMungers, declareParents, + declareAnnotationOnTypes); } - + } else { // Order isn't important for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { - //System.err.println("Working on "+new String(units[i].getFileName())); - weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents,declareAnnotationOnTypes); + // System.err.println("Working on "+new String(units[i].getFileName())); + weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents, declareAnnotationOnTypes); + } + } + + for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { + units[i].scope.checkParameterizedTypes(); + } + + for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { + SourceTypeBinding[] b = units[i].scope.topLevelTypes; + for (int j = 0; j < b.length; j++) { + ContextToken tok = CompilationAndWeavingContext.enteringPhase( + CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, b[j].sourceName); + resolvePointcutDeclarations(b[j].scope); + CompilationAndWeavingContext.leavingPhase(tok); } } - for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { - units[i].scope.checkParameterizedTypes(); - } - - for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { - SourceTypeBinding[] b = units[i].scope.topLevelTypes; - for (int j = 0; j < b.length; j++) { - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, b[j].sourceName); - resolvePointcutDeclarations(b[j].scope); - CompilationAndWeavingContext.leavingPhase(tok); - } - } - - for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { - SourceTypeBinding[] b = units[i].scope.topLevelTypes; - for (int j = 0; j < b.length; j++) { - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, b[j].sourceName); - addAdviceLikeDeclares(b[j].scope); - CompilationAndWeavingContext.leavingPhase(tok); - } - } - - for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { - units[i] = null; // release unnecessary reference to the parsed unit - } - + for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { + SourceTypeBinding[] b = units[i].scope.topLevelTypes; + for (int j = 0; j < b.length; j++) { + ContextToken tok = CompilationAndWeavingContext.enteringPhase( + CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, b[j].sourceName); + addAdviceLikeDeclares(b[j].scope); + CompilationAndWeavingContext.leavingPhase(tok); + } + } + + for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { + units[i] = null; // release unnecessary reference to the parsed unit + } + stepCompleted = BUILD_FIELDS_AND_METHODS; lastCompletedUnitIndex = lastUnitIndex; AsmManager.setCompletingTypeBindings(false); factory.getWorld().getCrosscuttingMembersSet().verify(); - CompilationAndWeavingContext.leavingPhase(completeTypeBindingsToken); + CompilationAndWeavingContext.leavingPhase(completeTypeBindingsToken); } - - - /** - * For any given sourcetypebinding, this method checks that if it is a parameterized aspect that - * the type parameters specified for any supertypes meet the bounds for the generic type - * variables. - */ - private void verifyAnyTypeParametersMeetBounds(SourceTypeBinding sourceType) { - ResolvedType onType = factory.fromEclipse(sourceType); - if (onType.isAspect()) { - ResolvedType superType = factory.fromEclipse(sourceType.superclass); - // Don't need to check if it was used in its RAW form or isnt generic - if (superType.isGenericType() || superType.isParameterizedType()) { - TypeVariable[] typeVariables = superType.getTypeVariables(); - UnresolvedType[] typeParams = superType.getTypeParameters(); - if (typeVariables!=null && typeParams!=null) { - for (int i = 0; i < typeVariables.length; i++) { - boolean ok = typeVariables[i].canBeBoundTo(typeParams[i].resolve(factory.getWorld())); - if (!ok) { // the supplied parameter violates the bounds - // Type {0} does not meet the specification for type parameter {1} ({2}) in generic type {3} - String msg = - WeaverMessages.format( - WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS, - typeParams[i], - new Integer(i+1), - typeVariables[i].getDisplayName(), - superType.getGenericType().getName()); - factory.getWorld().getMessageHandler().handleMessage(MessageUtil.error(msg,onType.getSourceLocation())); - } - } + + // /** + // * For any given sourcetypebinding, this method checks that if it is a parameterized aspect that + // * the type parameters specified for any supertypes meet the bounds for the generic type + // * variables. + // */ + // private void verifyAnyTypeParametersMeetBounds(SourceTypeBinding sourceType) { + // ResolvedType onType = factory.fromEclipse(sourceType); + // if (onType.isAspect()) { + // ResolvedType superType = factory.fromEclipse(sourceType.superclass); + // // Don't need to check if it was used in its RAW form or isnt generic + // if (superType.isGenericType() || superType.isParameterizedType()) { + // TypeVariable[] typeVariables = superType.getTypeVariables(); + // UnresolvedType[] typeParams = superType.getTypeParameters(); + // if (typeVariables!=null && typeParams!=null) { + // for (int i = 0; i < typeVariables.length; i++) { + // boolean ok = typeVariables[i].canBeBoundTo(typeParams[i].resolve(factory.getWorld())); + // if (!ok) { // the supplied parameter violates the bounds + // // Type {0} does not meet the specification for type parameter {1} ({2}) in generic type {3} + // String msg = + // WeaverMessages.format( + // WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS, + // typeParams[i], + // new Integer(i+1), + // typeVariables[i].getDisplayName(), + // superType.getGenericType().getName()); + // factory.getWorld().getMessageHandler().handleMessage(MessageUtil.error(msg,onType.getSourceLocation())); + // } + // } + // } + // } + // } + // } + + public void doSupertypesFirst(ReferenceBinding rb, Collection yetToProcess) { + if (rb instanceof SourceTypeBinding) { + if (yetToProcess.contains(rb)) { + collectAllITDsAndDeclares((SourceTypeBinding) rb, yetToProcess); } + } else if (rb instanceof ParameterizedTypeBinding) { + // If its a PTB we need to pull the SourceTypeBinding out of it. + ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) rb; + if (ptb.type instanceof SourceTypeBinding && yetToProcess.contains(ptb.type)) { + collectAllITDsAndDeclares((SourceTypeBinding) ptb.type, yetToProcess); } } - - - } - public void doSupertypesFirst(ReferenceBinding rb,Collection yetToProcess) { - if (rb instanceof SourceTypeBinding) { - if (yetToProcess.contains(rb)) { - collectAllITDsAndDeclares((SourceTypeBinding)rb, yetToProcess); - } - } else if (rb instanceof ParameterizedTypeBinding) { - // If its a PTB we need to pull the SourceTypeBinding out of it. - ParameterizedTypeBinding ptb = (ParameterizedTypeBinding)rb; - if (ptb.type instanceof SourceTypeBinding && yetToProcess.contains(ptb.type)) { - collectAllITDsAndDeclares((SourceTypeBinding)ptb.type, yetToProcess); - } - } - } /** - * Find all the ITDs and Declares, but it is important we do this from the supertypes - * down to the subtypes. + * Find all the ITDs and Declares, but it is important we do this from the supertypes down to the subtypes. + * * @param sourceType * @param yetToProcess */ private void collectAllITDsAndDeclares(SourceTypeBinding sourceType, Collection yetToProcess) { // Look at the supertype first - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.COLLECTING_ITDS_AND_DECLARES, sourceType.sourceName); + ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.COLLECTING_ITDS_AND_DECLARES, + sourceType.sourceName); - yetToProcess.remove(sourceType); + yetToProcess.remove(sourceType); // look out our direct supertype - doSupertypesFirst(sourceType.superclass(),yetToProcess); - - // now check our membertypes (pr119570) + doSupertypesFirst(sourceType.superclass(), yetToProcess); + + // now check our membertypes (pr119570) ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { - SourceTypeBinding rb = (SourceTypeBinding)memberTypes[i]; + SourceTypeBinding rb = (SourceTypeBinding) memberTypes[i]; if (!rb.superclass().equals(sourceType)) - doSupertypesFirst(rb.superclass(),yetToProcess); + doSupertypesFirst(rb.superclass(), yetToProcess); } - - buildInterTypeAndPerClause(sourceType.scope); - addCrosscuttingStructures(sourceType.scope); + + buildInterTypeAndPerClause(sourceType.scope); + addCrosscuttingStructures(sourceType.scope); CompilationAndWeavingContext.leavingPhase(tok); } - + /** - * Weave the parents and intertype decls into a given type. This method looks at the - * supertype and superinterfaces for the specified type and recurses to weave those first - * if they are in the full list of types we are going to process during this compile... it stops recursing - * the first time it hits a type we aren't going to process during this compile. This could cause 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 doing if you do that? + * Weave the parents and intertype decls into a given type. This method looks at the supertype and superinterfaces for the + * specified type and recurses to weave those first if they are in the full list of types we are going to process during this + * compile... it stops recursing the first time it hits a type we aren't going to process during this compile. This could cause + * 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 + * doing if you do that? */ - private void weaveIntertypes(List typesToProcess,SourceTypeBinding typeToWeave,Collection typeMungers, - Collection declareParents,Collection declareAnnotationOnTypes) { + private void weaveIntertypes(List typesToProcess, SourceTypeBinding typeToWeave, Collection typeMungers, + Collection declareParents, Collection declareAnnotationOnTypes) { // Look at the supertype first - ReferenceBinding superType = typeToWeave.superclass(); - if (typesToProcess.contains(superType) && superType instanceof SourceTypeBinding) { - //System.err.println("Recursing to supertype "+new String(superType.getFileName())); - weaveIntertypes(typesToProcess,(SourceTypeBinding)superType,typeMungers,declareParents,declareAnnotationOnTypes); - } - // Then look at the superinterface list + ReferenceBinding superType = typeToWeave.superclass(); + if (typesToProcess.contains(superType) && superType instanceof SourceTypeBinding) { + // System.err.println("Recursing to supertype "+new String(superType.getFileName())); + weaveIntertypes(typesToProcess, (SourceTypeBinding) superType, typeMungers, declareParents, declareAnnotationOnTypes); + } + // Then look at the superinterface list ReferenceBinding[] interfaceTypes = typeToWeave.superInterfaces(); - for (int i = 0; i < interfaceTypes.length; i++) { - ReferenceBinding binding = interfaceTypes[i]; - if (typesToProcess.contains(binding) && binding instanceof SourceTypeBinding) { - //System.err.println("Recursing to superinterface "+new String(binding.getFileName())); - weaveIntertypes(typesToProcess,(SourceTypeBinding)binding,typeMungers,declareParents,declareAnnotationOnTypes); - } + for (int i = 0; i < interfaceTypes.length; i++) { + ReferenceBinding binding = interfaceTypes[i]; + if (typesToProcess.contains(binding) && binding instanceof SourceTypeBinding) { + // System.err.println("Recursing to superinterface "+new String(binding.getFileName())); + weaveIntertypes(typesToProcess, (SourceTypeBinding) binding, typeMungers, declareParents, declareAnnotationOnTypes); + } } - weaveInterTypeDeclarations(typeToWeave,typeMungers,declareParents,declareAnnotationOnTypes,false); - typesToProcess.remove(typeToWeave); + weaveInterTypeDeclarations(typeToWeave, typeMungers, declareParents, declareAnnotationOnTypes, false); + typesToProcess.remove(typeToWeave); } private void doPendingWeaves() { - for (Iterator i = pendingTypesToWeave.iterator(); i.hasNext(); ) { - SourceTypeBinding t = (SourceTypeBinding)i.next(); - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, t.sourceName); + for (Iterator i = pendingTypesToWeave.iterator(); i.hasNext();) { + SourceTypeBinding t = (SourceTypeBinding) i.next(); + ContextToken tok = CompilationAndWeavingContext.enteringPhase( + CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, t.sourceName); weaveInterTypeDeclarations(t); CompilationAndWeavingContext.leavingPhase(tok); } pendingTypesToWeave.clear(); } - - private void addAdviceLikeDeclares(ClassScope s) { - TypeDeclaration dec = s.referenceContext; - - if (dec instanceof AspectDeclaration) { - ResolvedType typeX = factory.fromEclipse(dec.binding); - factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX); - } - - SourceTypeBinding sourceType = s.referenceContext.binding; - ReferenceBinding[] memberTypes = sourceType.memberTypes; - for (int i = 0, length = memberTypes.length; i < length; i++) { - addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope); - } - } - - private void addCrosscuttingStructures(ClassScope s) { - TypeDeclaration dec = s.referenceContext; - - if (dec instanceof AspectDeclaration) { - ResolvedType typeX = factory.fromEclipse(dec.binding); - factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX,false); - - if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) { - factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass(),false); - } - } - - SourceTypeBinding sourceType = s.referenceContext.binding; - ReferenceBinding[] memberTypes = sourceType.memberTypes; - for (int i = 0, length = memberTypes.length; i < length; i++) { - addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope); - } - } - - private void resolvePointcutDeclarations(ClassScope s) { - TypeDeclaration dec = s.referenceContext; - SourceTypeBinding sourceType = s.referenceContext.binding; - boolean hasPointcuts = false; - AbstractMethodDeclaration[] methods = dec.methods; - boolean initializedMethods = false; - if (methods != null) { - for (int i=0; i < methods.length; i++) { - if (methods[i] instanceof PointcutDeclaration) { - hasPointcuts = true; - if (!initializedMethods) { - sourceType.methods(); //force initialization - initializedMethods = true; - } - ((PointcutDeclaration)methods[i]).resolvePointcut(s); - } - } - } - + + private void addAdviceLikeDeclares(ClassScope s) { + TypeDeclaration dec = s.referenceContext; + + if (dec instanceof AspectDeclaration) { + ResolvedType typeX = factory.fromEclipse(dec.binding); + factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX); + } + + SourceTypeBinding sourceType = s.referenceContext.binding; + ReferenceBinding[] memberTypes = sourceType.memberTypes; + for (int i = 0, length = memberTypes.length; i < length; i++) { + addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope); + } + } + + private void addCrosscuttingStructures(ClassScope s) { + TypeDeclaration dec = s.referenceContext; + + if (dec instanceof AspectDeclaration) { + ResolvedType typeX = factory.fromEclipse(dec.binding); + factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX, false); + + if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) { + factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass(), false); + } + } + + SourceTypeBinding sourceType = s.referenceContext.binding; + ReferenceBinding[] memberTypes = sourceType.memberTypes; + for (int i = 0, length = memberTypes.length; i < length; i++) { + addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope); + } + } + + private void resolvePointcutDeclarations(ClassScope s) { + TypeDeclaration dec = s.referenceContext; + SourceTypeBinding sourceType = s.referenceContext.binding; + boolean hasPointcuts = false; + AbstractMethodDeclaration[] methods = dec.methods; + boolean initializedMethods = false; + if (methods != null) { + for (int i = 0; i < methods.length; i++) { + if (methods[i] instanceof PointcutDeclaration) { + hasPointcuts = true; + if (!initializedMethods) { + sourceType.methods(); // force initialization + initializedMethods = true; + } + ((PointcutDeclaration) methods[i]).resolvePointcut(s); + } + } + } + if (hasPointcuts || dec instanceof AspectDeclaration || couldBeAnnotationStyleAspectDeclaration(dec)) { - ReferenceType name = (ReferenceType)factory.fromEclipse(sourceType); - EclipseSourceType eclipseSourceType = (EclipseSourceType)name.getDelegate(); - eclipseSourceType.checkPointcutDeclarations(); + ReferenceType name = (ReferenceType) factory.fromEclipse(sourceType); + EclipseSourceType eclipseSourceType = (EclipseSourceType) name.getDelegate(); + eclipseSourceType.checkPointcutDeclarations(); } - - ReferenceBinding[] memberTypes = sourceType.memberTypes; - for (int i = 0, length = memberTypes.length; i < length; i++) { - resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope); - } - } - - /** - * Return true if the declaration has @Aspect annotation. Called 'couldBe' rather than - * 'is' because someone else may have defined an annotation called Aspect - we can't - * verify the full name (including package name) because it may not have been resolved - * just yet and rather going through expensive resolution when we dont have to, this - * gives us a cheap check that tells us whether to bother. - */ - private boolean couldBeAnnotationStyleAspectDeclaration(TypeDeclaration dec) { - Annotation[] annotations = dec.annotations; - boolean couldBeAtAspect = false; - if (annotations != null) { - for (int i = 0; i < annotations.length && !couldBeAtAspect; i++) { - if (annotations[i].toString().equals("@Aspect")) couldBeAtAspect=true; + + ReferenceBinding[] memberTypes = sourceType.memberTypes; + for (int i = 0, length = memberTypes.length; i < length; i++) { + resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope); + } + } + + /** + * Return true if the declaration has @Aspect annotation. Called 'couldBe' rather than 'is' because someone else may have + * defined an annotation called Aspect - we can't verify the full name (including package name) because it may not have been + * resolved just yet and rather going through expensive resolution when we dont have to, this gives us a cheap check that tells + * us whether to bother. + */ + private boolean couldBeAnnotationStyleAspectDeclaration(TypeDeclaration dec) { + Annotation[] annotations = dec.annotations; + boolean couldBeAtAspect = false; + if (annotations != null) { + for (int i = 0; i < annotations.length && !couldBeAtAspect; i++) { + if (annotations[i].toString().equals("@Aspect")) + couldBeAtAspect = true; } } - return couldBeAtAspect; + return couldBeAtAspect; } private void buildInterTypeAndPerClause(ClassScope s) { TypeDeclaration dec = s.referenceContext; if (dec instanceof AspectDeclaration) { - ((AspectDeclaration)dec).buildInterTypeAndPerClause(s); + ((AspectDeclaration) dec).buildInterTypeAndPerClause(s); } - + SourceTypeBinding sourceType = s.referenceContext.binding; // test classes don't extend aspects if (sourceType.superclass != null) { ResolvedType parent = factory.fromEclipse(sourceType.superclass); if (parent.isAspect() && !isAspect(dec)) { - factory.showMessage(IMessage.ERROR, "class \'" + new String(sourceType.sourceName) + - "\' can not extend aspect \'" + parent.getName() + "\'", - factory.fromEclipse(sourceType).getSourceLocation(), null); + factory.showMessage(IMessage.ERROR, "class \'" + new String(sourceType.sourceName) + "\' can not extend aspect \'" + + parent.getName() + "\'", factory.fromEclipse(sourceType).getSourceLocation(), null); } } @@ -479,7 +479,7 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC buildInterTypeAndPerClause(((SourceTypeBinding) memberTypes[i]).scope); } } - + private boolean isAspect(TypeDeclaration decl) { if ((decl instanceof AspectDeclaration)) { return true; @@ -489,121 +489,128 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC for (int i = 0; i < decl.annotations.length; i++) { Annotation ann = decl.annotations[i]; if (ann.type instanceof SingleTypeReference) { - if (CharOperation.equals("Aspect".toCharArray(),((SingleTypeReference)ann.type).token)) return true; + if (CharOperation.equals("Aspect".toCharArray(), ((SingleTypeReference) ann.type).token)) + return true; } else if (ann.type instanceof QualifiedTypeReference) { QualifiedTypeReference qtr = (QualifiedTypeReference) ann.type; - if (qtr.tokens.length != 5) return false; - if (!CharOperation.equals("org".toCharArray(),qtr.tokens[0])) return false; - if (!CharOperation.equals("aspectj".toCharArray(),qtr.tokens[1])) return false; - if (!CharOperation.equals("lang".toCharArray(),qtr.tokens[2])) return false; - if (!CharOperation.equals("annotation".toCharArray(),qtr.tokens[3])) return false; - if (!CharOperation.equals("Aspect".toCharArray(),qtr.tokens[4])) return false; + if (qtr.tokens.length != 5) + return false; + if (!CharOperation.equals("org".toCharArray(), qtr.tokens[0])) + return false; + if (!CharOperation.equals("aspectj".toCharArray(), qtr.tokens[1])) + return false; + if (!CharOperation.equals("lang".toCharArray(), qtr.tokens[2])) + return false; + if (!CharOperation.equals("annotation".toCharArray(), qtr.tokens[3])) + return false; + if (!CharOperation.equals("Aspect".toCharArray(), qtr.tokens[4])) + return false; return true; } } } - return false; + return false; } - - private void weaveInterTypeDeclarations(CompilationUnitScope unit, Collection typeMungers, - Collection declareParents, Collection declareAnnotationOnTypes) { + + private void weaveInterTypeDeclarations(CompilationUnitScope unit, Collection typeMungers, Collection declareParents, + Collection declareAnnotationOnTypes) { for (int i = 0, length = unit.topLevelTypes.length; i < length; i++) { - weaveInterTypeDeclarations(unit.topLevelTypes[i], typeMungers, declareParents, declareAnnotationOnTypes,false); + weaveInterTypeDeclarations(unit.topLevelTypes[i], typeMungers, declareParents, declareAnnotationOnTypes, false); } } - + private void weaveInterTypeDeclarations(SourceTypeBinding sourceType) { if (!factory.areTypeMungersFinished()) { - if (!pendingTypesToWeave.contains(sourceType)) pendingTypesToWeave.add(sourceType); + if (!pendingTypesToWeave.contains(sourceType)) + pendingTypesToWeave.add(sourceType); } else { - weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(), factory.getDeclareAnnotationOnTypes(),true); + weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(), factory + .getDeclareAnnotationOnTypes(), true); } } - - private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, Collection typeMungers, - Collection declareParents, Collection declareAnnotationOnTypes, boolean skipInners) { - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, sourceType.sourceName); + private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, Collection typeMungers, Collection declareParents, + Collection declareAnnotationOnTypes, boolean skipInners) { + ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, + sourceType.sourceName); ResolvedType onType = factory.fromEclipse(sourceType); - - // AMC we shouldn't need this when generic sigs are fixed?? - if (onType.isRawType()) onType = onType.getGenericType(); + if (onType.isRawType()) + onType = onType.getGenericType(); WeaverStateInfo info = onType.getWeaverState(); - + // this test isnt quite right - there will be a case where we fail to flag a problem // with a 'dangerous interface' because the type is reweavable when we should have // because the type wasn't going to be rewoven... if that happens, we should perhaps // move this test and dangerous interface processing to the end of this method and // make it conditional on whether any of the typeMungers passed into here actually // matched this type. - if (info != null && !info.isOldStyle() && !info.isReweavable()) { - processTypeMungersFromExistingWeaverState(sourceType,onType); + if (info != null && !info.isOldStyle() && !info.isReweavable()) { + processTypeMungersFromExistingWeaverState(sourceType, onType); CompilationAndWeavingContext.leavingPhase(tok); return; } - // Check if the type we are looking at is the topMostImplementor of a dangerous interface - + // Check if the type we are looking at is the topMostImplementor of a dangerous interface - // report a problem if it is. for (Iterator i = dangerousInterfaces.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); - ResolvedType interfaceType = (ResolvedType)entry.getKey(); + ResolvedType interfaceType = (ResolvedType) entry.getKey(); if (onType.isTopmostImplementor(interfaceType)) { - factory.showMessage(IMessage.ERROR, - onType + ": " + entry.getValue(), - onType.getSourceLocation(), null); + factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null); } } - + boolean needOldStyleWarning = (info != null && info.isOldStyle()); - + onType.clearInterTypeMungers(); - + // FIXME asc perf Could optimize here, after processing the expected set of types we may bring // binary types that are not exposed to the weaver, there is no need to attempt declare parents // or declare annotation really - unless we want to report the not-exposed to weaver // messages... - + List decpToRepeat = new ArrayList(); List decaToRepeat = new ArrayList(); boolean anyNewParents = false; boolean anyNewAnnotations = false; - // first pass - // try and apply all decps - if they match, then great. If they don't then - // check if they are starred-annotation patterns. If they are not starred + // first pass + // try and apply all decps - if they match, then great. If they don't then + // check if they are starred-annotation patterns. If they are not starred // annotation patterns then they might match later...remember that... for (Iterator i = declareParents.iterator(); i.hasNext();) { - DeclareParents decp = (DeclareParents)i.next(); + DeclareParents decp = (DeclareParents) i.next(); boolean didSomething = doDeclareParents(decp, sourceType); if (didSomething) { anyNewParents = true; } else { - if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); + if (!decp.getChild().isStarAnnotation()) + decpToRepeat.add(decp); } } for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) { - DeclareAnnotation deca = (DeclareAnnotation)i.next(); - boolean didSomething = doDeclareAnnotations(deca, sourceType,true); + DeclareAnnotation deca = (DeclareAnnotation) i.next(); + boolean didSomething = doDeclareAnnotations(deca, sourceType, true); if (didSomething) { anyNewAnnotations = true; } else { - if (!deca.getTypePattern().isStar()) decaToRepeat.add(deca); + if (!deca.getTypePattern().isStar()) + decaToRepeat.add(deca); } } - - // now lets loop over and over until we have done all we can - while ((anyNewAnnotations || anyNewParents) && - (!decpToRepeat.isEmpty() || !decaToRepeat.isEmpty())) { + + // now lets loop over and over until we have done all we can + while ((anyNewAnnotations || anyNewParents) && (!decpToRepeat.isEmpty() || !decaToRepeat.isEmpty())) { anyNewParents = anyNewAnnotations = false; List forRemoval = new ArrayList(); for (Iterator i = decpToRepeat.iterator(); i.hasNext();) { - DeclareParents decp = (DeclareParents)i.next(); + DeclareParents decp = (DeclareParents) i.next(); boolean didSomething = doDeclareParents(decp, sourceType); if (didSomething) { anyNewParents = true; @@ -612,52 +619,47 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC } decpToRepeat.removeAll(forRemoval); - forRemoval = new ArrayList(); + forRemoval = new ArrayList(); for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) { - DeclareAnnotation deca = (DeclareAnnotation)i.next(); - boolean didSomething = doDeclareAnnotations(deca, sourceType,false); + DeclareAnnotation deca = (DeclareAnnotation) i.next(); + boolean didSomething = doDeclareAnnotations(deca, sourceType, false); if (didSomething) { anyNewAnnotations = true; forRemoval.add(deca); - } + } } decaToRepeat.removeAll(forRemoval); } - - + for (Iterator i = typeMungers.iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); if (munger.matches(onType)) { if (needOldStyleWarning) { - factory.showMessage(IMessage.WARNING, - "The class for " + onType + " should be recompiled with ajc-1.1.1 for best results", - onType.getSourceLocation(), null); + factory.showMessage(IMessage.WARNING, "The class for " + onType + + " should be recompiled with ajc-1.1.1 for best results", onType.getSourceLocation(), null); needOldStyleWarning = false; } onType.addInterTypeMunger(munger); } } - - - onType.checkInterTypeMungers(); + onType.checkInterTypeMungers(); for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) { EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); - //System.out.println("applying: " + munger + " to " + new String(sourceType.sourceName)); - munger.munge(sourceType,onType); + // System.out.println("applying: " + munger + " to " + new String(sourceType.sourceName)); + munger.munge(sourceType, onType); } - - // Call if you would like to do source weaving of declare @method/@constructor + + // Call if you would like to do source weaving of declare @method/@constructor // at source time... no need to do this as it can't impact anything, but left here for - // future generations to enjoy. Method source is commented out at the end of this module + // future generations to enjoy. Method source is commented out at the end of this module // doDeclareAnnotationOnMethods(); - - // Call if you would like to do source weaving of declare @field + + // Call if you would like to do source weaving of declare @field // at source time... no need to do this as it can't impact anything, but left here for - // future generations to enjoy. Method source is commented out at the end of this module + // future generations to enjoy. Method source is commented out at the end of this module // doDeclareAnnotationOnFields(); - if (skipInners) { CompilationAndWeavingContext.leavingPhase(tok); return; @@ -666,56 +668,59 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC ReferenceBinding[] memberTypes = sourceType.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { if (memberTypes[i] instanceof SourceTypeBinding) { - weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents,declareAnnotationOnTypes, false); + weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents, + declareAnnotationOnTypes, false); } } - CompilationAndWeavingContext.leavingPhase(tok); - } - + CompilationAndWeavingContext.leavingPhase(tok); + } + /** - * Called when we discover we are weaving intertype declarations on some type that has - * an existing 'WeaverStateInfo' object - this is typically some previously woven type - * that has been passed on the inpath. + * Called when we discover we are weaving intertype declarations on some type that has an existing 'WeaverStateInfo' object - + * this is typically some previously woven type that has been passed on the inpath. * - * sourceType and onType are the 'same type' - the former is the 'Eclipse' version and - * the latter is the 'Weaver' version. + * sourceType and onType are the 'same type' - the former is the 'Eclipse' version and the latter is the 'Weaver' version. */ - private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType,ResolvedType onType) { + private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType, ResolvedType onType) { Collection previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType); - - for (Iterator i = previouslyAppliedMungers.iterator(); i.hasNext(); ) { - ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); + + for (Iterator i = previouslyAppliedMungers.iterator(); i.hasNext();) { + ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m); - if (munger.munge(sourceType,onType)) { - if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) { + if (munger.munge(sourceType, onType)) { + if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) { if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) { - dangerousInterfaces.put(onType, "implementors of "+onType+" must be woven by "+munger.getAspectType()); + dangerousInterfaces + .put(onType, "implementors of " + onType + " must be woven by " + munger.getAspectType()); } } } - + } } - + private boolean doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) { - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS, sourceType.sourceName); + ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS, + sourceType.sourceName); ResolvedType resolvedSourceType = factory.fromEclipse(sourceType); - List newParents = declareParents.findMatchingNewParents(resolvedSourceType,false); + List newParents = declareParents.findMatchingNewParents(resolvedSourceType, false); if (!newParents.isEmpty()) { - for (Iterator i = newParents.iterator(); i.hasNext(); ) { - ResolvedType parent = (ResolvedType)i.next(); + for (Iterator i = newParents.iterator(); i.hasNext();) { + ResolvedType parent = (ResolvedType) i.next(); if (dangerousInterfaces.containsKey(parent)) { ResolvedType onType = factory.fromEclipse(sourceType); - factory.showMessage(IMessage.ERROR, - onType + ": " + dangerousInterfaces.get(parent), - onType.getSourceLocation(), null); + factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent), + onType.getSourceLocation(), null); } if (Modifier.isFinal(parent.getModifiers())) { - factory.showMessage(IMessage.ERROR,"cannot extend final class " + parent.getClassName(),declareParents.getSourceLocation(),null); + factory.showMessage(IMessage.ERROR, "cannot extend final class " + parent.getClassName(), declareParents + .getSourceLocation(), null); } else { - // do not actually do it if the type isn't exposed - this will correctly reported as a problem elsewhere - if (!resolvedSourceType.isExposedToWeaver()) return false; - AsmRelationshipProvider.getDefault().addDeclareParentsRelationship(declareParents.getSourceLocation(),factory.fromEclipse(sourceType), newParents); + // do not actually do it if the type isn't exposed - this will correctly reported as a problem elsewhere + if (!resolvedSourceType.isExposedToWeaver()) + return false; + AsmRelationshipProvider.getDefault().addDeclareParentsRelationship(declareParents.getSourceLocation(), + factory.fromEclipse(sourceType), newParents); addParent(sourceType, parent); } } @@ -725,36 +730,49 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC CompilationAndWeavingContext.leavingPhase(tok); return false; } - + private String stringifyTargets(long bits) { - if ((bits & TagBits.AnnotationTargetMASK)==0) return ""; + if ((bits & TagBits.AnnotationTargetMASK) == 0) + return ""; Set s = new HashSet(); - if ((bits&TagBits.AnnotationForAnnotationType)!=0) s.add("ANNOTATION_TYPE"); - if ((bits&TagBits.AnnotationForConstructor)!=0) s.add("CONSTRUCTOR"); - if ((bits&TagBits.AnnotationForField)!=0) s.add("FIELD"); - if ((bits&TagBits.AnnotationForLocalVariable)!=0) s.add("LOCAL_VARIABLE"); - if ((bits&TagBits.AnnotationForMethod)!=0) s.add("METHOD"); - if ((bits&TagBits.AnnotationForPackage)!=0) s.add("PACKAGE"); - if ((bits&TagBits.AnnotationForParameter)!=0) s.add("PARAMETER"); - if ((bits&TagBits.AnnotationForType)!=0) s.add("TYPE"); + if ((bits & TagBits.AnnotationForAnnotationType) != 0) + s.add("ANNOTATION_TYPE"); + if ((bits & TagBits.AnnotationForConstructor) != 0) + s.add("CONSTRUCTOR"); + if ((bits & TagBits.AnnotationForField) != 0) + s.add("FIELD"); + if ((bits & TagBits.AnnotationForLocalVariable) != 0) + s.add("LOCAL_VARIABLE"); + if ((bits & TagBits.AnnotationForMethod) != 0) + s.add("METHOD"); + if ((bits & TagBits.AnnotationForPackage) != 0) + s.add("PACKAGE"); + if ((bits & TagBits.AnnotationForParameter) != 0) + s.add("PARAMETER"); + if ((bits & TagBits.AnnotationForType) != 0) + s.add("TYPE"); StringBuffer sb = new StringBuffer(); sb.append("{"); for (Iterator iter = s.iterator(); iter.hasNext();) { String element = (String) iter.next(); sb.append(element); - if (iter.hasNext()) sb.append(","); + if (iter.hasNext()) + sb.append(","); } sb.append("}"); return sb.toString(); } - - private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType,boolean reportProblems) { + + private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) { ResolvedType rtx = factory.fromEclipse(sourceType); - if (!decA.matches(rtx)) return false; - if (!rtx.isExposedToWeaver()) return false; + if (!decA.matches(rtx)) + return false; + if (!rtx.isExposedToWeaver()) + return false; + + ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS, + sourceType.sourceName); - ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS, sourceType.sourceName); - // Get the annotation specified in the declare UnresolvedType aspectType = decA.getAspect(); if (aspectType instanceof ReferenceType) { @@ -764,54 +782,57 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC } } TypeBinding tb = factory.makeTypeBinding(aspectType); - + // Hideousness follows: - + // There are multiple situations to consider here and they relate to the combinations of // where the annotation is coming from and where the annotation is going to be put: // // 1. Straight full build, all from source - the annotation is from a dec@type and - // is being put on some type. Both types are real SourceTypeBindings. WORKS + // is being put on some type. Both types are real SourceTypeBindings. WORKS // 2. Incremental build, changing the affected type - the annotation is from a - // dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and the - // affected type is a real SourceTypeBinding. Mostly works (pr128665) + // dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and the + // affected type is a real SourceTypeBinding. Mostly works (pr128665) // 3. ? - - SourceTypeBinding stb = (SourceTypeBinding)tb; + + SourceTypeBinding stb = (SourceTypeBinding) tb; Annotation[] toAdd = null; long abits = 0; - + // Might have to retrieve the annotation through BCEL and construct an eclipse one for it. if (stb instanceof BinaryTypeBinding) { - ReferenceType rt = (ReferenceType)factory.fromEclipse(stb); + ReferenceType rt = (ReferenceType) factory.fromEclipse(stb); ResolvedMember[] methods = rt.getDeclaredMethods(); ResolvedMember decaMethod = null; String nameToLookFor = decA.getAnnotationMethod(); for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals(nameToLookFor)) {decaMethod = methods[i];break;} + if (methods[i].getName().equals(nameToLookFor)) { + decaMethod = methods[i]; + break; + } } - if (decaMethod!=null) { // could assert this ... + if (decaMethod != null) { // could assert this ... AnnotationX[] axs = decaMethod.getAnnotations(); toAdd = new Annotation[1]; - toAdd[0] = createAnnotationFromBcelAnnotation(axs[0],decaMethod.getSourceLocation().getOffset(),factory); + toAdd[0] = createAnnotationFromBcelAnnotation(axs[0], decaMethod.getSourceLocation().getOffset(), factory); // BUG BUG BUG - We dont test these abits are correct, in fact we'll be very lucky if they are. - // What does that mean? It means on an incremental compile you might get away with an + // What does that mean? It means on an incremental compile you might get away with an // annotation that isn't allowed on a type being put on a type. if (toAdd[0].resolvedType != null) // pr184447 - abits = toAdd[0].resolvedType.getAnnotationTagBits(); - } + abits = toAdd[0].resolvedType.getAnnotationTagBits(); + } } else { // much nicer, its a real SourceTypeBinding so we can stay in eclipse land - MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray()); + MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray()); abits = mbs[0].getAnnotationTagBits(); // ensure resolved - TypeDeclaration typeDecl = ((SourceTypeBinding)mbs[0].declaringClass).scope.referenceContext; + TypeDeclaration typeDecl = ((SourceTypeBinding) mbs[0].declaringClass).scope.referenceContext; AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(mbs[0]); toAdd = methodDecl.annotations; // this is what to add toAdd[0] = createAnnotationCopy(toAdd[0]); - if (toAdd[0].resolvedType!=null) // pr148536 - abits = toAdd[0].resolvedType.getAnnotationTagBits(); + if (toAdd[0].resolvedType != null) // pr148536 + abits = toAdd[0].resolvedType.getAnnotationTagBits(); } - + if (sourceType instanceof BinaryTypeBinding) { // In this case we can't access the source type binding to add a new annotation, so let's put something // on the weaver type temporarily @@ -824,198 +845,203 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC CompilationAndWeavingContext.leavingPhase(tok); return false; } - + // FIXME asc tidy up this code that duplicates whats below! // Simple checks on the bits boolean giveupnow = false; - if (((abits & TagBits.AnnotationTargetMASK)!=0)) { - if ( isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) { + if (((abits & TagBits.AnnotationTargetMASK) != 0)) { + if (isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) { // error will have been already reported giveupnow = true; - } else if ( (sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType)==0) || - (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType)==0) ) { - - if (reportProblems) { - if (decA.isExactPattern()) { - factory.showMessage(IMessage.ERROR, - WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,rtx.getName(),toAdd[0].type,stringifyTargets(abits)), - decA.getSourceLocation(), null); - } - // dont put out the lint - the weaving process will do that -// else { -// if (factory.getWorld().getLint().invalidTargetForAnnotation.isEnabled()) { -// factory.getWorld().getLint().invalidTargetForAnnotation.signal(new String[]{rtx.getName(),toAdd[0].type.toString(),stringifyTargets(abits)},decA.getSourceLocation(),null); -// } -// } - } - giveupnow=true; - } + } else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0) + || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) { + + if (reportProblems) { + if (decA.isExactPattern()) { + factory.showMessage(IMessage.ERROR, WeaverMessages.format( + WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type, + stringifyTargets(abits)), decA.getSourceLocation(), null); + } + // dont put out the lint - the weaving process will do that + // else { + // if (factory.getWorld().getLint().invalidTargetForAnnotation.isEnabled()) { + // factory.getWorld().getLint().invalidTargetForAnnotation.signal(new + // String[]{rtx.getName(),toAdd[0].type.toString(),stringifyTargets(abits)},decA.getSourceLocation(),null); + // } + // } + } + giveupnow = true; + } } - if (giveupnow) { + if (giveupnow) { CompilationAndWeavingContext.leavingPhase(tok); return false; } - - theTargetType.addAnnotation(new AnnotationX(new FakeAnnotation(name,sig,(abits & TagBits.AnnotationRuntimeRetention)!=0),factory.getWorld())); + + theTargetType.addAnnotation(new AnnotationX(new FakeAnnotation(name, sig, + (abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld())); CompilationAndWeavingContext.leavingPhase(tok); return true; } - + Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations; - if (currentAnnotations!=null) - for (int i = 0; i < currentAnnotations.length; i++) { - Annotation annotation = currentAnnotations[i]; - String a = CharOperation.toString(annotation.type.getTypeName()); - String b = CharOperation.toString(toAdd[0].type.getTypeName()); - // FIXME asc we have a lint for attempting to add an annotation twice to a method, - // we could put it out here *if* we can resolve the problem of errors coming out - // multiple times if we have cause to loop through here - if (a.equals(b)) { + if (currentAnnotations != null) + for (int i = 0; i < currentAnnotations.length; i++) { + Annotation annotation = currentAnnotations[i]; + String a = CharOperation.toString(annotation.type.getTypeName()); + String b = CharOperation.toString(toAdd[0].type.getTypeName()); + // FIXME asc we have a lint for attempting to add an annotation twice to a method, + // we could put it out here *if* we can resolve the problem of errors coming out + // multiple times if we have cause to loop through here + if (a.equals(b)) { + CompilationAndWeavingContext.leavingPhase(tok); + return false; + } + } + + if (((abits & TagBits.AnnotationTargetMASK) != 0)) { + if ((abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0) { + // this means it specifies something other than annotation or normal type - error will have been already reported, + // just resolution process above CompilationAndWeavingContext.leavingPhase(tok); return false; } - } - - if (((abits & TagBits.AnnotationTargetMASK)!=0)) { - if ( (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType))==0) { - // this means it specifies something other than annotation or normal type - error will have been already reported, just resolution process above + if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0) + || (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) { + + if (reportProblems) { + if (decA.isExactPattern()) { + factory.showMessage(IMessage.ERROR, WeaverMessages.format( + WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type, + stringifyTargets(abits)), decA.getSourceLocation(), null); + } + // dont put out the lint - the weaving process will do that + // else { + // if (factory.getWorld().getLint().invalidTargetForAnnotation.isEnabled()) { + // factory.getWorld().getLint().invalidTargetForAnnotation.signal(new + // String[]{rtx.getName(),toAdd[0].type.toString(),stringifyTargets(abits)},decA.getSourceLocation(),null); + // } + // } + } CompilationAndWeavingContext.leavingPhase(tok); return false; } - if ( (sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType)==0) || - (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType)==0) ) { - - if (reportProblems) { - if (decA.isExactPattern()) { - factory.showMessage(IMessage.ERROR, - WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,rtx.getName(),toAdd[0].type,stringifyTargets(abits)), - decA.getSourceLocation(), null); - } - // dont put out the lint - the weaving process will do that -// else { -// if (factory.getWorld().getLint().invalidTargetForAnnotation.isEnabled()) { -// factory.getWorld().getLint().invalidTargetForAnnotation.signal(new String[]{rtx.getName(),toAdd[0].type.toString(),stringifyTargets(abits)},decA.getSourceLocation(),null); -// } -// } - } - CompilationAndWeavingContext.leavingPhase(tok); - return false; - } } - + // Build a new array of annotations - + // remember the current set (rememberAnnotations only does something the first time it is called for a type) - sourceType.scope.referenceContext.rememberAnnotations(); - - AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),rtx.getSourceLocation()); + sourceType.scope.referenceContext.rememberAnnotations(); + + AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(), rtx.getSourceLocation()); Annotation abefore[] = sourceType.scope.referenceContext.annotations; - Annotation[] newset = new Annotation[toAdd.length+(abefore==null?0:abefore.length)]; - System.arraycopy(toAdd,0,newset,0,toAdd.length); - if (abefore!=null) { - System.arraycopy(abefore,0,newset,toAdd.length,abefore.length); + Annotation[] newset = new Annotation[toAdd.length + (abefore == null ? 0 : abefore.length)]; + System.arraycopy(toAdd, 0, newset, 0, toAdd.length); + if (abefore != null) { + System.arraycopy(abefore, 0, newset, toAdd.length, abefore.length); } sourceType.scope.referenceContext.annotations = newset; CompilationAndWeavingContext.leavingPhase(tok); return true; } - + /** - * Transform an annotation from its AJ form to an eclipse form. We *DONT* care about the - * values of the annotation. that is because it is only being stuck on a type during - * type completion to allow for other constructs (decps, decas) that might be 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 the right thing copying across values too. + * Transform an annotation from its AJ form to an eclipse form. We *DONT* care about the values of the annotation. that is + * because it is only being stuck on a type during type completion to allow for other constructs (decps, decas) that might be + * 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 + * the right thing copying across values too. */ - private static Annotation createAnnotationFromBcelAnnotation(AnnotationX annX,int pos, EclipseFactory factory) { + private static Annotation createAnnotationFromBcelAnnotation(AnnotationX annX, int pos, EclipseFactory factory) { String name = annX.getTypeName(); TypeBinding tb = factory.makeTypeBinding(annX.getSignature()); String theName = annX.getSignature().getBaseName(); - char[][] typeName = CharOperation.splitOn('.',name.replace('$','.').toCharArray()); //pr149293 - not bulletproof... + char[][] typeName = CharOperation.splitOn('.', name.replace('$', '.').toCharArray()); // pr149293 - not bulletproof... long[] positions = new long[typeName.length]; - for (int i = 0; i < positions.length; i++) positions[i]=pos; - TypeReference annType = new QualifiedTypeReference(typeName,positions); - NormalAnnotation ann = new NormalAnnotation(annType,pos); - ann.resolvedType=tb; // yuck - is this OK in all cases? + for (int i = 0; i < positions.length; i++) + positions[i] = pos; + TypeReference annType = new QualifiedTypeReference(typeName, positions); + NormalAnnotation ann = new NormalAnnotation(annType, pos); + ann.resolvedType = tb; // yuck - is this OK in all cases? // We don't need membervalues... -// Expression pcExpr = new StringLiteral(pointcutExpression.toCharArray(),pos,pos); -// MemberValuePair[] mvps = new MemberValuePair[2]; -// mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr); -// Expression argNamesExpr = new StringLiteral(argNames.toCharArray(),pos,pos); -// mvps[1] = new MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr); -// ann.memberValuePairs = mvps; + // Expression pcExpr = new StringLiteral(pointcutExpression.toCharArray(),pos,pos); + // MemberValuePair[] mvps = new MemberValuePair[2]; + // mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr); + // Expression argNamesExpr = new StringLiteral(argNames.toCharArray(),pos,pos); + // mvps[1] = new MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr); + // ann.memberValuePairs = mvps; return ann; } - - /** 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 'recipient' */ + + /** + * 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 + * 'recipient' + */ private static Annotation createAnnotationCopy(Annotation ann) { - NormalAnnotation ann2 = new NormalAnnotation(ann.type,ann.sourceStart); + NormalAnnotation ann2 = new NormalAnnotation(ann.type, ann.sourceStart); ann2.memberValuePairs = ann.memberValuePairs(); ann2.resolvedType = ann.resolvedType; ann2.bits = ann.bits; return ann2; -// String name = annX.getTypeName(); -// TypeBinding tb = factory.makeTypeBinding(annX.getSignature()); -// String theName = annX.getSignature().getBaseName(); -// char[][] typeName = CharOperation.splitOn('.',name.replace('$','.').toCharArray()); //pr149293 - not bulletproof... -// long[] positions = new long[typeName.length]; -// for (int i = 0; i < positions.length; i++) positions[i]=pos; -// TypeReference annType = new QualifiedTypeReference(typeName,positions); -// NormalAnnotation ann = new NormalAnnotation(annType,pos); -// ann.resolvedType=tb; // yuck - is this OK in all cases? -// // We don't need membervalues... -//// Expression pcExpr = new StringLiteral(pointcutExpression.toCharArray(),pos,pos); -//// MemberValuePair[] mvps = new MemberValuePair[2]; -//// mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr); -//// Expression argNamesExpr = new StringLiteral(argNames.toCharArray(),pos,pos); -//// mvps[1] = new MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr); -//// ann.memberValuePairs = mvps; -// return ann; + // String name = annX.getTypeName(); + // TypeBinding tb = factory.makeTypeBinding(annX.getSignature()); + // String theName = annX.getSignature().getBaseName(); + // char[][] typeName = CharOperation.splitOn('.',name.replace('$','.').toCharArray()); //pr149293 - not bulletproof... + // long[] positions = new long[typeName.length]; + // for (int i = 0; i < positions.length; i++) positions[i]=pos; + // TypeReference annType = new QualifiedTypeReference(typeName,positions); + // NormalAnnotation ann = new NormalAnnotation(annType,pos); + // ann.resolvedType=tb; // yuck - is this OK in all cases? + // // We don't need membervalues... + // // Expression pcExpr = new StringLiteral(pointcutExpression.toCharArray(),pos,pos); + // // MemberValuePair[] mvps = new MemberValuePair[2]; + // // mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr); + // // Expression argNamesExpr = new StringLiteral(argNames.toCharArray(),pos,pos); + // // mvps[1] = new MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr); + // // ann.memberValuePairs = mvps; + // return ann; } private boolean isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(long abits) { - return (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType))==0; + return (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0; } - - private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk,SourceTypeBinding sourceType,ResolvedType parent) { + private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk, SourceTypeBinding sourceType, ResolvedType parent) { if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String filename = new String(sourceType.getFileName()); - + int takefrom = filename.lastIndexOf('/'); - if (takefrom == -1 ) takefrom = filename.lastIndexOf('\\'); - filename = filename.substring(takefrom+1); + if (takefrom == -1) + takefrom = filename.lastIndexOf('\\'); + filename = filename.substring(takefrom + 1); factory.getWorld().getMessageHandler().handleMessage( - WeaveMessage.constructWeavingMessage(wmk, - new String[]{CharOperation.toString(sourceType.compoundName), - filename, - parent.getClassName(), - getShortname(parent.getSourceLocation().getSourceFile().getPath())})); + WeaveMessage.constructWeavingMessage(wmk, new String[] { CharOperation.toString(sourceType.compoundName), + filename, parent.getClassName(), getShortname(parent.getSourceLocation().getSourceFile().getPath()) })); } } - - private String getShortname(String path) { + + private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } - return path.substring(takefrom+1); + return path.substring(takefrom + 1); } private void addParent(SourceTypeBinding sourceType, ResolvedType parent) { - ReferenceBinding parentBinding = (ReferenceBinding)factory.makeTypeBinding(parent); - if (parentBinding == null) return; // The parent is missing, it will be reported elsewhere. - sourceType.rememberTypeHierarchy(); - if (parentBinding.isClass()) { + ReferenceBinding parentBinding = (ReferenceBinding) factory.makeTypeBinding(parent); + if (parentBinding == null) + return; // The parent is missing, it will be reported elsewhere. + sourceType.rememberTypeHierarchy(); + if (parentBinding.isClass()) { sourceType.superclass = parentBinding; - - // this used to be true, but I think I've fixed it now, decp is done at weave time! - // TAG: WeavingMessage DECLARE PARENTS: EXTENDS + + // this used to be true, but I think I've fixed it now, decp is done at weave time! + // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // Compiler restriction: Can't do EXTENDS at weave time // So, only see this message if doing a source compilation - // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); - + // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); + } else { ReferenceBinding[] oldI = sourceType.superInterfaces; ReferenceBinding[] newI; @@ -1024,107 +1050,87 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC newI[0] = parentBinding; } else { int n = oldI.length; - newI = new ReferenceBinding[n+1]; + newI = new ReferenceBinding[n + 1]; System.arraycopy(oldI, 0, newI, 0, n); newI[n] = parentBinding; } sourceType.superInterfaces = newI; // warnOnAddedInterface(factory.fromEclipse(sourceType),parent); // now reported at weave time... - - // this used to be true, but I think I've fixed it now, decp is done at weave time! - // TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS + // this used to be true, but I think I've fixed it now, decp is done at weave time! + // TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS // This message will come out of BcelTypeMunger.munge if doing a binary weave - // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent); - + // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent); + } - - // also add it to the bcel delegate if there is one - if (sourceType instanceof BinaryTypeBinding) { - ResolvedType onType = factory.fromEclipse(sourceType); - ReferenceType rt = (ReferenceType)onType; - ReferenceTypeDelegate rtd = rt.getDelegate(); - if (rtd instanceof BcelObjectType) { - ((BcelObjectType)rtd).addParent(parent); - } - } - + + // also add it to the bcel delegate if there is one + if (sourceType instanceof BinaryTypeBinding) { + ResolvedType onType = factory.fromEclipse(sourceType); + ReferenceType rt = (ReferenceType) onType; + ReferenceTypeDelegate rtd = rt.getDelegate(); + if (rtd instanceof BcelObjectType) { + ((BcelObjectType) rtd).addParent(parent); + } + } + } - public void warnOnAddedInterface (ResolvedType type, ResolvedType parent) { + public void warnOnAddedInterface(ResolvedType type, ResolvedType parent) { World world = factory.getWorld(); ResolvedType serializable = world.getCoreType(UnresolvedType.SERIALIZABLE); - if (serializable.isAssignableFrom(type) - && !serializable.isAssignableFrom(parent) - && !LazyClassGen.hasSerialVersionUIDField(type)) { - world.getLint().needsSerialVersionUIDField.signal( - new String[] { - type.getName().toString(), - "added interface " + parent.getName().toString() - }, - null, - null); + if (serializable.isAssignableFrom(type) && !serializable.isAssignableFrom(parent) + && !LazyClassGen.hasSerialVersionUIDField(type)) { + world.getLint().needsSerialVersionUIDField.signal(new String[] { type.getName().toString(), + "added interface " + parent.getName().toString() }, null, null); } } - - - + private List pendingTypesToFinish = new ArrayList(); boolean inBinaryTypeCreationAndWeaving = false; boolean processingTheQueue = false; - - public BinaryTypeBinding createBinaryTypeFrom( - IBinaryType binaryType, - PackageBinding packageBinding, - boolean needFieldsAndMethods, - AccessRestriction accessRestriction) - { + + public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding, + boolean needFieldsAndMethods, AccessRestriction accessRestriction) { if (inBinaryTypeCreationAndWeaving) { - BinaryTypeBinding ret = super.createBinaryTypeFrom( - binaryType, - packageBinding, - needFieldsAndMethods, - accessRestriction); + BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction); pendingTypesToFinish.add(ret); return ret; } - + inBinaryTypeCreationAndWeaving = true; try { - BinaryTypeBinding ret = super.createBinaryTypeFrom( - binaryType, - packageBinding, - needFieldsAndMethods, - accessRestriction); + BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction); factory.getWorld().validateType(factory.fromBinding(ret)); // if you need the bytes to pass to validate, here they are:((ClassFileReader)binaryType).getReferenceBytes() - weaveInterTypeDeclarations(ret); + weaveInterTypeDeclarations(ret); return ret; } finally { inBinaryTypeCreationAndWeaving = false; - + // Start processing the list... - if (pendingTypesToFinish.size()>0) { + if (pendingTypesToFinish.size() > 0) { processingTheQueue = true; while (!pendingTypesToFinish.isEmpty()) { - BinaryTypeBinding nextVictim = (BinaryTypeBinding)pendingTypesToFinish.remove(0); - // During this call we may recurse into this method and add + BinaryTypeBinding nextVictim = (BinaryTypeBinding) pendingTypesToFinish.remove(0); + // During this call we may recurse into this method and add // more entries to the pendingTypesToFinish list. weaveInterTypeDeclarations(nextVictim); } processingTheQueue = false; } - } + } } /** - * Callback driven when the compiler detects an anonymous type during block resolution. - * We need to add it to the weaver so that we don't trip up later. + * Callback driven when the compiler detects an anonymous type during block resolution. We need to add it to the weaver so that + * we don't trip up later. + * * @param aBinding */ public void anonymousTypeBindingCreated(LocalTypeBinding aBinding) { - factory.addSourceTypeBinding(aBinding,null); + factory.addSourceTypeBinding(aBinding, null); } } @@ -1132,129 +1138,132 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC // // public void doDeclareAnnotationOnMethods() { // Do the declare annotation on fields/methods/ctors -//Collection daoms = factory.getDeclareAnnotationOnMethods(); -//if (daoms!=null && daoms.size()>0 && !(sourceType instanceof BinaryTypeBinding)) { -// System.err.println("Going through the methods on "+sourceType.debugName()+" looking for DECA matches"); -// // We better take a look through them... -// for (Iterator iter = daoms.iterator(); iter.hasNext();) { -// DeclareAnnotation element = (DeclareAnnotation) iter.next(); -// System.err.println("Looking for anything that might match "+element+" on "+sourceType.debugName()+" "+getType(sourceType.compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding)); +// Collection daoms = factory.getDeclareAnnotationOnMethods(); +// if (daoms!=null && daoms.size()>0 && !(sourceType instanceof BinaryTypeBinding)) { +// System.err.println("Going through the methods on "+sourceType.debugName()+" looking for DECA matches"); +// // We better take a look through them... +// for (Iterator iter = daoms.iterator(); iter.hasNext();) { +// DeclareAnnotation element = (DeclareAnnotation) iter.next(); +// System.err.println("Looking for anything that might match "+element+" on "+sourceType.debugName()+" "+getType(sourceType. +// compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding)); // -// ReferenceBinding rbb = getType(sourceType.compoundName); -// // fix me if we ever uncomment this code... should iterate the other way round, over the methods then over the decas -// sourceType.methods(); -// MethodBinding sourceMbs[] = sourceType.methods; -// for (int i = 0; i < sourceMbs.length; i++) { -// MethodBinding sourceMb = sourceMbs[i]; -// MethodBinding mbbbb = ((SourceTypeBinding)rbb).getExactMethod(sourceMb.selector,sourceMb.parameters); -// boolean isCtor = sourceMb.selector[0]=='<'; +// ReferenceBinding rbb = getType(sourceType.compoundName); +// // fix me if we ever uncomment this code... should iterate the other way round, over the methods then over the decas +// sourceType.methods(); +// MethodBinding sourceMbs[] = sourceType.methods; +// for (int i = 0; i < sourceMbs.length; i++) { +// MethodBinding sourceMb = sourceMbs[i]; +// MethodBinding mbbbb = ((SourceTypeBinding)rbb).getExactMethod(sourceMb.selector,sourceMb.parameters); +// boolean isCtor = sourceMb.selector[0]=='<'; // -// if ((element.isDeclareAtConstuctor() ^ !isCtor)) { -// System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb.declaringClass.debugName()+" rbb="+rbb.debugName()+" "+sourceMb.declaringClass.equals(rbb)); +// if ((element.isDeclareAtConstuctor() ^ !isCtor)) { +// System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb.declaringClass.debugName()+" rbb="+rbb.debugName()+" "+ +// sourceMb.declaringClass.equals(rbb)); // -// ResolvedMember rm = null; -// rm = EclipseFactory.makeResolvedMember(mbbbb); -// if (element.matches(rm,factory.getWorld())) { -// System.err.println("MATCH"); +// ResolvedMember rm = null; +// rm = EclipseFactory.makeResolvedMember(mbbbb); +// if (element.matches(rm,factory.getWorld())) { +// System.err.println("MATCH"); // -// // Determine the set of annotations that are currently on the method -// ReferenceBinding rb = getType(sourceType.compoundName); -//// TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); -// MethodBinding mb = ((SourceTypeBinding)rb).getExactMethod(sourceMb.selector,sourceMb.parameters); -// //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved -// TypeDeclaration typeDecl = ((SourceTypeBinding)sourceMb.declaringClass).scope.referenceContext; -// AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb); -// Annotation[] currentlyHas = methodDecl.annotations; // this is what to add -// //abits = toAdd[0].resolvedType.getAnnotationTagBits(); +// // Determine the set of annotations that are currently on the method +// ReferenceBinding rb = getType(sourceType.compoundName); +// // TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); +// MethodBinding mb = ((SourceTypeBinding)rb).getExactMethod(sourceMb.selector,sourceMb.parameters); +// //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved +// TypeDeclaration typeDecl = ((SourceTypeBinding)sourceMb.declaringClass).scope.referenceContext; +// AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb); +// Annotation[] currentlyHas = methodDecl.annotations; // this is what to add +// //abits = toAdd[0].resolvedType.getAnnotationTagBits(); // -// // Determine the annotations to add to that method -// TypeBinding tb = factory.makeTypeBinding(element.getAspect()); -// MethodBinding[] aspectMbs = ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod().toCharArray()); -// long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved -// TypeDeclaration typeDecl2 = ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext; -// AbstractMethodDeclaration methodDecl2 = typeDecl2.declarationOf(aspectMbs[0]); -// Annotation[] toAdd = methodDecl2.annotations; // this is what to add -// // abits = toAdd[0].resolvedType.getAnnotationTagBits(); -//System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd); +// // Determine the annotations to add to that method +// TypeBinding tb = factory.makeTypeBinding(element.getAspect()); +// MethodBinding[] aspectMbs = ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod().toCharArray()); +// long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved +// TypeDeclaration typeDecl2 = ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext; +// AbstractMethodDeclaration methodDecl2 = typeDecl2.declarationOf(aspectMbs[0]); +// Annotation[] toAdd = methodDecl2.annotations; // this is what to add +// // abits = toAdd[0].resolvedType.getAnnotationTagBits(); +// System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd); // -// // fix me? should check if it already has the annotation -// //Annotation abefore[] = sourceType.scope.referenceContext.annotations; -// Annotation[] newset = new Annotation[(currentlyHas==null?0:currentlyHas.length)+1]; -// System.arraycopy(toAdd,0,newset,0,toAdd.length); -// if (currentlyHas!=null) { -// System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length); -// } -// methodDecl.annotations = newset; -// System.err.println("New set on "+CharOperation.charToString(sourceMb.selector)+" is "+newset); -// } else -// System.err.println("NO MATCH"); -// } -// } -// } -//} -//} +// // fix me? should check if it already has the annotation +// //Annotation abefore[] = sourceType.scope.referenceContext.annotations; +// Annotation[] newset = new Annotation[(currentlyHas==null?0:currentlyHas.length)+1]; +// System.arraycopy(toAdd,0,newset,0,toAdd.length); +// if (currentlyHas!=null) { +// System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length); +// } +// methodDecl.annotations = newset; +// System.err.println("New set on "+CharOperation.charToString(sourceMb.selector)+" is "+newset); +// } else +// System.err.println("NO MATCH"); +// } +// } +// } +// } +// } // commented out, supplied as info on how to manipulate annotations in an eclipse world // // public void doDeclareAnnotationOnFields() { -// Collection daofs = factory.getDeclareAnnotationOnFields(); -// if (daofs!=null && daofs.size()>0 && !(sourceType instanceof BinaryTypeBinding)) { -// System.err.println("Going through the fields on "+sourceType.debugName()+" looking for DECA matches"); -// // We better take a look through them... -// for (Iterator iter = daofs.iterator(); iter.hasNext();) { -// DeclareAnnotation element = (DeclareAnnotation) iter.next(); -// System.err.println("Processing deca "+element+" on "+sourceType.debugName()+" "+getType(sourceType.compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding)); +// Collection daofs = factory.getDeclareAnnotationOnFields(); +// if (daofs!=null && daofs.size()>0 && !(sourceType instanceof BinaryTypeBinding)) { +// System.err.println("Going through the fields on "+sourceType.debugName()+" looking for DECA matches"); +// // We better take a look through them... +// for (Iterator iter = daofs.iterator(); iter.hasNext();) { +// DeclareAnnotation element = (DeclareAnnotation) iter.next(); +//System.err.println("Processing deca "+element+" on "+sourceType.debugName()+" "+getType(sourceType.compoundName).debugName()+" " +// +(sourceType instanceof BinaryTypeBinding)); // -// ReferenceBinding rbb = getType(sourceType.compoundName); -// // fix me? should iterate the other way round, over the methods then over the decas -// sourceType.fields(); // resolve the bloody things -// FieldBinding sourceFbs[] = sourceType.fields; -// for (int i = 0; i < sourceFbs.length; i++) { -// FieldBinding sourceFb = sourceFbs[i]; -// //FieldBinding fbbbb = ((SourceTypeBinding)rbb).getgetExactMethod(sourceMb.selector,sourceMb.parameters); +// ReferenceBinding rbb = getType(sourceType.compoundName); +// // fix me? should iterate the other way round, over the methods then over the decas +// sourceType.fields(); // resolve the bloody things +// FieldBinding sourceFbs[] = sourceType.fields; +// for (int i = 0; i < sourceFbs.length; i++) { +// FieldBinding sourceFb = sourceFbs[i]; +// //FieldBinding fbbbb = ((SourceTypeBinding)rbb).getgetExactMethod(sourceMb.selector,sourceMb.parameters); // -// System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb.declaringClass.debugName()+" rbb="+rbb.debugName()); +// System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb.declaringClass.debugName()+" rbb="+rbb.debugName()); // -// ResolvedMember rm = null; -// rm = EclipseFactory.makeResolvedMember(sourceFb); -// if (element.matches(rm,factory.getWorld())) { -// System.err.println("MATCH"); +// ResolvedMember rm = null; +// rm = EclipseFactory.makeResolvedMember(sourceFb); +// if (element.matches(rm,factory.getWorld())) { +// System.err.println("MATCH"); // -// // Determine the set of annotations that are currently on the field -// ReferenceBinding rb = getType(sourceType.compoundName); -//// TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); -// FieldBinding fb = ((SourceTypeBinding)rb).getField(sourceFb.name,true); -// //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved -// TypeDeclaration typeDecl = ((SourceTypeBinding)sourceFb.declaringClass).scope.referenceContext; -// FieldDeclaration fd = typeDecl.declarationOf(sourceFb); -// //AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb); -// Annotation[] currentlyHas = fd.annotations; // this is what to add -// //abits = toAdd[0].resolvedType.getAnnotationTagBits(); +// // Determine the set of annotations that are currently on the field +// ReferenceBinding rb = getType(sourceType.compoundName); +// // TypeBinding tb = factory.makeTypeBinding(decA.getAspect()); +// FieldBinding fb = ((SourceTypeBinding)rb).getField(sourceFb.name,true); +// //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved +// TypeDeclaration typeDecl = ((SourceTypeBinding)sourceFb.declaringClass).scope.referenceContext; +// FieldDeclaration fd = typeDecl.declarationOf(sourceFb); +// //AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb); +// Annotation[] currentlyHas = fd.annotations; // this is what to add +// //abits = toAdd[0].resolvedType.getAnnotationTagBits(); // -// // Determine the annotations to add to that method -// TypeBinding tb = factory.makeTypeBinding(element.getAspect()); -// MethodBinding[] aspectMbs = ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod().toCharArray()); -// long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved -// TypeDeclaration typeDecl2 = ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext; -// AbstractMethodDeclaration methodDecl2 = typeDecl2.declarationOf(aspectMbs[0]); -// Annotation[] toAdd = methodDecl2.annotations; // this is what to add -// // abits = toAdd[0].resolvedType.getAnnotationTagBits(); -//System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd); +// // Determine the annotations to add to that method +// TypeBinding tb = factory.makeTypeBinding(element.getAspect()); +// MethodBinding[] aspectMbs = ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod().toCharArray()); +// long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved +// TypeDeclaration typeDecl2 = ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext; +// AbstractMethodDeclaration methodDecl2 = typeDecl2.declarationOf(aspectMbs[0]); +// Annotation[] toAdd = methodDecl2.annotations; // this is what to add +// // abits = toAdd[0].resolvedType.getAnnotationTagBits(); +// System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd); // -// // fix me? check if it already has the annotation +// // fix me? check if it already has the annotation // // -// //Annotation abefore[] = sourceType.scope.referenceContext.annotations; -// Annotation[] newset = new Annotation[(currentlyHas==null?0:currentlyHas.length)+1]; -// System.arraycopy(toAdd,0,newset,0,toAdd.length); -// if (currentlyHas!=null) { -// System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length); -// } -// fd.annotations = newset; -// System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+" is "+newset); -// } else -// System.err.println("NO MATCH"); -// } +// //Annotation abefore[] = sourceType.scope.referenceContext.annotations; +// Annotation[] newset = new Annotation[(currentlyHas==null?0:currentlyHas.length)+1]; +// System.arraycopy(toAdd,0,newset,0,toAdd.length); +// if (currentlyHas!=null) { +// System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length); +// } +// fd.annotations = newset; +// System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+" is "+newset); +// } else +// System.err.println("NO MATCH"); +// } // -// } -// } +// } +// } diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseAnnotationConvertor.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseAnnotationConvertor.java index 1a46ece7b..5f9f787e7 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseAnnotationConvertor.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseAnnotationConvertor.java @@ -40,31 +40,30 @@ import org.aspectj.weaver.World; // not yet used... public class EclipseAnnotationConvertor { - /** + /** * Convert one eclipse annotation into an AnnotationX object containing an AnnotationAJ object. * - * This code and the helper methods used by it will go *BANG* if they encounter anything - * not currently supported - this is safer than limping along with a malformed annotation. When - * the *BANG* is encountered the bug reporter should indicate the kind of annotation they - * were working with and this code can be enhanced to support it. + * This code and the helper methods used by it will go *BANG* if they encounter anything not currently supported - this is safer + * than limping along with a malformed annotation. When the *BANG* is encountered the bug reporter should indicate the kind of + * annotation they were working with and this code can be enhanced to support it. */ - public static AnnotationX convertEclipseAnnotation(Annotation eclipseAnnotation,World w,EclipseFactory factory) { + public static AnnotationX convertEclipseAnnotation(Annotation eclipseAnnotation, World w, EclipseFactory factory) { // TODO if it is sourcevisible, we shouldn't let it through!!!!!!!!! testcase! ResolvedType annotationType = factory.fromTypeBindingToRTX(eclipseAnnotation.type.resolvedType); - long bs = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK); + // long bs = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK); boolean isRuntimeVisible = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention; - AnnotationAJ annotationAJ = new AnnotationAJ(annotationType.getSignature(),isRuntimeVisible); - generateAnnotation(eclipseAnnotation,annotationAJ); - return new AnnotationX(annotationAJ,w); + AnnotationAJ annotationAJ = new AnnotationAJ(annotationType.getSignature(), isRuntimeVisible); + generateAnnotation(eclipseAnnotation, annotationAJ); + return new AnnotationX(annotationAJ, w); } - + static class MissingImplementationException extends RuntimeException { MissingImplementationException(String reason) { super(reason); } } - private static void generateAnnotation(Annotation annotation,AnnotationAJ annotationAJ) { + private static void generateAnnotation(Annotation annotation, AnnotationAJ annotationAJ) { if (annotation instanceof NormalAnnotation) { NormalAnnotation normalAnnotation = (NormalAnnotation) annotation; MemberValuePair[] memberValuePairs = normalAnnotation.memberValuePairs; @@ -76,16 +75,17 @@ public class EclipseAnnotationConvertor { if (methodBinding == null) { // is this just a marker annotation? throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + + "]"); } else { AnnotationValue av = generateElementValue(memberValuePair.value, methodBinding.returnType); - AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name),av); + AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name), av); annotationAJ.addNameValuePair(anvp); } } } else { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + "]"); } } else if (annotation instanceof SingleMemberAnnotation) { // this is a single member annotation (one member value) @@ -93,34 +93,36 @@ public class EclipseAnnotationConvertor { MethodBinding methodBinding = singleMemberAnnotation.memberValuePairs()[0].binding; if (methodBinding == null) { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + "]"); } else { AnnotationValue av = generateElementValue(singleMemberAnnotation.memberValue, methodBinding.returnType); - annotationAJ.addNameValuePair( - new AnnotationNameValuePair(new String(singleMemberAnnotation.memberValuePairs()[0].name),av)); + annotationAJ.addNameValuePair(new AnnotationNameValuePair(new String( + singleMemberAnnotation.memberValuePairs()[0].name), av)); } } else { // this is a marker annotation (no member value pairs) throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + "]"); } } - - private static AnnotationValue generateElementValue(Expression defaultValue,TypeBinding memberValuePairReturnType) { + + private static AnnotationValue generateElementValue(Expression defaultValue, TypeBinding memberValuePairReturnType) { Constant constant = defaultValue.constant; TypeBinding defaultValueBinding = defaultValue.resolvedType; if (defaultValueBinding == null) { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + + "]"); } else { if (memberValuePairReturnType.isArrayType() && !defaultValueBinding.isArrayType()) { if (constant != null && constant != Constant.NotAConstant) { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); -// generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType()); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + + defaultValue + "]"); + // generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType()); } else { AnnotationValue av = generateElementValueForNonConstantExpression(defaultValue, defaultValueBinding); - return new ArrayAnnotationValue(new AnnotationValue[]{av}); + return new ArrayAnnotationValue(new AnnotationValue[] { av }); } } else { if (constant != null && constant != Constant.NotAConstant) { @@ -129,8 +131,9 @@ public class EclipseAnnotationConvertor { return av; } throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); -// generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType()); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + + defaultValue + "]"); + // generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType()); } else { AnnotationValue av = generateElementValueForNonConstantExpression(defaultValue, defaultValueBinding); return av; @@ -138,25 +141,26 @@ public class EclipseAnnotationConvertor { } } } - + public static AnnotationValue generateElementValueForConstantExpression(Expression defaultValue, TypeBinding defaultValueBinding) { if (defaultValueBinding != null) { Constant c = defaultValue.constant; if (c instanceof IntConstant) { - IntConstant iConstant = (IntConstant)c; - return new SimpleAnnotationValue(ElementValueGen.PRIMITIVE_INT,new Integer(iConstant.intValue())); + IntConstant iConstant = (IntConstant) c; + return new SimpleAnnotationValue(ElementValueGen.PRIMITIVE_INT, new Integer(iConstant.intValue())); } else if (c instanceof BooleanConstant) { - BooleanConstant iConstant = (BooleanConstant)c; - return new SimpleAnnotationValue(ElementValueGen.PRIMITIVE_BOOLEAN,new Boolean(iConstant.booleanValue())); + BooleanConstant iConstant = (BooleanConstant) c; + return new SimpleAnnotationValue(ElementValueGen.PRIMITIVE_BOOLEAN, new Boolean(iConstant.booleanValue())); } else if (c instanceof StringConstant) { - StringConstant sConstant = (StringConstant)c; - return new SimpleAnnotationValue(ElementValueGen.STRING,sConstant.stringValue()); + StringConstant sConstant = (StringConstant) c; + return new SimpleAnnotationValue(ElementValueGen.STRING, sConstant.stringValue()); } } return null; } - - private static AnnotationValue generateElementValueForNonConstantExpression(Expression defaultValue, TypeBinding defaultValueBinding) { + + private static AnnotationValue generateElementValueForNonConstantExpression(Expression defaultValue, + TypeBinding defaultValueBinding) { if (defaultValueBinding != null) { if (defaultValueBinding.isEnum()) { FieldBinding fieldBinding = null; @@ -168,20 +172,23 @@ public class EclipseAnnotationConvertor { fieldBinding = (FieldBinding) nameReference.binding; } else { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + + defaultValue + "]"); } if (fieldBinding != null) { String sig = new String(fieldBinding.type.signature()); - AnnotationValue enumValue = new EnumAnnotationValue(sig,new String(fieldBinding.name)); + AnnotationValue enumValue = new EnumAnnotationValue(sig, new String(fieldBinding.name)); return enumValue; } throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + + "]"); } else if (defaultValueBinding.isAnnotationType()) { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); -// contents[contentsOffset++] = (byte) '@'; -// generateAnnotation((Annotation) defaultValue, attributeOffset); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + + "]"); + // contents[contentsOffset++] = (byte) '@'; + // generateAnnotation((Annotation) defaultValue, attributeOffset); } else if (defaultValueBinding.isArrayType()) { // array type if (defaultValue instanceof ArrayInitializer) { @@ -189,35 +196,41 @@ public class EclipseAnnotationConvertor { int arrayLength = arrayInitializer.expressions != null ? arrayInitializer.expressions.length : 0; AnnotationValue[] values = new AnnotationValue[arrayLength]; for (int i = 0; i < arrayLength; i++) { - values[i] = generateElementValue(arrayInitializer.expressions[i], defaultValueBinding.leafComponentType());//, attributeOffset); + values[i] = generateElementValue(arrayInitializer.expressions[i], defaultValueBinding.leafComponentType());// , + // attributeOffset + // ) + // ; } ArrayAnnotationValue aav = new ArrayAnnotationValue(values); return aav; } else { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + + defaultValue + "]"); } } else { // class type throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); -// if (contentsOffset + 3 >= this.contents.length) { -// resizeContents(3); -// } -// contents[contentsOffset++] = (byte) 'c'; -// if (defaultValue instanceof ClassLiteralAccess) { -// ClassLiteralAccess classLiteralAccess = (ClassLiteralAccess) defaultValue; -// final int classInfoIndex = constantPool.literalIndex(classLiteralAccess.targetType.signature()); -// contents[contentsOffset++] = (byte) (classInfoIndex >> 8); -// contents[contentsOffset++] = (byte) classInfoIndex; -// } else { -// contentsOffset = attributeOffset; -// } + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + + "]"); + // if (contentsOffset + 3 >= this.contents.length) { + // resizeContents(3); + // } + // contents[contentsOffset++] = (byte) 'c'; + // if (defaultValue instanceof ClassLiteralAccess) { + // ClassLiteralAccess classLiteralAccess = (ClassLiteralAccess) defaultValue; + // final int classInfoIndex = constantPool.literalIndex(classLiteralAccess.targetType.signature()); + // contents[contentsOffset++] = (byte) (classInfoIndex >> 8); + // contents[contentsOffset++] = (byte) classInfoIndex; + // } else { + // contentsOffset = attributeOffset; + // } } } else { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); -// contentsOffset = attributeOffset; + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + + "]"); + // contentsOffset = attributeOffset; } } diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java index 808bff371..b9ca28911 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java @@ -12,7 +12,6 @@ * hierarchy builder * ******************************************************************/ - package org.aspectj.ajdt.internal.compiler.lookup; import java.lang.reflect.Modifier; @@ -77,132 +76,122 @@ import org.aspectj.weaver.WildcardedUnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.UnresolvedType.TypeKind; - /** * @author Jim Hugunin */ public class EclipseFactory { public static boolean DEBUG = false; public static int debug_mungerCount = -1; - + private AjBuildManager buildManager; private LookupEnvironment lookupEnvironment; private boolean xSerializableAspects; private World world; public Collection finishedTypeMungers = null; - + // We can get clashes if we don't treat raw types differently - we end up looking // up a raw and getting the generic type (pr115788) - private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap(); - private Map/*UnresolvedType, TypeBinding*/ rawTypeXToBinding = new HashMap(); - //XXX currently unused -// private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap(); - + private Map/* UnresolvedType, TypeBinding */typexToBinding = new HashMap(); + private Map/* UnresolvedType, TypeBinding */rawTypeXToBinding = new HashMap(); + + // XXX currently unused + // private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap(); + public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) { - AjLookupEnvironment aenv = (AjLookupEnvironment)env; + AjLookupEnvironment aenv = (AjLookupEnvironment) env; return aenv.factory; } - + public static EclipseFactory fromScopeLookupEnvironment(Scope scope) { return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment); } - - - public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) { + + public EclipseFactory(LookupEnvironment lookupEnvironment, AjBuildManager buildManager) { this.lookupEnvironment = lookupEnvironment; this.buildManager = buildManager; this.world = buildManager.getWorld(); this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects(); } - + public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) { this.lookupEnvironment = lookupEnvironment; this.world = world; this.xSerializableAspects = xSer; this.buildManager = null; } - + public World getWorld() { return world; } - - public void showMessage( - Kind kind, - String message, - ISourceLocation loc1, - ISourceLocation loc2) - { + + public void showMessage(Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { getWorld().showMessage(kind, message, loc1, loc2); } public ResolvedType fromEclipse(ReferenceBinding binding) { - if (binding == null) return ResolvedType.MISSING; - //??? this seems terribly inefficient - //System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding)); + if (binding == null) + return ResolvedType.MISSING; + // ??? this seems terribly inefficient + // System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding)); ResolvedType ret = getWorld().resolve(fromBinding(binding)); - //System.err.println(" got: " + ret); + // System.err.println(" got: " + ret); return ret; - } - + } + public ResolvedType fromTypeBindingToRTX(TypeBinding tb) { - if (tb == null) return ResolvedType.MISSING; + if (tb == null) + return ResolvedType.MISSING; ResolvedType ret = getWorld().resolve(fromBinding(tb)); return ret; } - + public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) { if (bindings == null) { return ResolvedType.NONE; } int len = bindings.length; ResolvedType[] ret = new ResolvedType[len]; - for (int i=0; i < len; i++) { + for (int i = 0; i < len; i++) { ret[i] = fromEclipse(bindings[i]); } return ret; - } - + } + public static String getName(TypeBinding binding) { if (binding instanceof TypeVariableBinding) { // The first bound may be null - so default to object? - TypeVariableBinding tvb = (TypeVariableBinding)binding; - if (tvb.firstBound!=null) { + TypeVariableBinding tvb = (TypeVariableBinding) binding; + if (tvb.firstBound != null) { return getName(tvb.firstBound); } else { return getName(tvb.superclass); } } - + if (binding instanceof ReferenceBinding) { - return new String( - CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.')); + return new String(CharOperation.concatWith(((ReferenceBinding) binding).compoundName, '.')); } - + String packageName = new String(binding.qualifiedPackageName()); String className = new String(binding.qualifiedSourceName()).replace('.', '$'); if (packageName.length() > 0) { className = packageName + "." + className; } - //XXX doesn't handle arrays correctly (or primitives?) + // XXX doesn't handle arrays correctly (or primitives?) return new String(className); } - - /** * Some generics notes: * - * Andy 6-May-05 - * We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we - * see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not - * sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back - * the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to - * remember the type variable. - * Adrian 10-July-05 - * When we forget it's a type variable we come unstuck when getting the declared members of a parameterized - * type - since we don't know it's a type variable we can't replace it with the type parameter. + * Andy 6-May-05 We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we + * see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not sure when/if + * this gets us unstuck? It does mean we forget that it is a type variable when going back the other way from the UnresolvedType + * and that would seem a bad thing - but I've yet to see the reason we need to remember the type variable. Adrian 10-July-05 + * When we forget it's a type variable we come unstuck when getting the declared members of a parameterized type - since we + * don't know it's a type variable we can't replace it with the type parameter. */ - //??? going back and forth between strings and bindings is a waste of cycles + // ??? going back and forth between strings and bindings is a waste of cycles public UnresolvedType fromBinding(TypeBinding binding) { if (binding instanceof HelperInterfaceBinding) { return ((HelperInterfaceBinding) binding).getTypeX(); @@ -216,155 +205,155 @@ public class EclipseFactory { UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb); return utvrt; } - + // handle arrays since the component type may need special treatment too... if (binding instanceof ArrayBinding) { ArrayBinding aBinding = (ArrayBinding) binding; UnresolvedType componentType = fromBinding(aBinding.leafComponentType); return UnresolvedType.makeArray(componentType, aBinding.dimensions); } - + if (binding instanceof WildcardBinding) { WildcardBinding eWB = (WildcardBinding) binding; // Repair the bound // e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then - // the type variable in the unresolvedtype will be correct only in name. In that + // the type variable in the unresolvedtype will be correct only in name. In that // case let's set it correctly based on the one in the eclipse WildcardBinding UnresolvedType theBound = null; if (eWB.bound instanceof TypeVariableBinding) { - theBound = fromTypeVariableBinding((TypeVariableBinding)eWB.bound); + theBound = fromTypeVariableBinding((TypeVariableBinding) eWB.bound); } else { theBound = fromBinding(eWB.bound); } - // if (eWB.boundKind == WildCard.SUPER) { - // - // } - WildcardedUnresolvedType theType = (WildcardedUnresolvedType) TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature())); - // if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound); - // if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound); + // if (eWB.boundKind == WildCard.SUPER) { + // + // } + WildcardedUnresolvedType theType = (WildcardedUnresolvedType) TypeFactory.createTypeFromSignature(CharOperation + .charToString(eWB.genericTypeSignature())); + // if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound); + // if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound); return theType; } - + if (binding instanceof ParameterizedTypeBinding) { if (binding instanceof RawTypeBinding) { // special case where no parameters are specified! return UnresolvedType.forRawTypeName(getName(binding)); } ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding; - + UnresolvedType[] arguments = null; - - if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227) + + if (ptb.arguments != null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own + // (pr100227) arguments = new UnresolvedType[ptb.arguments.length]; for (int i = 0; i < arguments.length; i++) { arguments[i] = fromBinding(ptb.arguments[i]); } } - + String baseTypeSignature = null; - - ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true); + + ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)), true); if (!baseType.isMissing()) { // can legitimately be missing if a bound refers to a type we haven't added to the world yet... - // pr168044 - sometimes (whilst resolving types) we are working with 'half finished' types and so (for example) the underlying generic type for a raw type hasnt been set yet - //if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType(); + // pr168044 - sometimes (whilst resolving types) we are working with 'half finished' types and so (for example) the + // underlying generic type for a raw type hasnt been set yet + // if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType(); baseTypeSignature = baseType.getErasureSignature(); } else { baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature(); } - - // Create an unresolved parameterized type. We can't create a resolved one as the + + // Create an unresolved parameterized type. We can't create a resolved one as the // act of resolution here may cause recursion problems since the parameters may // be type variables that we haven't fixed up yet. - if (arguments==null) arguments=new UnresolvedType[0]; -// StringBuffer parameterizedSig = new StringBuffer(); -// parameterizedSig.append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER); -// -//// String parameterizedSig = new StringBuffer().append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER).append(CharOperation.charToString(binding.genericTypeSignature()).substring(1)).toString(); -// return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments); - return TypeFactory.createUnresolvedParameterizedType(baseTypeSignature,arguments); + if (arguments == null) + arguments = new UnresolvedType[0]; + // StringBuffer parameterizedSig = new StringBuffer(); + // parameterizedSig.append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER); + // + // // String parameterizedSig = new + // StringBuffer().append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER).append(CharOperation + // .charToString(binding.genericTypeSignature()).substring(1)).toString(); + // return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments); + return TypeFactory.createUnresolvedParameterizedType(baseTypeSignature, arguments); } - + // Convert the source type binding for a generic type into a generic UnresolvedType // notice we can easily determine the type variables from the eclipse object // and we can recover the generic signature from it too - so we pass those // to the forGenericType() method. - if (binding.isGenericType() && - !binding.isParameterizedType() && - !binding.isRawType()) { + if (binding.isGenericType() && !binding.isParameterizedType() && !binding.isRawType()) { TypeVariableBinding[] tvbs = binding.typeVariables(); TypeVariable[] tVars = new TypeVariable[tvbs.length]; for (int i = 0; i < tvbs.length; i++) { TypeVariableBinding eclipseV = tvbs[i]; - tVars[i] = ((TypeVariableReference)fromTypeVariableBinding(eclipseV)).getTypeVariable(); + tVars[i] = ((TypeVariableReference) fromTypeVariableBinding(eclipseV)).getTypeVariable(); } - //TODO asc generics - temporary guard.... + // TODO asc generics - temporary guard.... if (!(binding instanceof SourceTypeBinding)) - throw new RuntimeException("Cant get the generic sig for "+binding.debugName()); - return UnresolvedType.forGenericType(getName(binding),tVars, - CharOperation.charToString(((SourceTypeBinding)binding).genericSignature())); - } - - // LocalTypeBinding have a name $Local$, we can get the real name by using the signature.... + throw new RuntimeException("Cant get the generic sig for " + binding.debugName()); + return UnresolvedType.forGenericType(getName(binding), tVars, CharOperation.charToString(((SourceTypeBinding) binding) + .genericSignature())); + } + + // LocalTypeBinding have a name $Local$, we can get the real name by using the signature.... if (binding instanceof LocalTypeBinding) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { return UnresolvedType.forSignature(new String(binding.signature())); - } else { - // we're reporting a problem and don't have a resolved name for an + } else { + // we're reporting a problem and don't have a resolved name for an // anonymous local type yet, report the issue on the enclosing type return UnresolvedType.forSignature(new String(ltb.enclosingType.signature())); } } - + // was: UnresolvedType.forName(getName(binding)); UnresolvedType ut = UnresolvedType.forSignature(new String(binding.signature())); return ut; } - /** - * Some type variables refer to themselves recursively, this enables us to avoid - * recursion problems. + * Some type variables refer to themselves recursively, this enables us to avoid recursion problems. */ private static Map typeVariableBindingsInProgress = new HashMap(); - + /** - * Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ - * form (TypeVariable). + * Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ form (TypeVariable). */ - private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) { - // first, check for recursive call to this method for the same tvBinding + private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) { + // first, check for recursive call to this method for the same tvBinding if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) { return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding); } - + // Check if its a type variable binding that we need to recover to an alias... - if (typeVariablesForAliasRecovery!=null) { - String aliasname = (String)typeVariablesForAliasRecovery.get(aTypeVariableBinding); - if (aliasname!=null) { + if (typeVariablesForAliasRecovery != null) { + String aliasname = (String) typeVariablesForAliasRecovery.get(aTypeVariableBinding); + if (aliasname != null) { UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType(); ret.setTypeVariable(new TypeVariable(aliasname)); return ret; } } - + if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) { - return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName)); + return (UnresolvedType) typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName)); } - - + // Create the UnresolvedTypeVariableReferenceType for the type variable String name = CharOperation.charToString(aTypeVariableBinding.sourceName()); - + UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType(); - typeVariableBindingsInProgress.put(aTypeVariableBinding,ret); - + typeVariableBindingsInProgress.put(aTypeVariableBinding, ret); + TypeVariable tv = new TypeVariable(name); ret.setTypeVariable(tv); // Dont set any bounds here, you'll get in a recursive mess // TODO -- what about lower bounds?? - UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass()); + UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass()); UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length]; for (int i = 0; i < superinterfaces.length; i++) { superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]); @@ -374,22 +363,23 @@ public class EclipseFactory { tv.setRank(aTypeVariableBinding.rank); if (aTypeVariableBinding.declaringElement instanceof MethodBinding) { tv.setDeclaringElementKind(TypeVariable.METHOD); -// tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement); + // tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement); } else { tv.setDeclaringElementKind(TypeVariable.TYPE); -// // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement)); + // // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement)); } - if (aTypeVariableBinding.declaringElement instanceof MethodBinding) - typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret); + if (aTypeVariableBinding.declaringElement instanceof MethodBinding) + typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName), ret); typeVariableBindingsInProgress.remove(aTypeVariableBinding); return ret; } - - public UnresolvedType[] fromBindings(TypeBinding[] bindings) { - if (bindings == null) return UnresolvedType.NONE; + + public UnresolvedType[] fromBindings(TypeBinding[] bindings) { + if (bindings == null) + return UnresolvedType.NONE; int len = bindings.length; UnresolvedType[] ret = new UnresolvedType[len]; - for (int i=0; i {}' - * and the ITD was 'public void I.m(List lxs) {}' then this map would contain a pointer - * from the eclipse type 'N extends Number' to the letter 'X'. + * Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done in the scope of some type variables. + * Before converting the parts of a methodbinding (params, return type) we store the type variables in this structure, then + * should any component of the method binding refer to them, we grab them from the map. + */ + private Map typeVariablesForThisMember = new HashMap(); + + /** + * This is a map from typevariablebindings (eclipsey things) to the names the user originally specified in their ITD. For + * example if the target is 'interface I {}' and the ITD was 'public void I.m(List lxs) {}' then this + * map would contain a pointer from the eclipse type 'N extends Number' to the letter 'X'. */ private Map typeVariablesForAliasRecovery; - + /** - * Construct a resolvedmember from a methodbinding. The supplied map tells us about any - * typevariablebindings that replaced typevariables whilst the compiler was resolving types - - * this only happens if it is a generic itd that shares type variables with its target type. + * Construct a resolvedmember from a methodbinding. The supplied map tells us about any typevariablebindings that replaced + * typevariables whilst the compiler was resolving types - this only happens if it is a generic itd that shares type variables + * with its target type. */ - public ResolvedMember makeResolvedMemberForITD(MethodBinding binding,TypeBinding declaringType, - Map /*TypeVariableBinding > original alias name*/ recoveryAliases) { + public ResolvedMember makeResolvedMemberForITD(MethodBinding binding, TypeBinding declaringType, Map /* + * TypeVariableBinding > + * original alias name + */recoveryAliases) { ResolvedMember result = null; try { typeVariablesForAliasRecovery = recoveryAliases; - result = makeResolvedMember(binding,declaringType); + result = makeResolvedMember(binding, declaringType); } finally { - typeVariablesForAliasRecovery = null; + typeVariablesForAliasRecovery = null; } return result; } public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) { - return makeResolvedMember(binding,declaringType, - binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD); + return makeResolvedMember(binding, declaringType, binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD); } public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType, MemberKind memberKind) { - //System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName)); + // System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName)); - // Convert the type variables and store them + // Convert the type variables and store them UnresolvedType[] ajTypeRefs = null; typeVariablesForThisMember.clear(); // This is the set of type variables available whilst building the resolved member... - if (binding.typeVariables!=null) { + if (binding.typeVariables != null) { ajTypeRefs = new UnresolvedType[binding.typeVariables.length]; for (int i = 0; i < binding.typeVariables.length; i++) { ajTypeRefs[i] = fromBinding(binding.typeVariables[i]); - typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]); + typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/* + * new + * Integer(binding.typeVariables[ + * i].rank), + */ajTypeRefs[i]); } } - + // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType)); - if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType(); - ResolvedMemberImpl ret = new EclipseResolvedMember(binding, - memberKind, - realDeclaringType, - binding.modifiers, - fromBinding(binding.returnType), - new String(binding.selector), - fromBindings(binding.parameters), - fromBindings(binding.thrownExceptions),this - ); + if (realDeclaringType.isRawType()) + realDeclaringType = realDeclaringType.getGenericType(); + ResolvedMemberImpl ret = new EclipseResolvedMember(binding, memberKind, realDeclaringType, binding.modifiers, + fromBinding(binding.returnType), new String(binding.selector), fromBindings(binding.parameters), + fromBindings(binding.thrownExceptions), this); if (binding.isVarargs()) { ret.setVarargsMethod(); } - if (ajTypeRefs!=null) { + if (ajTypeRefs != null) { TypeVariable[] tVars = new TypeVariable[ajTypeRefs.length]; - for (int i=0;i0) { - int i =0; + if (aliases != null && aliases.size() > 0) { + int i = 0; for (Iterator iter = aliases.iterator(); iter.hasNext();) { String element = (String) iter.next(); - typeVariableToTypeBinding.put(element,declaringType.typeVariables()[i++]); + typeVariableToTypeBinding.put(element, declaringType.typeVariables()[i++]); } } - + currentType = declaringType; - - FieldBinding fb = null; + + FieldBinding fb = null; if (member.getName().startsWith(NameMangler.PREFIX)) { - fb = new SyntheticFieldBinding(member.getName().toCharArray(), - makeTypeBinding(member.getReturnType()), - member.getModifiers() | Flags.AccSynthetic, - currentType, - Constant.NotAConstant,-1); // index filled in later + fb = new SyntheticFieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member + .getModifiers() + | Flags.AccSynthetic, currentType, Constant.NotAConstant, -1); // index filled in later } else { - fb = new FieldBinding(member.getName().toCharArray(), - makeTypeBinding(member.getReturnType()), - member.getModifiers(), - currentType, - Constant.NotAConstant); + fb = new FieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers(), + currentType, Constant.NotAConstant); } typeVariableToTypeBinding.clear(); currentType = null; - + if (member.getName().startsWith(NameMangler.PREFIX)) { fb.modifiers |= Flags.AccSynthetic; } @@ -819,105 +807,98 @@ public class EclipseFactory { private ReferenceBinding currentType = null; // method binding related - + public MethodBinding makeMethodBinding(NewMethodTypeMunger nmtm) { - return internalMakeMethodBinding(nmtm.getSignature(),nmtm.getTypeVariableAliases()); + return internalMakeMethodBinding(nmtm.getSignature(), nmtm.getTypeVariableAliases()); } - + /** * Convert a resolvedmember into an eclipse method binding. */ - public MethodBinding makeMethodBinding(ResolvedMember member,List aliases) { - return internalMakeMethodBinding(member,aliases); + public MethodBinding makeMethodBinding(ResolvedMember member, List aliases) { + return internalMakeMethodBinding(member, aliases); } - + /** - * Creates a method binding for a resolvedmember taking into account type variable aliases - - * this variant can take an aliasTargetType and should be used when the alias target type - * cannot be retrieved from the resolvedmember. - */ - public MethodBinding makeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) { - return internalMakeMethodBinding(member,aliases,aliasTargetType); + * Creates a method binding for a resolvedmember taking into account type variable aliases - this variant can take an + * aliasTargetType and should be used when the alias target type cannot be retrieved from the resolvedmember. + */ + public MethodBinding makeMethodBinding(ResolvedMember member, List aliases, UnresolvedType aliasTargetType) { + return internalMakeMethodBinding(member, aliases, aliasTargetType); } - + /** * Convert a resolvedmember into an eclipse method binding. */ public MethodBinding makeMethodBinding(ResolvedMember member) { - return internalMakeMethodBinding(member,null); // there are no aliases + return internalMakeMethodBinding(member, null); // there are no aliases } - - public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases) { - return internalMakeMethodBinding(member,aliases,member.getDeclaringType()); + + public MethodBinding internalMakeMethodBinding(ResolvedMember member, List aliases) { + return internalMakeMethodBinding(member, aliases, member.getDeclaringType()); } - + /** - * Take a normal AJ member and convert it into an eclipse methodBinding. - * Taking into account any aliases that it may include due to being a - * generic ITD. Any aliases are put into the typeVariableToBinding - * map so that they will be substituted as appropriate in the returned - * methodbinding + * Take a normal AJ member and convert it into an eclipse methodBinding. Taking into account any aliases that it may include due + * to being a generic ITD. Any aliases are put into the typeVariableToBinding map so that they will be substituted as + * appropriate in the returned methodbinding */ - public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) { + public MethodBinding internalMakeMethodBinding(ResolvedMember member, List aliases, UnresolvedType aliasTargetType) { typeVariableToTypeBinding.clear(); TypeVariableBinding[] tvbs = null; - if (member.getTypeVariables()!=null) { - if (member.getTypeVariables().length==0) { + if (member.getTypeVariables() != null) { + if (member.getTypeVariables().length == 0) { tvbs = Binding.NO_TYPE_VARIABLES; } else { tvbs = makeTypeVariableBindingsFromAJTypeVariables(member.getTypeVariables()); // QQQ do we need to bother fixing up the declaring element here? } - } + } + + ReferenceBinding declaringType = (ReferenceBinding) makeTypeBinding(member.getDeclaringType()); - ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType()); - // If there are aliases, place them in the map - if (aliases!=null && aliases.size()!=0) { - int i=0; - ReferenceBinding aliasTarget = (ReferenceBinding)makeTypeBinding(aliasTargetType); + if (aliases != null && aliases.size() != 0) { + int i = 0; + ReferenceBinding aliasTarget = (ReferenceBinding) makeTypeBinding(aliasTargetType); if (aliasTarget.isRawType()) { - aliasTarget = ((RawTypeBinding) aliasTarget).genericType(); - } + aliasTarget = ((RawTypeBinding) aliasTarget).genericType(); + } for (Iterator iter = aliases.iterator(); iter.hasNext();) { String element = (String) iter.next(); - typeVariableToTypeBinding.put(element,aliasTarget.typeVariables()[i++]); + typeVariableToTypeBinding.put(element, aliasTarget.typeVariables()[i++]); } } - + currentType = declaringType; - MethodBinding mb = new MethodBinding(member.getModifiers(), - member.getName().toCharArray(), - makeTypeBinding(member.getReturnType()), - makeTypeBindings(member.getParameterTypes()), - makeReferenceBindings(member.getExceptions()), + MethodBinding mb = new MethodBinding(member.getModifiers(), member.getName().toCharArray(), makeTypeBinding(member + .getReturnType()), makeTypeBindings(member.getParameterTypes()), makeReferenceBindings(member.getExceptions()), declaringType); - if (tvbs!=null) mb.typeVariables = tvbs; + if (tvbs != null) + mb.typeVariables = tvbs; typeVariableToTypeBinding.clear(); currentType = null; - + if (NameMangler.isSyntheticMethod(member.getName(), true)) { mb.modifiers |= Flags.AccSynthetic; } - + return mb; } - /** * Convert a bunch of type variables in one go, from AspectJ form to Eclipse form. */ -// private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) { -// int len = typeVariables.length; -// TypeVariableBinding[] ret = new TypeVariableBinding[len]; -// for (int i = 0; i < len; i++) { -// ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]); -// } -// return ret; -// } - + // private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) { + // int len = typeVariables.length; + // TypeVariableBinding[] ret = new TypeVariableBinding[len]; + // for (int i = 0; i < len; i++) { + // ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]); + // } + // return ret; + // } private TypeVariableBinding[] makeTypeVariableBindingsFromAJTypeVariables(TypeVariable[] typeVariables) { int len = typeVariables.length; TypeVariableBinding[] ret = new TypeVariableBinding[len]; @@ -927,96 +908,95 @@ public class EclipseFactory { return ret; } - // only accessed through private methods in this class. Ensures all type variables we encounter + // only accessed through private methods in this class. Ensures all type variables we encounter // map back to the same type binding - this is important later when Eclipse code is processing // a methodbinding trying to come up with possible bindings for the type variables. // key is currently the name of the type variable...is that ok? private Map typeVariableToTypeBinding = new HashMap(); - - /** - * Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference - * in AspectJ world holds a TypeVariable and it is this type variable that is converted - * to the TypeVariableBinding. - */ - private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) { - TypeVariable tv = tvReference.getTypeVariable(); - TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName()); - if (currentType!=null) { - TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray()); - if (tvb!=null) return tvb; - } - if (tvBinding==null) { - Binding declaringElement = null; - // this will cause an infinite loop or NPE... not required yet luckily. -// if (tVar.getDeclaringElement() instanceof Member) { -// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); -// } else { -// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); -// } - - tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),null,tv.getRank()); - - typeVariableToTypeBinding.put(tv.getName(),tvBinding); - tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound()); - tvBinding.firstBound=makeTypeBinding(tv.getFirstBound()); - if (tv.getAdditionalInterfaceBounds()==null) { - tvBinding.superInterfaces=TypeVariableBinding.NO_SUPERINTERFACES; - } else { - TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds()); - ReferenceBinding[] rbs= new ReferenceBinding[tbs.length]; - for (int i = 0; i < tbs.length; i++) { - rbs[i] = (ReferenceBinding)tbs[i]; - } - tvBinding.superInterfaces=rbs; - } - } - return tvBinding; - } - + + // /** + // * Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference + // * in AspectJ world holds a TypeVariable and it is this type variable that is converted + // * to the TypeVariableBinding. + // */ + // private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) { + // TypeVariable tv = tvReference.getTypeVariable(); + // TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName()); + // if (currentType!=null) { + // TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray()); + // if (tvb!=null) return tvb; + // } + // if (tvBinding==null) { + // Binding declaringElement = null; + // // this will cause an infinite loop or NPE... not required yet luckily. + // // if (tVar.getDeclaringElement() instanceof Member) { + // // declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); + // // } else { + // // declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); + // // } + // + // tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),null,tv.getRank()); + // + // typeVariableToTypeBinding.put(tv.getName(),tvBinding); + // tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound()); + // tvBinding.firstBound=makeTypeBinding(tv.getFirstBound()); + // if (tv.getAdditionalInterfaceBounds()==null) { + // tvBinding.superInterfaces=TypeVariableBinding.NO_SUPERINTERFACES; + // } else { + // TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds()); + // ReferenceBinding[] rbs= new ReferenceBinding[tbs.length]; + // for (int i = 0; i < tbs.length; i++) { + // rbs[i] = (ReferenceBinding)tbs[i]; + // } + // tvBinding.superInterfaces=rbs; + // } + // } + // return tvBinding; + // } + private TypeVariableBinding makeTypeVariableBindingFromAJTypeVariable(TypeVariable tv) { - TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName()); - if (currentType!=null) { - TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray()); - if (tvb!=null) return tvb; + TypeVariableBinding tvBinding = (TypeVariableBinding) typeVariableToTypeBinding.get(tv.getName()); + if (currentType != null) { + TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray()); + if (tvb != null) + return tvb; } - if (tvBinding==null) { - Binding declaringElement = null; - // this will cause an infinite loop or NPE... not required yet luckily. -// if (tVar.getDeclaringElement() instanceof Member) { -// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); -// } else { -// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); -// } - tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank()); - typeVariableToTypeBinding.put(tv.getName(),tvBinding); - tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound()); - tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound()); - if (tv.getAdditionalInterfaceBounds()==null) { - tvBinding.superInterfaces=TypeVariableBinding.NO_SUPERINTERFACES; - } else { - TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds()); - ReferenceBinding[] rbs= new ReferenceBinding[tbs.length]; - for (int i = 0; i < tbs.length; i++) { - rbs[i] = (ReferenceBinding)tbs[i]; + if (tvBinding == null) { + Binding declaringElement = null; + // this will cause an infinite loop or NPE... not required yet luckily. + // if (tVar.getDeclaringElement() instanceof Member) { + // declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); + // } else { + // declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); + // } + tvBinding = new TypeVariableBinding(tv.getName().toCharArray(), declaringElement, tv.getRank()); + typeVariableToTypeBinding.put(tv.getName(), tvBinding); + tvBinding.superclass = (ReferenceBinding) makeTypeBinding(tv.getUpperBound()); + tvBinding.firstBound = (ReferenceBinding) makeTypeBinding(tv.getFirstBound()); + if (tv.getAdditionalInterfaceBounds() == null) { + tvBinding.superInterfaces = TypeVariableBinding.NO_SUPERINTERFACES; + } else { + TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds()); + ReferenceBinding[] rbs = new ReferenceBinding[tbs.length]; + for (int i = 0; i < tbs.length; i++) { + rbs[i] = (ReferenceBinding) tbs[i]; + } + tvBinding.superInterfaces = rbs; } - tvBinding.superInterfaces=rbs; - } - } + } return tvBinding; } public MethodBinding makeMethodBindingForCall(Member member) { - return new MethodBinding(member.getModifiers() & ~ Modifier.INTERFACE, - member.getName().toCharArray(), - makeTypeBinding(member.getReturnType()), - makeTypeBindings(member.getParameterTypes()), - new ReferenceBinding[0], - (ReferenceBinding)makeTypeBinding(member.getDeclaringType())); + return new MethodBinding(member.getModifiers() & ~Modifier.INTERFACE, member.getName().toCharArray(), + makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), new ReferenceBinding[0], + (ReferenceBinding) makeTypeBinding(member.getDeclaringType())); } public void finishedCompilationUnit(CompilationUnitDeclaration unit) { if ((buildManager != null) && buildManager.doGenerateModel()) { - AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig); + AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), + buildManager.buildConfig); } } @@ -1033,96 +1013,97 @@ public class EclipseFactory { public Shadow makeShadow(ASTNode location, ReferenceContext context) { return EclipseShadow.makeShadow(this, location, context); } - + public Shadow makeShadow(ReferenceContext context) { return EclipseShadow.makeShadow(this, (ASTNode) context, context); } - + public void addSourceTypeBinding(SourceTypeBinding binding, CompilationUnitDeclaration unit) { TypeDeclaration decl = binding.scope.referenceContext; - + // Deal with the raw/basic type to give us an entry in the world type map UnresolvedType simpleTx = null; if (binding.isGenericType()) { - simpleTx = UnresolvedType.forRawTypeName(getName(binding)); - } else if (binding.isLocalType()) { + simpleTx = UnresolvedType.forRawTypeName(getName(binding)); + } else if (binding.isLocalType()) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { simpleTx = UnresolvedType.forSignature(new String(binding.signature())); } else { simpleTx = UnresolvedType.forName(getName(binding)); } - }else { - simpleTx = UnresolvedType.forName(getName(binding)); + } else { + simpleTx = UnresolvedType.forName(getName(binding)); } - ReferenceType name = getWorld().lookupOrCreateName(simpleTx); - + ReferenceType name = getWorld().lookupOrCreateName(simpleTx); + // A type can change from simple > generic > simple across a set of compiles. We need - // to ensure the entry in the typemap is promoted and demoted correctly. The call + // to ensure the entry in the typemap is promoted and demoted correctly. The call // to setGenericType() below promotes a simple to a raw. This call demotes it back // to simple // pr125405 - if (!binding.isRawType() && !binding.isGenericType() && name.getTypekind()==TypeKind.RAW) { + if (!binding.isRawType() && !binding.isGenericType() && name.getTypekind() == TypeKind.RAW) { name.demoteToSimpleType(); } EclipseSourceType t = new EclipseSourceType(name, this, binding, decl, unit); - + // For generics, go a bit further - build a typex for the generic type // give it the same delegate and link it to the raw type if (binding.isGenericType()) { UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info - ResolvedType cName = world.resolve(complexTx,true); + ResolvedType cName = world.resolve(complexTx, true); ReferenceType complexName = null; if (!cName.isMissing()) { complexName = (ReferenceType) cName; complexName = (ReferenceType) complexName.getGenericType(); - if (complexName == null) complexName = new ReferenceType(complexTx,world); + if (complexName == null) + complexName = new ReferenceType(complexTx, world); } else { - complexName = new ReferenceType(complexTx,world); + complexName = new ReferenceType(complexTx, world); } name.setGenericType(complexName); complexName.setDelegate(t); } - + name.setDelegate(t); if (decl instanceof AspectDeclaration) { - ((AspectDeclaration)decl).typeX = name; - ((AspectDeclaration)decl).concreteName = t; + ((AspectDeclaration) decl).typeX = name; + ((AspectDeclaration) decl).concreteName = t; } - + ReferenceBinding[] memberTypes = binding.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit); } } - + // XXX this doesn't feel like it belongs here, but it breaks a hard dependency on // exposing AjBuildManager (needed by AspectDeclaration). public boolean isXSerializableAspects() { return xSerializableAspects; } - + public ResolvedMember fromBinding(MethodBinding binding) { - return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers, - fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters)); + return new ResolvedMemberImpl(Member.METHOD, fromBinding(binding.declaringClass), binding.modifiers, + fromBinding(binding.returnType), CharOperation.charToString(binding.selector), fromBindings(binding.parameters)); } public TypeVariableDeclaringElement fromBinding(Binding declaringElement) { if (declaringElement instanceof TypeBinding) { - return fromBinding(((TypeBinding)declaringElement)); + return fromBinding(((TypeBinding) declaringElement)); } else { - return fromBinding((MethodBinding)declaringElement); + return fromBinding((MethodBinding) declaringElement); } } - + public void cleanup() { this.typexToBinding.clear(); this.rawTypeXToBinding.clear(); this.finishedTypeMungers = null; } - + public void minicleanup() { this.typexToBinding.clear(); this.rawTypeXToBinding.clear(); diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java index 7fd1d9ba0..dfb1379cb 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java @@ -11,7 +11,6 @@ * Alexandre Vasseur support for @AJ perClause * ******************************************************************/ - package org.aspectj.ajdt.internal.compiler.lookup; import java.util.ArrayList; @@ -88,184 +87,194 @@ import org.aspectj.weaver.patterns.Pointcut; */ public class EclipseSourceType extends AbstractReferenceTypeDelegate { private static final char[] pointcutSig = "Lorg/aspectj/lang/annotation/Pointcut;".toCharArray(); - private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray(); + private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray(); protected ResolvedPointcutDefinition[] declaredPointcuts = null; protected ResolvedMember[] declaredMethods = null; protected ResolvedMember[] declaredFields = null; - + public List declares = new ArrayList(); public List typeMungers = new ArrayList(); - + private EclipseFactory factory; - + private SourceTypeBinding binding; private TypeDeclaration declaration; private CompilationUnitDeclaration unit; private boolean annotationsResolved = false; private ResolvedType[] resolvedAnnotations = null; - + private boolean discoveredAnnotationTargetKinds = false; private AnnotationTargetKind[] annotationTargetKinds; private AnnotationX[] annotations = null; private final static ResolvedType[] NO_ANNOTATION_TYPES = new ResolvedType[0]; private final static AnnotationX[] NO_ANNOTATIONS = new AnnotationX[0]; - + protected EclipseFactory eclipseWorld() { return factory; } - public EclipseSourceType(ReferenceType resolvedTypeX, EclipseFactory factory, - SourceTypeBinding binding, TypeDeclaration declaration, - CompilationUnitDeclaration unit) - { + public EclipseSourceType(ReferenceType resolvedTypeX, EclipseFactory factory, SourceTypeBinding binding, + TypeDeclaration declaration, CompilationUnitDeclaration unit) { super(resolvedTypeX, true); this.factory = factory; this.binding = binding; this.declaration = declaration; this.unit = unit; - + setSourceContext(new EclipseSourceContext(declaration.compilationResult)); resolvedTypeX.setStartPos(declaration.sourceStart); resolvedTypeX.setEndPos(declaration.sourceEnd); } - public boolean isAspect() { final boolean isCodeStyle = declaration instanceof AspectDeclaration; - return isCodeStyle?isCodeStyle:isAnnotationStyleAspect(); + return isCodeStyle ? isCodeStyle : isAnnotationStyleAspect(); } - + public boolean isAnonymous() { - if (declaration.binding != null) - return declaration.binding.isAnonymousType(); - return ((declaration.modifiers & (ASTNode.IsAnonymousType | ASTNode.IsLocalType)) != 0); + if (declaration.binding != null) + return declaration.binding.isAnonymousType(); + return ((declaration.modifiers & (ASTNode.IsAnonymousType | ASTNode.IsLocalType)) != 0); } - + public boolean isNested() { - if (declaration.binding!=null) return (declaration.binding.isMemberType()); + if (declaration.binding != null) + return (declaration.binding.isMemberType()); return ((declaration.modifiers & ASTNode.IsMemberType) != 0); } - + public ResolvedType getOuterClass() { - if (declaration.enclosingType==null) return null; + if (declaration.enclosingType == null) + return null; return eclipseWorld().fromEclipse(declaration.enclosingType.binding); } - public boolean isAnnotationStyleAspect() { - if (declaration.annotations == null) { - return false; - } - ResolvedType[] annotations = getAnnotationTypes(); - for (int i = 0; i < annotations.length; i++) { - if ("org.aspectj.lang.annotation.Aspect".equals(annotations[i].getName())) { - return true; - } - } - return false; - } - - /** Returns "" if there is a problem */ - private String getPointcutStringFromAnnotationStylePointcut(AbstractMethodDeclaration amd) { - Annotation[] ans = amd.annotations; - if (ans == null) return ""; + public boolean isAnnotationStyleAspect() { + if (declaration.annotations == null) { + return false; + } + ResolvedType[] annotations = getAnnotationTypes(); + for (int i = 0; i < annotations.length; i++) { + if ("org.aspectj.lang.annotation.Aspect".equals(annotations[i].getName())) { + return true; + } + } + return false; + } + + /** Returns "" if there is a problem */ + private String getPointcutStringFromAnnotationStylePointcut(AbstractMethodDeclaration amd) { + Annotation[] ans = amd.annotations; + if (ans == null) + return ""; for (int i = 0; i < ans.length; i++) { - if (ans[i].resolvedType == null) continue; // XXX happens if we do this very early from buildInterTypeandPerClause - // may prevent us from resolving references made in @Pointcuts to - // an @Pointcut in a code-style aspect + if (ans[i].resolvedType == null) + continue; // XXX happens if we do this very early from buildInterTypeandPerClause + // may prevent us from resolving references made in @Pointcuts to + // an @Pointcut in a code-style aspect char[] sig = ans[i].resolvedType.signature(); - if (CharOperation.equals(pointcutSig,sig)) { - if (ans[i].memberValuePairs().length==0) return ""; // empty pointcut expression + if (CharOperation.equals(pointcutSig, sig)) { + if (ans[i].memberValuePairs().length == 0) + return ""; // empty pointcut expression Expression expr = ans[i].memberValuePairs()[0].value; if (expr instanceof StringLiteral) { - StringLiteral sLit = ((StringLiteral)expr); + StringLiteral sLit = ((StringLiteral) expr); return new String(sLit.source()); - } else if (expr instanceof NameReference && (((NameReference)expr).binding instanceof FieldBinding)) { - Binding b = ((NameReference)expr).binding; - Constant c = ((FieldBinding)b).constant; + } else if (expr instanceof NameReference && (((NameReference) expr).binding instanceof FieldBinding)) { + Binding b = ((NameReference) expr).binding; + Constant c = ((FieldBinding) b).constant; return c.stringValue(); } else { - throw new BCException("Do not know how to recover pointcut definition from "+expr+" (type "+expr.getClass().getName()+")"); + throw new BCException("Do not know how to recover pointcut definition from " + expr + " (type " + + expr.getClass().getName() + ")"); } } } return ""; - } + } private boolean isAnnotationStylePointcut(Annotation[] annotations) { - if (annotations == null) return false; + if (annotations == null) + return false; for (int i = 0; i < annotations.length; i++) { - if (annotations[i].resolvedType == null) continue; // XXX happens if we do this very early from buildInterTypeandPerClause - // may prevent us from resolving references made in @Pointcuts to - // an @Pointcut in a code-style aspect + if (annotations[i].resolvedType == null) + continue; // XXX happens if we do this very early from buildInterTypeandPerClause + // may prevent us from resolving references made in @Pointcuts to + // an @Pointcut in a code-style aspect char[] sig = annotations[i].resolvedType.signature(); - if (CharOperation.equals(pointcutSig,sig)) { + if (CharOperation.equals(pointcutSig, sig)) { return true; } } return false; } - + public WeaverStateInfo getWeaverState() { return null; } - + public ResolvedType getSuperclass() { - if (binding.isInterface()) return getResolvedTypeX().getWorld().getCoreType(UnresolvedType.OBJECT); - //XXX what about java.lang.Object + if (binding.isInterface()) + return getResolvedTypeX().getWorld().getCoreType(UnresolvedType.OBJECT); + // XXX what about java.lang.Object return eclipseWorld().fromEclipse(binding.superclass()); } - + public ResolvedType[] getDeclaredInterfaces() { return eclipseWorld().fromEclipse(binding.superInterfaces()); } - protected void fillDeclaredMembers() { List declaredPointcuts = new ArrayList(); List declaredMethods = new ArrayList(); List declaredFields = new ArrayList(); - - binding.methods(); // the important side-effect of this call is to make sure bindings are completed + + binding.methods(); // the important side-effect of this call is to make sure bindings are completed AbstractMethodDeclaration[] methods = declaration.methods; if (methods != null) { - for (int i=0, len=methods.length; i < len; i++) { + for (int i = 0, len = methods.length; i < len; i++) { AbstractMethodDeclaration amd = methods[i]; - if (amd == null || amd.ignoreFurtherInvestigation) continue; + if (amd == null || amd.ignoreFurtherInvestigation) + continue; if (amd instanceof PointcutDeclaration) { - PointcutDeclaration d = (PointcutDeclaration)amd; + PointcutDeclaration d = (PointcutDeclaration) amd; ResolvedPointcutDefinition df = d.makeResolvedPointcutDefinition(factory); declaredPointcuts.add(df); - } else if (amd instanceof InterTypeDeclaration) { + } else if (amd instanceof InterTypeDeclaration) { // these are handled in a separate pass continue; - } else if (amd instanceof DeclareDeclaration && - !(amd instanceof DeclareAnnotationDeclaration)) { // surfaces the annotated ajc$ method + } else if (amd instanceof DeclareDeclaration && !(amd instanceof DeclareAnnotationDeclaration)) { // surfaces the + // annotated + // ajc$ method // these are handled in a separate pass continue; } else if (amd instanceof AdviceDeclaration) { // these are ignored during compilation and only used during weaving continue; - } else if ((amd.annotations != null) && isAnnotationStylePointcut(amd.annotations)) { + } else if ((amd.annotations != null) && isAnnotationStylePointcut(amd.annotations)) { // consider pointcuts defined via annotations ResolvedPointcutDefinition df = makeResolvedPointcutDefinition(amd); - if (df!=null) declaredPointcuts.add(df); + if (df != null) + declaredPointcuts.add(df); } else { - if (amd.binding == null || !amd.binding.isValidBinding()) continue; + if (amd.binding == null || !amd.binding.isValidBinding()) + continue; ResolvedMember member = factory.makeResolvedMember(amd.binding); if (unit != null) { boolean positionKnown = true; if (amd.binding.sourceMethod() == null) { if (amd.binding.declaringClass instanceof SourceTypeBinding) { SourceTypeBinding stb = ((SourceTypeBinding) amd.binding.declaringClass); - if (stb.scope==null || stb.scope.referenceContext==null) positionKnown = false; + if (stb.scope == null || stb.scope.referenceContext == null) + positionKnown = false; } } if (positionKnown) { // pr229829 - member.setSourceContext(new EclipseSourceContext(unit.compilationResult,amd.binding.sourceStart())); - member.setPosition(amd.binding.sourceStart(),amd.binding.sourceEnd()); + member.setSourceContext(new EclipseSourceContext(unit.compilationResult, amd.binding.sourceStart())); + member.setPosition(amd.binding.sourceStart(), amd.binding.sourceEnd()); } else { - member.setSourceContext(new EclipseSourceContext(unit.compilationResult,0)); - member.setPosition(0,0); + member.setSourceContext(new EclipseSourceContext(unit.compilationResult, 0)); + member.setPosition(0, 0); } } declaredMethods.add(member); @@ -274,42 +283,37 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { } FieldBinding[] fields = binding.fields(); - for (int i=0, len=fields.length; i < len; i++) { + for (int i = 0, len = fields.length; i < len; i++) { FieldBinding f = fields[i]; declaredFields.add(factory.makeResolvedMember(f)); } - - this.declaredPointcuts = (ResolvedPointcutDefinition[]) - declaredPointcuts.toArray(new ResolvedPointcutDefinition[declaredPointcuts.size()]); - this.declaredMethods = (ResolvedMember[]) - declaredMethods.toArray(new ResolvedMember[declaredMethods.size()]); - this.declaredFields = (ResolvedMember[]) - declaredFields.toArray(new ResolvedMember[declaredFields.size()]); + + this.declaredPointcuts = (ResolvedPointcutDefinition[]) declaredPointcuts + .toArray(new ResolvedPointcutDefinition[declaredPointcuts.size()]); + this.declaredMethods = (ResolvedMember[]) declaredMethods.toArray(new ResolvedMember[declaredMethods.size()]); + this.declaredFields = (ResolvedMember[]) declaredFields.toArray(new ResolvedMember[declaredFields.size()]); } private ResolvedPointcutDefinition makeResolvedPointcutDefinition(AbstractMethodDeclaration md) { - if (md.binding==null) return null; // there is another error that has caused this... pr138143 + if (md.binding == null) + return null; // there is another error that has caused this... pr138143 EclipseSourceContext eSourceContext = new EclipseSourceContext(md.compilationResult); Pointcut pc = null; if (!md.isAbstract()) { String expression = getPointcutStringFromAnnotationStylePointcut(md); - try { - pc = new PatternParser(expression,eSourceContext).parsePointcut(); + try { + pc = new PatternParser(expression, eSourceContext).parsePointcut(); } catch (ParserException pe) { // error will be reported by other means... pc = Pointcut.makeMatchesNothing(Pointcut.SYMBOLIC); } } - + FormalBinding[] bindings = buildFormalAdviceBindingsFrom(md); - - ResolvedPointcutDefinition rpd = new LazyResolvedPointcutDefinition( - factory.fromBinding(md.binding.declaringClass), - md.modifiers, - new String(md.selector), - factory.fromBindings(md.binding.parameters), - factory.fromBinding(md.binding.returnType), - pc,new EclipseScope(bindings,md.scope)); + + ResolvedPointcutDefinition rpd = new LazyResolvedPointcutDefinition(factory.fromBinding(md.binding.declaringClass), + md.modifiers, new String(md.selector), factory.fromBindings(md.binding.parameters), factory + .fromBinding(md.binding.returnType), pc, new EclipseScope(bindings, md.scope)); rpd.setPosition(md.sourceStart, md.sourceEnd); rpd.setSourceContext(eSourceContext); @@ -322,210 +326,217 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { private static final char[] proceedingJoinPoint = "Lorg/aspectj/lang/ProceedingJoinPoint;".toCharArray(); private FormalBinding[] buildFormalAdviceBindingsFrom(AbstractMethodDeclaration mDecl) { - if (mDecl.arguments == null) return new FormalBinding[0]; - if (mDecl.binding == null) return new FormalBinding[0]; + if (mDecl.arguments == null) + return new FormalBinding[0]; + if (mDecl.binding == null) + return new FormalBinding[0]; EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(mDecl.scope); - String extraArgName = null;//maybeGetExtraArgName(); - if (extraArgName == null) extraArgName = ""; + String extraArgName = "";// maybeGetExtraArgName(); FormalBinding[] ret = new FormalBinding[mDecl.arguments.length]; for (int i = 0; i < mDecl.arguments.length; i++) { - Argument arg = mDecl.arguments[i]; - String name = new String(arg.name); - TypeBinding argTypeBinding = mDecl.binding.parameters[i]; - UnresolvedType type = factory.fromBinding(argTypeBinding); - if (CharOperation.equals(joinPoint,argTypeBinding.signature()) || - CharOperation.equals(joinPointStaticPart,argTypeBinding.signature()) || - CharOperation.equals(joinPointEnclosingStaticPart,argTypeBinding.signature()) || - CharOperation.equals(proceedingJoinPoint,argTypeBinding.signature()) || - name.equals(extraArgName)) { - ret[i] = new FormalBinding.ImplicitFormalBinding(type,name,i); + Argument arg = mDecl.arguments[i]; + String name = new String(arg.name); + TypeBinding argTypeBinding = mDecl.binding.parameters[i]; + UnresolvedType type = factory.fromBinding(argTypeBinding); + if (CharOperation.equals(joinPoint, argTypeBinding.signature()) + || CharOperation.equals(joinPointStaticPart, argTypeBinding.signature()) + || CharOperation.equals(joinPointEnclosingStaticPart, argTypeBinding.signature()) + || CharOperation.equals(proceedingJoinPoint, argTypeBinding.signature()) || name.equals(extraArgName)) { + ret[i] = new FormalBinding.ImplicitFormalBinding(type, name, i); } else { - ret[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown"); + ret[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown"); } } return ret; } - + /** - * This method may not return all fields, for example it may - * not include the ajc$initFailureCause or ajc$perSingletonInstance + * This method may not return all fields, for example it may not include the ajc$initFailureCause or ajc$perSingletonInstance * fields - see bug 129613 */ public ResolvedMember[] getDeclaredFields() { - if (declaredFields == null) fillDeclaredMembers(); + if (declaredFields == null) + fillDeclaredMembers(); return declaredFields; } /** - * This method may not return all methods, for example it may - * not include clinit, aspectOf, hasAspect or ajc$postClinit - * methods - see bug 129613 + * This method may not return all methods, for example it may not include clinit, aspectOf, hasAspect or ajc$postClinit methods + * - see bug 129613 */ public ResolvedMember[] getDeclaredMethods() { - if (declaredMethods == null) fillDeclaredMembers(); + if (declaredMethods == null) + fillDeclaredMembers(); return declaredMethods; } public ResolvedMember[] getDeclaredPointcuts() { - if (declaredPointcuts == null) fillDeclaredMembers(); + if (declaredPointcuts == null) + fillDeclaredMembers(); return declaredPointcuts; } - public int getModifiers() { // only return the real Java modifiers, not the extra eclipse ones return binding.modifiers & ExtraCompilerModifiers.AccJustFlag; } - + public String toString() { return "EclipseSourceType(" + new String(binding.sourceName()) + ")"; } - - //XXX make sure this is applied to classes and interfaces + // XXX make sure this is applied to classes and interfaces public void checkPointcutDeclarations() { ResolvedMember[] pointcuts = getDeclaredPointcuts(); boolean sawError = false; - for (int i=0, len=pointcuts.length; i < len; i++) { + for (int i = 0, len = pointcuts.length; i < len; i++) { if (pointcuts[i].isAbstract()) { if (!this.isAspect()) { - eclipseWorld().showMessage(IMessage.ERROR, - "abstract pointcut only allowed in aspect" + pointcuts[i].getName(), - pointcuts[i].getSourceLocation(), null); + eclipseWorld().showMessage(IMessage.ERROR, "abstract pointcut only allowed in aspect" + pointcuts[i].getName(), + pointcuts[i].getSourceLocation(), null); sawError = true; } else if (!binding.isAbstract()) { - eclipseWorld().showMessage(IMessage.ERROR, - "abstract pointcut in concrete aspect" + pointcuts[i], - pointcuts[i].getSourceLocation(), null); + eclipseWorld().showMessage(IMessage.ERROR, "abstract pointcut in concrete aspect" + pointcuts[i], + pointcuts[i].getSourceLocation(), null); sawError = true; } } - - for (int j=i+1; j < len; j++) { + + for (int j = i + 1; j < len; j++) { if (pointcuts[i].getName().equals(pointcuts[j].getName())) { - eclipseWorld().showMessage(IMessage.ERROR, - "duplicate pointcut name: " + pointcuts[j].getName(), - pointcuts[i].getSourceLocation(), pointcuts[j].getSourceLocation()); + eclipseWorld().showMessage(IMessage.ERROR, "duplicate pointcut name: " + pointcuts[j].getName(), + pointcuts[i].getSourceLocation(), pointcuts[j].getSourceLocation()); sawError = true; } } } - - //now check all inherited pointcuts to be sure that they're handled reasonably - if (sawError || !isAspect()) return; - - + // now check all inherited pointcuts to be sure that they're handled reasonably + if (sawError || !isAspect()) + return; + // find all pointcuts that override ones from super and check override is legal - // i.e. same signatures and greater or equal visibility + // i.e. same signatures and greater or equal visibility // find all inherited abstract pointcuts and make sure they're concretized if I'm concrete // find all inherited pointcuts and make sure they don't conflict - getResolvedTypeX().getExposedPointcuts(); //??? this is an odd construction + getResolvedTypeX().getExposedPointcuts(); // ??? this is an odd construction } - - //??? -// public CrosscuttingMembers collectCrosscuttingMembers() { -// return crosscuttingMembers; -// } -// public ISourceLocation getSourceLocation() { -// TypeDeclaration dec = binding.scope.referenceContext; -// return new EclipseSourceLocation(dec.compilationResult, dec.sourceStart, dec.sourceEnd); -// } + // ??? + // public CrosscuttingMembers collectCrosscuttingMembers() { + // return crosscuttingMembers; + // } + + // public ISourceLocation getSourceLocation() { + // TypeDeclaration dec = binding.scope.referenceContext; + // return new EclipseSourceLocation(dec.compilationResult, dec.sourceStart, dec.sourceEnd); + // } public boolean isInterface() { return binding.isInterface(); } // XXXAJ5: Should be constants in the eclipse compiler somewhere, once it supports 1.5 - public final static short ACC_ANNOTATION = 0x2000; - public final static short ACC_ENUM = 0x4000; - + public final static short ACC_ANNOTATION = 0x2000; + public final static short ACC_ENUM = 0x4000; + public boolean isEnum() { - return (binding.getAccessFlags() & ACC_ENUM)!=0; + return (binding.getAccessFlags() & ACC_ENUM) != 0; } - + public boolean isAnnotation() { - return (binding.getAccessFlags() & ACC_ANNOTATION)!=0; + return (binding.getAccessFlags() & ACC_ANNOTATION) != 0; } - + public void addAnnotation(AnnotationX annotationX) { // XXX Big hole here - annotationX holds a BCEL annotation but // we need an Eclipse one here, we haven't written the conversion utils - // yet. Not sure if this method will be called in practice... + // yet. Not sure if this method will be called in practice... throw new RuntimeException("EclipseSourceType.addAnnotation() not implemented"); } - + public boolean isAnnotationWithRuntimeRetention() { - if (!isAnnotation()) { - return false; - } else { - return (binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention; - } + if (!isAnnotation()) { + return false; + } else { + return (binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention; + } } - + public String getRetentionPolicy() { if (isAnnotation()) { - if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention) return "RUNTIME"; - if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationSourceRetention) return "SOURCE"; - if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationClassRetention) return "CLASS"; + if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention) + return "RUNTIME"; + if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationSourceRetention) + return "SOURCE"; + if ((binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationClassRetention) + return "CLASS"; } return null; } - + public boolean canAnnotationTargetType() { if (isAnnotation()) { - return ((binding.getAnnotationTagBits() & TagBits.AnnotationForType) != 0 ); + return ((binding.getAnnotationTagBits() & TagBits.AnnotationForType) != 0); } return false; } - + public AnnotationTargetKind[] getAnnotationTargetKinds() { - if (discoveredAnnotationTargetKinds) return annotationTargetKinds; + if (discoveredAnnotationTargetKinds) + return annotationTargetKinds; discoveredAnnotationTargetKinds = true; annotationTargetKinds = null; // null means we have no idea or the @Target annotation hasn't been used -// if (isAnnotation()) { -// Annotation[] annotationsOnThisType = declaration.annotations; -// if (annotationsOnThisType != null) { -// for (int i = 0; i < annotationsOnThisType.length; i++) { -// Annotation a = annotationsOnThisType[i]; -// if (a.resolvedType != null) { -// String packageName = new String(a.resolvedType.qualifiedPackageName()).concat("."); -// String sourceName = new String(a.resolvedType.qualifiedSourceName()); -// if ((packageName + sourceName).equals(UnresolvedType.AT_TARGET.getName())) { -// MemberValuePair[] pairs = a.memberValuePairs(); -// for (int j = 0; j < pairs.length; j++) { -// MemberValuePair pair = pairs[j]; -// targetKind = pair.value.toString(); -// return targetKind; -// } -// } -// } -// } -// } -// } -// return targetKind; + // if (isAnnotation()) { + // Annotation[] annotationsOnThisType = declaration.annotations; + // if (annotationsOnThisType != null) { + // for (int i = 0; i < annotationsOnThisType.length; i++) { + // Annotation a = annotationsOnThisType[i]; + // if (a.resolvedType != null) { + // String packageName = new String(a.resolvedType.qualifiedPackageName()).concat("."); + // String sourceName = new String(a.resolvedType.qualifiedSourceName()); + // if ((packageName + sourceName).equals(UnresolvedType.AT_TARGET.getName())) { + // MemberValuePair[] pairs = a.memberValuePairs(); + // for (int j = 0; j < pairs.length; j++) { + // MemberValuePair pair = pairs[j]; + // targetKind = pair.value.toString(); + // return targetKind; + // } + // } + // } + // } + // } + // } + // return targetKind; if (isAnnotation()) { List targetKinds = new ArrayList(); - - if ((binding.getAnnotationTagBits() & TagBits.AnnotationForAnnotationType) != 0) targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE); - if ((binding.getAnnotationTagBits() & TagBits.AnnotationForConstructor) != 0) targetKinds.add(AnnotationTargetKind.CONSTRUCTOR); - if ((binding.getAnnotationTagBits() & TagBits.AnnotationForField) != 0) targetKinds.add(AnnotationTargetKind.FIELD); - if ((binding.getAnnotationTagBits() & TagBits.AnnotationForLocalVariable) != 0) targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE); - if ((binding.getAnnotationTagBits() & TagBits.AnnotationForMethod) != 0) targetKinds.add(AnnotationTargetKind.METHOD); - if ((binding.getAnnotationTagBits() & TagBits.AnnotationForPackage) != 0) targetKinds.add(AnnotationTargetKind.PACKAGE); - if ((binding.getAnnotationTagBits() & TagBits.AnnotationForParameter) != 0) targetKinds.add(AnnotationTargetKind.PARAMETER); - if ((binding.getAnnotationTagBits() & TagBits.AnnotationForType) != 0) targetKinds.add(AnnotationTargetKind.TYPE); - + + if ((binding.getAnnotationTagBits() & TagBits.AnnotationForAnnotationType) != 0) + targetKinds.add(AnnotationTargetKind.ANNOTATION_TYPE); + if ((binding.getAnnotationTagBits() & TagBits.AnnotationForConstructor) != 0) + targetKinds.add(AnnotationTargetKind.CONSTRUCTOR); + if ((binding.getAnnotationTagBits() & TagBits.AnnotationForField) != 0) + targetKinds.add(AnnotationTargetKind.FIELD); + if ((binding.getAnnotationTagBits() & TagBits.AnnotationForLocalVariable) != 0) + targetKinds.add(AnnotationTargetKind.LOCAL_VARIABLE); + if ((binding.getAnnotationTagBits() & TagBits.AnnotationForMethod) != 0) + targetKinds.add(AnnotationTargetKind.METHOD); + if ((binding.getAnnotationTagBits() & TagBits.AnnotationForPackage) != 0) + targetKinds.add(AnnotationTargetKind.PACKAGE); + if ((binding.getAnnotationTagBits() & TagBits.AnnotationForParameter) != 0) + targetKinds.add(AnnotationTargetKind.PARAMETER); + if ((binding.getAnnotationTagBits() & TagBits.AnnotationForType) != 0) + targetKinds.add(AnnotationTargetKind.TYPE); + if (!targetKinds.isEmpty()) { annotationTargetKinds = new AnnotationTargetKind[targetKinds.size()]; - return (AnnotationTargetKind[]) targetKinds.toArray(annotationTargetKinds); + return (AnnotationTargetKind[]) targetKinds.toArray(annotationTargetKinds); } } return annotationTargetKinds; } - + public boolean hasAnnotation(UnresolvedType ofType) { // Make sure they are resolved @@ -534,7 +545,8 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { annotationsResolved = true; } Annotation[] as = declaration.annotations; - if (as == null) return false; + if (as == null) + return false; for (int i = 0; i < as.length; i++) { Annotation annotation = as[i]; if (annotation.resolvedType == null) { @@ -545,71 +557,66 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { String tname = CharOperation.charToString(annotation.resolvedType.constantPoolName()); if (UnresolvedType.forName(tname).equals(ofType)) { return true; - } + } } return false; } /** - * WARNING: This method does not have a complete implementation. + * WARNING: This method does not have a complete implementation. * - * The aim is that it converts Eclipse annotation objects to the AspectJ form of - * annotations (the type AnnotationAJ). The AnnotationX objects returned are wrappers - * over either a Bcel annotation type or the AspectJ AnnotationAJ type. - * The minimal implementation provided here is for processing the RetentionPolicy and - * Target annotation types - these are the only ones which the weaver will attempt to - * process from an EclipseSourceType. + * The aim is that it converts Eclipse annotation objects to the AspectJ form of annotations (the type AnnotationAJ). The + * AnnotationX objects returned are wrappers over either a Bcel annotation type or the AspectJ AnnotationAJ type. The minimal + * implementation provided here is for processing the RetentionPolicy and Target annotation types - these are the only ones + * which the weaver will attempt to process from an EclipseSourceType. * - * More notes: - * The pipeline has required us to implement this. With the pipeline we can be weaving - * a type and asking questions of annotations before they have been turned into Bcel - * objects - ie. when they are still in EclipseSourceType form. Without the pipeline we - * would have converted everything to Bcel objects before proceeding with weaving. - * Because the pipeline won't start weaving until all aspects have been compiled and - * the fact that no AspectJ constructs match on the values within annotations, this code - * only needs to deal with converting system annotations that the weaver needs to process + * More notes: The pipeline has required us to implement this. With the pipeline we can be weaving a type and asking questions + * of annotations before they have been turned into Bcel objects - ie. when they are still in EclipseSourceType form. Without + * the pipeline we would have converted everything to Bcel objects before proceeding with weaving. Because the pipeline won't + * start weaving until all aspects have been compiled and the fact that no AspectJ constructs match on the values within + * annotations, this code only needs to deal with converting system annotations that the weaver needs to process * (RetentionPolicy, Target). */ public AnnotationX[] getAnnotations() { - if (annotations!=null) return annotations; // only do this once + if (annotations != null) + return annotations; // only do this once getAnnotationTypes(); // forces resolution and sets resolvedAnnotations Annotation[] as = declaration.annotations; - if (as==null || as.length==0) { + if (as == null || as.length == 0) { annotations = NO_ANNOTATIONS; } else { annotations = new AnnotationX[as.length]; for (int i = 0; i < as.length; i++) { - annotations[i]=convertEclipseAnnotation(as[i],factory.getWorld()); + annotations[i] = convertEclipseAnnotation(as[i], factory.getWorld()); } } return annotations; } - /** + /** * Convert one eclipse annotation into an AnnotationX object containing an AnnotationAJ object. * - * This code and the helper methods used by it will go *BANG* if they encounter anything - * not currently supported - this is safer than limping along with a malformed annotation. When - * the *BANG* is encountered the bug reporter should indicate the kind of annotation they - * were working with and this code can be enhanced to support it. + * This code and the helper methods used by it will go *BANG* if they encounter anything not currently supported - this is safer + * than limping along with a malformed annotation. When the *BANG* is encountered the bug reporter should indicate the kind of + * annotation they were working with and this code can be enhanced to support it. */ - public AnnotationX convertEclipseAnnotation(Annotation eclipseAnnotation,World w) { + public AnnotationX convertEclipseAnnotation(Annotation eclipseAnnotation, World w) { // TODO if it is sourcevisible, we shouldn't let it through!!!!!!!!! testcase! ResolvedType annotationType = factory.fromTypeBindingToRTX(eclipseAnnotation.type.resolvedType); long bs = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK); boolean isRuntimeVisible = (eclipseAnnotation.bits & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention; - AnnotationAJ annotationAJ = new AnnotationAJ(annotationType.getSignature(),isRuntimeVisible); - generateAnnotation(eclipseAnnotation,annotationAJ); - return new AnnotationX(annotationAJ,w); + AnnotationAJ annotationAJ = new AnnotationAJ(annotationType.getSignature(), isRuntimeVisible); + generateAnnotation(eclipseAnnotation, annotationAJ); + return new AnnotationX(annotationAJ, w); } - + static class MissingImplementationException extends RuntimeException { MissingImplementationException(String reason) { super(reason); } } - private void generateAnnotation(Annotation annotation,AnnotationAJ annotationAJ) { + private void generateAnnotation(Annotation annotation, AnnotationAJ annotationAJ) { if (annotation instanceof NormalAnnotation) { NormalAnnotation normalAnnotation = (NormalAnnotation) annotation; MemberValuePair[] memberValuePairs = normalAnnotation.memberValuePairs; @@ -621,16 +628,17 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { if (methodBinding == null) { // is this just a marker annotation? throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + + "]"); } else { AnnotationValue av = generateElementValue(memberValuePair.value, methodBinding.returnType); - AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name),av); + AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name), av); annotationAJ.addNameValuePair(anvp); } } } else { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + "]"); } } else if (annotation instanceof SingleMemberAnnotation) { // this is a single member annotation (one member value) @@ -638,46 +646,50 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { MethodBinding methodBinding = singleMemberAnnotation.memberValuePairs()[0].binding; if (methodBinding == null) { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + "]"); } else { AnnotationValue av = generateElementValue(singleMemberAnnotation.memberValue, methodBinding.returnType); - annotationAJ.addNameValuePair( - new AnnotationNameValuePair(new String(singleMemberAnnotation.memberValuePairs()[0].name),av)); + annotationAJ.addNameValuePair(new AnnotationNameValuePair(new String( + singleMemberAnnotation.memberValuePairs()[0].name), av)); } } else if (annotation instanceof MarkerAnnotation) { return; } else { // this is something else... throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation ["+annotation+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation + "]"); } } - - private AnnotationValue generateElementValue(Expression defaultValue,TypeBinding memberValuePairReturnType) { + + private AnnotationValue generateElementValue(Expression defaultValue, TypeBinding memberValuePairReturnType) { Constant constant = defaultValue.constant; TypeBinding defaultValueBinding = defaultValue.resolvedType; if (defaultValueBinding == null) { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + + "]"); } else { if (memberValuePairReturnType.isArrayType() && !defaultValueBinding.isArrayType()) { if (constant != null && constant != Constant.NotAConstant) { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); -// generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType()); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + + defaultValue + "]"); + // generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType()); } else { AnnotationValue av = generateElementValueForNonConstantExpression(defaultValue, defaultValueBinding); - return new ArrayAnnotationValue(new AnnotationValue[]{av}); + return new ArrayAnnotationValue(new AnnotationValue[] { av }); } } else { if (constant != null && constant != Constant.NotAConstant) { - AnnotationValue av = EclipseAnnotationConvertor.generateElementValueForConstantExpression(defaultValue,defaultValueBinding); - if (av==null) { + AnnotationValue av = EclipseAnnotationConvertor.generateElementValueForConstantExpression(defaultValue, + defaultValueBinding); + if (av == null) { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + + defaultValue + "]"); } return av; -// generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType()); + // generateElementValue(attributeOffset, defaultValue, constant, memberValuePairReturnType.leafComponentType()); } else { AnnotationValue av = generateElementValueForNonConstantExpression(defaultValue, defaultValueBinding); return av; @@ -685,7 +697,7 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { } } } - + private AnnotationValue generateElementValueForNonConstantExpression(Expression defaultValue, TypeBinding defaultValueBinding) { if (defaultValueBinding != null) { if (defaultValueBinding.isEnum()) { @@ -698,20 +710,23 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { fieldBinding = (FieldBinding) nameReference.binding; } else { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + + defaultValue + "]"); } if (fieldBinding != null) { String sig = new String(fieldBinding.type.signature()); - AnnotationValue enumValue = new EnumAnnotationValue(sig,new String(fieldBinding.name)); + AnnotationValue enumValue = new EnumAnnotationValue(sig, new String(fieldBinding.name)); return enumValue; } throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + + "]"); } else if (defaultValueBinding.isAnnotationType()) { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); -// contents[contentsOffset++] = (byte) '@'; -// generateAnnotation((Annotation) defaultValue, attributeOffset); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + + "]"); + // contents[contentsOffset++] = (byte) '@'; + // generateAnnotation((Annotation) defaultValue, attributeOffset); } else if (defaultValueBinding.isArrayType()) { // array type if (defaultValue instanceof ArrayInitializer) { @@ -719,185 +734,195 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { int arrayLength = arrayInitializer.expressions != null ? arrayInitializer.expressions.length : 0; AnnotationValue[] values = new AnnotationValue[arrayLength]; for (int i = 0; i < arrayLength; i++) { - values[i] = generateElementValue(arrayInitializer.expressions[i], defaultValueBinding.leafComponentType());//, attributeOffset); + values[i] = generateElementValue(arrayInitializer.expressions[i], defaultValueBinding.leafComponentType());// , + // attributeOffset + // ) + // ; } ArrayAnnotationValue aav = new ArrayAnnotationValue(values); return aav; } else { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + + defaultValue + "]"); } -// } else if (defaultValue instanceof MagicLiteral) { -// if (defaultValue instanceof FalseLiteral) { -// new AnnotationValue -// } else if (defaultValue instanceof TrueLiteral) { -// -// } else { -// throw new MissingImplementationException( -// "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); -// } + // } else if (defaultValue instanceof MagicLiteral) { + // if (defaultValue instanceof FalseLiteral) { + // new AnnotationValue + // } else if (defaultValue instanceof TrueLiteral) { + // + // } else { + // throw new MissingImplementationException( + // "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); + // } } else { // class type throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); -// if (contentsOffset + 3 >= this.contents.length) { -// resizeContents(3); -// } -// contents[contentsOffset++] = (byte) 'c'; -// if (defaultValue instanceof ClassLiteralAccess) { -// ClassLiteralAccess classLiteralAccess = (ClassLiteralAccess) defaultValue; -// final int classInfoIndex = constantPool.literalIndex(classLiteralAccess.targetType.signature()); -// contents[contentsOffset++] = (byte) (classInfoIndex >> 8); -// contents[contentsOffset++] = (byte) classInfoIndex; -// } else { -// contentsOffset = attributeOffset; -// } + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + + "]"); + // if (contentsOffset + 3 >= this.contents.length) { + // resizeContents(3); + // } + // contents[contentsOffset++] = (byte) 'c'; + // if (defaultValue instanceof ClassLiteralAccess) { + // ClassLiteralAccess classLiteralAccess = (ClassLiteralAccess) defaultValue; + // final int classInfoIndex = constantPool.literalIndex(classLiteralAccess.targetType.signature()); + // contents[contentsOffset++] = (byte) (classInfoIndex >> 8); + // contents[contentsOffset++] = (byte) classInfoIndex; + // } else { + // contentsOffset = attributeOffset; + // } } } else { throw new MissingImplementationException( - "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value ["+defaultValue+"]"); -// contentsOffset = attributeOffset; + "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation value [" + defaultValue + + "]"); + // contentsOffset = attributeOffset; } } - + // --------------------------------- - + public ResolvedType[] getAnnotationTypes() { - if (resolvedAnnotations!=null) return resolvedAnnotations; + if (resolvedAnnotations != null) + return resolvedAnnotations; // Make sure they are resolved if (!annotationsResolved) { TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding); annotationsResolved = true; } - + if (declaration.annotations == null) { - resolvedAnnotations = NO_ANNOTATION_TYPES;//new ResolvedType[0]; + resolvedAnnotations = NO_ANNOTATION_TYPES;// new ResolvedType[0]; } else { resolvedAnnotations = new ResolvedType[declaration.annotations.length]; Annotation[] as = declaration.annotations; for (int i = 0; i < as.length; i++) { Annotation annotation = as[i]; - resolvedAnnotations[i] =factory.fromTypeBindingToRTX(annotation.type.resolvedType); + resolvedAnnotations[i] = factory.fromTypeBindingToRTX(annotation.type.resolvedType); } } return resolvedAnnotations; } public PerClause getPerClause() { - //should probably be: ((AspectDeclaration)declaration).perClause; + // should probably be: ((AspectDeclaration)declaration).perClause; // but we don't need this level of detail, and working with real per clauses // at this stage of compilation is not worth the trouble - if (!isAnnotationStyleAspect()) { - if(declaration instanceof AspectDeclaration) { - PerClause pc = ((AspectDeclaration)declaration).perClause; - if (pc != null) return pc; - } - return new PerSingleton(); - } else { - // for @Aspect, we do need the real kind though we don't need the real perClause - // at least try to get the right perclause - PerClause pc = null; - if (declaration instanceof AspectDeclaration) - pc = ((AspectDeclaration)declaration).perClause; - if (pc==null) { - PerClause.Kind kind = getPerClauseForTypeDeclaration(declaration); - //returning a perFromSuper is enough to get the correct kind.. (that's really a hack - AV) - return new PerFromSuper(kind); - } - return pc; - } - } - - PerClause.Kind getPerClauseForTypeDeclaration(TypeDeclaration typeDeclaration) { - Annotation[] annotations = typeDeclaration.annotations; - for (int i = 0; i < annotations.length; i++) { - Annotation annotation = annotations[i]; - if (CharOperation.equals(aspectSig, annotation.resolvedType.signature())) { - // found @Aspect(...) - if (annotation.memberValuePairs() == null || annotation.memberValuePairs().length == 0) { - // it is an @Aspect or @Aspect() - // needs to use PerFromSuper if declaration extends a super aspect - PerClause.Kind kind = lookupPerClauseKind(typeDeclaration.binding.superclass); - // if no super aspect, we have a @Aspect() means singleton - if (kind == null) { - return PerClause.SINGLETON; - } else { - return kind; - } - } else if (annotation instanceof SingleMemberAnnotation) { - // it is an @Aspect(...something...) - SingleMemberAnnotation theAnnotation = (SingleMemberAnnotation)annotation; - String clause = new String(((StringLiteral)theAnnotation.memberValue).source());//TODO cast safe ? - return determinePerClause(typeDeclaration, clause); - } else if (annotation instanceof NormalAnnotation) { // this kind if it was added by the visitor ! - // it is an @Aspect(...something...) - NormalAnnotation theAnnotation = (NormalAnnotation)annotation; - if (theAnnotation.memberValuePairs==null || theAnnotation.memberValuePairs.length<1) return PerClause.SINGLETON; - String clause = new String(((StringLiteral)theAnnotation.memberValuePairs[0].value).source());//TODO cast safe ? - return determinePerClause(typeDeclaration, clause); - } else { - eclipseWorld().showMessage(IMessage.ABORT, - "@Aspect annotation is expected to be SingleMemberAnnotation with 'String value()' as unique element", - new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, typeDeclaration.sourceEnd), null); - return PerClause.SINGLETON;//fallback strategy just to avoid NPE - } - } - } - return null;//no @Aspect annotation at all (not as aspect) - } + if (!isAnnotationStyleAspect()) { + if (declaration instanceof AspectDeclaration) { + PerClause pc = ((AspectDeclaration) declaration).perClause; + if (pc != null) + return pc; + } + return new PerSingleton(); + } else { + // for @Aspect, we do need the real kind though we don't need the real perClause + // at least try to get the right perclause + PerClause pc = null; + if (declaration instanceof AspectDeclaration) + pc = ((AspectDeclaration) declaration).perClause; + if (pc == null) { + PerClause.Kind kind = getPerClauseForTypeDeclaration(declaration); + // returning a perFromSuper is enough to get the correct kind.. (that's really a hack - AV) + return new PerFromSuper(kind); + } + return pc; + } + } + + PerClause.Kind getPerClauseForTypeDeclaration(TypeDeclaration typeDeclaration) { + Annotation[] annotations = typeDeclaration.annotations; + for (int i = 0; i < annotations.length; i++) { + Annotation annotation = annotations[i]; + if (CharOperation.equals(aspectSig, annotation.resolvedType.signature())) { + // found @Aspect(...) + if (annotation.memberValuePairs() == null || annotation.memberValuePairs().length == 0) { + // it is an @Aspect or @Aspect() + // needs to use PerFromSuper if declaration extends a super aspect + PerClause.Kind kind = lookupPerClauseKind(typeDeclaration.binding.superclass); + // if no super aspect, we have a @Aspect() means singleton + if (kind == null) { + return PerClause.SINGLETON; + } else { + return kind; + } + } else if (annotation instanceof SingleMemberAnnotation) { + // it is an @Aspect(...something...) + SingleMemberAnnotation theAnnotation = (SingleMemberAnnotation) annotation; + String clause = new String(((StringLiteral) theAnnotation.memberValue).source());// TODO cast safe ? + return determinePerClause(typeDeclaration, clause); + } else if (annotation instanceof NormalAnnotation) { // this kind if it was added by the visitor ! + // it is an @Aspect(...something...) + NormalAnnotation theAnnotation = (NormalAnnotation) annotation; + if (theAnnotation.memberValuePairs == null || theAnnotation.memberValuePairs.length < 1) + return PerClause.SINGLETON; + String clause = new String(((StringLiteral) theAnnotation.memberValuePairs[0].value).source());// TODO cast safe + // ? + return determinePerClause(typeDeclaration, clause); + } else { + eclipseWorld().showMessage( + IMessage.ABORT, + "@Aspect annotation is expected to be SingleMemberAnnotation with 'String value()' as unique element", + new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, + typeDeclaration.sourceEnd), null); + return PerClause.SINGLETON;// fallback strategy just to avoid NPE + } + } + } + return null;// no @Aspect annotation at all (not as aspect) + } private PerClause.Kind determinePerClause(TypeDeclaration typeDeclaration, String clause) { if (clause.startsWith("perthis(")) { - return PerClause.PEROBJECT; + return PerClause.PEROBJECT; } else if (clause.startsWith("pertarget(")) { - return PerClause.PEROBJECT; + return PerClause.PEROBJECT; } else if (clause.startsWith("percflow(")) { - return PerClause.PERCFLOW; + return PerClause.PERCFLOW; } else if (clause.startsWith("percflowbelow(")) { - return PerClause.PERCFLOW; + return PerClause.PERCFLOW; } else if (clause.startsWith("pertypewithin(")) { - return PerClause.PERTYPEWITHIN; + return PerClause.PERTYPEWITHIN; } else if (clause.startsWith("issingleton(")) { - return PerClause.SINGLETON; + return PerClause.SINGLETON; } else { - eclipseWorld().showMessage(IMessage.ABORT, - "cannot determine perClause '" + clause + "'", - new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, typeDeclaration.sourceEnd), null); - return PerClause.SINGLETON;//fallback strategy just to avoid NPE + eclipseWorld().showMessage( + IMessage.ABORT, + "cannot determine perClause '" + clause + "'", + new EclipseSourceLocation(typeDeclaration.compilationResult, typeDeclaration.sourceStart, + typeDeclaration.sourceEnd), null); + return PerClause.SINGLETON;// fallback strategy just to avoid NPE } } - // adapted from AspectDeclaration - private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) { - final PerClause.Kind kind; - if (binding instanceof BinaryTypeBinding) { - ResolvedType superTypeX = factory.fromEclipse(binding); - PerClause perClause = superTypeX.getPerClause(); - // clause is null for non aspect classes since coming from BCEL attributes - if (perClause != null) { - kind = superTypeX.getPerClause().getKind(); - } else { - kind = null; - } - } else if (binding instanceof SourceTypeBinding ) { - SourceTypeBinding sourceSc = (SourceTypeBinding)binding; - if (sourceSc.scope.referenceContext instanceof AspectDeclaration) { - //code style - kind = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause.getKind(); - } else if (sourceSc.scope.referenceContext instanceof TypeDeclaration) { - // if @Aspect: perFromSuper, else if @Aspect(..) get from anno value, else null - kind = getPerClauseForTypeDeclaration((TypeDeclaration)(sourceSc.scope.referenceContext)); - } else { - //XXX should not happen - kind = null; - } - } else { - //XXX need to handle this too - kind = null; - } - return kind; - } - + // adapted from AspectDeclaration + private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) { + final PerClause.Kind kind; + if (binding instanceof BinaryTypeBinding) { + ResolvedType superTypeX = factory.fromEclipse(binding); + PerClause perClause = superTypeX.getPerClause(); + // clause is null for non aspect classes since coming from BCEL attributes + if (perClause != null) { + kind = superTypeX.getPerClause().getKind(); + } else { + kind = null; + } + } else if (binding instanceof SourceTypeBinding) { + SourceTypeBinding sourceSc = (SourceTypeBinding) binding; + if (sourceSc.scope.referenceContext instanceof AspectDeclaration) { + // code style + kind = ((AspectDeclaration) sourceSc.scope.referenceContext).perClause.getKind(); + } else { // if (sourceSc.scope.referenceContext instanceof TypeDeclaration) { + // if @Aspect: perFromSuper, else if @Aspect(..) get from anno value, else null + kind = getPerClauseForTypeDeclaration((sourceSc.scope.referenceContext)); + } + } else { + // XXX need to handle this too + kind = null; + } + return kind; + } public Collection getDeclares() { return declares; @@ -914,24 +939,25 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { public boolean doesNotExposeShadowMungers() { return true; } - + public String getDeclaredGenericSignature() { return CharOperation.charToString(binding.genericSignature()); } - + public boolean isGeneric() { return binding.isGenericType(); } - + public TypeVariable[] getTypeVariables() { - if (declaration.typeParameters == null) return new TypeVariable[0]; + if (declaration.typeParameters == null) + return new TypeVariable[0]; TypeVariable[] typeVariables = new TypeVariable[declaration.typeParameters.length]; for (int i = 0; i < typeVariables.length; i++) { typeVariables[i] = typeParameter2TypeVariable(declaration.typeParameters[i]); } return typeVariables; } - + private TypeVariable typeParameter2TypeVariable(TypeParameter aTypeParameter) { String name = new String(aTypeParameter.name); ReferenceBinding superclassBinding = aTypeParameter.binding.superclass; @@ -945,7 +971,7 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { } } // XXX what about lower binding? - TypeVariable tv = new TypeVariable(name,superclass,superinterfaces); + TypeVariable tv = new TypeVariable(name, superclass, superinterfaces); tv.setDeclaringElement(factory.fromBinding(aTypeParameter.binding.declaringElement)); tv.setRank(aTypeParameter.binding.rank); return tv; @@ -954,5 +980,5 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { public void ensureDelegateConsistent() { // do nothing, currently these can't become inconsistent (phew) } - + } diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMethodBinding.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMethodBinding.java index 7206f7ad2..ec50597a3 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMethodBinding.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMethodBinding.java @@ -10,7 +10,6 @@ * PARC initial implementation * ******************************************************************/ - package org.aspectj.ajdt.internal.compiler.lookup; import org.aspectj.ajdt.internal.compiler.ast.InterTypeMethodDeclaration; @@ -21,7 +20,6 @@ import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; -import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; @@ -29,40 +27,36 @@ import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.UnresolvedType; /** - * A special method binding representing an ITD that pretends to be a - * member in some target type for matching purposes. + * A special method binding representing an ITD that pretends to be a member in some target type for matching purposes. */ public class InterTypeMethodBinding extends MethodBinding { - + /** The target type upon which the ITD is declared */ private ReferenceBinding targetType; - - /** - * This is the 'pretend' method that should be the target of any attempt - * to call the ITD'd method. + + /** + * This is the 'pretend' method that should be the target of any attempt to call the ITD'd method. */ private MethodBinding syntheticMethod; - - + public MethodBinding postDispatchMethod; - + public AbstractMethodDeclaration sourceMethod; - + public InterTypeMethodBinding(EclipseFactory world, ResolvedTypeMunger munger, UnresolvedType withinType, - AbstractMethodDeclaration sourceMethod) - { + AbstractMethodDeclaration sourceMethod) { super(); ResolvedMember signature = munger.getSignature(); - MethodBinding mb = world.makeMethodBinding(signature,munger.getTypeVariableAliases()); - this.modifiers = mb.modifiers; - this.selector = mb.selector; - this.returnType = mb.returnType; - this.parameters = mb.parameters; + MethodBinding mb = world.makeMethodBinding(signature, munger.getTypeVariableAliases()); + this.modifiers = mb.modifiers; + this.selector = mb.selector; + this.returnType = mb.returnType; + this.parameters = mb.parameters; this.thrownExceptions = mb.thrownExceptions; - this.typeVariables = mb.typeVariables; - this.sourceMethod = sourceMethod; - this.targetType = (ReferenceBinding)world.makeTypeBinding(signature.getDeclaringType()); - this.declaringClass = (ReferenceBinding)world.makeTypeBinding(withinType); + this.typeVariables = mb.typeVariables; + this.sourceMethod = sourceMethod; + this.targetType = (ReferenceBinding) world.makeTypeBinding(signature.getDeclaringType()); + this.declaringClass = (ReferenceBinding) world.makeTypeBinding(withinType); // Ok, we need to set the typevariable declaring elements // 1st set: @@ -71,57 +65,55 @@ public class InterTypeMethodBinding extends MethodBinding { typeVariables[i].declaringElement = this; } for (int i = 0; i < typeVariables.length; i++) { - if (typeVariables[i].declaringElement==null) throw new RuntimeException("Declaring element not set"); - + if (typeVariables[i].declaringElement == null) + throw new RuntimeException("Declaring element not set"); + } -// typeVariables[0].declaringElement=this; -// if (tVar.getDeclaringElement() instanceof Member) { -// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); -// } else { -// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); -// } - if (signature.getKind() == Member.METHOD) { - syntheticMethod = - world.makeMethodBinding(AjcMemberMaker.interMethodDispatcher(signature, withinType)); - postDispatchMethod = - world.makeMethodBinding(AjcMemberMaker.interMethodBody(signature, withinType)); + // typeVariables[0].declaringElement=this; + // if (tVar.getDeclaringElement() instanceof Member) { + // declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); + // } else { + // declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); + // } + if (signature.getKind() == Member.METHOD) { + syntheticMethod = world.makeMethodBinding(AjcMemberMaker.interMethodDispatcher(signature, withinType)); + postDispatchMethod = world.makeMethodBinding(AjcMemberMaker.interMethodBody(signature, withinType)); } else { - syntheticMethod = world.makeMethodBinding( - AjcMemberMaker.interConstructor(world.getWorld().resolve(signature.getDeclaringType()), - signature, withinType)); + syntheticMethod = world.makeMethodBinding(AjcMemberMaker.interConstructor(world.getWorld().resolve( + signature.getDeclaringType()), signature, withinType)); postDispatchMethod = syntheticMethod; } - } - - //XXX this is identical to InterTypeFieldBinding + + // XXX this is identical to InterTypeFieldBinding public boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) { scope.compilationUnitScope().recordTypeReference(declaringClass); - - if (isPublic()) return true; - + + if (isPublic()) + return true; + SourceTypeBinding invocationType = scope.invocationType(); - //System.out.println("receiver: " + receiverType + ", " + invocationType); - - if (invocationType == declaringClass) return true; - - - // if (invocationType.isPrivileged) { - // System.out.println("privileged access to: " + this); - // return true; - // } - + // System.out.println("receiver: " + receiverType + ", " + invocationType); + + if (invocationType == declaringClass) + return true; + + // if (invocationType.isPrivileged) { + // System.out.println("privileged access to: " + this); + // return true; + // } + if (isProtected()) { throw new RuntimeException("unimplemented"); } - - //XXX make sure this walks correctly + + // XXX make sure this walks correctly if (isPrivate()) { // answer true if the receiverType is the declaringClass // AND the invocationType and the declaringClass have a common enclosingType - //if (receiverType != declaringClass) return false; - + // if (receiverType != declaringClass) return false; + if (invocationType != declaringClass) { ReferenceBinding outerInvocationType = invocationType; ReferenceBinding temp = outerInvocationType.enclosingType(); @@ -129,51 +121,58 @@ public class InterTypeMethodBinding extends MethodBinding { outerInvocationType = temp; temp = temp.enclosingType(); } - + ReferenceBinding outerDeclaringClass = declaringClass; temp = outerDeclaringClass.enclosingType(); while (temp != null) { outerDeclaringClass = temp; temp = temp.enclosingType(); } - - //System.err.println("outer dec: " + - if (outerInvocationType != outerDeclaringClass) return false; + + // System.err.println("outer dec: " + + if (outerInvocationType != outerDeclaringClass) + return false; } return true; } - + // isDefault() - if (invocationType.fPackage == declaringClass.fPackage) return true; + if (invocationType.fPackage == declaringClass.fPackage) + return true; return false; } public boolean isFinal() { - if (sourceMethod == null || !(sourceMethod instanceof InterTypeMethodDeclaration)) return super.isFinal(); - return ((InterTypeMethodDeclaration)sourceMethod).isFinal(); + if (sourceMethod == null || !(sourceMethod instanceof InterTypeMethodDeclaration)) + return super.isFinal(); + return ((InterTypeMethodDeclaration) sourceMethod).isFinal(); } - + public MethodBinding getAccessMethod(boolean staticReference) { - if (staticReference) return postDispatchMethod; - else return syntheticMethod; + if (staticReference) + return postDispatchMethod; + else + return syntheticMethod; + } + + public boolean alwaysNeedsAccessMethod() { + return true; } - - public boolean alwaysNeedsAccessMethod() { return true; } public AbstractMethodDeclaration sourceMethod() { return sourceMethod; } - + public ReferenceBinding getTargetType() { return targetType; } - + // override method in MethodBinding to ensure correct behaviour in some of JDTs generics checks. public ReferenceBinding getOwningClass() { return targetType; } - + public String toString() { - return "InterTypeMethodBinding(" + super.toString() + ", " + getTargetType() +")"; + return "InterTypeMethodBinding(" + super.toString() + ", " + getTargetType() + ")"; } } diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java index 8614ed3ad..fe5901c98 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java @@ -614,23 +614,23 @@ public class AjState { return false; } - /** - * For a given class file, determine which source file it came from. This will only succeed if the class file is from a source - * file within this project. - */ - private File getSourceFileForClassFile(File classfile) { - Set sourceFiles = fullyQualifiedTypeNamesResultingFromCompilationUnit.keySet(); - for (Iterator sourceFileIterator = sourceFiles.iterator(); sourceFileIterator.hasNext();) { - File sourceFile = (File) sourceFileIterator.next(); - List/* ClassFile */classesFromSourceFile = (List/* ClassFile */) fullyQualifiedTypeNamesResultingFromCompilationUnit - .get(sourceFile); - for (int i = 0; i < classesFromSourceFile.size(); i++) { - if (((ClassFile) classesFromSourceFile.get(i)).locationOnDisk.equals(classfile)) - return sourceFile; - } - } - return null; - } + // /** + // * For a given class file, determine which source file it came from. This will only succeed if the class file is from a source + // * file within this project. + // */ + // private File getSourceFileForClassFile(File classfile) { + // Set sourceFiles = fullyQualifiedTypeNamesResultingFromCompilationUnit.keySet(); + // for (Iterator sourceFileIterator = sourceFiles.iterator(); sourceFileIterator.hasNext();) { + // File sourceFile = (File) sourceFileIterator.next(); + // List/* ClassFile */classesFromSourceFile = (List/* ClassFile */) fullyQualifiedTypeNamesResultingFromCompilationUnit + // .get(sourceFile); + // for (int i = 0; i < classesFromSourceFile.size(); i++) { + // if (((ClassFile) classesFromSourceFile.get(i)).locationOnDisk.equals(classfile)) + // return sourceFile; + // } + // } + // return null; + // } public String toString() { StringBuffer sb = new StringBuffer(); @@ -1090,19 +1090,19 @@ public class AjState { } - private UnwovenClassFile removeFromPreviousIfPresent(UnwovenClassFile cf, InterimCompilationResult previous) { - if (previous == null) - return null; - UnwovenClassFile[] unwovenClassFiles = previous.unwovenClassFiles(); - for (int i = 0; i < unwovenClassFiles.length; i++) { - UnwovenClassFile candidate = unwovenClassFiles[i]; - if ((candidate != null) && candidate.getFilename().equals(cf.getFilename())) { - unwovenClassFiles[i] = null; - return candidate; - } - } - return null; - } + // private UnwovenClassFile removeFromPreviousIfPresent(UnwovenClassFile cf, InterimCompilationResult previous) { + // if (previous == null) + // return null; + // UnwovenClassFile[] unwovenClassFiles = previous.unwovenClassFiles(); + // for (int i = 0; i < unwovenClassFiles.length; i++) { + // UnwovenClassFile candidate = unwovenClassFiles[i]; + // if ((candidate != null) && candidate.getFilename().equals(cf.getFilename())) { + // unwovenClassFiles[i] = null; + // return candidate; + // } + // } + // return null; + // } private void recordClassFile(UnwovenClassFile thisTime, File lastTime) { if (simpleStrings == null) { diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java index 661aaaa28..e4fd440fb 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java @@ -51,54 +51,54 @@ import org.aspectj.weaver.patterns.TypePatternList; public class AsmElementFormatter { public void genLabelAndKind(MethodDeclaration methodDeclaration, IProgramElement node) { - - if (methodDeclaration instanceof AdviceDeclaration) { - AdviceDeclaration ad = (AdviceDeclaration)methodDeclaration; + + if (methodDeclaration instanceof AdviceDeclaration) { + AdviceDeclaration ad = (AdviceDeclaration) methodDeclaration; node.setKind(IProgramElement.Kind.ADVICE); if (ad.kind == AdviceKind.Around) { - node.setCorrespondingType(ad.returnType.toString()); //returnTypeToString(0)); + node.setCorrespondingType(ad.returnType.toString()); // returnTypeToString(0)); } - + StringBuffer details = new StringBuffer(); - if (ad.pointcutDesignator != null) { + if (ad.pointcutDesignator != null) { details.append(AsmRelationshipUtils.genPointcutDetails(ad.pointcutDesignator.getPointcut())); } else { details.append(AsmRelationshipUtils.POINTCUT_ABSTRACT); - } + } node.setName(ad.kind.toString()); - //if (details.length()!=0) + // if (details.length()!=0) node.setDetails(details.toString()); setParameters(methodDeclaration, node); - } else if (methodDeclaration instanceof PointcutDeclaration) { - PointcutDeclaration pd = (PointcutDeclaration)methodDeclaration; + } else if (methodDeclaration instanceof PointcutDeclaration) { + PointcutDeclaration pd = (PointcutDeclaration) methodDeclaration; node.setKind(IProgramElement.Kind.POINTCUT); node.setName(translatePointcutName(new String(methodDeclaration.selector))); setParameters(methodDeclaration, node); - - } else if (methodDeclaration instanceof DeclareDeclaration) { - DeclareDeclaration declare = (DeclareDeclaration)methodDeclaration; + + } else if (methodDeclaration instanceof DeclareDeclaration) { + DeclareDeclaration declare = (DeclareDeclaration) methodDeclaration; String name = AsmRelationshipUtils.DEC_LABEL + " "; if (declare.declareDecl instanceof DeclareErrorOrWarning) { - DeclareErrorOrWarning deow = (DeclareErrorOrWarning)declare.declareDecl; - + DeclareErrorOrWarning deow = (DeclareErrorOrWarning) declare.declareDecl; + if (deow.isError()) { - node.setKind( IProgramElement.Kind.DECLARE_ERROR); + node.setKind(IProgramElement.Kind.DECLARE_ERROR); name += AsmRelationshipUtils.DECLARE_ERROR; } else { - node.setKind( IProgramElement.Kind.DECLARE_WARNING); + node.setKind(IProgramElement.Kind.DECLARE_WARNING); name += AsmRelationshipUtils.DECLARE_WARNING; } - node.setName(name) ; + node.setName(name); node.setDetails("\"" + AsmRelationshipUtils.genDeclareMessage(deow.getMessage()) + "\""); - + } else if (declare.declareDecl instanceof DeclareParents) { - node.setKind( IProgramElement.Kind.DECLARE_PARENTS); - DeclareParents dp = (DeclareParents)declare.declareDecl; + node.setKind(IProgramElement.Kind.DECLARE_PARENTS); + DeclareParents dp = (DeclareParents) declare.declareDecl; node.setName(name + AsmRelationshipUtils.DECLARE_PARENTS); - + String kindOfDP = null; StringBuffer details = new StringBuffer(""); TypePattern[] newParents = dp.getParents().getTypePatterns(); @@ -106,60 +106,62 @@ public class AsmElementFormatter { TypePattern tp = newParents[i]; UnresolvedType tx = tp.getExactType(); if (kindOfDP == null) { - kindOfDP = "implements "; - try { - ResolvedType rtx = tx.resolve(((AjLookupEnvironment)declare.scope.environment()).factory.getWorld()); - if (!rtx.isInterface()) kindOfDP = "extends "; - } catch (Throwable t) { - // What can go wrong???? who knows! - } - + kindOfDP = "implements "; + try { + ResolvedType rtx = tx.resolve(((AjLookupEnvironment) declare.scope.environment()).factory.getWorld()); + if (!rtx.isInterface()) + kindOfDP = "extends "; + } catch (Throwable t) { + // What can go wrong???? who knows! + } + } - String typename= tp.toString(); - if (typename.lastIndexOf(".")!=-1) { - typename=typename.substring(typename.lastIndexOf(".")+1); + String typename = tp.toString(); + if (typename.lastIndexOf(".") != -1) { + typename = typename.substring(typename.lastIndexOf(".") + 1); } details.append(typename); - if ((i+1)1) { -// -// for (int i = 1;i1) { + // + // for (int i = 1;i"; -// } - -// // !!! move or replace -// private String translateDeclareName(String name) { -// int colonIndex = name.indexOf(":"); -// if (colonIndex != -1) { -// return name.substring(0, colonIndex); -// } else { -// return name; -// } -// } - // !!! move or replace -// private String translateInterTypeDecName(String name) { -// int index = name.lastIndexOf('$'); -// if (index != -1) { -// return name.substring(index+1); -// } else { -// return name; -// } -// } + // // TODO: + // private String translateAdviceName(String label) { + // if (label.indexOf("before") != -1) return "before"; + // if (label.indexOf("returning") != -1) return "after returning"; + // if (label.indexOf("after") != -1) return "after"; + // if (label.indexOf("around") != -1) return "around"; + // else return ""; + // } + + // // !!! move or replace + // private String translateDeclareName(String name) { + // int colonIndex = name.indexOf(":"); + // if (colonIndex != -1) { + // return name.substring(0, colonIndex); + // } else { + // return name; + // } + // } + // !!! move or replace + // private String translateInterTypeDecName(String name) { + // int index = name.lastIndexOf('$'); + // if (index != -1) { + // return name.substring(index+1); + // } else { + // return name; + // } + // } - // !!! move or replace + // !!! move or replace private String translatePointcutName(String name) { - int index = name.indexOf("$$")+2; + int index = name.indexOf("$$") + 2; int endIndex = name.lastIndexOf('$'); if (index != -1 && endIndex != -1) { return name.substring(index, endIndex); - } else { + } else { return name; } } - } diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java index e1508757e..22fe843ca 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java @@ -394,16 +394,16 @@ public class AsmHierarchyBuilder extends ASTVisitor { return output.toString(); } - private IProgramElement findEnclosingClass(Stack stack) { - for (int i = stack.size() - 1; i >= 0; i--) { - IProgramElement pe = (IProgramElement) stack.get(i); - if (pe.getKind() == IProgramElement.Kind.CLASS) { - return pe; - } - - } - return (IProgramElement) stack.peek(); - } + // private IProgramElement findEnclosingClass(Stack stack) { + // for (int i = stack.size() - 1; i >= 0; i--) { + // IProgramElement pe = (IProgramElement) stack.get(i); + // if (pe.getKind() == IProgramElement.Kind.CLASS) { + // return pe; + // } + // + // } + // return (IProgramElement) stack.peek(); + // } public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { IProgramElement peNode = null; diff --git a/org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTMatcher.java b/org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTMatcher.java index 1c084ae4d..8ec7b29a1 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTMatcher.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTMatcher.java @@ -10,16 +10,13 @@ *******************************************************************************/ package org.aspectj.org.eclipse.jdt.core.dom; - public class AjASTMatcher extends ASTMatcher { - + /** * Creates a new AST matcher instance. *

- * For backwards compatibility, the matcher ignores tag - * elements below doc comments by default. Use - * {@link #ASTMatcher(boolean) ASTMatcher(true)} - * for a matcher that compares doc tags by default. + * For backwards compatibility, the matcher ignores tag elements below doc comments by default. Use {@link #ASTMatcher(boolean) + * ASTMatcher(true)} for a matcher that compares doc tags by default. *

*/ public AjASTMatcher() { @@ -29,8 +26,7 @@ public class AjASTMatcher extends ASTMatcher { /** * Creates a new AST matcher instance. * - * @param matchDocTags true if doc comment tags are - * to be compared by default, and false otherwise + * @param matchDocTags true if doc comment tags are to be compared by default, and false otherwise * @see #match(Javadoc,Object) * @since 3.0 */ @@ -38,7 +34,6 @@ public class AjASTMatcher extends ASTMatcher { super(matchDocTags); } - public boolean match(PointcutDeclaration node, Object other) { // ajh02: method added if (!(other instanceof PointcutDeclaration)) { @@ -56,29 +51,28 @@ public class AjASTMatcher extends ASTMatcher { return false; } } - return - safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) - && safeSubtreeMatch(node.getName(), o.getName()) - && safeSubtreeMatch(node.getDesignator(), o.getDesignator()); + return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeMatch(node.getName(), o.getName()) + && safeSubtreeMatch(node.getDesignator(), o.getDesignator()); } - + public boolean match(DefaultPointcut node, Object other) { - if (!(other instanceof DefaultPointcut)) { - return false; - } - return node.getDetail().equals(((DefaultPointcut) other).getDetail()); + if (!(other instanceof DefaultPointcut)) { + return false; + } + return node.getDetail().equals(((DefaultPointcut) other).getDetail()); } - + public boolean match(ReferencePointcut node, Object other) { if (!(other instanceof ReferencePointcut)) { return false; } ReferencePointcut o = (ReferencePointcut) other; - int level = node.getAST().apiLevel; + // int level = node.getAST().apiLevel; return safeSubtreeMatch(node.getName(), o.getName()); // ajh02: will have to add something here when ReferencePointcuts are given // a list of Types for parameters } + public boolean match(NotPointcut node, Object other) { if (!(other instanceof NotPointcut)) { return false; @@ -86,22 +80,23 @@ public class AjASTMatcher extends ASTMatcher { NotPointcut o = (NotPointcut) other; return safeSubtreeMatch(node.getBody(), o.getBody()); } + public boolean match(PerObject node, Object other) { if (!(other instanceof PerObject)) { return false; } PerObject o = (PerObject) other; - return safeSubtreeMatch(node.getBody(), o.getBody()) - && o.isThis() == node.isThis(); + return safeSubtreeMatch(node.getBody(), o.getBody()) && o.isThis() == node.isThis(); } + public boolean match(PerCflow node, Object other) { if (!(other instanceof PerCflow)) { return false; } PerCflow o = (PerCflow) other; - return safeSubtreeMatch(node.getBody(), o.getBody()) - && node.isBelow() == o.isBelow(); + return safeSubtreeMatch(node.getBody(), o.getBody()) && node.isBelow() == o.isBelow(); } + public boolean match(PerTypeWithin node, Object other) { if (!(other instanceof PerTypeWithin)) { return false; @@ -109,6 +104,7 @@ public class AjASTMatcher extends ASTMatcher { PerTypeWithin o = (PerTypeWithin) other; return true; // ajh02: stub, should look at the type pattern } + public boolean match(CflowPointcut node, Object other) { if (!(other instanceof CflowPointcut)) { return false; @@ -116,35 +112,35 @@ public class AjASTMatcher extends ASTMatcher { CflowPointcut o = (CflowPointcut) other; return safeSubtreeMatch(node.getBody(), o.getBody()); } + public boolean match(AndPointcut node, Object other) { if (!(other instanceof AndPointcut)) { return false; } AndPointcut o = (AndPointcut) other; - return safeSubtreeMatch(node.getLeft(), o.getLeft()) - && safeSubtreeMatch(node.getRight(), o.getRight()); + return safeSubtreeMatch(node.getLeft(), o.getLeft()) && safeSubtreeMatch(node.getRight(), o.getRight()); } + public boolean match(OrPointcut node, Object other) { if (!(other instanceof OrPointcut)) { return false; } OrPointcut o = (OrPointcut) other; - return safeSubtreeMatch(node.getLeft(), o.getLeft()) - && safeSubtreeMatch(node.getRight(), o.getRight()); + return safeSubtreeMatch(node.getLeft(), o.getLeft()) && safeSubtreeMatch(node.getRight(), o.getRight()); } + public boolean match(BeforeAdviceDeclaration node, Object other) { // ajh02: method added if (!(other instanceof BeforeAdviceDeclaration)) { return false; } BeforeAdviceDeclaration o = (BeforeAdviceDeclaration) other; - return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) - && safeSubtreeListMatch(node.parameters(), o.parameters()) + return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeListMatch(node.parameters(), o.parameters()) && safeSubtreeMatch(node.getPointcut(), o.getPointcut()) && safeSubtreeListMatch(node.thrownExceptions(), o.thrownExceptions()) && safeSubtreeMatch(node.getBody(), o.getBody()); } - + public boolean match(AfterAdviceDeclaration node, Object other) { // ajh02: todo: should have special methods to match // afterReturning and afterThrowing @@ -152,13 +148,12 @@ public class AjASTMatcher extends ASTMatcher { return false; } AfterAdviceDeclaration o = (AfterAdviceDeclaration) other; - return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) - && safeSubtreeListMatch(node.parameters(), o.parameters()) + return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeListMatch(node.parameters(), o.parameters()) && safeSubtreeMatch(node.getPointcut(), o.getPointcut()) && safeSubtreeListMatch(node.thrownExceptions(), o.thrownExceptions()) && safeSubtreeMatch(node.getBody(), o.getBody()); } - + public boolean match(AroundAdviceDeclaration node, Object other) { if (!(other instanceof AroundAdviceDeclaration)) { return false; @@ -178,21 +173,22 @@ public class AjASTMatcher extends ASTMatcher { return false; } } - return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) - && safeSubtreeListMatch(node.parameters(), o.parameters()) + return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeListMatch(node.parameters(), o.parameters()) && safeSubtreeMatch(node.getPointcut(), o.getPointcut()) && safeSubtreeListMatch(node.thrownExceptions(), o.thrownExceptions()) && safeSubtreeMatch(node.getBody(), o.getBody()); } + public boolean match(DeclareDeclaration node, Object other) { // ajh02: method added if (!(other instanceof DeclareDeclaration)) { return false; } DeclareDeclaration o = (DeclareDeclaration) other; - int level = node.getAST().apiLevel; + // int level = node.getAST().apiLevel; return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()); } + public boolean match(InterTypeFieldDeclaration node, Object other) { // ajh02: method added if (!(other instanceof InterTypeFieldDeclaration)) { @@ -210,11 +206,10 @@ public class AjASTMatcher extends ASTMatcher { return false; } } - return - safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) - && safeSubtreeMatch(node.getType(), o.getType()) - && safeSubtreeListMatch(node.fragments(), o.fragments()); + return safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeMatch(node.getType(), o.getType()) + && safeSubtreeListMatch(node.fragments(), o.fragments()); } + public boolean match(InterTypeMethodDeclaration node, Object other) { // ajh02: method added if (!(other instanceof InterTypeMethodDeclaration)) { @@ -242,27 +237,25 @@ public class AjASTMatcher extends ASTMatcher { return false; } } - return ((node.isConstructor() == o.isConstructor()) - && safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) + return ((node.isConstructor() == o.isConstructor()) && safeSubtreeMatch(node.getJavadoc(), o.getJavadoc()) && safeSubtreeMatch(node.getName(), o.getName()) // n.b. compare return type even for constructors - && safeSubtreeListMatch(node.parameters(), o.parameters()) - && node.getExtraDimensions() == o.getExtraDimensions() - && safeSubtreeListMatch(node.thrownExceptions(), o.thrownExceptions()) - && safeSubtreeMatch(node.getBody(), o.getBody())); + && safeSubtreeListMatch(node.parameters(), o.parameters()) && node.getExtraDimensions() == o.getExtraDimensions() + && safeSubtreeListMatch(node.thrownExceptions(), o.thrownExceptions()) && safeSubtreeMatch(node.getBody(), o + .getBody())); } - + public boolean match(DefaultTypePattern node, Object other) { - if (!(other instanceof DefaultTypePattern)) { - return false; - } - return node.getDetail().equals(((DefaultTypePattern) other).getDetail()); + if (!(other instanceof DefaultTypePattern)) { + return false; + } + return node.getDetail().equals(((DefaultTypePattern) other).getDetail()); } - + public boolean match(SignaturePattern node, Object other) { - if (!(other instanceof SignaturePattern)) { - return false; - } - return node.getDetail().equals(((SignaturePattern) other).getDetail()); + if (!(other instanceof SignaturePattern)) { + return false; + } + return node.getDetail().equals(((SignaturePattern) other).getDetail()); } } diff --git a/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/DeclareParents.java b/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/DeclareParents.java index a1d323dbd..34b0222bc 100644 --- a/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/DeclareParents.java +++ b/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/DeclareParents.java @@ -15,11 +15,6 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.aspectj.apache.bcel.Repository; -import org.aspectj.apache.bcel.classfile.JavaClass; -import org.aspectj.apache.bcel.verifier.VerificationResult; -import org.aspectj.apache.bcel.verifier.Verifier; -import org.aspectj.apache.bcel.verifier.VerifierFactory; import org.aspectj.bridge.IMessage; import org.aspectj.tools.ajc.AjcTestCase; import org.aspectj.tools.ajc.CompilationResult; @@ -126,7 +121,6 @@ public class DeclareParents extends AjcTestCase { * Note: Error messages and locations for binary weaving are much better than their source counterparts ! */ public void test_cantMakeInheritedInstanceMethodsStatic() { - File testBase = new File(baseDir, "TestC"); runSourceAndBinaryTestcase(new File(baseDir, "TestC"), new String[] { "A1.java", "B1.java" }, new String[] { "X1.java" }, true, false); } @@ -135,7 +129,6 @@ public class DeclareParents extends AjcTestCase { * Cannot extend a final class */ public void xxxtest_cantExtendFinalClass() { // XXX removed test, need to discuss with andy how to repair... - File testBase = new File(baseDir, "TestC"); runSourceAndBinaryTestcase(new File(baseDir, "TestC"), new String[] { "A2.java", "B2.java" }, new String[] { "X2.java" }, true, true); } @@ -150,7 +143,6 @@ public class DeclareParents extends AjcTestCase { * if you inherit methods you cannot override them and reduce their visibility */ public void test_cantReduceVisibilityOfOverriddenMethods_1() { - File testBase = new File(baseDir, "TestB"); runSourceAndBinaryTestcase(new File(baseDir, "TestB"), new String[] { "Top1.java", "Middle1.java" }, new String[] { "Aspect1.java" }, true, false); } @@ -161,7 +153,6 @@ public class DeclareParents extends AjcTestCase { * test 2 in this set checks methods from a superclass of the named new parent. */ public void test_cantReduceVisibilityOfOverriddenMethods_2() { - File testBase = new File(baseDir, "TestB"); runSourceAndBinaryTestcase(new File(baseDir, "TestB"), new String[] { "TopTop6.java", "Top6.java", "Middle6.java" }, new String[] { "Aspect6.java" }, true, false); } @@ -170,8 +161,6 @@ public class DeclareParents extends AjcTestCase { * If you inherit methods you cannot have incompatible return types (java1.5 will make this a little messier). */ public void test_overriddenMethodsCantHaveIncompatibleReturnTypes() { - File testBase = new File(baseDir, "TestB"); - CompilationResult result = null; runSourceAndBinaryTestcase(new File(baseDir, "TestB"), new String[] { "Top2.java", "Middle2.java", "Super.java", "Sub.java" }, new String[] { "Aspect2.java" }, true); } @@ -182,8 +171,6 @@ public class DeclareParents extends AjcTestCase { * Test 1 in this set is simple. */ public void test_inheritedAbstractMethodsMustBeImplemented_1() { - File testBase = new File(baseDir, "TestB"); - CompilationResult result = null; runSourceAndBinaryTestcase(new File(baseDir, "TestB"), new String[] { "Top3.java", "Middle3.java", "Super.java", "Sub.java" }, new String[] { "Aspect3.java" }, true); } @@ -193,7 +180,6 @@ public class DeclareParents extends AjcTestCase { */ public void test_interfaceMethodsImplemented() { File testBase = new File(baseDir, "TestD"); - CompilationResult result = null; runSourceAndBinaryTestcase(testBase, new String[] { "SimpleClass1.java", "SimpleIntf1.java" }, new String[] { "SimpleAspect1.java" }, true); } @@ -204,8 +190,6 @@ public class DeclareParents extends AjcTestCase { * Test 2 in this set includes methods further up the hierarchy that must be implemented. */ public void test_inheritedAbstractMethodsMustBeImplemented_2() { - File testBase = new File(baseDir, "TestB"); - CompilationResult result = null; runSourceAndBinaryTestcase(new File(baseDir, "TestB"), new String[] { "TopTop4.java", "Top4.java", "Middle4.java" }, new String[] { "Aspect4.java" }, true); } @@ -217,8 +201,6 @@ public class DeclareParents extends AjcTestCase { * ITDs from the aspect */ public void test_inheritedAbstractMethodsMustBeImplemented_3() { - File testBase = new File(baseDir, "TestD"); - CompilationResult result = null; runSourceAndBinaryTestcase(new File(baseDir, "TestD"), new String[] { "SimpleClass2.java" }, new String[] { "SimpleAspect2.java" }, true); } @@ -228,7 +210,6 @@ public class DeclareParents extends AjcTestCase { */ public void test_missingCtorAddedViaITD() { File testBase = new File(baseDir, "TestE"); - CompilationResult result = null; runSourceAndBinaryTestcase(testBase, new String[] { "A.java", "B.java", "C.java" }, new String[] { "X.java" }, true); } @@ -390,59 +371,59 @@ public class DeclareParents extends AjcTestCase { baseDir = new File("../org.aspectj.ajdt.core/testdata", PROJECT_DIR); } - private List verify(String name) { - List verifyProblems = new ArrayList(); - System.out.println("Now verifying: " + name + "\n"); - - Verifier v = VerifierFactory.getVerifier(name); - VerificationResult vr; - - vr = v.doPass1(); - if (vr != VerificationResult.VR_OK) - verifyProblems.add("Pass1: " + vr.getMessage()); - - vr = v.doPass2(); - if (vr != VerificationResult.VR_OK) - verifyProblems.add("Pass2: " + vr.getMessage()); - - if (vr == VerificationResult.VR_OK) { - JavaClass jc = Repository.lookupClass(name); - for (int i = 0; i < jc.getMethods().length; i++) { - vr = v.doPass3a(i); - if (vr != VerificationResult.VR_OK) - verifyProblems.add("Pass3a: " + jc.getMethods()[i] + " " + vr.getMessage()); - - vr = v.doPass3b(i); - if (vr != VerificationResult.VR_OK) - verifyProblems.add("Pass3b: " + jc.getMethods()[i] + " " + vr.getMessage()); - } - } - - System.out.println("Warnings:"); - String[] warnings = v.getMessages(); - if (warnings.length == 0) - System.out.println(""); - for (int j = 0; j < warnings.length; j++) { - System.out.println(warnings[j]); - } - - System.out.println("\n"); - - // avoid swapping. - v.flush(); - Repository.clearCache(); - return verifyProblems; - } - - private void runClass(String name) { - RunResult rr = null; - try { - rr = run(name, new String[] {}, ajc.getSandboxDirectory() + File.separator + "classes2"); - } catch (VerifyError ve) { - ve.printStackTrace(); - fail("Unexpected VerifyError for type upon which we declared parents"); - } - // assertTrue("Didn't expect any errors from the run of "+name+", but got: "+rr.toString(),rr.get); - } + // private List verify(String name) { + // List verifyProblems = new ArrayList(); + // System.out.println("Now verifying: " + name + "\n"); + // + // Verifier v = VerifierFactory.getVerifier(name); + // VerificationResult vr; + // + // vr = v.doPass1(); + // if (vr != VerificationResult.VR_OK) + // verifyProblems.add("Pass1: " + vr.getMessage()); + // + // vr = v.doPass2(); + // if (vr != VerificationResult.VR_OK) + // verifyProblems.add("Pass2: " + vr.getMessage()); + // + // if (vr == VerificationResult.VR_OK) { + // JavaClass jc = Repository.lookupClass(name); + // for (int i = 0; i < jc.getMethods().length; i++) { + // vr = v.doPass3a(i); + // if (vr != VerificationResult.VR_OK) + // verifyProblems.add("Pass3a: " + jc.getMethods()[i] + " " + vr.getMessage()); + // + // vr = v.doPass3b(i); + // if (vr != VerificationResult.VR_OK) + // verifyProblems.add("Pass3b: " + jc.getMethods()[i] + " " + vr.getMessage()); + // } + // } + // + // System.out.println("Warnings:"); + // String[] warnings = v.getMessages(); + // if (warnings.length == 0) + // System.out.println(""); + // for (int j = 0; j < warnings.length; j++) { + // System.out.println(warnings[j]); + // } + // + // System.out.println("\n"); + // + // // avoid swapping. + // v.flush(); + // Repository.clearCache(); + // return verifyProblems; + // } + + // private void runClass(String name) { + // RunResult rr = null; + // try { + // rr = run(name, new String[] {}, ajc.getSandboxDirectory() + File.separator + "classes2"); + // } catch (VerifyError ve) { + // ve.printStackTrace(); + // fail("Unexpected VerifyError for type upon which we declared parents"); + // } + // // assertTrue("Didn't expect any errors from the run of "+name+", but got: "+rr.toString(),rr.get); + // } } diff --git a/org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/AjASTTest.java b/org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/AjASTTest.java index ba7196de5..6b588513b 100644 --- a/org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/AjASTTest.java +++ b/org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/AjASTTest.java @@ -1284,7 +1284,8 @@ public class AjASTTest extends AjASTTestCase { public void testPropertyDescriptorsForDeclareParentsDeclaration() { AjAST ajast = createAjAST(); - DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration(); + // DeclareParentsDeclaration d = + ajast.newDeclareParentsDeclaration(); List props = DeclareParentsDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundTypePattern = false; @@ -1370,7 +1371,8 @@ public class AjASTTest extends AjASTTestCase { public void testPropertyDescriptorsForDeclarePrecedence() { AjAST ajast = createAjAST(); - DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration(); + // DeclarePrecedenceDeclaration d = + ajast.newDeclarePrecedenceDeclaration(); List props = DeclarePrecedenceDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundTypePatterns = false; @@ -1441,7 +1443,8 @@ public class AjASTTest extends AjASTTestCase { public void testPropertyDescriptorsForDeclareSoftDeclaration() { AjAST ajast = createAjAST(); - DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration(); + // DeclareSoftDeclaration d = + ajast.newDeclareSoftDeclaration(); List props = DeclareSoftDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundPointcut = false; @@ -1531,7 +1534,8 @@ public class AjASTTest extends AjASTTestCase { public void testPropertyDescriptorsForDeclareWarningDeclaration() { AjAST ajast = createAjAST(); - DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration(); + // DeclareWarningDeclaration d = + ajast.newDeclareWarningDeclaration(); List props = DeclareWarningDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundPointcut = false; -- 2.39.5