issue_id
int64
2.03k
426k
title
stringlengths
9
251
body
stringlengths
1
32.8k
status
stringclasses
6 values
after_fix_sha
stringlengths
7
7
project_name
stringclasses
6 values
repo_url
stringclasses
6 values
repo_name
stringclasses
6 values
language
stringclasses
1 value
issue_url
null
before_fix_sha
null
pull_url
null
commit_datetime
timestamp[us, tz=UTC]
report_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
2
187
file_content
stringlengths
0
368k
108,118
Bug 108118 Complete implementation of @SuppressAjWarnings
ensure that @SuppressAJWarnings are indeed suppressed during pointcut operations. This requires wrapping major pointcut operations with calls to Lint from the associated advice.
resolved fixed
81a0790
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-29T15:42:52Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.patterns.ExactTypePattern; import org.aspectj.weaver.patterns.ExposedState; import org.aspectj.weaver.patterns.Pointcut; /** * Advice implemented for bcel. * * @author Erik Hilsdale * @author Jim Hugunin */ public class BcelAdvice extends Advice { private Test pointcutTest; private ExposedState exposedState; private boolean hasMatchedAtLeastOnce = false; public BcelAdvice( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature, ResolvedType concreteAspect) { super(attribute, pointcut, signature); this.concreteAspect = concreteAspect; } // !!! must only be used for testing public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature, int extraArgumentFlags, int start, int end, ISourceContext sourceContext, ResolvedType concreteAspect) { this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext), pointcut, signature, concreteAspect); thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests } // ---- implementations of ShadowMunger's methods public void specializeOn(Shadow shadow) { if (getKind() == AdviceKind.Around) { ((BcelShadow)shadow).initializeForAroundClosure(); } //XXX this case is just here for supporting lazy test code if (getKind() == null) { exposedState = new ExposedState(0); return; } if (getKind().isPerEntry()) { exposedState = new ExposedState(0); } else if (getKind().isCflow()) { exposedState = new ExposedState(nFreeVars); } else if (getSignature() != null) { exposedState = new ExposedState(getSignature()); } else { exposedState = new ExposedState(0); return; //XXX this case is just here for supporting lazy test code } World world = shadow.getIWorld(); if (suppressedLintKinds == null) { if (signature instanceof BcelMethod) { this.suppressedLintKinds = Utility.getSuppressedWarnings(signature.getAnnotations(), world.getLint()); } else { this.suppressedLintKinds = Collections.EMPTY_LIST; } } world.getLint().suppressKinds(suppressedLintKinds); pointcutTest = getPointcut().findResidue(shadow, exposedState); world.getLint().clearSuppressions(); // these initializations won't be performed by findResidue, but need to be // so that the joinpoint is primed for weaving if (getKind() == AdviceKind.PerThisEntry) { shadow.getThisVar(); } else if (getKind() == AdviceKind.PerTargetEntry) { shadow.getTargetVar(); } // make sure thisJoinPoint parameters are initialized if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) { ((BcelShadow)shadow).getThisJoinPointStaticPartVar(); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); } if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { ((BcelShadow)shadow).requireThisJoinPoint(pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); } if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) { ((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar(); ((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation()); } } private boolean canInline(Shadow s) { if (attribute.isProceedInInners()) return false; //XXX this guard seems to only be needed for bad test cases if (concreteAspect == null || concreteAspect == ResolvedType.MISSING) return false; if (concreteAspect.getWorld().isXnoInline()) return false; //System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState()); return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven(); } public void implementOn(Shadow s) { hasMatchedAtLeastOnce=true; BcelShadow shadow = (BcelShadow) s; //FIXME AV - see #75442, this logic is not enough so for now comment it out until we fix the bug // // callback for perObject AJC MightHaveAspect postMunge (#75442) // if (getConcreteAspect() != null // && getConcreteAspect().getPerClause() != null // && PerClause.PEROBJECT.equals(getConcreteAspect().getPerClause().getKind())) { // final PerObject clause; // if (getConcreteAspect().getPerClause() instanceof PerFromSuper) { // clause = (PerObject)((PerFromSuper) getConcreteAspect().getPerClause()).lookupConcretePerClause(getConcreteAspect()); // } else { // clause = (PerObject) getConcreteAspect().getPerClause(); // } // if (clause.isThis()) { // PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getThisVar().getType(), getConcreteAspect()); // } else { // PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getTargetVar().getType(), getConcreteAspect()); // } // } if (getKind() == AdviceKind.Before) { shadow.weaveBefore(this); } else if (getKind() == AdviceKind.AfterReturning) { shadow.weaveAfterReturning(this); } else if (getKind() == AdviceKind.AfterThrowing) { UnresolvedType catchType = hasExtraParameter() ? getExtraParameterType() : UnresolvedType.THROWABLE; shadow.weaveAfterThrowing(this, catchType); } else if (getKind() == AdviceKind.After) { shadow.weaveAfter(this); } else if (getKind() == AdviceKind.Around) { // Note: under regular LTW the aspect is usually loaded after the first use of any class affecteted by it // This means that as long as the aspect has not been thru the LTW, it's woven state is unknown // and thus canInline(s) will return false. // To force inlining (test), ones can do Class aspect = FQNAspect.class in the clinit of the target class // FIXME AV : for AJC compiled @AJ aspect (or any code style aspect), the woven state can never be known // if the aspect belongs to a parent classloader. In that case the aspect will never be inlined. // It might be dangerous to change that especially for @AJ aspect non compiled with AJC since if those // are not weaved (f.e. use of some limiteed LTW etc) then they cannot be prepared for inlining. // One solution would be to flag @AJ aspect with an annotation as "prepared" and query that one. if (!canInline(s)) { shadow.weaveAroundClosure(this, hasDynamicTests()); } else { shadow.weaveAroundInline(this, hasDynamicTests()); } } else if (getKind() == AdviceKind.InterInitializer) { shadow.weaveAfterReturning(this); } else if (getKind().isCflow()) { shadow.weaveCflowEntry(this, getSignature()); } else if (getKind() == AdviceKind.PerThisEntry) { shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar()); } else if (getKind() == AdviceKind.PerTargetEntry) { shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar()); } else if (getKind() == AdviceKind.Softener) { shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType()); } else if (getKind() == AdviceKind.PerTypeWithinEntry) { // PTWIMPL Entry to ptw is the static initialization of a type that matched the ptw type pattern shadow.weavePerTypeWithinAspectInitialization(this,shadow.getEnclosingType()); } else { throw new BCException("unimplemented kind: " + getKind()); } } // ---- implementations private Collection collectCheckedExceptions(UnresolvedType[] excs) { if (excs == null || excs.length == 0) return Collections.EMPTY_LIST; Collection ret = new ArrayList(); World world = concreteAspect.getWorld(); ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION); ResolvedType error = world.getCoreType(UnresolvedType.ERROR); for (int i=0, len=excs.length; i < len; i++) { ResolvedType t = world.resolve(excs[i],true); if (t == ResolvedType.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()), "",IMessage.ERROR,getSourceLocation(),null,null); world.getMessageHandler().handleMessage(msg); } if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) { ret.add(t); } } return ret; } private Collection thrownExceptions = null; public Collection getThrownExceptions() { if (thrownExceptions == null) { //??? can we really lump in Around here, how does this interact with Throwable if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness (getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around)) { World world = concreteAspect.getWorld(); ResolvedMember m = world.resolve(signature); if (m == null) { thrownExceptions = Collections.EMPTY_LIST; } else { thrownExceptions = collectCheckedExceptions(m.getExceptions()); } } else { thrownExceptions = Collections.EMPTY_LIST; } } return thrownExceptions; } /** * The munger must not check for the advice exceptions to be declared by the shadow in the case * of @AJ aspects so that around can throws Throwable * * @return */ public boolean mustCheckExceptions() { if (getConcreteAspect() == null) { return true; } return !getConcreteAspect().isAnnotationStyleAspect(); } // only call me after prepare has been called public boolean hasDynamicTests() { // if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) { // UnresolvedType extraParameterType = getExtraParameterType(); // if (! extraParameterType.equals(UnresolvedType.OBJECT) // && ! extraParameterType.isPrimitive()) // return true; // } return pointcutTest != null && !(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST); } /** * get the instruction list for the really simple version of this advice. * Is broken apart * for other advice, but if you want it in one block, this is the method to call. * * @param s The shadow around which these instructions will eventually live. * @param extraArgVar The var that will hold the return value or thrown exception * for afterX advice * @param ifNoAdvice The instructionHandle to jump to if the dynamic * tests for this munger fails. */ InstructionList getAdviceInstructions( BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { BcelShadow shadow = (BcelShadow) s; InstructionFactory fact = shadow.getFactory(); BcelWorld world = shadow.getWorld(); InstructionList il = new InstructionList(); // we test to see if we have the right kind of thing... // after throwing does this just by the exception mechanism. if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) { UnresolvedType extraParameterType = getExtraParameterType(); if (! extraParameterType.equals(UnresolvedType.OBJECT) && ! extraParameterType.isPrimitiveType()) { il.append( BcelRenderer.renderTest( fact, world, Test.makeInstanceof( extraArgVar, getExtraParameterType().resolve(world)), null, ifNoAdvice, null)); } } il.append(getAdviceArgSetup(shadow, extraArgVar, null)); il.append(getNonTestAdviceInstructions(shadow)); InstructionHandle ifYesAdvice = il.getStart(); il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice)); return il; } public InstructionList getAdviceArgSetup( BcelShadow shadow, BcelVar extraVar, InstructionList closureInstantiation) { InstructionFactory fact = shadow.getFactory(); BcelWorld world = shadow.getWorld(); InstructionList il = new InstructionList(); // if (targetAspectField != null) { // il.append(fact.createFieldAccess( // targetAspectField.getDeclaringType().getName(), // targetAspectField.getName(), // BcelWorld.makeBcelType(targetAspectField.getType()), // Constants.GETSTATIC)); // } // //System.err.println("BcelAdvice: " + exposedState); if (exposedState.getAspectInstance() != null) { il.append(BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance())); } final boolean isAnnotationStyleAspect = getConcreteAspect()!=null && getConcreteAspect().isAnnotationStyleAspect(); boolean previousIsClosure = false; for (int i = 0, len = exposedState.size(); i < len; i++) { if (exposedState.isErroneousVar(i)) continue; // Erroneous vars have already had error msgs reported! BcelVar v = (BcelVar) exposedState.get(i); if (v == null) { // if not @AJ aspect, go on with the regular binding handling if (!isAnnotationStyleAspect) { ; } else { // ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint //if (getKind() == AdviceKind.Around) { // previousIsClosure = true; // il.append(closureInstantiation); if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) { //make sure we are in an around, since we deal with the closure, not the arg here if (getKind() != AdviceKind.Around) { previousIsClosure = false; getConcreteAspect().getWorld().getMessageHandler().handleMessage( new Message( "use of ProceedingJoinPoint is allowed only on around advice (" + "arg " + i + " in " + toString() + ")", this.getSourceLocation(), true ) ); // try to avoid verify error and pass in null il.append(InstructionConstants.ACONST_NULL); } else { if (previousIsClosure) { il.append(InstructionConstants.DUP); } else { previousIsClosure = true; il.append(closureInstantiation.copy()); } } } else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) { previousIsClosure = false; if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) { shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact); } } else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) { previousIsClosure = false; if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { il.append(shadow.loadThisJoinPoint()); } } else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) { previousIsClosure = false; if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) { shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact); } } else if (hasExtraParameter()) { previousIsClosure = false; extraVar.appendLoadAndConvert( il, fact, getExtraParameterType().resolve(world)); } else { previousIsClosure = false; getConcreteAspect().getWorld().getMessageHandler().handleMessage( new Message( "use of ProceedingJoinPoint is allowed only on around advice (" + "arg " + i + " in " + toString() + ")", this.getSourceLocation(), true ) ); // try to avoid verify error and pass in null il.append(InstructionConstants.ACONST_NULL); } } } else { UnresolvedType desiredTy = getSignature().getParameterTypes()[i]; v.appendLoadAndConvert(il, fact, desiredTy.resolve(world)); } } // ATAJ: for code style aspect, handles the extraFlag as usual ie not // in the middle of the formal bindings but at the end, in a rock solid ordering if (!isAnnotationStyleAspect) { if (getKind() == AdviceKind.Around) { il.append(closureInstantiation); } else if (hasExtraParameter()) { extraVar.appendLoadAndConvert( il, fact, getExtraParameterType().resolve(world)); } // handle thisJoinPoint parameters // these need to be in that same order as parameters in // org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) { shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact); } if ((getExtraParameterFlags() & ThisJoinPoint) != 0) { il.append(shadow.loadThisJoinPoint()); } if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) { shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact); } } return il; } public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) { return new InstructionList( Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getSignature())); } public InstructionList getTestInstructions( BcelShadow shadow, InstructionHandle sk, InstructionHandle fk, InstructionHandle next) { //System.err.println("test: " + pointcutTest); return BcelRenderer.renderTest( shadow.getFactory(), shadow.getWorld(), pointcutTest, sk, fk, next); } public int compareTo(Object other) { if (!(other instanceof BcelAdvice)) return 0; BcelAdvice o = (BcelAdvice)other; //System.err.println("compareTo: " + this + ", " + o); if (kind.getPrecedence() != o.kind.getPrecedence()) { if (kind.getPrecedence() > o.kind.getPrecedence()) return +1; else return -1; } if (kind.isCflow()) { // System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries); // System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries); boolean isBelow = (kind == AdviceKind.CflowBelowEntry); if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1; else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1; else return 0; } if (kind.isPerEntry() || kind == AdviceKind.Softener) { return 0; } //System.out.println("compare: " + this + " with " + other); World world = concreteAspect.getWorld(); int ret = concreteAspect.getWorld().compareByPrecedence( concreteAspect, o.concreteAspect); if (ret != 0) return ret; ResolvedType declaringAspect = getDeclaringAspect().resolve(world); ResolvedType o_declaringAspect = o.getDeclaringAspect().resolve(world); if (declaringAspect == o_declaringAspect) { if (kind.isAfter() || o.kind.isAfter()) { return this.getStart() < o.getStart() ? -1: +1; } else { return this.getStart()< o.getStart() ? +1: -1; } } else if (declaringAspect.isAssignableFrom(o_declaringAspect)) { return -1; } else if (o_declaringAspect.isAssignableFrom(declaringAspect)) { return +1; } else { return 0; } } public BcelVar[] getExposedStateAsBcelVars() { // ATAJ aspect // the closure instantiation has the same mapping as the extracted method from wich it is called if (getConcreteAspect()!= null && getConcreteAspect().isAnnotationStyleAspect()) { return BcelVar.NONE; } //System.out.println("vars: " + Arrays.asList(exposedState.vars)); if (exposedState == null) return BcelVar.NONE; int len = exposedState.vars.length; BcelVar[] ret = new BcelVar[len]; for (int i=0; i < len; i++) { ret[i] = (BcelVar)exposedState.vars[i]; } return ret; //(BcelVar[]) exposedState.vars; } public boolean hasMatchedSomething() { return hasMatchedAtLeastOnce; } }
108,118
Bug 108118 Complete implementation of @SuppressAjWarnings
ensure that @SuppressAJWarnings are indeed suppressed during pointcut operations. This requires wrapping major pointcut operations with calls to Lint from the associated advice.
resolved fixed
81a0790
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-29T15:42:52Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/bcel/Utility.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.List; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.ArrayElementValue; import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePair; import org.aspectj.apache.bcel.classfile.annotation.ElementValue; import org.aspectj.apache.bcel.classfile.annotation.SimpleElementValue; import org.aspectj.apache.bcel.generic.ArrayType; import org.aspectj.apache.bcel.generic.BIPUSH; import org.aspectj.apache.bcel.generic.BasicType; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.ConstantPushInstruction; import org.aspectj.apache.bcel.generic.INSTANCEOF; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.LDC; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.ReferenceType; import org.aspectj.apache.bcel.generic.SIPUSH; import org.aspectj.apache.bcel.generic.SWITCH; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.TargetLostException; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Lint; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; public class Utility { private Utility() { super(); } /* * Ensure we report a nice source location - particular in the case * where the source info is missing (binary weave). */ public static String beautifyLocation(ISourceLocation isl) { StringBuffer nice = new StringBuffer(); if (isl==null || isl.getSourceFile()==null || isl.getSourceFile().getName().indexOf("no debug info available")!=-1) { nice.append("no debug info available"); } else { // can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/'); if (takeFrom == -1) { takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\'); } nice.append(isl.getSourceFile().getPath().substring(takeFrom +1)); if (isl.getLine()!=0) nice.append(":").append(isl.getLine()); } return nice.toString(); } public static Instruction createSuperInvoke( InstructionFactory fact, BcelWorld world, Member signature) { short kind; if (signature.isInterface()) { throw new RuntimeException("bad"); } else if (signature.isPrivate() || signature.getName().equals("<init>")) { throw new RuntimeException("unimplemented, possibly bad"); } else if (signature.isStatic()) { throw new RuntimeException("bad"); } else { kind = Constants.INVOKESPECIAL; } return fact.createInvoke( signature.getDeclaringType().getName(), signature.getName(), BcelWorld.makeBcelType(signature.getReturnType()), BcelWorld.makeBcelTypes(signature.getParameterTypes()), kind); } // XXX don't need the world now public static Instruction createInvoke( InstructionFactory fact, BcelWorld world, Member signature) { short kind; if (signature.isInterface()) { kind = Constants.INVOKEINTERFACE; } else if (signature.isStatic()) { kind = Constants.INVOKESTATIC; } else if (signature.isPrivate() || signature.getName().equals("<init>")) { kind = Constants.INVOKESPECIAL; } else { kind = Constants.INVOKEVIRTUAL; } return fact.createInvoke( signature.getDeclaringType().getName(), signature.getName(), BcelWorld.makeBcelType(signature.getReturnType()), BcelWorld.makeBcelTypes(signature.getParameterTypes()), kind); } public static Instruction createGet(InstructionFactory fact, Member signature) { short kind; if (signature.isStatic()) { kind = Constants.GETSTATIC; } else { kind = Constants.GETFIELD; } return fact.createFieldAccess( signature.getDeclaringType().getName(), signature.getName(), BcelWorld.makeBcelType(signature.getReturnType()), kind); } /** * Creae a field GET instruction * * @param fact * @param signature * @param declaringType * @return */ public static Instruction createGetOn(InstructionFactory fact, Member signature, UnresolvedType declaringType) { short kind; if (signature.isStatic()) { kind = Constants.GETSTATIC; } else { kind = Constants.GETFIELD; } return fact.createFieldAccess( declaringType.getName(), signature.getName(), BcelWorld.makeBcelType(signature.getReturnType()), kind); } public static Instruction createSet(InstructionFactory fact, Member signature) { short kind; if (signature.isStatic()) { kind = Constants.PUTSTATIC; } else { kind = Constants.PUTFIELD; } return fact.createFieldAccess( signature.getDeclaringType().getName(), signature.getName(), BcelWorld.makeBcelType(signature.getReturnType()), kind); } public static Instruction createInvoke( InstructionFactory fact, JavaClass declaringClass, Method newMethod) { short kind; if (newMethod.isInterface()) { kind = Constants.INVOKEINTERFACE; } else if (newMethod.isStatic()) { kind = Constants.INVOKESTATIC; } else if (newMethod.isPrivate() || newMethod.getName().equals("<init>")) { kind = Constants.INVOKESPECIAL; } else { kind = Constants.INVOKEVIRTUAL; } return fact.createInvoke( declaringClass.getClassName(), newMethod.getName(), Type.getReturnType(newMethod.getSignature()), Type.getArgumentTypes(newMethod.getSignature()), kind); } public static byte[] stringToUTF(String s) { try { ByteArrayOutputStream out0 = new ByteArrayOutputStream(); DataOutputStream out1 = new DataOutputStream(out0); out1.writeUTF(s); return out0.toByteArray(); } catch (IOException e) { throw new RuntimeException("sanity check"); } } public static Instruction createInstanceof(InstructionFactory fact, ReferenceType t) { int cpoolEntry = (t instanceof ArrayType) ? fact.getConstantPool().addArrayClass((ArrayType)t) : fact.getConstantPool().addClass((ObjectType)t); return new INSTANCEOF(cpoolEntry); } public static Instruction createInvoke( InstructionFactory fact, LazyMethodGen m) { short kind; if (m.getEnclosingClass().isInterface()) { kind = Constants.INVOKEINTERFACE; } else if (m.isStatic()) { kind = Constants.INVOKESTATIC; } else if (m.isPrivate() || m.getName().equals("<init>")) { kind = Constants.INVOKESPECIAL; } else { kind = Constants.INVOKEVIRTUAL; } return fact.createInvoke( m.getClassName(), m.getName(), m.getReturnType(), m.getArgumentTypes(), kind); } /** * Create an invoke instruction * * @param fact * @param kind INVOKEINTERFACE, INVOKEVIRTUAL.. * @param member * @return */ public static Instruction createInvoke( InstructionFactory fact, short kind, Member member) { return fact.createInvoke( member.getDeclaringType().getName(), member.getName(), BcelWorld.makeBcelType(member.getReturnType()), BcelWorld.makeBcelTypes(member.getParameterTypes()), kind); } // ??? these should perhaps be cached. Remember to profile this to see if it's a problem. public static String[] makeArgNames(int n) { String[] ret = new String[n]; for (int i=0; i<n; i++) { ret[i] = "arg" + i; } return ret; } // Lookup table, for converting between pairs of types, it gives // us the method name in the Conversions class private static Hashtable validBoxing = new Hashtable(); static { validBoxing.put("Ljava/lang/Byte;B","byteObject"); validBoxing.put("Ljava/lang/Character;C","charObject"); validBoxing.put("Ljava/lang/Double;D","doubleObject"); validBoxing.put("Ljava/lang/Float;F","floatObject"); validBoxing.put("Ljava/lang/Integer;I","intObject"); validBoxing.put("Ljava/lang/Long;J","longObject"); validBoxing.put("Ljava/lang/Short;S","shortObject"); validBoxing.put("Ljava/lang/Boolean;Z","booleanObject"); validBoxing.put("BLjava/lang/Byte;","byteValue"); validBoxing.put("CLjava/lang/Character;","charValue"); validBoxing.put("DLjava/lang/Double;","doubleValue"); validBoxing.put("FLjava/lang/Float;","floatValue"); validBoxing.put("ILjava/lang/Integer;","intValue"); validBoxing.put("JLjava/lang/Long;","longValue"); validBoxing.put("SLjava/lang/Short;","shortValue"); validBoxing.put("ZLjava/lang/Boolean;","booleanValue"); } public static void appendConversion( InstructionList il, InstructionFactory fact, ResolvedType fromType, ResolvedType toType) { if (! toType.isConvertableFrom(fromType) && ! fromType.isConvertableFrom(toType)) { throw new BCException("can't convert from " + fromType + " to " + toType); } // XXX I'm sure this test can be simpler but my brain hurts and this works if (!toType.getWorld().isInJava5Mode()) { if (toType.needsNoConversionFrom(fromType)) return; } else { if (toType.needsNoConversionFrom(fromType) && !(toType.isPrimitiveType()^fromType.isPrimitiveType())) return; } if (toType.equals(ResolvedType.VOID)) { // assert fromType.equals(UnresolvedType.OBJECT) il.append(InstructionFactory.createPop(fromType.getSize())); } else if (fromType.equals(ResolvedType.VOID)) { // assert toType.equals(UnresolvedType.OBJECT) il.append(InstructionFactory.createNull(Type.OBJECT)); return; } else if (fromType.equals(UnresolvedType.OBJECT)) { Type to = BcelWorld.makeBcelType(toType); if (toType.isPrimitiveType()) { String name = toType.toString() + "Value"; il.append( fact.createInvoke( "org.aspectj.runtime.internal.Conversions", name, to, new Type[] { Type.OBJECT }, Constants.INVOKESTATIC)); } else { il.append(fact.createCheckCast((ReferenceType)to)); } } else if (toType.equals(UnresolvedType.OBJECT)) { // assert fromType.isPrimitive() Type from = BcelWorld.makeBcelType(fromType); String name = fromType.toString() + "Object"; il.append( fact.createInvoke( "org.aspectj.runtime.internal.Conversions", name, Type.OBJECT, new Type[] { from }, Constants.INVOKESTATIC)); } else if (toType.getWorld().isInJava5Mode() && validBoxing.get(toType.getSignature()+fromType.getSignature())!=null) { // XXX could optimize by using any java boxing code that may be just before the call... Type from = BcelWorld.makeBcelType(fromType); Type to = BcelWorld.makeBcelType(toType); String name = (String)validBoxing.get(toType.getSignature()+fromType.getSignature()); if (toType.isPrimitiveType()) { il.append( fact.createInvoke( "org.aspectj.runtime.internal.Conversions", name, to, new Type[]{Type.OBJECT}, Constants.INVOKESTATIC)); } else { il.append( fact.createInvoke( "org.aspectj.runtime.internal.Conversions", name, Type.OBJECT, new Type[] { from }, Constants.INVOKESTATIC)); il.append(fact.createCheckCast((ReferenceType) to)); } } else if (fromType.isPrimitiveType()) { // assert toType.isPrimitive() Type from = BcelWorld.makeBcelType(fromType); Type to = BcelWorld.makeBcelType(toType); try { il.append(fact.createCast(from, to)); } catch (RuntimeException e) { il.append(fact.createCast(from, Type.INT)); il.append(fact.createCast(Type.INT, to)); } } else { Type to = BcelWorld.makeBcelType(toType); // assert ! fromType.isPrimitive() && ! toType.isPrimitive() il.append(fact.createCheckCast((ReferenceType) to)); } } public static InstructionList createConversion( InstructionFactory fact, Type fromType, Type toType) { //System.out.println("cast to: " + toType); InstructionList il = new InstructionList(); //PR71273 if ((fromType.equals(Type.BYTE) || fromType.equals(Type.CHAR) || fromType.equals(Type.SHORT)) && (toType.equals(Type.INT))) { return il; } if (fromType.equals(toType)) return il; if (toType.equals(Type.VOID)) { il.append(InstructionFactory.createPop(fromType.getSize())); return il; } if (fromType.equals(Type.VOID)) { if (toType instanceof BasicType) throw new BCException("attempting to cast from void to basic type"); il.append(InstructionFactory.createNull(Type.OBJECT)); return il; } if (fromType.equals(Type.OBJECT)) { if (toType instanceof BasicType) { String name = toType.toString() + "Value"; il.append( fact.createInvoke( "org.aspectj.runtime.internal.Conversions", name, toType, new Type[] { Type.OBJECT }, Constants.INVOKESTATIC)); return il; } } if (toType.equals(Type.OBJECT)) { if (fromType instanceof BasicType) { String name = fromType.toString() + "Object"; il.append( fact.createInvoke( "org.aspectj.runtime.internal.Conversions", name, Type.OBJECT, new Type[] { fromType }, Constants.INVOKESTATIC)); return il; } else if (fromType instanceof ReferenceType) { return il; } else { throw new RuntimeException(); } } if (fromType instanceof ReferenceType && ((ReferenceType)fromType).isAssignmentCompatibleWith(toType)) { return il; } il.append(fact.createCast(fromType, toType)); return il; } public static Instruction createConstant( InstructionFactory fact, int i) { Instruction inst; switch(i) { case -1: inst = InstructionConstants.ICONST_M1; break; case 0: inst = InstructionConstants.ICONST_0; break; case 1: inst = InstructionConstants.ICONST_1; break; case 2: inst = InstructionConstants.ICONST_2; break; case 3: inst = InstructionConstants.ICONST_3; break; case 4: inst = InstructionConstants.ICONST_4; break; case 5: inst = InstructionConstants.ICONST_5; break; } if (i <= Byte.MAX_VALUE && i >= Byte.MIN_VALUE) { inst = new BIPUSH((byte)i); } else if (i <= Short.MAX_VALUE && i >= Short.MIN_VALUE) { inst = new SIPUSH((short)i); } else { inst = new LDC(fact.getClassGen().getConstantPool().addInteger(i)); } return inst; } public static JavaClass makeJavaClass(String filename, byte[] bytes) { try { ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), filename); return parser.parse(); } catch (IOException e) { throw new BCException("malformed class file"); } } public static String arrayToString(int[] a) { int len = a.length; if (len == 0) return "[]"; StringBuffer buf = new StringBuffer("["); buf.append(a[0]); for (int i = 1; i < len; i++) { buf.append(", "); buf.append(a[i]); } buf.append("]"); return buf.toString(); } /** * replace an instruction handle with another instruction, in this case, a branch instruction. * * @param ih the instruction handle to replace. * @param branchInstruction the branch instruction to replace ih with * @param enclosingMethod where to find ih's instruction list. */ public static void replaceInstruction( InstructionHandle ih, BranchInstruction branchInstruction, LazyMethodGen enclosingMethod) { InstructionList il = enclosingMethod.getBody(); InstructionHandle fresh = il.append(ih, branchInstruction); deleteInstruction(ih, fresh, enclosingMethod); } /** delete an instruction handle and retarget all targeters of the deleted instruction * to the next instruction. Obviously, this should not be used to delete * a control transfer instruction unless you know what you're doing. * * @param ih the instruction handle to delete. * @param enclosingMethod where to find ih's instruction list. */ public static void deleteInstruction( InstructionHandle ih, LazyMethodGen enclosingMethod) { deleteInstruction(ih, ih.getNext(), enclosingMethod); } /** delete an instruction handle and retarget all targeters of the deleted instruction * to the provided target. * * @param ih the instruction handle to delete * @param retargetTo the instruction handle to retarget targeters of ih to. * @param enclosingMethod where to find ih's instruction list. */ public static void deleteInstruction( InstructionHandle ih, InstructionHandle retargetTo, LazyMethodGen enclosingMethod) { InstructionList il = enclosingMethod.getBody(); InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; targeter.updateTarget(ih, retargetTo); } ih.removeAllTargeters(); } try { il.delete(ih); } catch (TargetLostException e) { throw new BCException("this really can't happen"); } } /** * Fix for Bugzilla #39479, #40109 patch contributed by Andy Clement * * Need to manually copy Select instructions - if we rely on the the 'fresh' object * created by copy(), the InstructionHandle array 'targets' inside the Select * object will not have been deep copied, so modifying targets in fresh will modify * the original Select - not what we want ! (It is a bug in BCEL to do with cloning * Select objects). * * <pre> * declare error: * call(* Instruction.copy()) && within(org.aspectj.weaver) * && !withincode(* Utility.copyInstruction(Instruction)): * "use Utility.copyInstruction to work-around bug in Select.copy()"; * </pre> */ public static Instruction copyInstruction(Instruction i) { if (i instanceof Select) { Select freshSelect = (Select)i; // Create a new targets array that looks just like the existing one InstructionHandle[] targets = new InstructionHandle[freshSelect.getTargets().length]; for (int ii = 0; ii < targets.length; ii++) { targets[ii] = freshSelect.getTargets()[ii]; } // Create a new select statement with the new targets array SWITCH switchStatement = new SWITCH(freshSelect.getMatchs(), targets, freshSelect.getTarget()); return (Select)switchStatement.getInstruction(); } else { return i.copy(); // Use clone for shallow copy... } } /** returns -1 if no source line attribute */ // this naive version overruns the JVM stack size, if only Java understood tail recursion... // public static int getSourceLine(InstructionHandle ih) { // if (ih == null) return -1; // // InstructionTargeter[] ts = ih.getTargeters(); // if (ts != null) { // for (int j = ts.length - 1; j >= 0; j--) { // InstructionTargeter t = ts[j]; // if (t instanceof LineNumberTag) { // return ((LineNumberTag)t).getLineNumber(); // } // } // } // return getSourceLine(ih.getNext()); // } public static int getSourceLine(InstructionHandle ih) { int lookahead=0; // arbitrary rule that we will never lookahead more than 100 instructions for a line # while (lookahead++ < 100) { if (ih == null) return -1; InstructionTargeter[] ts = ih.getTargeters(); if (ts != null) { for (int j = ts.length - 1; j >= 0; j--) { InstructionTargeter t = ts[j]; if (t instanceof LineNumberTag) { return ((LineNumberTag)t).getLineNumber(); } } } ih = ih.getNext(); } //System.err.println("no line information available for: " + ih); return -1; } // assumes that there is no already extant source line tag. Otherwise we'll have to be better. public static void setSourceLine(InstructionHandle ih, int lineNumber) { ih.addTargeter(new LineNumberTag(lineNumber)); } public static int makePublic(int i) { return i & ~(Modifier.PROTECTED | Modifier.PRIVATE) | Modifier.PUBLIC; } public static int makePrivate(int i) { return i & ~(Modifier.PROTECTED | Modifier.PUBLIC) | Modifier.PRIVATE; } public static BcelVar[] pushAndReturnArrayOfVars( ResolvedType[] proceedParamTypes, InstructionList il, InstructionFactory fact, LazyMethodGen enclosingMethod) { int len = proceedParamTypes.length; BcelVar[] ret = new BcelVar[len]; for (int i = len - 1; i >= 0; i--) { ResolvedType typeX = proceedParamTypes[i]; Type type = BcelWorld.makeBcelType(typeX); int local = enclosingMethod.allocateLocal(type); il.append(InstructionFactory.createStore(type, local)); ret[i] = new BcelVar(typeX, local); } return ret; } public static boolean isConstantPushInstruction(Instruction i) { return (i instanceof ConstantPushInstruction) || (i instanceof LDC); } /** * Check if the annotations contain a SuppressAjWarnings annotation and * if that annotation specifies that the given lint message (identified * by its key) should be ignored. * */ public static boolean isSuppressing(AnnotationX[] anns,String lintkey) { if (anns == null) return false; boolean suppressed = false; // Go through the annotation types on the advice for (int i = 0;!suppressed && i<anns.length;i++) { // Check for the SuppressAjWarnings annotation if (UnresolvedType.SUPPRESS_AJ_WARNINGS.getSignature().equals(anns[i].getBcelAnnotation().getTypeSignature())) { // Two possibilities: // 1. there are no values specified (i.e. @SuppressAjWarnings) // 2. there are values specified (i.e. @SuppressAjWarnings("A") or @SuppressAjWarnings({"A","B"}) List vals = anns[i].getBcelAnnotation().getValues(); if (vals == null || vals.size()==0) { // (1) suppressed = true; } else { // (2) // We know the value is an array value ArrayElementValue array = (ArrayElementValue)((ElementNameValuePair)vals.get(0)).getValue(); ElementValue[] values = array.getElementValuesArray(); for (int j = 0; j < values.length; j++) { // We know values in the array are strings SimpleElementValue value = (SimpleElementValue)values[j]; if (value.getValueString().equals(lintkey)) { suppressed = true; } } } } } return suppressed; } public static List/*Lint.Kind*/ getSuppressedWarnings(AnnotationX[] anns, Lint lint) { if (anns == null) return Collections.EMPTY_LIST; // Go through the annotation types List suppressedWarnings = new ArrayList(); boolean found = false; for (int i = 0;!found && i<anns.length;i++) { // Check for the SuppressAjWarnings annotation if (UnresolvedType.SUPPRESS_AJ_WARNINGS.getSignature().equals(anns[i].getBcelAnnotation().getTypeSignature())) { found = true; // Two possibilities: // 1. there are no values specified (i.e. @SuppressAjWarnings) // 2. there are values specified (i.e. @SuppressAjWarnings("A") or @SuppressAjWarnings({"A","B"}) List vals = anns[i].getBcelAnnotation().getValues(); if (vals == null || vals.size()==0) { // (1) suppressedWarnings.addAll(lint.allKinds()); } else { // (2) // We know the value is an array value ArrayElementValue array = (ArrayElementValue)((ElementNameValuePair)vals.get(0)).getValue(); ElementValue[] values = array.getElementValuesArray(); for (int j = 0; j < values.length; j++) { // We know values in the array are strings SimpleElementValue value = (SimpleElementValue)values[j]; suppressedWarnings.add(lint.getLintKind(value.getValueString())); } } } } return suppressedWarnings; } }
77,269
Bug 77269 Advice on inner classes not show in Outline view or gutter
Advice associated with pointcuts that match join points in inner classes are not shown. Declare warning/error are shown however. See attached screenshot for example below. Notice WEAVEINFO messages indicate problem is in AJDT not AspectJ. Also notice phantom entry in Outline view "injar aspectL Test.java". package bug_nnnnn; public class Test { public void test () { new Runnable() { public void run() { try { throw new Exception(); } catch (Exception ex) { handleException(ex); } } }; } public static void handleException (Throwable th) { } public static void main(String[] args) { try { throw new Exception(); } catch (Exception ex) { handleException(ex); } } } aspect Aspect { declare warning : call(void handleException(..)) && !within(Aspect) : "Only Aspect should handle exceptions"; pointcut caughtExceptions (Throwable th) : handler(Throwable+) && args(th); before (Throwable th) : caughtExceptions(th) { Test.handleException(th); } }
resolved fixed
4573068
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-04T08:05:55Z
2004-10-29T11:40:00Z
asm/src/org/aspectj/asm/internal/AspectJElementHierarchy.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * Andy Clement Extensions for better IDE representation * ******************************************************************/ package org.aspectj.asm.internal; import java.io.*; import java.util.*; import org.aspectj.asm.*; import org.aspectj.bridge.*; /** * @author Mik Kersten */ public class AspectJElementHierarchy implements IHierarchy { protected IProgramElement root = null; protected String configFile = null; private Map fileMap = null; private Map handleMap = null; private Map typeMap = null; public IProgramElement getElement(String handle) { IProgramElement cachedEntry = (IProgramElement)handleMap.get(handle); if (cachedEntry!=null) return cachedEntry; // StringTokenizer st = new StringTokenizer(handle, ProgramElement.ID_DELIM); // int line = new Integer(st.nextToken()).intValue(); // int col = new Integer(st.nextToken()).intValue(); TODO: use column number when available String file = AsmManager.getDefault().getHandleProvider().getFileForHandle(handle); // st.nextToken(); int line = AsmManager.getDefault().getHandleProvider().getLineNumberForHandle(handle); // st.nextToken(); String canonicalSFP = AsmManager.getDefault().getCanonicalFilePath(new File(file)); IProgramElement ret = findNodeForSourceLineHelper(root,canonicalSFP, line); if (ret!=null) { handleMap.put(handle,ret); } return ret; } public IProgramElement getRoot() { return root; } public void setRoot(IProgramElement root) { this.root = root; handleMap = new HashMap(); typeMap = new HashMap(); } public void addToFileMap( Object key, Object value ){ fileMap.put( key, value ); } public boolean removeFromFileMap(Object key) { return (fileMap.remove(key)!=null); } public void setFileMap(HashMap fileMap) { this.fileMap = fileMap; } public Object findInFileMap( Object key ) { return fileMap.get(key); } public Set getFileMapEntrySet() { return fileMap.entrySet(); } public boolean isValid() { return root != null && fileMap != null; } /** * Returns the first match * * @param parent * @param kind not null * @return null if not found */ public IProgramElement findElementForSignature(IProgramElement parent, IProgramElement.Kind kind, String signature) { for (Iterator it = parent.getChildren().iterator(); it.hasNext(); ) { IProgramElement node = (IProgramElement)it.next(); if (node.getKind() == kind && signature.equals(node.toSignatureString())) { return node; } else { IProgramElement childSearch = findElementForSignature(node, kind, signature); if (childSearch != null) return childSearch; } } return null; } public IProgramElement findElementForLabel( IProgramElement parent, IProgramElement.Kind kind, String label) { for (Iterator it = parent.getChildren().iterator(); it.hasNext(); ) { IProgramElement node = (IProgramElement)it.next(); if (node.getKind() == kind && label.equals(node.toLabelString())) { return node; } else { IProgramElement childSearch = findElementForLabel(node, kind, label); if (childSearch != null) return childSearch; } } return null; } /** * @param packageName if null default package is searched * @param className can't be null */ public IProgramElement findElementForType(String packageName, String typeName) { StringBuffer keyb = (packageName == null) ? new StringBuffer() : new StringBuffer(packageName); keyb.append("."); keyb.append(typeName); String key = keyb.toString(); IProgramElement ret = (IProgramElement) typeMap.get(key); if (ret == null) { IProgramElement packageNode = null; if (packageName == null) { packageNode = root; } else { if (root == null) return null; List kids = root.getChildren(); if (kids == null) return null; for (Iterator it = kids.iterator(); it.hasNext(); ) { IProgramElement node = (IProgramElement)it.next(); if (packageName.equals(node.getName())) { packageNode = node; } } if (packageNode == null) return null; } // this searches each file for a class for (Iterator it = packageNode.getChildren().iterator(); it.hasNext(); ) { IProgramElement fileNode = (IProgramElement)it.next(); IProgramElement cNode = findClassInNodes(fileNode.getChildren(), typeName); if (cNode != null) { ret = cNode; typeMap.put(key,ret); } } } return ret; } private IProgramElement findClassInNodes(Collection nodes, String name) { String baseName; String innerName; int dollar = name.indexOf('$'); if (dollar == -1) { baseName = name; innerName = null; } else { baseName = name.substring(0, dollar); innerName = name.substring(dollar+1); } for (Iterator j = nodes.iterator(); j.hasNext(); ) { IProgramElement classNode = (IProgramElement)j.next(); if (baseName.equals(classNode.getName())) { if (innerName == null) return classNode; else return findClassInNodes(classNode.getChildren(), innerName); } else if (name.equals(classNode.getName())) { return classNode; } } return null; } /** * @param sourceFilePath modified to '/' delimited path for consistency * @return a new structure node for the file if it was not found in the model */ public IProgramElement findElementForSourceFile(String sourceFile) { try { if (!isValid() || sourceFile == null) { return IHierarchy.NO_STRUCTURE; } else { String correctedPath = AsmManager.getDefault().getCanonicalFilePath(new File(sourceFile)); //StructureNode node = (StructureNode)getFileMap().get(correctedPath);//findFileNode(filePath, model); IProgramElement node = (IProgramElement)findInFileMap(correctedPath);//findFileNode(filePath, model); if (node != null) { return node; } else { return createFileStructureNode(correctedPath); } } } catch (Exception e) { return IHierarchy.NO_STRUCTURE; } } /** * TODO: discriminate columns */ public IProgramElement findElementForSourceLine(ISourceLocation location) { try { return findElementForSourceLine( AsmManager.getDefault().getCanonicalFilePath( location.getSourceFile()), location.getLine()); } catch (Exception e) { return null; } } /** * Never returns null * * @param sourceFilePath canonicalized path for consistency * @param lineNumber if 0 or 1 the corresponding file node will be returned * @return a new structure node for the file if it was not found in the model */ public IProgramElement findElementForSourceLine(String sourceFilePath, int lineNumber) { String canonicalSFP = AsmManager.getDefault().getCanonicalFilePath( new File(sourceFilePath)); IProgramElement node = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber); if (node != null) { return node; } else { return createFileStructureNode(sourceFilePath); } } private IProgramElement createFileStructureNode(String sourceFilePath) { // SourceFilePath might have originated on windows on linux... int lastSlash = sourceFilePath.lastIndexOf('\\'); if (lastSlash == -1) { lastSlash = sourceFilePath.lastIndexOf('/'); } String fileName = sourceFilePath.substring(lastSlash+1); IProgramElement fileNode = new ProgramElement(fileName, IProgramElement.Kind.FILE_JAVA, null); fileNode.setSourceLocation(new SourceLocation(new File(sourceFilePath), 1, 1)); fileNode.addChild(NO_STRUCTURE); return fileNode; } private IProgramElement findNodeForSourceLineHelper(IProgramElement node, String sourceFilePath, int lineNumber) { if (matches(node, sourceFilePath, lineNumber) && !hasMoreSpecificChild(node, sourceFilePath, lineNumber)) { return node; } if (node != null && node.getChildren() != null) { for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { IProgramElement foundNode = findNodeForSourceLineHelper( (IProgramElement)it.next(), sourceFilePath, lineNumber); if (foundNode != null) return foundNode; } } return null; } private boolean matches(IProgramElement node, String sourceFilePath, int lineNumber) { // try { // if (node != null && node.getSourceLocation() != null) // System.err.println("====\n1: " + // sourceFilePath + "\n2: " + // node.getSourceLocation().getSourceFile().getCanonicalPath().equals(sourceFilePath) // ); return node != null && node.getSourceLocation() != null && node.getSourceLocation().getSourceFile().getAbsolutePath().equals(sourceFilePath) && ((node.getSourceLocation().getLine() <= lineNumber && node.getSourceLocation().getEndLine() >= lineNumber) || (lineNumber <= 1 && node.getKind().isSourceFile()) ); // } catch (IOException ioe) { // return false; // } } private boolean hasMoreSpecificChild(IProgramElement node, String sourceFilePath, int lineNumber) { for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { IProgramElement child = (IProgramElement)it.next(); if (matches(child, sourceFilePath, lineNumber)) return true; } return false; } public String getConfigFile() { return configFile; } public void setConfigFile(String configFile) { this.configFile = configFile; } // TODO: optimize this lookup public IProgramElement findElementForHandle(String handle) { // try the cache first... IProgramElement ret = (IProgramElement) handleMap.get(handle); if (ret != null) return ret; // StringTokenizer st = new StringTokenizer(handle, ProgramElement.ID_DELIM); // String file = st.nextToken(); // int line = new Integer(st.nextToken()).intValue(); // int col = new Integer(st.nextToken()).intValue(); // TODO: use column number when available String file = AsmManager.getDefault().getHandleProvider().getFileForHandle(handle); // st.nextToken(); int line = AsmManager.getDefault().getHandleProvider().getLineNumberForHandle(handle); // st.nextToken(); ret = findElementForSourceLine(file, line); if (ret != null) { cache(handle,(ProgramElement)ret); } return ret; // IProgramElement parent = findElementForType(packageName, typeName); // if (parent == null) return null; // if (kind == IProgramElement.Kind.CLASS || // kind == IProgramElement.Kind.ASPECT) { // return parent; // } else { // return findElementForSignature(parent, kind, name); // } } // // private IProgramElement findElementForBytecodeInfo( // IProgramElement node, // String parentName, // String name, // String signature) { // for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { // IProgramElement curr = (IProgramElement)it.next(); // if (parentName.equals(curr.getParent().getBytecodeName()) // && name.equals(curr.getBytecodeName()) // && signature.equals(curr.getBytecodeSignature())) { // return node; // } else { // IProgramElement childSearch = findElementForBytecodeInfo(curr, parentName, name, signature); // if (childSearch != null) return childSearch; // } // } // return null; // } protected void cache(String handle, ProgramElement pe) { handleMap.put(handle,pe); } public void flushTypeMap() { typeMap.clear(); } public void flushHandleMap() { handleMap.clear(); } public void updateHandleMap(Set deletedFiles) { // Only delete the entries we need to from the handle map - for performance reasons List forRemoval = new ArrayList(); Set k = handleMap.keySet(); for (Iterator iter = k.iterator(); iter.hasNext();) { String handle = (String) iter.next(); if (deletedFiles.contains(getFilename(handle))) forRemoval.add(handle); } for (Iterator iter = forRemoval.iterator(); iter.hasNext();) { String handle = (String) iter.next(); handleMap.remove(handle); } } // XXX shouldn't be aware of the delimiter private String getFilename(String hid) { return hid.substring(0,hid.indexOf("|")); } }
77,269
Bug 77269 Advice on inner classes not show in Outline view or gutter
Advice associated with pointcuts that match join points in inner classes are not shown. Declare warning/error are shown however. See attached screenshot for example below. Notice WEAVEINFO messages indicate problem is in AJDT not AspectJ. Also notice phantom entry in Outline view "injar aspectL Test.java". package bug_nnnnn; public class Test { public void test () { new Runnable() { public void run() { try { throw new Exception(); } catch (Exception ex) { handleException(ex); } } }; } public static void handleException (Throwable th) { } public static void main(String[] args) { try { throw new Exception(); } catch (Exception ex) { handleException(ex); } } } aspect Aspect { declare warning : call(void handleException(..)) && !within(Aspect) : "Only Aspect should handle exceptions"; pointcut caughtExceptions (Throwable th) : handler(Throwable+) && args(th); before (Throwable th) : caughtExceptions(th) { Test.handleException(th); } }
resolved fixed
4573068
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-04T08:05:55Z
2004-10-29T11:40:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Mik Kersten revisions, added additional relationships * Alexandre Vasseur support for @AJ style * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.IOException; import java.util.*; import org.aspectj.ajdt.internal.compiler.ast.*; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.asm.*; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.*; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.*; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemHandler; import org.aspectj.util.LangUtil; import org.aspectj.weaver.*; import org.aspectj.weaver.patterns.*; /** * At each iteration of <CODE>processCompilationUnit</CODE> the declarations for a * particular compilation unit are added to the hierarchy passed as a a parameter. * <p> * Clients who extend this class need to ensure that they do not override any of the existing * behavior. If they do, the structure model will not be built properly and tools such as IDE * structure views and ajdoc will fail. * <p> * <b>Note:</b> this class is not considered public API and the overridable * methods are subject to change. * * @author Mik Kersten */ public class AsmHierarchyBuilder extends ASTVisitor { protected AsmElementFormatter formatter = new AsmElementFormatter(); /** * Reset for every compilation unit. */ protected AjBuildConfig buildConfig; /** * Reset for every compilation unit. */ protected Stack stack; /** * Reset for every compilation unit. */ private CompilationResult currCompilationResult; /** * * @param cuDeclaration * @param buildConfig * @param structureModel hiearchy to add this unit's declarations to */ public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) { currCompilationResult = cuDeclaration.compilationResult(); LangUtil.throwIaxIfNull(currCompilationResult, "result"); stack = new Stack(); this.buildConfig = buildConfig; internalBuild(cuDeclaration, structureModel); // throw new RuntimeException("not implemented"); } private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) { LangUtil.throwIaxIfNull(structureModel, "structureModel"); if (!currCompilationResult.equals(unit.compilationResult())) { throw new IllegalArgumentException("invalid unit: " + unit); } // ---- summary // add unit to package (or root if no package), // first removing any duplicate (XXX? removes children if 3 classes in same file?) // push the node on the stack // and traverse // -- create node to add final File file = new File(new String(unit.getFileName())); final IProgramElement cuNode; { // AMC - use the source start and end from the compilation unit decl int startLine = getStartLine(unit); int endLine = getEndLine(unit); SourceLocation sourceLocation = new SourceLocation(file, startLine, endLine); sourceLocation.setOffset(unit.sourceStart); cuNode = new ProgramElement( new String(file.getName()), IProgramElement.Kind.FILE_JAVA, sourceLocation, 0, "", new ArrayList()); } cuNode.addChild(new ProgramElement( "import declarations", IProgramElement.Kind.IMPORT_REFERENCE, null, 0, "", new ArrayList())); final IProgramElement addToNode = genAddToNode(unit, structureModel); // -- remove duplicates before adding (XXX use them instead?) if (addToNode!=null && addToNode.getChildren()!=null) { for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) { IProgramElement child = (IProgramElement)itt.next(); ISourceLocation childLoc = child.getSourceLocation(); if (null == childLoc) { // XXX ok, packages have null source locations // signal others? } else if (childLoc.getSourceFile().equals(file)) { itt.remove(); } } } // -- add and traverse addToNode.addChild(cuNode); stack.push(cuNode); unit.traverse(this, unit.scope); // -- update file map (XXX do this before traversal?) try { structureModel.addToFileMap(file.getCanonicalPath(), cuNode); } catch (IOException e) { System.err.println("IOException " + e.getMessage() + " creating path for " + file ); // XXX signal IOException when canonicalizing file path } } /** * Get/create the node (package or root) to add to. */ private IProgramElement genAddToNode( CompilationUnitDeclaration unit, IHierarchy structureModel) { final IProgramElement addToNode; { ImportReference currentPackage = unit.currentPackage; if (null == currentPackage) { addToNode = structureModel.getRoot(); } else { String pkgName; { StringBuffer nameBuffer = new StringBuffer(); final char[][] importName = currentPackage.getImportName(); final int last = importName.length-1; for (int i = 0; i < importName.length; i++) { nameBuffer.append(new String(importName[i])); if (i < last) { nameBuffer.append('.'); } } pkgName = nameBuffer.toString(); } IProgramElement pkgNode = null; if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) { for (Iterator it = structureModel.getRoot().getChildren().iterator(); it.hasNext(); ) { IProgramElement currNode = (IProgramElement)it.next(); if (pkgName.equals(currNode.getName())) { pkgNode = currNode; break; } } } if (pkgNode == null) { // note packages themselves have no source location pkgNode = new ProgramElement( pkgName, IProgramElement.Kind.PACKAGE, new ArrayList() ); structureModel.getRoot().addChild(pkgNode); } addToNode = pkgNode; } } return addToNode; } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { String name = new String(typeDeclaration.name); IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT; else if (typeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE; else if (typeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM; else if (typeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION; //@AJ support if (typeDeclaration.annotations != null) { for (int i = 0; i < typeDeclaration.annotations.length; i++) { Annotation annotation = typeDeclaration.annotations[i]; if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(), "Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) { kind = IProgramElement.Kind.ASPECT; } } } int typeModifiers = typeDeclaration.modifiers; if (typeDeclaration instanceof AspectDeclaration) { typeModifiers = ((AspectDeclaration)typeDeclaration).getDeclaredModifiers(); } IProgramElement peNode = new ProgramElement( name, kind, makeLocation(typeDeclaration), typeModifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(typeDeclaration)); peNode.setFormalComment(generateJavadocComment(typeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { stack.pop(); } // ??? share impl with visit(TypeDeclaration, ..) ? public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { String name = new String(memberTypeDeclaration.name); IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT; else if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE; else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM; else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION; //@AJ support if (memberTypeDeclaration.annotations != null) { for (int i = 0; i < memberTypeDeclaration.annotations.length; i++) { Annotation annotation = memberTypeDeclaration.annotations[i]; if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(), "Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) { kind = IProgramElement.Kind.ASPECT; } } } int typeModifiers = memberTypeDeclaration.modifiers; if (memberTypeDeclaration instanceof AspectDeclaration) { typeModifiers = ((AspectDeclaration)memberTypeDeclaration).getDeclaredModifiers(); } IProgramElement peNode = new ProgramElement( name, kind, makeLocation(memberTypeDeclaration), typeModifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration)); peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { stack.pop(); } public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) { String fullName = "<undefined>"; if (memberTypeDeclaration.allocation != null && memberTypeDeclaration.allocation.type != null) { // Create a name something like 'new Runnable() {..}' fullName = "new "+memberTypeDeclaration.allocation.type.toString()+"() {..}"; } else if (memberTypeDeclaration.binding != null && memberTypeDeclaration.binding.constantPoolName() != null) { // If we couldn't find a nice name like 'new Runnable() {..}' then use the number after the $ fullName = new String(memberTypeDeclaration.binding.constantPoolName()); int dollar = fullName.indexOf('$'); fullName = fullName.substring(dollar+1); } IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE; else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM; else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION; //@AJ support if (memberTypeDeclaration.annotations != null) { for (int i = 0; i < memberTypeDeclaration.annotations.length; i++) { Annotation annotation = memberTypeDeclaration.annotations[i]; if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(), "Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) { kind = IProgramElement.Kind.ASPECT; break; } } } IProgramElement peNode = new ProgramElement( fullName, kind, makeLocation(memberTypeDeclaration), memberTypeDeclaration.modifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration)); peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration memberTypeDeclaration, BlockScope scope) { stack.pop(); } private String genSourceSignature(TypeDeclaration typeDeclaration) { StringBuffer output = new StringBuffer(); typeDeclaration.printHeader(0, output); 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(); } public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { IProgramElement peNode = null; // For intertype decls, use the modifiers from the original signature, not the generated method if (methodDeclaration instanceof InterTypeDeclaration) { InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration; ResolvedMember sig = itd.getSignature(); peNode = new ProgramElement( "", IProgramElement.Kind.ERROR, makeLocation(methodDeclaration), (sig!=null?sig.getModifiers():0), "", new ArrayList()); } else { peNode = new ProgramElement( "", IProgramElement.Kind.ERROR, makeLocation(methodDeclaration), methodDeclaration.modifiers, "", new ArrayList()); } formatter.genLabelAndKind(methodDeclaration, peNode); genBytecodeInfo(methodDeclaration, peNode); List namedPointcuts = genNamedPointcuts(methodDeclaration); addUsesPointcutRelationsForNode(peNode, namedPointcuts, methodDeclaration); if (methodDeclaration.returnType!=null) { peNode.setCorrespondingType(methodDeclaration.returnType.toString()); } else { peNode.setCorrespondingType(null); } peNode.setSourceSignature(genSourceSignature(methodDeclaration)); peNode.setFormalComment(generateJavadocComment(methodDeclaration)); // TODO: add return type test if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) { if (peNode.toLabelString().equals("main(String[])") && peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC) && peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) { ((IProgramElement)stack.peek()).setRunnable(true); } } stack.push(peNode); return true; } private void addUsesPointcutRelationsForNode(IProgramElement peNode, List namedPointcuts, MethodDeclaration declaration) { for (Iterator it = namedPointcuts.iterator(); it.hasNext();) { ReferencePointcut rp = (ReferencePointcut) it.next(); ResolvedMember member = getPointcutDeclaration(rp, declaration); if (member != null) { IRelationship foreward = AsmManager.getDefault().getRelationshipMap().get(peNode.getHandleIdentifier(), IRelationship.Kind.USES_POINTCUT, "uses pointcut", false, true); foreward.addTarget(AsmManager.getDefault().getHandleProvider().createHandleIdentifier(member.getSourceLocation())); IRelationship back = AsmManager.getDefault().getRelationshipMap().get(AsmManager.getDefault().getHandleProvider().createHandleIdentifier(member.getSourceLocation()), IRelationship.Kind.USES_POINTCUT, "pointcut used by", false, true); back.addTarget(peNode.getHandleIdentifier()); } } } private ResolvedMember getPointcutDeclaration(ReferencePointcut rp, MethodDeclaration declaration) { EclipseFactory factory = ((AjLookupEnvironment)declaration.scope.environment()).factory; World world = factory.getWorld(); UnresolvedType onType = rp.onType; if (onType == null) { if (declaration.binding != null) { Member member = factory.makeResolvedMember(declaration.binding); onType = member.getDeclaringType(); } else { return null; } } ResolvedMember[] members = onType.resolve(world).getDeclaredPointcuts(); if (members != null) { for (int i = 0; i < members.length; i++) { if (members[i].getName().equals(rp.name)) { return members[i]; } } } return null; } /** * @param methodDeclaration * @return all of the named pointcuts referenced by the PCD of this declaration */ private List genNamedPointcuts(MethodDeclaration methodDeclaration) { List pointcuts = new ArrayList(); if (methodDeclaration instanceof AdviceDeclaration) { if (((AdviceDeclaration)methodDeclaration).pointcutDesignator != null) addAllNamed(((AdviceDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts); } else if (methodDeclaration instanceof PointcutDeclaration) { if (((PointcutDeclaration)methodDeclaration).pointcutDesignator != null) addAllNamed(((PointcutDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts); } return pointcuts; } /** * @param left * @param pointcuts accumulator for named pointcuts */ private void addAllNamed(Pointcut pointcut, List pointcuts) { if (pointcut == null) return; if (pointcut instanceof ReferencePointcut) { ReferencePointcut rp = (ReferencePointcut)pointcut; pointcuts.add(rp); } else if (pointcut instanceof AndPointcut) { AndPointcut ap = (AndPointcut)pointcut; addAllNamed(ap.getLeft(), pointcuts); addAllNamed(ap.getRight(), pointcuts); } else if (pointcut instanceof OrPointcut) { OrPointcut op = (OrPointcut)pointcut; addAllNamed(op.getLeft(), pointcuts); addAllNamed(op.getRight(), pointcuts); } } private String genSourceSignature(MethodDeclaration methodDeclaration) { StringBuffer output = new StringBuffer(); ASTNode.printModifiers(methodDeclaration.modifiers, output); methodDeclaration.printReturnType(0, output).append(methodDeclaration.selector).append('('); if (methodDeclaration.arguments != null) { for (int i = 0; i < methodDeclaration.arguments.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ methodDeclaration.arguments[i].print(0, output); } } output.append(')'); if (methodDeclaration.thrownExceptions != null) { output.append(" throws "); //$NON-NLS-1$ for (int i = 0; i < methodDeclaration.thrownExceptions.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ methodDeclaration.thrownExceptions[i].print(0, output); } } return output.toString(); } protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) { if (methodDeclaration.binding != null) { String memberName = ""; String memberBytecodeSignature = ""; try { EclipseFactory factory = ((AjLookupEnvironment)methodDeclaration.scope.environment()).factory; Member member = factory.makeResolvedMember(methodDeclaration.binding); memberName = member.getName(); memberBytecodeSignature = member.getSignature(); } catch (BCException bce) { // bad type name memberName = "<undefined>"; } catch (NullPointerException npe) { memberName = "<undefined>"; } peNode.setBytecodeName(memberName); peNode.setBytecodeSignature(memberBytecodeSignature); } ((IProgramElement)stack.peek()).addChild(peNode); } public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) { stack.pop(); } public boolean visit(ImportReference importRef, CompilationUnitScope scope) { int dotIndex = importRef.toString().lastIndexOf('.'); String currPackageImport = ""; if (dotIndex != -1) { currPackageImport = importRef.toString().substring(0, dotIndex); } if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) { IProgramElement peNode = new ProgramElement( new String(importRef.toString()), IProgramElement.Kind.IMPORT_REFERENCE, makeLocation(importRef), 0, "", new ArrayList()); ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0); imports.addChild(0, peNode); stack.push(peNode); } return true; } public void endVisit(ImportReference importRef, CompilationUnitScope scope) { int dotIndex = importRef.toString().lastIndexOf('.'); String currPackageImport = ""; if (dotIndex != -1) { currPackageImport = importRef.toString().substring(0, dotIndex); } if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) { stack.pop(); } } public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { IProgramElement peNode = null; if (fieldDeclaration.type == null) { // The field represents an enum value peNode = new ProgramElement( new String(fieldDeclaration.name),IProgramElement.Kind.ENUM_VALUE, makeLocation(fieldDeclaration), fieldDeclaration.modifiers, "", new ArrayList()); peNode.setCorrespondingType(fieldDeclaration.binding.type.debugName()); } else { peNode = new ProgramElement( new String(fieldDeclaration.name),IProgramElement.Kind.FIELD, makeLocation(fieldDeclaration), fieldDeclaration.modifiers, "", new ArrayList()); peNode.setCorrespondingType(fieldDeclaration.type.toString()); } peNode.setSourceSignature(genSourceSignature(fieldDeclaration)); peNode.setFormalComment(generateJavadocComment(fieldDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) { stack.pop(); } /** * Checks if comments should be added to the model before generating. */ protected String generateJavadocComment(ASTNode astNode) { if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null; StringBuffer sb = new StringBuffer(); // !!! specify length? boolean completed = false; int startIndex = -1; if (astNode instanceof MethodDeclaration) { startIndex = ((MethodDeclaration)astNode).declarationSourceStart; } else if (astNode instanceof FieldDeclaration) { startIndex = ((FieldDeclaration)astNode).declarationSourceStart; } else if (astNode instanceof TypeDeclaration) { startIndex = ((TypeDeclaration)astNode).declarationSourceStart; } if (startIndex == -1) { return null; } else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /** && currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*' && currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') { for (int i = startIndex; i < astNode.sourceStart && !completed; i++) { char curr = currCompilationResult.compilationUnit.getContents()[i]; if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */ sb.append(currCompilationResult.compilationUnit.getContents()[i]); } return sb.toString(); } else { return null; } } /** * Doesn't print qualified allocation expressions. */ protected String genSourceSignature(FieldDeclaration fieldDeclaration) { StringBuffer output = new StringBuffer(); if (fieldDeclaration.type == null) { // This is an enum value output.append(fieldDeclaration.name); // the "," or ";" has to be put on by whatever uses the sourceSignature return output.toString(); } else { FieldDeclaration.printModifiers(fieldDeclaration.modifiers, output); fieldDeclaration.type.print(0, output).append(' ').append(fieldDeclaration.name); } if (fieldDeclaration.initialization != null && !(fieldDeclaration.initialization instanceof QualifiedAllocationExpression)) { output.append(" = "); //$NON-NLS-1$ if (fieldDeclaration.initialization instanceof ExtendedStringLiteral) { output.append("\"<extended string literal>\""); } else { fieldDeclaration.initialization.printExpression(0, output); } } output.append(';'); return output.toString(); } // public boolean visit(ImportReference importRef, CompilationUnitScope scope) { // ProgramElementNode peNode = new ProgramElementNode( // new String(importRef.toString()), // ProgramElementNode.Kind., // makeLocation(importRef), // 0, // "", // new ArrayList()); // ((IProgramElement)stack.peek()).addChild(0, peNode); // stack.push(peNode); // return true; // } // public void endVisit(ImportReference importRef,CompilationUnitScope scope) { // stack.pop(); // } public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { if (constructorDeclaration.isDefaultConstructor) { stack.push(null); // a little wierd but does the job return true; } StringBuffer argumentsSignature = new StringBuffer(); argumentsSignature.append("("); if (constructorDeclaration.arguments!=null) { for (int i = 0;i<constructorDeclaration.arguments.length;i++) { argumentsSignature.append(constructorDeclaration.arguments[i].type); if (i+1<constructorDeclaration.arguments.length) argumentsSignature.append(","); } } argumentsSignature.append(")"); IProgramElement peNode = new ProgramElement( new String(constructorDeclaration.selector)+argumentsSignature, IProgramElement.Kind.CONSTRUCTOR, makeLocation(constructorDeclaration), constructorDeclaration.modifiers, "", new ArrayList()); peNode.setModifiers(constructorDeclaration.modifiers); peNode.setSourceSignature(genSourceSignature(constructorDeclaration)); // Fix to enable us to anchor things from ctor nodes if (constructorDeclaration.binding != null) { String memberName = ""; String memberBytecodeSignature = ""; try { EclipseFactory factory = ((AjLookupEnvironment)constructorDeclaration.scope.environment()).factory; Member member = factory.makeResolvedMember(constructorDeclaration.binding); memberName = member.getName(); memberBytecodeSignature = member.getSignature(); } catch (BCException bce) { // bad type name memberName = "<undefined>"; } catch (NullPointerException npe) { memberName = "<undefined>"; } peNode.setBytecodeName(memberName); peNode.setBytecodeSignature(memberBytecodeSignature); } ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { stack.pop(); } private String genSourceSignature(ConstructorDeclaration constructorDeclaration) { StringBuffer output = new StringBuffer(); ASTNode.printModifiers(constructorDeclaration.modifiers, output); output.append(constructorDeclaration.selector).append('('); if (constructorDeclaration.arguments != null) { for (int i = 0; i < constructorDeclaration.arguments.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ constructorDeclaration.arguments[i].print(0, output); } } output.append(')'); if (constructorDeclaration.thrownExceptions != null) { output.append(" throws "); //$NON-NLS-1$ for (int i = 0; i < constructorDeclaration.thrownExceptions.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ constructorDeclaration.thrownExceptions[i].print(0, output); } } return output.toString(); } // public boolean visit(Clinit clinit, ClassScope scope) { // ProgramElementNode peNode = new ProgramElementNode( // "<clinit>", // ProgramElementNode.Kind.INITIALIZER, // makeLocation(clinit), // clinit.modifiers, // "", // new ArrayList()); // ((IProgramElement)stack.peek()).addChild(peNode); // stack.push(peNode); // return false; // } // public void endVisit(Clinit clinit, ClassScope scope) { // stack.pop(); // } /** This method works-around an odd traverse implementation on Initializer */ private Initializer inInitializer = null; public boolean visit(Initializer initializer, MethodScope scope) { if (initializer == inInitializer) return false; inInitializer = initializer; IProgramElement peNode = new ProgramElement( "...", IProgramElement.Kind.INITIALIZER, makeLocation(initializer), initializer.modifiers, "", new ArrayList()); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); initializer.block.traverse(this, scope); stack.pop(); return false; } // ??? handle non-existant files protected ISourceLocation makeLocation(ASTNode node) { String fileName = ""; if (currCompilationResult.getFileName() != null) { fileName = new String(currCompilationResult.getFileName()); } // AMC - different strategies based on node kind int startLine = getStartLine(node); int endLine = getEndLine(node); SourceLocation loc = null; if ( startLine <= endLine ) { // found a valid end line for this node... loc = new SourceLocation(new File(fileName), startLine, endLine); loc.setOffset(node.sourceStart); } else { loc = new SourceLocation(new File(fileName), startLine); loc.setOffset(node.sourceStart); } return loc; } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! protected int getStartLine( ASTNode n){ // if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n); // if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n); // if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n); return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, n.sourceStart); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! protected int getEndLine( ASTNode n){ if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n); if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n); if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n); return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, n.sourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( AbstractVariableDeclaration avd ) { // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // avd.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( AbstractVariableDeclaration avd ){ return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, avd.declarationSourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( AbstractMethodDeclaration amd ){ // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // amd.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( AbstractMethodDeclaration amd) { return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, amd.declarationSourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( TypeDeclaration td ){ // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // td.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( TypeDeclaration td){ return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, td.declarationSourceEnd); } }
77,269
Bug 77269 Advice on inner classes not show in Outline view or gutter
Advice associated with pointcuts that match join points in inner classes are not shown. Declare warning/error are shown however. See attached screenshot for example below. Notice WEAVEINFO messages indicate problem is in AJDT not AspectJ. Also notice phantom entry in Outline view "injar aspectL Test.java". package bug_nnnnn; public class Test { public void test () { new Runnable() { public void run() { try { throw new Exception(); } catch (Exception ex) { handleException(ex); } } }; } public static void handleException (Throwable th) { } public static void main(String[] args) { try { throw new Exception(); } catch (Exception ex) { handleException(ex); } } } aspect Aspect { declare warning : call(void handleException(..)) && !within(Aspect) : "Only Aspect should handle exceptions"; pointcut caughtExceptions (Throwable th) : handler(Throwable+) && args(th); before (Throwable th) : caughtExceptions(th) { Test.handleException(th); } }
resolved fixed
4573068
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-04T08:05:55Z
2004-10-29T11:40:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } /* Andys bug area - enter at your own risk... public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");} public void testMissingAccessor_pr73856() { runTest("missing accessor");} public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");} public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");} public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");} */ public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");} public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");} public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");} public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");} public void testBadGenericSigAttribute_pr110927() { runTest("cant create signature attribute"); Signature sig = GenericsTests.getClassSignature(ajc,"I"); if (sig==null) fail("Couldn't find signature attribute for type I"); String sigString = sig.getSignature(); if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") || sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) { fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"); } } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");} public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } // IfPointcut.findResidueInternal() was modified to make this test complete in a short amount // of time - if you see it hanging, someone has messed with the optimization. public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");} public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testAtAnnotationBadTest_pr103740() { runTest("Compiler failure on at_annotation"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } public void testNoVerifyErrorOnGenericCollectionMemberAccess() { runTest("no verify error on generic collection member access"); } public void testRawAndGenericTypeConversionITDCons() { runTest("raw and generic type conversion with itd cons"); } public void testAtAnnotationBindingWithAround() { runTest("@annotation binding with around advice"); } public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");} public void testMessageOnMissingTypeInDecP() { runTest("declare parents on a missing type"); } public void testParameterizedGenericMethods() { runTest("parameterized generic methods"); } public void testCallJoinPointsInAnonymousInnerClasses() { runTest("call join points in anonymous inner classes"); } public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() { runTest("default impl of Runnable"); } public void testArrayCloneCallJoinPoints() { runTest("array clone call join points in 1.4 vs 1.3"); } public void testDebugInfoForAroundAdvice() { runTest("debug info in around advice inlining"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
111,481
Bug 111481 varargs doesn't work for ITD'd constructors
null
resolved fixed
2b0e675
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T08:12:20Z
2005-10-04T15:33:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeConstructorDeclaration.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import org.aspectj.ajdt.internal.compiler.lookup.*; import org.aspectj.weaver.*; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.*; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.*; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; /** * An inter-type constructor declaration. * * This will generate two implementation methods in the aspect, the main one for the body * of the constructor, and an additional <code>preMethod</code> for the code that * runs before the super constructor is called. * * @author Jim Hugunin */ public class InterTypeConstructorDeclaration extends InterTypeDeclaration { private MethodDeclaration preMethod; private ExplicitConstructorCall explicitConstructorCall = null; public InterTypeConstructorDeclaration(CompilationResult result, TypeReference onType) { super(result, onType); } public void parseStatements(Parser parser, CompilationUnitDeclaration unit) { if (ignoreFurtherInvestigation) return; parser.parse(this, unit); } protected char[] getPrefix() { return (NameMangler.ITD_PREFIX + "interConstructor$").toCharArray(); } public void resolve(ClassScope upperScope) { if (munger == null || binding == null) ignoreFurtherInvestigation = true; if (ignoreFurtherInvestigation) return; explicitConstructorCall = null; if (statements != null && statements.length > 0 && statements[0] instanceof ExplicitConstructorCall) { explicitConstructorCall = (ExplicitConstructorCall) statements[0]; statements = AstUtil.remove(0, statements); } preMethod = makePreMethod(upperScope, explicitConstructorCall); binding.parameters = AstUtil.insert(onTypeBinding, binding.parameters); this.arguments = AstUtil.insert( AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding), this.arguments); super.resolve(upperScope); } private MethodDeclaration makePreMethod(ClassScope scope, ExplicitConstructorCall explicitConstructorCall) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); UnresolvedType aspectTypeX = world.fromBinding(binding.declaringClass); UnresolvedType targetTypeX = world.fromBinding(onTypeBinding); ArrayBinding objectArrayBinding = scope.createArrayType(scope.getJavaLangObject(), 1); MethodDeclaration pre = new MethodDeclaration(compilationResult); pre.modifiers = AccPublic | AccStatic; pre.returnType = AstUtil.makeTypeReference(objectArrayBinding); pre.selector = NameMangler.postIntroducedConstructor(aspectTypeX, targetTypeX).toCharArray(); pre.arguments = AstUtil.copyArguments(this.arguments); //XXX should do exceptions pre.scope = new MethodScope(scope, pre, true); //??? do we need to do anything with scope??? // Use the factory to build a semi-correct resolvedmember - then patch it up with // reset calls. This is SAFE ResolvedMember preIntroducedConstructorRM = world.makeResolvedMember(binding); preIntroducedConstructorRM.resetName(NameMangler.preIntroducedConstructor(aspectTypeX, targetTypeX)); preIntroducedConstructorRM.resetModifiers(Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL); preIntroducedConstructorRM.resetReturnTypeToObjectArray(); pre.binding = world.makeMethodBinding(preIntroducedConstructorRM); pre.bindArguments(); pre.bindThrownExceptions(); if (explicitConstructorCall == null) { pre.statements = new Statement[] {}; } else { pre.statements = new Statement[] { explicitConstructorCall }; } InterTypeScope newParent = new InterTypeScope(scope, onTypeBinding); pre.scope.parent = newParent; pre.resolveStatements(); //newParent); int nParams = pre.arguments.length; MethodBinding explicitConstructor = null; if (explicitConstructorCall != null) { explicitConstructor = explicitConstructorCall.binding; if (explicitConstructor.alwaysNeedsAccessMethod()) { explicitConstructor = explicitConstructor.getAccessMethod(true); } } int nExprs; if (explicitConstructor == null) nExprs = 0; else nExprs = explicitConstructor.parameters.length; ArrayInitializer init = new ArrayInitializer(); init.expressions = new Expression[nExprs + nParams]; int index = 0; for (int i=0; i < nExprs; i++) { if (i >= explicitConstructorCall.arguments.length) { init.expressions[index++] = new NullLiteral(0, 0); continue; } Expression arg = explicitConstructorCall.arguments[i]; ResolvedMember conversionMethod = AjcMemberMaker.toObjectConversionMethod(world.fromBinding(explicitConstructorCall.binding.parameters[i])); if (conversionMethod != null) { arg = new KnownMessageSend(world.makeMethodBindingForCall(conversionMethod), new CastExpression(new NullLiteral(0, 0), AstUtil.makeTypeReference(world.makeTypeBinding(AjcMemberMaker.CONVERSIONS_TYPE))), new Expression[] {arg }); } init.expressions[index++] = arg; } for (int i=0; i < nParams; i++) { LocalVariableBinding binding = pre.arguments[i].binding; Expression arg = AstUtil.makeResolvedLocalVariableReference(binding); ResolvedMember conversionMethod = AjcMemberMaker.toObjectConversionMethod(world.fromBinding(binding.type)); if (conversionMethod != null) { arg = new KnownMessageSend(world.makeMethodBindingForCall(conversionMethod), new CastExpression(new NullLiteral(0, 0), AstUtil.makeTypeReference(world.makeTypeBinding(AjcMemberMaker.CONVERSIONS_TYPE))), new Expression[] {arg }); } init.expressions[index++] = arg; } init.binding =objectArrayBinding; ArrayAllocationExpression newArray = new ArrayAllocationExpression(); newArray.initializer = init; newArray.type = AstUtil.makeTypeReference(scope.getJavaLangObject()); newArray.dimensions = new Expression[1]; newArray.constant = NotAConstant; pre.statements = new Statement[] { new ReturnStatement(newArray, 0, 0), }; return pre; } public EclipseTypeMunger build(ClassScope classScope) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope); resolveOnType(classScope); if (ignoreFurtherInvestigation) return null; binding = classScope.referenceContext.binding.resolveTypesFor(binding); if (isTargetAnnotation(classScope,"constructor")) return null; // Error message output in isTargetAnnotation if (isTargetEnum(classScope,"constructor")) return null; // Error message output in isTargetEnum if (onTypeBinding.isInterface()) { classScope.problemReporter().signalError(sourceStart, sourceEnd, "can't define constructors on interfaces"); ignoreFurtherInvestigation = true; return null; } if (onTypeBinding.isNestedType()) { classScope.problemReporter().signalError(sourceStart, sourceEnd, "can't define constructors on nested types (compiler limitation)"); ignoreFurtherInvestigation = true; return null; } ResolvedType declaringTypeX = world.fromEclipse(onTypeBinding); ResolvedType aspectType = world.fromEclipse(classScope.referenceContext.binding); // This signature represents what we want consumers of the targetted type to 'see' ResolvedMember signature = world.makeResolvedMember(binding,onTypeBinding); signature.resetKind(Member.CONSTRUCTOR); signature.resetName("<init>"); signature.resetModifiers(declaredModifiers); ResolvedMember syntheticInterMember = AjcMemberMaker.interConstructor(declaringTypeX, signature, aspectType); NewConstructorTypeMunger myMunger = new NewConstructorTypeMunger(signature, syntheticInterMember, null, null); setMunger(myMunger); myMunger.check(world.getWorld()); this.selector = binding.selector = NameMangler.postIntroducedConstructor( world.fromBinding(binding.declaringClass), declaringTypeX).toCharArray(); return new EclipseTypeMunger(world, myMunger, aspectType, this); } private AjAttribute makeAttribute(EclipseFactory world) { if (explicitConstructorCall != null && !(explicitConstructorCall.binding instanceof ProblemMethodBinding)) { MethodBinding explicitConstructor = explicitConstructorCall.binding; if (explicitConstructor.alwaysNeedsAccessMethod()) { explicitConstructor = explicitConstructor.getAccessMethod(true); } ((NewConstructorTypeMunger)munger).setExplicitConstructor( world.makeResolvedMember(explicitConstructor)); } else { ((NewConstructorTypeMunger)munger).setExplicitConstructor( new ResolvedMemberImpl(Member.CONSTRUCTOR, world.fromBinding(onTypeBinding.superclass()), 0, ResolvedType.VOID, "<init>", UnresolvedType.NONE)); } return new AjAttribute.TypeMunger(munger); } public void generateCode(ClassScope classScope, ClassFile classFile) { if (ignoreFurtherInvestigation) return; EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope); classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute(world))); super.generateCode(classScope, classFile); preMethod.generateCode(classScope, classFile); } protected Shadow.Kind getShadowKindForBody() { return Shadow.ConstructorExecution; } }
111,481
Bug 111481 varargs doesn't work for ITD'd constructors
null
resolved fixed
2b0e675
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T08:12:20Z
2005-10-04T15:33:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.internal.Relationship; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } /* Andys bug area - enter at your own risk... public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");} public void testMissingAccessor_pr73856() { runTest("missing accessor");} public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");} public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");} public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");} */ public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");} public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");} public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");} public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");} public void testVarargsITD_pr110906() { runTest("ITD varargs problem");} public void testBadGenericSigAttribute_pr110927() { runTest("cant create signature attribute"); Signature sig = GenericsTests.getClassSignature(ajc,"I"); if (sig==null) fail("Couldn't find signature attribute for type I"); String sigString = sig.getSignature(); if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") || sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) { fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"); } } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");} public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } // IfPointcut.findResidueInternal() was modified to make this test complete in a short amount // of time - if you see it hanging, someone has messed with the optimization. public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");} public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testAtAnnotationBadTest_pr103740() { runTest("Compiler failure on at_annotation"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } public void testNoVerifyErrorOnGenericCollectionMemberAccess() { runTest("no verify error on generic collection member access"); } public void testRawAndGenericTypeConversionITDCons() { runTest("raw and generic type conversion with itd cons"); } public void testAtAnnotationBindingWithAround() { runTest("@annotation binding with around advice"); } public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");} public void testMessageOnMissingTypeInDecP() { runTest("declare parents on a missing type"); } public void testParameterizedGenericMethods() { runTest("parameterized generic methods"); } public void testCallJoinPointsInAnonymousInnerClasses() { runTest("call join points in anonymous inner classes"); } public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() { runTest("default impl of Runnable"); } public void testArrayCloneCallJoinPoints() { runTest("array clone call join points in 1.4 vs 1.3"); } public void testDebugInfoForAroundAdvice() { runTest("debug info in around advice inlining"); } public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the run() method inside anonymous inner class is in // the structure model IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"run()"); assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'run()' but is " + target.toLabelString(),"run()",target.toLabelString()); } public void testAdviceInStructureModelWithNamedInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with named inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the m() method inside named inner class is in // the structure model IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"m()"); assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'm()' but is " + target.toLabelString(),"m()",target.toLabelString()); } public void testDWInStructureModelWithAnonymousInnerClass_pr77269() { // AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("declare warning in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())"); assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/AnnotationPatternList.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class AnnotationPatternList extends PatternNode { private AnnotationTypePattern[] typePatterns; int ellipsisCount = 0; public static final AnnotationPatternList EMPTY = new AnnotationPatternList(new AnnotationTypePattern[] {}); public static final AnnotationPatternList ANY = new AnnotationPatternList(new AnnotationTypePattern[] {AnnotationTypePattern.ELLIPSIS}); public AnnotationPatternList() { typePatterns = new AnnotationTypePattern[0]; ellipsisCount = 0; } public AnnotationPatternList(AnnotationTypePattern[] arguments) { this.typePatterns = arguments; for (int i=0; i<arguments.length; i++) { if (arguments[i] == AnnotationTypePattern.ELLIPSIS) ellipsisCount++; } } public AnnotationPatternList(List l) { this((AnnotationTypePattern[]) l.toArray(new AnnotationTypePattern[l.size()])); } protected AnnotationTypePattern[] getAnnotationPatterns() { return typePatterns; } public void resolve(World inWorld) { for (int i = 0; i < typePatterns.length; i++) { typePatterns[i].resolve(inWorld); } } public FuzzyBoolean matches(ResolvedType[] someArgs) { // do some quick length tests first int numArgsMatchedByEllipsis = (someArgs.length + ellipsisCount) - typePatterns.length; if (numArgsMatchedByEllipsis < 0) return FuzzyBoolean.NO; if ((numArgsMatchedByEllipsis > 0) && (ellipsisCount == 0)) { return FuzzyBoolean.NO; } // now work through the args and the patterns, skipping at ellipsis FuzzyBoolean ret = FuzzyBoolean.YES; int argsIndex = 0; for (int i = 0; i < typePatterns.length; i++) { if (typePatterns[i] == AnnotationTypePattern.ELLIPSIS) { // match ellipsisMatchCount args argsIndex += numArgsMatchedByEllipsis; } else if (typePatterns[i] == AnnotationTypePattern.ANY) { argsIndex++; } else { // match the argument type at argsIndex with the ExactAnnotationTypePattern // we know it is exact because nothing else is allowed in args if (someArgs[argsIndex].isPrimitiveType()) return FuzzyBoolean.NO; // can never match ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern)typePatterns[i]; FuzzyBoolean matches = ap.matchesRuntimeType(someArgs[argsIndex]); if (matches == FuzzyBoolean.NO) { return FuzzyBoolean.MAYBE; // could still match at runtime } else { argsIndex++; ret = ret.and(matches); } } } return ret; } public int size() { return typePatterns.length; } public AnnotationTypePattern get(int index) { return typePatterns[index]; } public AnnotationPatternList resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { for (int i=0; i<typePatterns.length; i++) { AnnotationTypePattern p = typePatterns[i]; if (p != null) { typePatterns[i] = typePatterns[i].resolveBindings(scope, bindings, allowBinding); } } return this; } public AnnotationPatternList resolveReferences(IntMap bindings) { int len = typePatterns.length; AnnotationTypePattern[] ret = new AnnotationTypePattern[len]; for (int i=0; i < len; i++) { ret[i] = typePatterns[i].remapAdviceFormals(bindings); } return new AnnotationPatternList(ret); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("("); for (int i=0, len=typePatterns.length; i < len; i++) { AnnotationTypePattern type = typePatterns[i]; if (i > 0) buf.append(", "); if (type == AnnotationTypePattern.ELLIPSIS) { buf.append(".."); } else { String annPatt = type.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); } } buf.append(")"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof AnnotationPatternList)) return false; AnnotationPatternList o = (AnnotationPatternList)other; int len = o.typePatterns.length; if (len != this.typePatterns.length) return false; for (int i=0; i<len; i++) { if (!this.typePatterns[i].equals(o.typePatterns[i])) return false; } return true; } public int hashCode() { int result = 41; for (int i = 0, len = typePatterns.length; i < len; i++) { result = 37*result + typePatterns[i].hashCode(); } return result; } public static AnnotationPatternList read(VersionedDataInputStream s, ISourceContext context) throws IOException { short len = s.readShort(); AnnotationTypePattern[] arguments = new AnnotationTypePattern[len]; for (int i=0; i<len; i++) { arguments[i] = AnnotationTypePattern.read(s, context); } AnnotationPatternList ret = new AnnotationPatternList(arguments); ret.readLocation(context, s); return ret; } public void write(DataOutputStream s) throws IOException { s.writeShort(typePatterns.length); for (int i=0; i<typePatterns.length; i++) { typePatterns[i].write(s); } writeLocation(s); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor, data); for (int i = 0; i < typePatterns.length; i++) { typePatterns[i].traverse(visitor,ret); } return ret; } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/AnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.bcel.BcelTypeMunger; /** * @annotation(@Foo) or @annotation(foo) * * Matches any join point where the subject of the join point has an * annotation matching the annotationTypePattern: * * Join Point Kind Subject * ================================ * method call the target method * method execution the method * constructor call the constructor * constructor execution the constructor * get the target field * set the target field * adviceexecution the advice * initialization the constructor * preinitialization the constructor * staticinitialization the type being initialized * handler the declared type of the handled exception */ public class AnnotationPointcut extends NameBindingPointcut { private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger = null; // only set after concretization public AnnotationPointcut(ExactAnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = Pointcut.ANNOTATION; } public AnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; } public ExactAnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { if (info.getKind() == Shadow.StaticInitialization) { return annotationTypePattern.fastMatches(info.getType()); } else { return FuzzyBoolean.MAYBE; } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { AnnotatedElement toMatchAgainst = null; Member member = shadow.getSignature(); ResolvedMember rMember = member.resolve(shadow.getIWorld()); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } Shadow.Kind kind = shadow.getKind(); if (kind == Shadow.StaticInitialization) { toMatchAgainst = rMember.getDeclaringType().resolve(shadow.getIWorld()); } else if ( (kind == Shadow.ExceptionHandler)) { toMatchAgainst = rMember.getParameterTypes()[0].resolve(shadow.getIWorld()); } else { toMatchAgainst = rMember; // FIXME asc I'd like to get rid of this bit of logic altogether, shame ITD fields don't have an effective sig attribute // FIXME asc perf cache the result of discovering the member that contains the real annotations if (rMember.isAnnotatedElsewhere()) { if (kind==Shadow.FieldGet || kind==Shadow.FieldSet) { List mungers = rMember.getDeclaringType().resolve(shadow.getIWorld()).getInterTypeMungers(); // FIXME asc should include supers with getInterTypeMungersIncludingSupers? for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); if (fakerm.equals(member)) { ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); toMatchAgainst = rmm; } } } } } } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(toMatchAgainst); } private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); for (int i = 0; i < decMethods.length; i++) { ResolvedMember member = decMethods[i]; if (member.equals(ajcMethod)) return member; } return null; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new AnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.getAnnotationType(); Var var = shadow.getKindedAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]");//return Literal.FALSE; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId == shadow.shadowId)) { // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use @pointcut to match at this location and bind a formal to type '"+var.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic binding.", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } state.set(btp.getFormalIndex(),var); } if (matchInternal(shadow).alwaysTrue()) return Literal.TRUE; else return Literal.FALSE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ANNOTATION); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); AnnotationPointcut ret = new AnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof AnnotationPointcut)) return false; AnnotationPointcut o = (AnnotationPointcut)other; return o.annotationTypePattern.equals(this.annotationTypePattern); } public int hashCode() { int result = 17; result = 37*result + annotationTypePattern.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("@annotation("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); return buf.toString(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/ArgsAnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ArgsAnnotationPointcut extends NameBindingPointcut { private AnnotationPatternList arguments; /** * */ public ArgsAnnotationPointcut(AnnotationPatternList arguments) { super(); this.arguments = arguments; this.pointcutKind = ATARGS; } public AnnotationPatternList getArguments() { return arguments; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; // empty args() matches jps with no args } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { arguments.resolve(shadow.getIWorld()); FuzzyBoolean ret = arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes())); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { arguments.resolveBindings(scope, bindings, true); if (arguments.ellipsisCount > 1) { scope.message(IMessage.ERROR, this, "uses more than one .. in args (compiler limitation)"); } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } AnnotationPatternList list = arguments.resolveReferences(bindings); Pointcut ret = new ArgsAnnotationPointcut(list); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { int len = shadow.getArgCount(); // do some quick length tests first int numArgsMatchedByEllipsis = (len + arguments.ellipsisCount) - arguments.size(); if (numArgsMatchedByEllipsis < 0) return Literal.FALSE; // should never happen if ((numArgsMatchedByEllipsis > 0) && (arguments.ellipsisCount == 0)) { return Literal.FALSE; // should never happen } // now work through the args and the patterns, skipping at ellipsis Test ret = Literal.TRUE; int argsIndex = 0; for (int i = 0; i < arguments.size(); i++) { if (arguments.get(i) == AnnotationTypePattern.ELLIPSIS) { // match ellipsisMatchCount args argsIndex += numArgsMatchedByEllipsis; } else if (arguments.get(i) == AnnotationTypePattern.ANY) { argsIndex++; } else { // match the argument type at argsIndex with the ExactAnnotationTypePattern // we know it is exact because nothing else is allowed in args ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern)arguments.get(i); UnresolvedType argType = shadow.getArgType(argsIndex); ResolvedType rArgType = argType.resolve(shadow.getIWorld()); if (rArgType == ResolvedType.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()), "",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()}); } ResolvedType rAnnType = ap.getAnnotationType().resolve(shadow.getIWorld()); if (ap instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)ap; Var annvar = shadow.getArgAnnotationVar(argsIndex,rAnnType); state.set(btp.getFormalIndex(),annvar); } if (!ap.matches(rArgType).alwaysTrue()) { // we need a test... ret = Test.makeAnd(ret, Test.makeHasAnnotation( shadow.getArgVar(argsIndex), rAnnType)); } argsIndex++; } } return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { List l = new ArrayList(); AnnotationTypePattern[] pats = arguments.getAnnotationPatterns(); for (int i = 0; i < pats.length; i++) { if (pats[i] instanceof BindingAnnotationTypePattern) { l.add(pats[i]); } } return l; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATARGS); arguments.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationPatternList annotationPatternList = AnnotationPatternList.read(s,context); ArgsAnnotationPointcut ret = new ArgsAnnotationPointcut(annotationPatternList); ret.readLocation(context, s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof ArgsAnnotationPointcut)) return false; ArgsAnnotationPointcut other = (ArgsAnnotationPointcut) obj; return other.arguments.equals(arguments); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37*arguments.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer("@args"); buf.append(arguments.toString()); return buf.toString(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/ArgsPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BetaException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; /** * args(arguments) * * @author Erik Hilsdale * @author Jim Hugunin */ public class ArgsPointcut extends NameBindingPointcut { private static final String ASPECTJ_JP_SIGNATURE_PREFIX = "Lorg/aspectj/lang/JoinPoint"; private static final String ASPECTJ_SYNTHETIC_SIGNATURE_PREFIX = "Lorg/aspectj/runtime/internal/"; private TypePatternList arguments; public ArgsPointcut(TypePatternList arguments) { this.arguments = arguments; this.pointcutKind = ARGS; } public TypePatternList getArguments() { return arguments; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; // empty args() matches jps with no args } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedType[] argumentsToMatchAgainst = getArgumentsToMatchAgainst(shadow); FuzzyBoolean ret = arguments.matches(argumentsToMatchAgainst, TypePattern.DYNAMIC); return ret; } private ResolvedType[] getArgumentsToMatchAgainst(Shadow shadow) { ResolvedType[] argumentsToMatchAgainst = shadow.getIWorld().resolve(shadow.getGenericArgTypes()); // special treatment for adviceexecution which may have synthetic arguments we // want to ignore. if (shadow.getKind() == Shadow.AdviceExecution) { int numExtraArgs = 0; for (int i = 0; i < argumentsToMatchAgainst.length; i++) { String argumentSignature = argumentsToMatchAgainst[i].getSignature(); if (argumentSignature.startsWith(ASPECTJ_JP_SIGNATURE_PREFIX) || argumentSignature.startsWith(ASPECTJ_SYNTHETIC_SIGNATURE_PREFIX)) { numExtraArgs++; } else { // normal arg after AJ type means earlier arg was NOT synthetic numExtraArgs = 0; } } if (numExtraArgs > 0) { int newArgLength = argumentsToMatchAgainst.length - numExtraArgs; ResolvedType[] argsSubset = new ResolvedType[newArgLength]; System.arraycopy(argumentsToMatchAgainst, 0, argsSubset, 0, newArgLength); argumentsToMatchAgainst = argsSubset; } } else if (shadow.getKind() == Shadow.ConstructorExecution) { if (shadow.getMatchingSignature().getParameterTypes().length < argumentsToMatchAgainst.length) { // there are one or more synthetic args on the end, caused by non-public itd constructor int newArgLength = shadow.getMatchingSignature().getParameterTypes().length; ResolvedType[] argsSubset = new ResolvedType[newArgLength]; System.arraycopy(argumentsToMatchAgainst, 0, argsSubset, 0, newArgLength); argumentsToMatchAgainst = argsSubset; } } return argumentsToMatchAgainst; } /** * @param ret * @param pTypes * @return */ private FuzzyBoolean checkSignatureMatch(Class[] pTypes) { Collection tps = arguments.getExactTypes(); int sigIndex = 0; for (Iterator iter = tps.iterator(); iter.hasNext();) { UnresolvedType tp = (UnresolvedType) iter.next(); Class lookForClass = getPossiblyBoxed(tp); if (lookForClass != null) { boolean foundMatchInSig = false; while (sigIndex < pTypes.length && !foundMatchInSig) { if (pTypes[sigIndex++] == lookForClass) foundMatchInSig = true; } if (!foundMatchInSig) { return FuzzyBoolean.NO; } } } return FuzzyBoolean.YES; } private Class getPossiblyBoxed(UnresolvedType tp) { Class ret = (Class) ExactTypePattern.primitiveTypesMap.get(tp.getName()); if (ret == null) ret = (Class) ExactTypePattern.boxedPrimitivesMap.get(tp.getName()); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { List l = new ArrayList(); TypePattern[] pats = arguments.getTypePatterns(); for (int i = 0; i < pats.length; i++) { if (pats[i] instanceof BindingTypePattern) { l.add(pats[i]); } } return l; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ARGS); arguments.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { ArgsPointcut ret = new ArgsPointcut(TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof ArgsPointcut)) return false; ArgsPointcut o = (ArgsPointcut)other; return o.arguments.equals(this.arguments); } public int hashCode() { return arguments.hashCode(); } public void resolveBindings(IScope scope, Bindings bindings) { arguments.resolveBindings(scope, bindings, true, true); if (arguments.ellipsisCount > 1) { scope.message(IMessage.ERROR, this, "uses more than one .. in args (compiler limitation)"); } } public void postRead(ResolvedType enclosingType) { arguments.postRead(enclosingType); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } TypePatternList args = arguments.resolveReferences(bindings); if (inAspect.crosscuttingMembers != null) { inAspect.crosscuttingMembers.exposeTypes(args.getExactTypes()); } Pointcut ret = new ArgsPointcut(args); ret.copyLocationFrom(this); return ret; } private Test findResidueNoEllipsis(Shadow shadow, ExposedState state, TypePattern[] patterns) { ResolvedType[] argumentsToMatchAgainst = getArgumentsToMatchAgainst(shadow); int len = argumentsToMatchAgainst.length; //System.err.println("boudn to : " + len + ", " + patterns.length); if (patterns.length != len) { return Literal.FALSE; } Test ret = Literal.TRUE; for (int i=0; i < len; i++) { UnresolvedType argType = shadow.getGenericArgTypes()[i]; TypePattern type = patterns[i]; ResolvedType argRTX = shadow.getIWorld().resolve(argType,true); if (!(type instanceof BindingTypePattern)) { if (argRTX == ResolvedType.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()), "",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()}); } if (type.matchesInstanceof(argRTX).alwaysTrue()) { continue; } } else { BindingTypePattern btp = (BindingTypePattern)type; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId != shadow.shadowId)) { // ISourceLocation isl = getSourceLocation(); // Message errorMessage = new Message( // "Ambiguous binding of type "+type.getExactType().toString()+ // " using args(..) at this line - formal is already bound"+ // ". See secondary source location for location of args(..)", // shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } } World world = shadow.getIWorld(); ResolvedType typeToExpose = type.getExactType().resolve(world); if (typeToExpose.isParameterizedType()) { boolean inDoubt = (type.matchesInstanceof(argRTX) == FuzzyBoolean.MAYBE); if (inDoubt && world.getLint().uncheckedArgument.isEnabled()) { String uncheckedMatchWith = typeToExpose.getSimpleBaseName(); if (argRTX.isParameterizedType() && (argRTX.getRawType() == typeToExpose.getRawType())) { uncheckedMatchWith = argRTX.getSimpleName(); } if (!isUncheckedArgumentWarningSuppressed()) { world.getLint().uncheckedArgument.signal( new String[] { typeToExpose.getSimpleName(), uncheckedMatchWith, typeToExpose.getSimpleBaseName(), shadow.toResolvedString(world)}, getSourceLocation(), new ISourceLocation[] {shadow.getSourceLocation()}); } } } ret = Test.makeAnd(ret, exposeStateForVar(shadow.getArgVar(i), type, state,shadow.getIWorld())); } return ret; } /** * We need to find out if someone has put the @SuppressAjWarnings{"uncheckedArgument"} * annotation somewhere. That somewhere is going to be an a piece of advice that uses this * pointcut. But how do we find it??? * @return */ private boolean isUncheckedArgumentWarningSuppressed() { return false; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { ResolvedType[] argsToMatch = getArgumentsToMatchAgainst(shadow); if (arguments.matches(argsToMatch, TypePattern.DYNAMIC).alwaysFalse()) { return Literal.FALSE; } int ellipsisCount = arguments.ellipsisCount; if (ellipsisCount == 0) { return findResidueNoEllipsis(shadow, state, arguments.getTypePatterns()); } else if (ellipsisCount == 1) { TypePattern[] patternsWithEllipsis = arguments.getTypePatterns(); TypePattern[] patternsWithoutEllipsis = new TypePattern[argsToMatch.length]; int lenWithEllipsis = patternsWithEllipsis.length; int lenWithoutEllipsis = patternsWithoutEllipsis.length; // l1+1 >= l0 int indexWithEllipsis = 0; int indexWithoutEllipsis = 0; while (indexWithoutEllipsis < lenWithoutEllipsis) { TypePattern p = patternsWithEllipsis[indexWithEllipsis++]; if (p == TypePattern.ELLIPSIS) { int newLenWithoutEllipsis = lenWithoutEllipsis - (lenWithEllipsis-indexWithEllipsis); while (indexWithoutEllipsis < newLenWithoutEllipsis) { patternsWithoutEllipsis[indexWithoutEllipsis++] = TypePattern.ANY; } } else { patternsWithoutEllipsis[indexWithoutEllipsis++] = p; } } return findResidueNoEllipsis(shadow, state, patternsWithoutEllipsis); } else { throw new BetaException("unimplemented"); } } public String toString() { return "args" + arguments.toString() + ""; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/CflowPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.CrosscuttingMembers; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Test; public class CflowPointcut extends Pointcut { private Pointcut entry; // The pointcut inside the cflow() that represents the 'entry' point boolean isBelow;// Is this cflowbelow? private int[] freeVars; private static Hashtable cflowFields = new Hashtable(); private static Hashtable cflowBelowFields = new Hashtable(); /** * Used to indicate that we're in the context of a cflow when concretizing if's * * Will be removed or replaced with something better when we handle this * as a non-error */ public static final ResolvedPointcutDefinition CFLOW_MARKER = new ResolvedPointcutDefinition(null, 0, null, UnresolvedType.NONE, Pointcut.makeMatchesNothing(Pointcut.RESOLVED)); public CflowPointcut(Pointcut entry, boolean isBelow, int[] freeVars) { // System.err.println("Building cflow pointcut "+entry.toString()); this.entry = entry; this.isBelow = isBelow; this.freeVars = freeVars; this.pointcutKind = CFLOW; } /** * @return Returns true is this is a cflowbelow pointcut */ public boolean isCflowBelow() { return isBelow; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } // enh 76055 public Pointcut getEntry() { return entry; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.CFLOW); entry.write(s); s.writeBoolean(isBelow); FileUtil.writeIntArray(freeVars, s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { CflowPointcut ret = new CflowPointcut(Pointcut.read(s, context), s.readBoolean(), FileUtil.readIntArray(s)); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { if (bindings == null) { entry.resolveBindings(scope, null); entry.state = RESOLVED; freeVars = new int[0]; } else { //??? for if's sake we might need to be more careful here Bindings entryBindings = new Bindings(bindings.size()); entry.resolveBindings(scope, entryBindings); entry.state = RESOLVED; freeVars = entryBindings.getUsedFormals(); bindings.mergeIn(entryBindings, scope); } } public boolean equals(Object other) { if (!(other instanceof CflowPointcut)) return false; CflowPointcut o = (CflowPointcut)other; return o.entry.equals(this.entry) && o.isBelow == this.isBelow; } public int hashCode() { int result = 17; result = 37*result + entry.hashCode(); result = 37*result + (isBelow ? 0 : 1); return result; } public String toString() { return "cflow" + (isBelow ? "below" : "") + "(" + entry + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { throw new RuntimeException("unimplemented"); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { // Enforce rule about which designators are supported in declare if (isDeclare(bindings.getEnclosingAdvice())) { inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CFLOW_IN_DECLARE,isBelow?"below":""), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } //make this remap from formal positions to arrayIndices IntMap entryBindings = new IntMap(); for (int i=0, len=freeVars.length; i < len; i++) { int freeVar = freeVars[i]; //int formalIndex = bindings.get(freeVar); entryBindings.put(freeVar, i); } entryBindings.copyContext(bindings); //System.out.println(this + " bindings: " + entryBindings); World world = inAspect.getWorld(); Pointcut concreteEntry; ResolvedType concreteAspect = bindings.getConcreteAspect(); CrosscuttingMembers xcut = concreteAspect.crosscuttingMembers; Collection previousCflowEntries = xcut.getCflowEntries(); entryBindings.pushEnclosingDefinition(CFLOW_MARKER); // This block concretizes the pointcut within the cflow pointcut try { concreteEntry = entry.concretize(inAspect, declaringType, entryBindings); } finally { entryBindings.popEnclosingDefinitition(); } List innerCflowEntries = new ArrayList(xcut.getCflowEntries()); innerCflowEntries.removeAll(previousCflowEntries); Object field = getCflowfield(concreteEntry); // Four routes of interest through this code (did I hear someone say refactor??) // 1) no state in the cflow - we can use a counter *and* we have seen this pointcut // before - so use the same counter as before. // 2) no state in the cflow - we can use a counter, but this is the first time // we have seen this pointcut, so build the infrastructure. // 3) state in the cflow - we need to use a stack *and* we have seen this pointcut // before - so share the stack. // 4) state in the cflow - we need to use a stack, but this is the first time // we have seen this pointcut, so build the infrastructure. if (freeVars.length == 0) { // No state, so don't use a stack, use a counter. ResolvedMember localCflowField = null; // Check if we have already got a counter for this cflow pointcut if (field != null) { localCflowField = (ResolvedMember)field; // Use the one we already have } else { // Create a counter field in the aspect localCflowField = new ResolvedMemberImpl(Member.FIELD,concreteAspect,Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL, NameMangler.cflowCounter(xcut),UnresolvedType.forName(NameMangler.CFLOW_COUNTER_TYPE).getSignature()); // Create type munger to add field to the aspect concreteAspect.crosscuttingMembers.addTypeMunger(world.makeCflowCounterFieldAdder(localCflowField)); // Create shadow munger to push stuff onto the stack concreteAspect.crosscuttingMembers.addConcreteShadowMunger( Advice.makeCflowEntry(world,concreteEntry,isBelow,localCflowField,freeVars.length,innerCflowEntries,inAspect)); putCflowfield(concreteEntry,localCflowField); // Remember it } Pointcut ret = new ConcreteCflowPointcut(localCflowField, null,true); ret.copyLocationFrom(this); return ret; } else { List slots = new ArrayList(); for (int i=0, len=freeVars.length; i < len; i++) { int freeVar = freeVars[i]; // we don't need to keep state that isn't actually exposed to advice //??? this means that we will store some state that we won't actually use, optimize this later if (!bindings.hasKey(freeVar)) continue; int formalIndex = bindings.get(freeVar); ResolvedType formalType = bindings.getAdviceSignature().getParameterTypes()[formalIndex].resolve(world); ConcreteCflowPointcut.Slot slot = new ConcreteCflowPointcut.Slot(formalIndex, formalType, i); slots.add(slot); } ResolvedMember localCflowField = null; if (field != null) { localCflowField = (ResolvedMember)field; } else { localCflowField = new ResolvedMemberImpl( Member.FIELD, concreteAspect, Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL, NameMangler.cflowStack(xcut), UnresolvedType.forName(NameMangler.CFLOW_STACK_TYPE).getSignature()); //System.out.println("adding field to: " + inAspect + " field " + cflowField); // add field and initializer to inAspect //XXX and then that info above needs to be mapped down here to help with //XXX getting the exposed state right concreteAspect.crosscuttingMembers.addConcreteShadowMunger( Advice.makeCflowEntry(world, concreteEntry, isBelow, localCflowField, freeVars.length, innerCflowEntries,inAspect)); concreteAspect.crosscuttingMembers.addTypeMunger( world.makeCflowStackFieldAdder(localCflowField)); putCflowfield(concreteEntry,localCflowField); } Pointcut ret = new ConcreteCflowPointcut(localCflowField, slots,false); ret.copyLocationFrom(this); return ret; } } public static void clearCaches() { cflowFields.clear(); cflowBelowFields.clear(); } private Object getCflowfield(Pointcut pcutkey) { if (isBelow) { return cflowBelowFields.get(pcutkey); } else { return cflowFields.get(pcutkey); } } private void putCflowfield(Pointcut pcutkey,Object o) { if (isBelow) { cflowBelowFields.put(pcutkey,o); } else { cflowFields.put(pcutkey,o); } } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/ConcreteCflowPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.bcel.BcelCflowAccessVar; public class ConcreteCflowPointcut extends Pointcut { private Member cflowField; List/*Slot*/ slots; // exposed for testing boolean usesCounter; // Can either use a counter or a stack to implement cflow. public ConcreteCflowPointcut(Member cflowField, List slots,boolean usesCounter) { this.cflowField = cflowField; this.slots = slots; this.usesCounter = usesCounter; this.pointcutKind = CFLOW; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } // used by weaver when validating bindings public int[] getUsedFormalSlots() { if (slots == null) return new int[0]; int[] indices = new int[slots.size()]; for (int i = 0; i < indices.length; i++) { indices[i] = ((Slot)slots.get(i)).formalIndex; } return indices; } public void write(DataOutputStream s) throws IOException { throw new RuntimeException("unimplemented"); } public void resolveBindings(IScope scope, Bindings bindings) { throw new RuntimeException("unimplemented"); } public boolean equals(Object other) { if (!(other instanceof ConcreteCflowPointcut)) return false; ConcreteCflowPointcut o = (ConcreteCflowPointcut)other; return o.cflowField.equals(this.cflowField); } public int hashCode() { int result = 17; result = 37*result + cflowField.hashCode(); return result; } public String toString() { return "concretecflow(" + cflowField + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { //System.out.println("find residue: " + this); if (usesCounter) { return Test.makeFieldGetCall(cflowField, cflowCounterIsValidMethod, Expr.NONE); } else { if (slots != null) { // null for cflows managed by counters for (Iterator i = slots.iterator(); i.hasNext();) { Slot slot = (Slot) i.next(); //System.out.println("slot: " + slot.formalIndex); state.set(slot.formalIndex, new BcelCflowAccessVar(slot.formalType, cflowField, slot.arrayIndex)); } } return Test.makeFieldGetCall(cflowField, cflowStackIsValidMethod, Expr.NONE); } } private static final Member cflowStackIsValidMethod = MemberImpl.method(UnresolvedType.forName(NameMangler.CFLOW_STACK_TYPE), 0, "isValid", "()Z"); private static final Member cflowCounterIsValidMethod = MemberImpl.method(UnresolvedType.forName(NameMangler.CFLOW_COUNTER_TYPE), 0, "isValid", "()Z"); public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { throw new RuntimeException("unimplemented"); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public static class Slot { int formalIndex; ResolvedType formalType; int arrayIndex; public Slot( int formalIndex, ResolvedType formalType, int arrayIndex) { this.formalIndex = formalIndex; this.formalType = formalType; this.arrayIndex = arrayIndex; } public boolean equals(Object other) { if (!(other instanceof Slot)) return false; Slot o = (Slot)other; return o.formalIndex == this.formalIndex && o.arrayIndex == this.arrayIndex && o.formalType.equals(this.formalType); } public String toString() { return "Slot(" + formalIndex + ", " + formalType + ", " + arrayIndex + ")"; } } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/DeclareAnnotation.java
/* ******************************************************************* * Copyright (c) 2005 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Adrian Colyer initial implementation * Andy Clement got it working * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.Map; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; public class DeclareAnnotation extends Declare { public static final Kind AT_TYPE = new Kind(1,"type"); public static final Kind AT_FIELD = new Kind(2,"field"); public static final Kind AT_METHOD = new Kind(3,"method"); public static final Kind AT_CONSTRUCTOR = new Kind(4,"constructor"); private Kind kind; private TypePattern typePattern; // for declare @type private SignaturePattern sigPattern; // for declare @field,@method,@constructor private String annotationMethod = "unknown"; private String annotationString = "@<annotation>"; private ResolvedType containingAspect; private AnnotationX annotation; /** * Captures type of declare annotation (method/type/field/constructor) */ public static class Kind { private final int id; private String s; private Kind(int n,String name) { id = n; s = name; } public int hashCode() { return (19 + 37*id); } public boolean equals(Object obj) { if (!(obj instanceof Kind)) return false; Kind other = (Kind) obj; return other.id == id; } public String toString() { return "at_"+s; } } public DeclareAnnotation(Kind kind, TypePattern typePattern) { this.typePattern = typePattern; this.kind = kind; } /** * Returns the string, useful before the real annotation has been resolved */ public String getAnnotationString() { return annotationString;} public DeclareAnnotation(Kind kind, SignaturePattern sigPattern) { this.sigPattern = sigPattern; this.kind = kind; } public boolean isExactPattern() { return typePattern instanceof ExactTypePattern; } public String getAnnotationMethod() { return annotationMethod;} public String toString() { StringBuffer ret = new StringBuffer(); ret.append("declare @"); ret.append(kind); ret.append(" : "); ret.append(typePattern != null ? typePattern.toString() : sigPattern.toString()); ret.append(" : "); ret.append(annotationString); return ret.toString(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public void resolve(IScope scope) { if (typePattern != null) { typePattern = typePattern.resolveBindings(scope,Bindings.NONE,false,false); } if (sigPattern != null) { sigPattern = sigPattern.resolveBindings(scope,Bindings.NONE); } } public Declare parameterizeWith(Map typeVariableBindingMap) { // TODO Auto-generated method stub return this; } public boolean isAdviceLike() { return false; } public void setAnnotationString(String as) { this.annotationString = as; } public void setAnnotationMethod(String methName){ this.annotationMethod = methName; } public boolean equals(Object obj) { if (!(obj instanceof DeclareAnnotation)) return false; DeclareAnnotation other = (DeclareAnnotation) obj; if (!this.kind.equals(other.kind)) return false; if (!this.annotationString.equals(other.annotationString)) return false; if (!this.annotationMethod.equals(other.annotationMethod)) return false; if (this.typePattern != null) { if (!typePattern.equals(other.typePattern)) return false; } if (this.sigPattern != null) { if (!sigPattern.equals(other.sigPattern)) return false; } return true; } public int hashCode() { int result = 19; result = 37*result + kind.hashCode(); result = 37*result + annotationString.hashCode(); result = 37*result + annotationMethod.hashCode(); if (typePattern != null) result = 37*result + typePattern.hashCode(); if (sigPattern != null) result = 37*result + sigPattern.hashCode(); return result; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.ANNOTATION); s.writeInt(kind.id); s.writeUTF(annotationString); s.writeUTF(annotationMethod); if (typePattern != null) typePattern.write(s); if (sigPattern != null) sigPattern.write(s); writeLocation(s); } public static Declare read(VersionedDataInputStream s, ISourceContext context) throws IOException { DeclareAnnotation ret = null; int kind = s.readInt(); String annotationString = s.readUTF(); String annotationMethod = s.readUTF(); TypePattern tp = null; SignaturePattern sp = null; switch (kind) { case 1: tp = TypePattern.read(s,context); ret = new DeclareAnnotation(AT_TYPE,tp); break; case 2: sp = SignaturePattern.read(s,context); ret = new DeclareAnnotation(AT_FIELD,sp); break; case 3: sp = SignaturePattern.read(s,context); ret = new DeclareAnnotation(AT_METHOD,sp); break; case 4: sp = SignaturePattern.read(s,context); ret = new DeclareAnnotation(AT_CONSTRUCTOR,sp); break; } // if (kind==AT_TYPE.id) { // tp = TypePattern.read(s,context); // ret = new DeclareAnnotation(AT_TYPE,tp); // } else { // sp = SignaturePattern.read(s,context); // ret = new DeclareAnnotation(kind,sp); // } ret.setAnnotationString(annotationString); ret.setAnnotationMethod(annotationMethod); ret.readLocation(context,s); return ret; } // public boolean getAnnotationIfMatches(ResolvedType onType) { // return (match(onType)); // } /** * For @constructor, @method, @field */ public boolean matches(ResolvedMember rm,World world) { return sigPattern.matches(rm,world,false); } /** * For @type */ public boolean matches(ResolvedType typeX) { if (!typePattern.matchesStatically(typeX)) return false; if (typeX.getWorld().getLint().typeNotExposedToWeaver.isEnabled() && !typeX.isExposedToWeaver()) { typeX.getWorld().getLint().typeNotExposedToWeaver.signal(typeX.getName(), getSourceLocation()); } return true; } public void setAspect(ResolvedType typeX) { containingAspect = typeX; } public UnresolvedType getAspect() { return containingAspect; } public void copyAnnotationTo(ResolvedType onType) { ensureAnnotationDiscovered(); if (!onType.hasAnnotation(annotation.getSignature())) { onType.addAnnotation(annotation); } } public AnnotationX getAnnotationX() { ensureAnnotationDiscovered(); return annotation; } /** * The annotation specified in the declare @type is stored against * a simple method of the form "ajc$declare_<NN>", this method * finds that method and retrieves the annotation */ private void ensureAnnotationDiscovered() { if (annotation!=null) return; for (Iterator iter = containingAspect.getMethods(); iter.hasNext();) { ResolvedMember member = (ResolvedMember) iter.next(); if (member.getName().equals(annotationMethod)) { annotation = member.getAnnotations()[0]; } } } public TypePattern getTypePattern() { return typePattern; } public boolean isStarredAnnotationPattern() { if (typePattern!=null) return typePattern.isStarAnnotation(); if (sigPattern!=null) return sigPattern.isStarAnnotation(); throw new RuntimeException("Impossible! what kind of deca is this: "+this); } public Kind getKind() { return kind; } public boolean isDeclareAtConstuctor() { return kind.equals(AT_CONSTRUCTOR); } public boolean isDeclareAtMethod() { return kind.equals(AT_METHOD); } public boolean isDeclareAtType() { return kind.equals(AT_TYPE); } public boolean isDeclareAtField() { return kind.equals(AT_FIELD); } /** * @return UnresolvedType for the annotation */ public UnresolvedType getAnnotationTypeX() { ensureAnnotationDiscovered(); return this.annotation.getSignature(); } /** * @return true if the annotation specified is allowed on a field */ public boolean isAnnotationAllowedOnField() { ensureAnnotationDiscovered(); return annotation.allowedOnField(); } public String getPatternAsString() { if (sigPattern!=null) return sigPattern.toString(); if (typePattern!=null) return typePattern.toString(); return "DONT KNOW"; } /** * Return true if this declare annotation could ever match something * in the specified type - only really able to make intelligent * decision if a type was specified in the sig/type pattern * signature. */ public boolean couldEverMatch(ResolvedType type) { // Haven't implemented variant for typePattern (doesn't seem worth it!) // BUGWARNING This test might not be sufficient for funny cases relating // to interfaces and the use of '+' - but it seems really important to // do something here so we don't iterate over all fields and all methods // in all types exposed to the weaver! So look out for bugs here and // we can update the test as appropriate. if (sigPattern!=null) return sigPattern.getDeclaringType().matches(type,TypePattern.STATIC).maybeTrue(); return true; } /** * Provide a name suffix so that we can tell the different declare annotations * forms apart in the AjProblemReporter */ public String getNameSuffix() { return getKind().toString(); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/DeclarePrecedence.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; public class DeclarePrecedence extends Declare { private TypePatternList patterns; public DeclarePrecedence(List patterns) { this(new TypePatternList(patterns)); } private DeclarePrecedence(TypePatternList patterns) { this.patterns = patterns; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Declare parameterizeWith(Map typeVariableBindingMap) { // TODO Auto-generated method stub return this; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("declare precedence: "); buf.append(patterns); buf.append(";"); return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof DeclarePrecedence)) return false; DeclarePrecedence o = (DeclarePrecedence)other; return o.patterns.equals(patterns); } public int hashCode() { return patterns.hashCode(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Declare.DOMINATES); patterns.write(s); writeLocation(s); } public static Declare read(VersionedDataInputStream s, ISourceContext context) throws IOException { Declare ret = new DeclarePrecedence(TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public void resolve(IScope scope) { patterns = patterns.resolveBindings(scope, Bindings.NONE, false, false); boolean seenStar = false; for (int i=0; i < patterns.size(); i++) { TypePattern pi = patterns.get(i); if (pi.isStar()) { if (seenStar) { scope.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.TWO_STARS_IN_PRECEDENCE), pi.getSourceLocation(), null); } seenStar = true; continue; } ResolvedType exactType = pi.getExactType().resolve(scope.getWorld()); if (exactType == ResolvedType.MISSING) continue; // Cannot do a dec prec specifying a non-aspect types unless suffixed with a '+' if (!exactType.isAspect() && !pi.isIncludeSubtypes()) { scope.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.CLASSES_IN_PRECEDENCE,exactType.getName()), pi.getSourceLocation(),null); } for (int j=0; j < patterns.size(); j++) { if (j == i) continue; TypePattern pj = patterns.get(j); if (pj.isStar()) continue; if (pj.matchesStatically(exactType)) { scope.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.TWO_PATTERN_MATCHES_IN_PRECEDENCE,exactType.getName()), pi.getSourceLocation(), pj.getSourceLocation()); } } } } public TypePatternList getPatterns() { return patterns; } private int matchingIndex(ResolvedType a) { int knownMatch = -1; int starMatch = -1; for (int i=0, len=patterns.size(); i < len; i++) { TypePattern p = patterns.get(i); if (p.isStar()) { starMatch = i; } else if (p.matchesStatically(a)) { if (knownMatch != -1) { a.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MULTIPLE_MATCHES_IN_PRECEDENCE,a,patterns.get(knownMatch),p), patterns.get(knownMatch).getSourceLocation(), p.getSourceLocation()); return -1; } else { knownMatch = i; } } } if (knownMatch == -1) return starMatch; else return knownMatch; } public int compare(ResolvedType aspect1, ResolvedType aspect2) { int index1 = matchingIndex(aspect1); int index2 = matchingIndex(aspect2); //System.out.println("a1: " + aspect1 + ", " + aspect2 + " = " + index1 + ", " + index2); if (index1 == -1 || index2 == -1) return 0; if (index1 == index2) return 0; else if (index1 > index2) return -1; else return +1; } public boolean isAdviceLike() { return false; } public String getNameSuffix() { return "precedence"; } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/HandlerPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; /** * This is a kind of KindedPointcut. This belongs either in * a hierarchy with it or in a new place to share code * with other potential future statement-level pointcuts like * synchronized and throws */ public class HandlerPointcut extends Pointcut { TypePattern exceptionType; private static final Set MATCH_KINDS = new HashSet(); static { MATCH_KINDS.add(Shadow.ExceptionHandler); } public HandlerPointcut(TypePattern exceptionType) { this.exceptionType = exceptionType; this.pointcutKind = HANDLER; } public Set couldMatchKinds() { return MATCH_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { //??? should be able to do better by finding all referenced types in type return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { if (shadow.getKind() != Shadow.ExceptionHandler) return FuzzyBoolean.NO; exceptionType.resolve(shadow.getIWorld()); // we know we have exactly one parameter since we're checking an exception handler return exceptionType.matches( shadow.getSignature().getParameterTypes()[0].resolve(shadow.getIWorld()), TypePattern.STATIC); } public boolean equals(Object other) { if (!(other instanceof HandlerPointcut)) return false; HandlerPointcut o = (HandlerPointcut)other; return o.exceptionType.equals(this.exceptionType); } public int hashCode() { int result = 17; result = 37*result + exceptionType.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("handler("); buf.append(exceptionType.toString()); buf.append(")"); return buf.toString(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.HANDLER); exceptionType.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { HandlerPointcut ret = new HandlerPointcut(TypePattern.read(s, context)); ret.readLocation(context, s); return ret; } // XXX note: there is no namebinding in any kinded pointcut. // still might want to do something for better error messages // We want to do something here to make sure we don't sidestep the parameter // list in capturing type identifiers. public void resolveBindings(IScope scope, Bindings bindings) { exceptionType = exceptionType.resolveBindings(scope, bindings, false, false); boolean invalidParameterization = false; if (exceptionType.getTypeParameters().size() > 0) invalidParameterization = true ; UnresolvedType exactType = exceptionType.getExactType(); if (exactType != null && exactType.isParameterizedType()) invalidParameterization = true; if (invalidParameterization) { // no parameterized or generic types for handler scope.message( MessageUtil.error(WeaverMessages.format(WeaverMessages.HANDLER_PCD_DOESNT_SUPPORT_PARAMETERS), getSourceLocation())); } //XXX add error if exact binding and not an exception } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new HandlerPointcut(exceptionType); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/PerCflow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.CrosscuttingMembers; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelAccessForInlineMunger; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Test; public class PerCflow extends PerClause { private boolean isBelow; private Pointcut entry; public PerCflow(Pointcut entry, boolean isBelow) { this.entry = entry; this.isBelow = isBelow; } // ----- public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.YES; } public void resolveBindings(IScope scope, Bindings bindings) { // assert bindings == null; entry.resolve(scope); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { Expr myInstance = Expr.makeCallExpr(AjcMemberMaker.perCflowAspectOfMethod(inAspect), Expr.NONE, inAspect); state.setAspectInstance(myInstance); return Test.makeCall(AjcMemberMaker.perCflowHasAspectMethod(inAspect), Expr.NONE); } public PerClause concretize(ResolvedType inAspect) { PerCflow ret = new PerCflow(entry, isBelow); ret.inAspect = inAspect; if (inAspect.isAbstract()) return ret; Member cflowStackField = new ResolvedMemberImpl( Member.FIELD, inAspect, Modifier.STATIC|Modifier.PUBLIC|Modifier.FINAL, UnresolvedType.forName(NameMangler.CFLOW_STACK_TYPE), NameMangler.PERCFLOW_FIELD_NAME, UnresolvedType.NONE); World world = inAspect.getWorld(); CrosscuttingMembers xcut = inAspect.crosscuttingMembers; Collection previousCflowEntries = xcut.getCflowEntries(); Pointcut concreteEntry = entry.concretize(inAspect, inAspect, 0, null); //IntMap.EMPTY); List innerCflowEntries = new ArrayList(xcut.getCflowEntries()); innerCflowEntries.removeAll(previousCflowEntries); xcut.addConcreteShadowMunger( Advice.makePerCflowEntry(world, concreteEntry, isBelow, cflowStackField, inAspect, innerCflowEntries)); //ATAJ: add a munger to add the aspectOf(..) to the @AJ aspects if (inAspect.isAnnotationStyleAspect() && !inAspect.isAbstract()) { inAspect.crosscuttingMembers.addLateTypeMunger( inAspect.getWorld().makePerClauseAspect(inAspect, getKind()) ); } //ATAJ inline around advice support - don't use a late munger to allow around inling for itself if (inAspect.isAnnotationStyleAspect() && !inAspect.getWorld().isXnoInline()) { inAspect.crosscuttingMembers.addTypeMunger(new BcelAccessForInlineMunger(inAspect)); } return ret; } public void write(DataOutputStream s) throws IOException { PERCFLOW.write(s); entry.write(s); s.writeBoolean(isBelow); writeLocation(s); } public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { PerCflow ret = new PerCflow(Pointcut.read(s, context), s.readBoolean()); ret.readLocation(context, s); return ret; } public PerClause.Kind getKind() { return PERCFLOW; } public Pointcut getEntry(){ return entry; } public String toString() { return "percflow(" + inAspect + " on " + entry + ")"; } public String toDeclarationString() { if (isBelow) return "percflowbelow(" + entry + ")"; return "percflow(" + entry + ")"; } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/PerFromSuper.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Set; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Test; public class PerFromSuper extends PerClause { private PerClause.Kind kind; public PerFromSuper(PerClause.Kind kind) { this.kind = kind; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { throw new RuntimeException("unimplemented"); } protected FuzzyBoolean matchInternal(Shadow shadow) { throw new RuntimeException("unimplemented"); } public void resolveBindings(IScope scope, Bindings bindings) { // this method intentionally left blank } protected Test findResidueInternal(Shadow shadow, ExposedState state) { throw new RuntimeException("unimplemented"); } public PerClause concretize(ResolvedType inAspect) { PerClause p = lookupConcretePerClause(inAspect.getSuperclass()); if (p == null) { inAspect.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.MISSING_PER_CLAUSE,inAspect.getSuperclass()), getSourceLocation()) ); return new PerSingleton().concretize(inAspect);// AV: fallback on something else NPE in AJDT } else { if (p.getKind() != kind) { inAspect.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WRONG_PER_CLAUSE,kind,p.getKind()), getSourceLocation()) ); } return p.concretize(inAspect); } } public PerClause lookupConcretePerClause(ResolvedType lookupType) { PerClause ret = lookupType.getPerClause(); if (ret == null) return null; if (ret instanceof PerFromSuper) { return lookupConcretePerClause(lookupType.getSuperclass()); } return ret; } public void write(DataOutputStream s) throws IOException { FROMSUPER.write(s); kind.write(s); writeLocation(s); } public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { PerFromSuper ret = new PerFromSuper(Kind.read(s)); ret.readLocation(context, s); return ret; } public String toString() { return "perFromSuper(" + kind + ", " + inAspect + ")"; } public String toDeclarationString() { return ""; } public PerClause.Kind getKind() { return kind; } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/PerObject.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelAccessForInlineMunger; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; public class PerObject extends PerClause { private boolean isThis; private Pointcut entry; private static final Set thisKindSet = new HashSet(Shadow.ALL_SHADOW_KINDS); private static final Set targetKindSet = new HashSet(Shadow.ALL_SHADOW_KINDS); static { for (Iterator iter = Shadow.ALL_SHADOW_KINDS.iterator(); iter.hasNext();) { Shadow.Kind kind = (Shadow.Kind) iter.next(); if (kind.neverHasThis()) thisKindSet.remove(kind); if (kind.neverHasTarget()) targetKindSet.remove(kind); } } public PerObject(Pointcut entry, boolean isThis) { this.entry = entry; this.isThis = isThis; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Set couldMatchKinds() { return isThis ? thisKindSet : targetKindSet; } // ----- public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //System.err.println("matches " + this + " ? " + shadow + ", " + shadow.hasTarget()); //??? could probably optimize this better by testing could match if (isThis) return FuzzyBoolean.fromBoolean(shadow.hasThis()); else return FuzzyBoolean.fromBoolean(shadow.hasTarget()); } public void resolveBindings(IScope scope, Bindings bindings) { // assert bindings == null; entry.resolve(scope); } private Var getVar(Shadow shadow) { return isThis ? shadow.getThisVar() : shadow.getTargetVar(); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { Expr myInstance = Expr.makeCallExpr(AjcMemberMaker.perObjectAspectOfMethod(inAspect), new Expr[] {getVar(shadow)}, inAspect); state.setAspectInstance(myInstance); return Test.makeCall(AjcMemberMaker.perObjectHasAspectMethod(inAspect), new Expr[] { getVar(shadow) }); } public PerClause concretize(ResolvedType inAspect) { PerObject ret = new PerObject(entry, isThis); ret.inAspect = inAspect; if (inAspect.isAbstract()) return ret; World world = inAspect.getWorld(); Pointcut concreteEntry = entry.concretize(inAspect, inAspect, 0, null); //concreteEntry = new AndPointcut(this, concreteEntry); //concreteEntry.state = Pointcut.CONCRETE; inAspect.crosscuttingMembers.addConcreteShadowMunger( Advice.makePerObjectEntry(world, concreteEntry, isThis, inAspect)); // FIXME AV - don't use lateMunger here due to test "inheritance, around advice and abstract pointcuts" // see #75442 thread. Issue with weaving order. ResolvedTypeMunger munger = new PerObjectInterfaceTypeMunger(inAspect, concreteEntry); inAspect.crosscuttingMembers.addLateTypeMunger(world.concreteTypeMunger(munger, inAspect)); //ATAJ: add a munger to add the aspectOf(..) to the @AJ aspects if (inAspect.isAnnotationStyleAspect() && !inAspect.isAbstract()) { inAspect.crosscuttingMembers.addLateTypeMunger( inAspect.getWorld().makePerClauseAspect(inAspect, getKind()) ); } //ATAJ inline around advice support - don't use a late munger to allow around inling for itself if (inAspect.isAnnotationStyleAspect() && !inAspect.getWorld().isXnoInline()) { inAspect.crosscuttingMembers.addTypeMunger(new BcelAccessForInlineMunger(inAspect)); } return ret; } public void write(DataOutputStream s) throws IOException { PEROBJECT.write(s); entry.write(s); s.writeBoolean(isThis); writeLocation(s); } public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { PerClause ret = new PerObject(Pointcut.read(s, context), s.readBoolean()); ret.readLocation(context, s); return ret; } public PerClause.Kind getKind() { return PEROBJECT; } public boolean isThis() { return isThis; } public String toString() { return "per" + (isThis ? "this" : "target") + "(" + entry + ")"; } public String toDeclarationString() { return toString(); } public Pointcut getEntry() { return entry; } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/PerSingleton.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Set; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.bcel.BcelAccessForInlineMunger; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class PerSingleton extends PerClause { public PerSingleton() { } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.YES; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.YES; } public void resolveBindings(IScope scope, Bindings bindings) { // this method intentionally left blank } public Test findResidueInternal(Shadow shadow, ExposedState state) { // TODO: the commented code is for slow Aspects.aspectOf() style - keep or remove // // Expr myInstance = // Expr.makeCallExpr(AjcMemberMaker.perSingletonAspectOfMethod(inAspect), // Expr.NONE, inAspect); // // state.setAspectInstance(myInstance); // // // we have no test // // a NoAspectBoundException will be thrown if we need an instance of this // // aspect before we are bound // return Literal.TRUE; // if (!Ajc5MemberMaker.isSlowAspect(inAspect)) { Expr myInstance = Expr.makeCallExpr(AjcMemberMaker.perSingletonAspectOfMethod(inAspect), Expr.NONE, inAspect); state.setAspectInstance(myInstance); // we have no test // a NoAspectBoundException will be thrown if we need an instance of this // aspect before we are bound return Literal.TRUE; // } else { // CallExpr callAspectOf =Expr.makeCallExpr( // Ajc5MemberMaker.perSingletonAspectOfMethod(inAspect), // new Expr[]{ // Expr.makeStringConstantExpr(inAspect.getName(), inAspect), // //FieldGet is using ResolvedType and I don't need that here // new FieldGetOn(Member.ajClassField, shadow.getEnclosingType()) // }, // inAspect // ); // Expr castedCallAspectOf = new CastExpr(callAspectOf, inAspect.getName()); // state.setAspectInstance(castedCallAspectOf); // return Literal.TRUE; // } } public PerClause concretize(ResolvedType inAspect) { PerSingleton ret = new PerSingleton(); ret.copyLocationFrom(this); ret.inAspect = inAspect; //ATAJ: add a munger to add the aspectOf(..) to the @AJ aspects if (inAspect.isAnnotationStyleAspect() && !inAspect.isAbstract()) { //TODO will those change be ok if we add a serializable aspect ? // dig: "can't be Serializable/Cloneable unless -XserializableAspects" inAspect.crosscuttingMembers.addLateTypeMunger( inAspect.getWorld().makePerClauseAspect(inAspect, getKind()) ); } //ATAJ inline around advice support if (inAspect.isAnnotationStyleAspect() && !inAspect.getWorld().isXnoInline()) { inAspect.crosscuttingMembers.addTypeMunger(new BcelAccessForInlineMunger(inAspect)); } return ret; } public void write(DataOutputStream s) throws IOException { SINGLETON.write(s); writeLocation(s); } public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { PerSingleton ret = new PerSingleton(); ret.readLocation(context, s); return ret; } public PerClause.Kind getKind() { return SINGLETON; } public String toString() { return "persingleton(" + inAspect + ")"; } public String toDeclarationString() { return ""; } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/PerTypeWithin.java
/* ******************************************************************* * Copyright (c) 2005 IBM * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; //import org.aspectj.weaver.PerTypeWithinTargetTypeMunger; import org.aspectj.weaver.PerTypeWithinTargetTypeMunger; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelAccessForInlineMunger; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; // PTWIMPL Represents a parsed pertypewithin() public class PerTypeWithin extends PerClause { private TypePattern typePattern; // Any shadow could be considered within a pertypewithin() type pattern private static final Set kindSet = new HashSet(Shadow.ALL_SHADOW_KINDS); public TypePattern getTypePattern() { return typePattern; } public PerTypeWithin(TypePattern p) { this.typePattern = p; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Set couldMatchKinds() { return kindSet; } // ----- public FuzzyBoolean fastMatch(FastMatchInfo info) { if (typePattern.annotationPattern instanceof AnyAnnotationTypePattern) { return isWithinType(info.getType()); } return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedType enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true); if (enclosingType == ResolvedType.MISSING) { //PTWIMPL ?? Add a proper message IMessage msg = new Message( "Cant find type pertypewithin matching...", shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); shadow.getIWorld().getMessageHandler().handleMessage(msg); } // See pr106554 - we can't put advice calls in an interface when the advice is defined // in a pertypewithin aspect - the JPs only exist in the static initializer and can't // call the localAspectOf() method. if (enclosingType.isInterface()) return FuzzyBoolean.NO; typePattern.resolve(shadow.getIWorld()); return isWithinType(enclosingType); } public void resolveBindings(IScope scope, Bindings bindings) { typePattern = typePattern.resolveBindings(scope, bindings, false, false); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { Member ptwField = AjcMemberMaker.perTypeWithinField(shadow.getEnclosingType(),inAspect); Expr myInstance = Expr.makeCallExpr(AjcMemberMaker.perTypeWithinLocalAspectOf(shadow.getEnclosingType(),inAspect/*shadow.getEnclosingType()*/), Expr.NONE,inAspect); state.setAspectInstance(myInstance); // this worked at one point //Expr myInstance = Expr.makeFieldGet(ptwField,shadow.getEnclosingType().resolve(shadow.getIWorld()));//inAspect); //state.setAspectInstance(myInstance); // return Test.makeFieldGetCall(ptwField,null,Expr.NONE); // cflowField, cflowCounterIsValidMethod, Expr.NONE // This is what is in the perObject variant of this ... // Expr myInstance = // Expr.makeCallExpr(AjcMemberMaker.perTypeWithinAspectOfMethod(inAspect), // new Expr[] {getVar(shadow)}, inAspect); // state.setAspectInstance(myInstance); // return Test.makeCall(AjcMemberMaker.perTypeWithinHasAspectMethod(inAspect), // new Expr[] { getVar(shadow) }); // return match(shadow).alwaysTrue()?Literal.TRUE:Literal.FALSE; } public PerClause concretize(ResolvedType inAspect) { PerTypeWithin ret = new PerTypeWithin(typePattern); ret.copyLocationFrom(this); ret.inAspect = inAspect; if (inAspect.isAbstract()) return ret; World world = inAspect.getWorld(); SignaturePattern sigpat = new SignaturePattern( Member.STATIC_INITIALIZATION, ModifiersPattern.ANY, TypePattern.ANY, TypePattern.ANY,//typePattern, NamePattern.ANY, TypePatternList.ANY, ThrowsPattern.ANY, AnnotationTypePattern.ANY ); Pointcut staticInitStar = new KindedPointcut(Shadow.StaticInitialization,sigpat); Pointcut withinTp= new WithinPointcut(typePattern); Pointcut andPcut = new AndPointcut(staticInitStar,withinTp); // We want the pointcut to be 'staticinitialization(*) && within(<typepattern>' - // we *cannot* shortcut this to staticinitialization(<typepattern>) because it // doesnt mean the same thing. // This munger will initialize the aspect instance field in the matched type inAspect.crosscuttingMembers.addConcreteShadowMunger(Advice.makePerTypeWithinEntry(world, andPcut, inAspect)); ResolvedTypeMunger munger = new PerTypeWithinTargetTypeMunger(inAspect, ret); inAspect.crosscuttingMembers.addTypeMunger(world.concreteTypeMunger(munger, inAspect)); //ATAJ: add a munger to add the aspectOf(..) to the @AJ aspects if (inAspect.isAnnotationStyleAspect() && !inAspect.isAbstract()) { inAspect.crosscuttingMembers.addLateTypeMunger( inAspect.getWorld().makePerClauseAspect(inAspect, getKind()) ); } //ATAJ inline around advice support - don't use a late munger to allow around inling for itself if (inAspect.isAnnotationStyleAspect() && !inAspect.getWorld().isXnoInline()) { inAspect.crosscuttingMembers.addTypeMunger(new BcelAccessForInlineMunger(inAspect)); } return ret; } public void write(DataOutputStream s) throws IOException { PERTYPEWITHIN.write(s); typePattern.write(s); writeLocation(s); } public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { PerClause ret = new PerTypeWithin(TypePattern.read(s, context)); ret.readLocation(context, s); return ret; } public PerClause.Kind getKind() { return PERTYPEWITHIN; } public String toString() { return "pertypewithin("+typePattern+")"; } public String toDeclarationString() { return toString(); } private FuzzyBoolean isWithinType(ResolvedType type) { while (type != null) { if (typePattern.matchesStatically(type)) { return FuzzyBoolean.YES; } type = type.getDeclaringType(); } return FuzzyBoolean.NO; } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/Pointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.Set; import org.aspectj.util.FuzzyBoolean; import org.aspectj.util.TypeSafeEnum; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Checker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; /** * The lifecycle of Pointcuts is modeled by Pointcut.State. It has three things: * * <p>Creation -- SYMBOLIC -- then resolve(IScope) -- RESOLVED -- concretize(...) -- CONCRETE * * @author Erik Hilsdale * @author Jim Hugunin * * A day in the life of a pointcut.... - AMC. * ========================================== * * Pointcuts are created by the PatternParser, which is called by ajdt to * parse a pointcut from the PseudoTokens AST node (which in turn are part * of a PointcutDesignator AST node). * * Pointcuts are resolved by ajdt when an AdviceDeclaration or a * PointcutDeclaration has its statements resolved. This happens as * part of completeTypeBindings in the AjLookupEnvironment which is * called after the diet parse phase of the compiler. Named pointcuts, * and references to named pointcuts are instances of ReferencePointcut. * * At the end of the compilation process, the pointcuts are serialized * (write method) into attributes in the class file. * * When the weaver loads the class files, it unpacks the attributes * and deserializes the pointcuts (read). All aspects are added to the * world, by calling addOrReplaceAspect on * the crosscutting members set of the world. When aspects are added or * replaced, the crosscutting members in the aspect are extracted as * ShadowMungers (each holding a pointcut). The ShadowMungers are * concretized, which concretizes the pointcuts. At this stage * ReferencePointcuts are replaced by their declared content. * * During weaving, the weaver processes type by type. It first culls * potentially matching ShadowMungers by calling the fastMatch method * on their pointcuts. Only those that might match make it through to * the next phase. At the next phase, all of the shadows within the * type are created and passed to the pointcut for matching (match). * * When the actual munging happens, matched pointcuts are asked for * their residue (findResidue) - the runtime test if any. Because of * negation, findResidue may be called on pointcuts that could never * match the shadow. * */ public abstract class Pointcut extends PatternNode { public static final class State extends TypeSafeEnum { public State(String name, int key) { super(name, key); } } /** * ATAJ the name of the formal for which we don't want any warning when unbound since * we consider them as implicitly bound. f.e. JoinPoint for @AJ advices */ public String[] m_ignoreUnboundBindingForNames = new String[0]; public static final State SYMBOLIC = new State("symbolic", 0); public static final State RESOLVED = new State("resolved", 1); public static final State CONCRETE = new State("concrete", 2); protected byte pointcutKind; public State state; protected int lastMatchedShadowId; private FuzzyBoolean lastMatchedShadowResult; private String[] typeVariablesInScope = new String[0]; /** * Constructor for Pattern. */ public Pointcut() { super(); this.state = SYMBOLIC; } /** * Could I match any shadows in the code defined within this type? */ public abstract FuzzyBoolean fastMatch(FastMatchInfo info); /** * The set of ShadowKinds that this Pointcut could possibly match */ public abstract /*Enum*/Set/*<Shadow.Kind>*/ couldMatchKinds(); public String[] getTypeVariablesInScope() { return typeVariablesInScope; } public void setTypeVariablesInScope(String[] typeVars) { this.typeVariablesInScope = typeVars; } /** * Do I really match this shadow? * XXX implementors need to handle state */ public final FuzzyBoolean match(Shadow shadow) { if (shadow.shadowId == lastMatchedShadowId) return lastMatchedShadowResult; FuzzyBoolean ret; // this next test will prevent a lot of un-needed matching going on.... if (couldMatchKinds().contains(shadow.getKind())) { ret = matchInternal(shadow); } else { ret = FuzzyBoolean.NO; } lastMatchedShadowId = shadow.shadowId; lastMatchedShadowResult = ret; return ret; } protected abstract FuzzyBoolean matchInternal(Shadow shadow); public static final byte KINDED = 1; public static final byte WITHIN = 2; public static final byte THIS_OR_TARGET = 3; public static final byte ARGS = 4; public static final byte AND = 5; public static final byte OR = 6; public static final byte NOT = 7; public static final byte REFERENCE = 8; public static final byte IF = 9; public static final byte CFLOW = 10; public static final byte WITHINCODE = 12; public static final byte HANDLER = 13; public static final byte IF_TRUE = 14; public static final byte IF_FALSE = 15; public static final byte ANNOTATION = 16; public static final byte ATWITHIN = 17; public static final byte ATWITHINCODE = 18; public static final byte ATTHIS_OR_TARGET = 19; public static final byte NONE = 20; // DO NOT CHANGE OR REORDER THIS SEQUENCE, THIS VALUE CAN BE PUT OUT BY ASPECTJ1.2.1 public static final byte ATARGS = 21; public byte getPointcutKind() { return pointcutKind; } // internal, only called from resolve protected abstract void resolveBindings(IScope scope, Bindings bindings); /** * Returns this pointcut mutated */ public final Pointcut resolve(IScope scope) { assertState(SYMBOLIC); Bindings bindingTable = new Bindings(scope.getFormalCount()); IScope bindingResolutionScope = scope; if (typeVariablesInScope.length > 0) { bindingResolutionScope = new ScopeWithTypeVariables(typeVariablesInScope,scope); } this.resolveBindings(bindingResolutionScope, bindingTable); bindingTable.checkAllBound(bindingResolutionScope); this.state = RESOLVED; return this; } /** * Returns a new pointcut * Only used by test cases */ public final Pointcut concretize(ResolvedType inAspect, ResolvedType declaringType, int arity) { Pointcut ret = concretize(inAspect, declaringType, IntMap.idMap(arity)); // copy the unbound ignore list ret.m_ignoreUnboundBindingForNames = m_ignoreUnboundBindingForNames; return ret; } //XXX this is the signature we're moving to public final Pointcut concretize(ResolvedType inAspect, ResolvedType declaringType, int arity, ShadowMunger advice) { //if (state == CONCRETE) return this; //??? IntMap map = IntMap.idMap(arity); map.setEnclosingAdvice(advice); map.setConcreteAspect(inAspect); return concretize(inAspect, declaringType, map); } public boolean isDeclare(ShadowMunger munger) { if (munger == null) return false; // ??? Is it actually an error if we get a null munger into this method. if (munger instanceof Checker) return true; if (((Advice)munger).getKind().equals(AdviceKind.Softener)) return true; return false; } public final Pointcut concretize(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { //!!! add this test -- assertState(RESOLVED); Pointcut ret = this.concretize1(inAspect, declaringType, bindings); if (shouldCopyLocationForConcretize()) ret.copyLocationFrom(this); ret.state = CONCRETE; // copy the unbound ignore list ret.m_ignoreUnboundBindingForNames = m_ignoreUnboundBindingForNames; return ret; } protected boolean shouldCopyLocationForConcretize() { return true; } /** * Resolves and removes ReferencePointcuts, replacing with basic ones * * @param inAspect the aspect to resolve relative to * @param bindings a Map from formal index in the current lexical context * -> formal index in the concrete advice that will run * * This must always return a new Pointcut object (even if the concretized * Pointcut is identical to the resolved one). That behavior is * assumed in many places. * XXX fix implementors to handle state */ protected abstract Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings); //XXX implementors need to handle state /** * This can be called from NotPointcut even for Pointcuts that * don't match the shadow */ public final Test findResidue(Shadow shadow, ExposedState state) { // if (shadow.shadowId == lastMatchedShadowId) return lastMatchedShadowResidue; Test ret = findResidueInternal(shadow,state); // lastMatchedShadowResidue = ret; lastMatchedShadowId = shadow.shadowId; return ret; } protected abstract Test findResidueInternal(Shadow shadow,ExposedState state); //XXX we're not sure whether or not this is needed //XXX currently it's unused we're keeping it around as a stub public void postRead(ResolvedType enclosingType) {} public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { byte kind = s.readByte(); Pointcut ret; switch(kind) { case KINDED: ret = KindedPointcut.read(s, context); break; case WITHIN: ret = WithinPointcut.read(s, context); break; case THIS_OR_TARGET: ret = ThisOrTargetPointcut.read(s, context); break; case ARGS: ret = ArgsPointcut.read(s, context); break; case AND: ret = AndPointcut.read(s, context); break; case OR: ret = OrPointcut.read(s, context); break; case NOT: ret = NotPointcut.read(s, context); break; case REFERENCE: ret = ReferencePointcut.read(s, context); break; case IF: ret = IfPointcut.read(s, context); break; case CFLOW: ret = CflowPointcut.read(s, context); break; case WITHINCODE: ret = WithincodePointcut.read(s, context); break; case HANDLER: ret = HandlerPointcut.read(s, context); break; case IF_TRUE: ret = IfPointcut.makeIfTruePointcut(RESOLVED); break; case IF_FALSE: ret = IfPointcut.makeIfFalsePointcut(RESOLVED); break; case ANNOTATION: ret = AnnotationPointcut.read(s, context); break; case ATWITHIN: ret = WithinAnnotationPointcut.read(s, context); break; case ATWITHINCODE: ret = WithinCodeAnnotationPointcut.read(s, context); break; case ATTHIS_OR_TARGET: ret = ThisOrTargetAnnotationPointcut.read(s, context); break; case ATARGS: ret = ArgsAnnotationPointcut.read(s,context); break; case NONE: ret = makeMatchesNothing(RESOLVED); break; default: throw new BCException("unknown kind: " + kind); } ret.state = RESOLVED; ret.pointcutKind = kind; return ret; } //public void prepare(Shadow shadow) {} // ---- test method public static Pointcut fromString(String str) { PatternParser parser = new PatternParser(str); return parser.parsePointcut(); } static class MatchesNothingPointcut extends Pointcut { protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Literal.FALSE; // can only get here if an earlier error occurred } public Set couldMatchKinds() { return Collections.EMPTY_SET; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.NO; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public void resolveBindings(IScope scope, Bindings bindings) { } public void postRead(ResolvedType enclosingType) { } public Pointcut concretize1( ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { return makeMatchesNothing(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(NONE); } public String toString() { return ""; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Pointcut parameterizeWith(Map typeVariableMap) { return this; } } //public static Pointcut MatchesNothing = new MatchesNothingPointcut(); //??? there could possibly be some good optimizations to be done at this point public static Pointcut makeMatchesNothing(State state) { Pointcut ret = new MatchesNothingPointcut(); ret.state = state; return ret; } public void assertState(State state) { if (this.state != state) { throw new BCException("expected state: " + state + " got: " + this.state); } } public Pointcut parameterizeWith(Map typeVariableMap) { throw new UnsupportedOperationException("this method needs to be defined in all subtypes and then made abstract when the work is complete"); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/ThisOrTargetAnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ThisOrTargetAnnotationPointcut extends NameBindingPointcut { private boolean isThis; private boolean alreadyWarnedAboutDEoW = false; private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger; private static final Set thisKindSet = new HashSet(Shadow.ALL_SHADOW_KINDS); private static final Set targetKindSet = new HashSet(Shadow.ALL_SHADOW_KINDS); static { for (Iterator iter = Shadow.ALL_SHADOW_KINDS.iterator(); iter.hasNext();) { Shadow.Kind kind = (Shadow.Kind) iter.next(); if (kind.neverHasThis()) thisKindSet.remove(kind); if (kind.neverHasTarget()) targetKindSet.remove(kind); } } /** * */ public ThisOrTargetAnnotationPointcut(boolean isThis, ExactAnnotationTypePattern type) { super(); this.isThis = isThis; this.annotationTypePattern = type; this.pointcutKind = ATTHIS_OR_TARGET; } public ThisOrTargetAnnotationPointcut(boolean isThis, ExactAnnotationTypePattern type, ShadowMunger munger) { this(isThis,type); this.munger = munger; } public ExactAnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public Set couldMatchKinds() { return isThis ? thisKindSet : targetKindSet; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { if (!couldMatch(shadow)) return FuzzyBoolean.NO; ResolvedType toMatchAgainst = (isThis ? shadow.getThisType() : shadow.getTargetType() ).resolve(shadow.getIWorld()); annotationTypePattern.resolve(shadow.getIWorld()); if (annotationTypePattern.matchesRuntimeType(toMatchAgainst).alwaysTrue()) { return FuzzyBoolean.YES; } else { // a subtype may match at runtime return FuzzyBoolean.MAYBE; } } public boolean isThis() { return isThis; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern // if annotationType does not have runtime retention, this is an error if (annotationTypePattern.annotationType == null) { // it's a formal with a binding error return; } ResolvedType rAnnotationType = (ResolvedType) annotationTypePattern.annotationType; if (!(rAnnotationType.isAnnotationWithRuntimeRetention())) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.BINDING_NON_RUNTIME_RETENTION_ANNOTATION,rAnnotationType.getName()), getSourceLocation()); scope.getMessageHandler().handleMessage(m); } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare if (!alreadyWarnedAboutDEoW) { inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.THIS_OR_TARGET_IN_DECLARE,isThis?"this":"target"), bindings.getEnclosingAdvice().getSourceLocation(), null); alreadyWarnedAboutDEoW = true; } return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); ThisOrTargetAnnotationPointcut ret = new ThisOrTargetAnnotationPointcut(isThis, newType, bindings.getEnclosingAdvice()); ret.alreadyWarnedAboutDEoW = alreadyWarnedAboutDEoW; ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ /** * The guard here is going to be the hasAnnotation() test - if it gets through (which we cannot determine until runtime) then * we must have a TypeAnnotationAccessVar in place - this means we must *always* have one in place. */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (!couldMatch(shadow)) return Literal.FALSE; boolean alwaysMatches = match(shadow).alwaysTrue(); Var var = isThis ? shadow.getThisVar() : shadow.getTargetVar(); Var annVar = null; // Are annotations being bound? UnresolvedType annotationType = annotationTypePattern.annotationType; if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; annotationType = btp.annotationType; annVar = isThis ? shadow.getThisAnnotationVar(annotationType) : shadow.getTargetAnnotationVar(annotationType); if (annVar == null) throw new RuntimeException("Impossible!"); // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId == shadow.shadowId)) { // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use @pointcut to match at this location and bind a formal to type '"+annVar.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic binding.", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } state.set(btp.getFormalIndex(),annVar); } if (alwaysMatches && (annVar == null)) {//change check to verify if its the 'generic' annVar that is being used return Literal.TRUE; } else { ResolvedType rType = annotationType.resolve(shadow.getIWorld()); return Test.makeHasAnnotation(var,rType); } } private boolean couldMatch(Shadow shadow) { return isThis ? shadow.hasThis() : shadow.hasTarget(); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATTHIS_OR_TARGET); s.writeBoolean(isThis); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { boolean isThis = s.readBoolean(); AnnotationTypePattern type = AnnotationTypePattern.read(s, context); ThisOrTargetAnnotationPointcut ret = new ThisOrTargetAnnotationPointcut(isThis,(ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof ThisOrTargetAnnotationPointcut)) return false; ThisOrTargetAnnotationPointcut other = (ThisOrTargetAnnotationPointcut) obj; return ( other.annotationTypePattern.equals(this.annotationTypePattern) && (other.isThis == this.isThis) ); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37*annotationTypePattern.hashCode() + (isThis ? 49 : 13); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append(isThis ? "@this(" : "@target("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); return buf.toString(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/ThisOrTargetPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; // /** * Corresponds to target or this pcd. * * <p>type is initially a WildTypePattern. If it stays that way, it's a this(Foo) * type deal. * however, the resolveBindings method may convert it to a BindingTypePattern, * in which * case, it's a this(foo) type deal. * * @author Erik Hilsdale * @author Jim Hugunin */ public class ThisOrTargetPointcut extends NameBindingPointcut { private boolean isThis; private TypePattern type; private static final Set thisKindSet = new HashSet(Shadow.ALL_SHADOW_KINDS); private static final Set targetKindSet = new HashSet(Shadow.ALL_SHADOW_KINDS); static { for (Iterator iter = Shadow.ALL_SHADOW_KINDS.iterator(); iter.hasNext();) { Shadow.Kind kind = (Shadow.Kind) iter.next(); if (kind.neverHasThis()) thisKindSet.remove(kind); if (kind.neverHasTarget()) targetKindSet.remove(kind); } } public ThisOrTargetPointcut(boolean isThis, TypePattern type) { this.isThis = isThis; this.type = type; this.pointcutKind = THIS_OR_TARGET; } public TypePattern getType() { return type; } public boolean isThis() { return isThis; } public Set couldMatchKinds() { return isThis ? thisKindSet : targetKindSet; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } private boolean couldMatch(Shadow shadow) { return isThis ? shadow.hasThis() : shadow.hasTarget(); } protected FuzzyBoolean matchInternal(Shadow shadow) { if (!couldMatch(shadow)) return FuzzyBoolean.NO; UnresolvedType typeToMatch = isThis ? shadow.getThisType() : shadow.getTargetType(); //if (typeToMatch == ResolvedType.MISSING) return FuzzyBoolean.NO; return type.matches(typeToMatch.resolve(shadow.getIWorld()), TypePattern.DYNAMIC);//AVPT was DYNAMIC } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.THIS_OR_TARGET); s.writeBoolean(isThis); type.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { boolean isThis = s.readBoolean(); TypePattern type = TypePattern.read(s, context); ThisOrTargetPointcut ret = new ThisOrTargetPointcut(isThis, type); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { type = type.resolveBindings(scope, bindings, true, true); // look for parameterized type patterns which are not supported... HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); type.traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.THIS_AND_TARGET_DONT_SUPPORT_PARAMETERS), getSourceLocation())); } // ??? handle non-formal } public void postRead(ResolvedType enclosingType) { type.postRead(enclosingType); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { if (type instanceof BindingTypePattern) { List l = new ArrayList(); l.add(type); return l; } else return Collections.EMPTY_LIST; } public boolean equals(Object other) { if (!(other instanceof ThisOrTargetPointcut)) return false; ThisOrTargetPointcut o = (ThisOrTargetPointcut)other; return o.isThis == this.isThis && o.type.equals(this.type); } public int hashCode() { int result = 17; result = 37*result + (isThis ? 0 : 1); result = 37*result + type.hashCode(); return result; } public String toString() { return (isThis ? "this(" : "target(") + type + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (!couldMatch(shadow)) return Literal.FALSE; if (type == TypePattern.ANY) return Literal.TRUE; Var var = isThis ? shadow.getThisVar() : shadow.getTargetVar(); if (type instanceof BindingTypePattern) { BindingTypePattern btp = (BindingTypePattern)type; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) && (lastMatchedShadowId != shadow.shadowId)){ // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use "+(isThis?"this()":"target()")+" to match at this location and bind a formal to type '"+var.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic "+(isThis?"this()":"target()")+".", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); //return null; } } return exposeStateForVar(var, type, state, shadow.getIWorld()); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.THIS_OR_TARGET_IN_DECLARE,isThis?"this":"target"), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } TypePattern newType = type.remapAdviceFormals(bindings); if (inAspect.crosscuttingMembers != null) { inAspect.crosscuttingMembers.exposeType(newType.getExactType()); } Pointcut ret = new ThisOrTargetPointcut(isThis, newType); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/TypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * On creation, type pattern only contains WildTypePattern nodes, not BindingType or ExactType. * * <p>Then we call resolveBindings() during compilation * During concretization of enclosing pointcuts, we call remapAdviceFormals * * @author Erik Hilsdale * @author Jim Hugunin */ public abstract class TypePattern extends PatternNode { public static class MatchKind { private String name; public MatchKind(String name) { this.name = name; } public String toString() { return name; } } public static final MatchKind STATIC = new MatchKind("STATIC"); public static final MatchKind DYNAMIC = new MatchKind("DYNAMIC"); public static final TypePattern ELLIPSIS = new EllipsisTypePattern(); public static final TypePattern ANY = new AnyTypePattern(); public static final TypePattern NO = new NoTypePattern(); protected boolean includeSubtypes; protected boolean isVarArgs = false; protected AnnotationTypePattern annotationPattern = AnnotationTypePattern.ANY; protected TypePatternList typeParameters = TypePatternList.EMPTY; protected TypePattern(boolean includeSubtypes,boolean isVarArgs,TypePatternList typeParams) { this.includeSubtypes = includeSubtypes; this.isVarArgs = isVarArgs; this.typeParameters = (typeParams == null ? TypePatternList.EMPTY : typeParams); } protected TypePattern(boolean includeSubtypes, boolean isVarArgs) { this(includeSubtypes,isVarArgs,null); } public AnnotationTypePattern getAnnotationPattern() { return annotationPattern; } public boolean isVarArgs() { return isVarArgs; } public boolean isStarAnnotation() { return annotationPattern == AnnotationTypePattern.ANY; } public boolean isArray() { return false; } protected TypePattern(boolean includeSubtypes) { this(includeSubtypes,false); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { this.annotationPattern = annPatt; } public void setTypeParameters(TypePatternList typeParams) { this.typeParameters = typeParams; } public TypePatternList getTypeParameters() { return this.typeParameters; } public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; } // answer conservatively... protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (this.includeSubtypes || other.includeSubtypes) return true; if (this.annotationPattern != AnnotationTypePattern.ANY) return true; if (other.annotationPattern != AnnotationTypePattern.ANY) return true; return false; } //XXX non-final for Not, && and || public boolean matchesStatically(ResolvedType type) { if (includeSubtypes) { return matchesSubtypes(type); } else { return matchesExactly(type); } } public abstract FuzzyBoolean matchesInstanceof(ResolvedType type); public final FuzzyBoolean matches(ResolvedType type, MatchKind kind) { FuzzyBoolean typeMatch = null; //??? This is part of gracefully handling missing references if (type == ResolvedType.MISSING) return FuzzyBoolean.NO; if (kind == STATIC) { // typeMatch = FuzzyBoolean.fromBoolean(matchesStatically(type)); // return typeMatch.and(annotationPattern.matches(type)); return FuzzyBoolean.fromBoolean(matchesStatically(type)); } else if (kind == DYNAMIC) { //System.err.println("matching: " + this + " with " + type); // typeMatch = matchesInstanceof(type); //System.err.println(" got: " + ret); // return typeMatch.and(annotationPattern.matches(type)); return matchesInstanceof(type); } else { throw new IllegalArgumentException("kind must be DYNAMIC or STATIC"); } } protected abstract boolean matchesExactly(ResolvedType type); protected abstract boolean matchesExactly(ResolvedType type, ResolvedType annotatedType); protected boolean matchesSubtypes(ResolvedType type) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(type)) { //System.out.println(" true"); return true; } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = type.getDirectSupertypes(); i.hasNext(); ) { ResolvedType superType = (ResolvedType)i.next(); // TODO asc generics, temporary whilst matching isnt aware.. //if (superType.isParameterizedType()) superType = superType.getRawType().resolve(superType.getWorld()); if (matchesSubtypes(superType,type)) return true; } return false; } protected boolean matchesSubtypes(ResolvedType superType, ResolvedType annotatedType) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(superType,annotatedType)) { //System.out.println(" true"); return true; } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = superType.getDirectSupertypes(); i.hasNext(); ) { ResolvedType superSuperType = (ResolvedType)i.next(); if (matchesSubtypes(superSuperType,annotatedType)) return true; } return false; } public UnresolvedType resolveExactType(IScope scope, Bindings bindings) { TypePattern p = resolveBindings(scope, bindings, false, true); if (p == NO) return ResolvedType.MISSING; return ((ExactTypePattern)p).getType(); } public UnresolvedType getExactType() { if (this instanceof ExactTypePattern) return ((ExactTypePattern)this).getType(); else return ResolvedType.MISSING; } protected TypePattern notExactType(IScope s) { s.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.EXACT_TYPE_PATTERN_REQD), getSourceLocation())); return NO; } // public boolean assertExactType(IMessageHandler m) { // if (this instanceof ExactTypePattern) return true; // // //XXX should try harder to avoid multiple errors for one problem // m.handleMessage(MessageUtil.error("exact type pattern required", getSourceLocation())); // return false; // } /** * This can modify in place, or return a new TypePattern if the type changes. */ public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); return this; } public void resolve(World world) { annotationPattern.resolve(world); } /** * return a version of this type pattern in which all type variable references have been * replaced by their corresponding entry in the map. */ public abstract TypePattern parameterizeWith(Map typeVariableMap); public void postRead(ResolvedType enclosingType) { } public boolean isStar() { return false; } /** * This is called during concretization of pointcuts, it is used by BindingTypePattern * to return a new BindingTypePattern with a formal index appropiate for the advice, * rather than for the lexical declaration, i.e. this handles transforamtions through * named pointcuts. * <pre> * pointcut foo(String name): args(name); * --&gt; This makes a BindingTypePattern(0) pointing to the 0th formal * * before(Foo f, String n): this(f) && foo(n) { ... } * --&gt; when resolveReferences is called on the args from the above, it * will return a BindingTypePattern(1) * * before(Foo f): this(f) && foo(*) { ... } * --&gt; when resolveReferences is called on the args from the above, it * will return an ExactTypePattern(String) * </pre> */ public TypePattern remapAdviceFormals(IntMap bindings) { return this; } public static final byte WILD = 1; public static final byte EXACT = 2; public static final byte BINDING = 3; public static final byte ELLIPSIS_KEY = 4; public static final byte ANY_KEY = 5; public static final byte NOT = 6; public static final byte OR = 7; public static final byte AND = 8; public static final byte NO_KEY = 9; public static final byte ANY_WITH_ANNO = 10; public static final byte HAS_MEMBER = 11; public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { byte key = s.readByte(); switch(key) { case WILD: return WildTypePattern.read(s, context); case EXACT: return ExactTypePattern.read(s, context); case BINDING: return BindingTypePattern.read(s, context); case ELLIPSIS_KEY: return ELLIPSIS; case ANY_KEY: return ANY; case NO_KEY: return NO; case NOT: return NotTypePattern.read(s, context); case OR: return OrTypePattern.read(s, context); case AND: return AndTypePattern.read(s, context); case ANY_WITH_ANNO: return AnyWithAnnotationTypePattern.read(s,context); case HAS_MEMBER: return HasMemberTypePattern.read(s,context); } throw new BCException("unknown TypePattern kind: " + key); } public boolean isIncludeSubtypes() { return includeSubtypes; } } class EllipsisTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public EllipsisTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return false; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(ELLIPSIS_KEY); } public String toString() { return ".."; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (obj instanceof EllipsisTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 * 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map typeVariableMap) { return this; } } class AnyTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public AnyTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return true; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.YES; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(ANY_KEY); } /** * @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind) */ // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType) */ protected boolean matchesSubtypes(ResolvedType type) { return true; } public boolean isStar() { return true; } public String toString() { return "*"; } public boolean equals(Object obj) { return (obj instanceof AnyTypePattern); } public int hashCode() { return 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map arg0) { return this; } } /** * This type represents a type pattern of '*' but with an annotation specified, * e.g. '@Color *' */ class AnyWithAnnotationTypePattern extends TypePattern { public AnyWithAnnotationTypePattern(AnnotationTypePattern atp) { super(false,false); annotationPattern = atp; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } protected boolean matchesExactly(ResolvedType type) { annotationPattern.resolve(type.getWorld()); return annotationPattern.matches(type).alwaysTrue(); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { annotationPattern.resolve(type.getWorld()); return annotationPattern.matches(annotatedType).alwaysTrue(); } public FuzzyBoolean matchesInstanceof(ResolvedType type) { if (Modifier.isFinal(type.getModifiers())) { return FuzzyBoolean.fromBoolean(matchesExactly(type)); } return FuzzyBoolean.MAYBE; } public TypePattern parameterizeWith(Map typeVariableMap) { return this; } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.ANY_WITH_ANNO); annotationPattern.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s,ISourceContext c) throws IOException { AnnotationTypePattern annPatt = AnnotationTypePattern.read(s,c); AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annPatt); ret.readLocation(c, s); return ret; } // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } protected boolean matchesSubtypes(ResolvedType type) { return true; } public boolean isStar() { return false; } public String toString() { return annotationPattern+" *"; } public boolean equals(Object obj) { if (!(obj instanceof AnyWithAnnotationTypePattern)) return false; AnyWithAnnotationTypePattern awatp = (AnyWithAnnotationTypePattern) obj; return (annotationPattern.equals(awatp.annotationPattern)); } public int hashCode() { return annotationPattern.hashCode(); } } class NoTypePattern extends TypePattern { public NoTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return false; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(NO_KEY); } /** * @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind) */ // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType) */ protected boolean matchesSubtypes(ResolvedType type) { return false; } public boolean isStar() { return false; } public String toString() { return "<nothing>"; }//FIXME AV - bad! toString() cannot be parsed back (not idempotent) /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (obj instanceof NoTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 * 37 * 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map arg0) { return this; } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/WithinAnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class WithinAnnotationPointcut extends NameBindingPointcut { private AnnotationTypePattern annotationTypePattern; private ShadowMunger munger; /** * */ public WithinAnnotationPointcut(AnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = ATWITHIN; } public WithinAnnotationPointcut(AnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; this.pointcutKind = ATWITHIN; } public AnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return annotationTypePattern.fastMatches(info.getType()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedType enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true); if (enclosingType == ResolvedType.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_WITHINPCD, shadow.getEnclosingType().getName()), shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); shadow.getIWorld().getMessageHandler().handleMessage(msg); } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(enclosingType); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new WithinAnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.annotationType; Var var = shadow.getWithinAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]"); // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId == shadow.shadowId)) { // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use @pointcut to match at this location and bind a formal to type '"+var.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic binding.", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } state.set(btp.getFormalIndex(),var); } return Literal.TRUE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATWITHIN); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); WithinAnnotationPointcut ret = new WithinAnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof WithinAnnotationPointcut)) return false; WithinAnnotationPointcut other = (WithinAnnotationPointcut) obj; return other.annotationTypePattern.equals(this.annotationTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 19*annotationTypePattern.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("@within("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); return buf.toString(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/WithinCodeAnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class WithinCodeAnnotationPointcut extends NameBindingPointcut { private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger = null; // only set after concretization private static final Set matchedShadowKinds = new HashSet(); static { matchedShadowKinds.addAll(Shadow.ALL_SHADOW_KINDS); for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (Shadow.SHADOW_KINDS[i].isEnclosingKind()) matchedShadowKinds.remove(Shadow.SHADOW_KINDS[i]); } } public WithinCodeAnnotationPointcut(ExactAnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = Pointcut.ATWITHINCODE; } public WithinCodeAnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; this.pointcutKind = Pointcut.ATWITHINCODE; } public ExactAnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public Set couldMatchKinds() { return matchedShadowKinds; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { AnnotatedElement toMatchAgainst = null; Member member = shadow.getEnclosingCodeSignature(); ResolvedMember rMember = member.resolve(shadow.getIWorld()); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(rMember); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new WithinCodeAnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.annotationType; Var var = shadow.getWithinCodeAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]"); // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId == shadow.shadowId)) { // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use @pointcut to match at this location and bind a formal to type '"+var.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic binding.", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } state.set(btp.getFormalIndex(),var); } return Literal.TRUE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATWITHINCODE); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); WithinCodeAnnotationPointcut ret = new WithinCodeAnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof WithinCodeAnnotationPointcut)) return false; WithinCodeAnnotationPointcut o = (WithinCodeAnnotationPointcut)other; return o.annotationTypePattern.equals(this.annotationTypePattern); } public int hashCode() { int result = 17; result = 23*result + annotationTypePattern.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("@withincode("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); return buf.toString(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/WithinPointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class WithinPointcut extends Pointcut { private TypePattern typePattern; public WithinPointcut(TypePattern type) { this.typePattern = type; this.pointcutKind = WITHIN; } public TypePattern getTypePattern() { return typePattern; } private FuzzyBoolean isWithinType(ResolvedType type) { while (type != null) { if (typePattern.matchesStatically(type)) { return FuzzyBoolean.YES; } type = type.getDeclaringType(); } return FuzzyBoolean.NO; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo info) { if (typePattern.annotationPattern instanceof AnyAnnotationTypePattern) { return isWithinType(info.getType()); } return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedType enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true); if (enclosingType == ResolvedType.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_WITHINPCD, shadow.getEnclosingType().getName()), shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()}); shadow.getIWorld().getMessageHandler().handleMessage(msg); } typePattern.resolve(shadow.getIWorld()); return isWithinType(enclosingType); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.WITHIN); typePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { TypePattern type = TypePattern.read(s, context); WithinPointcut ret = new WithinPointcut(type); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { typePattern = typePattern.resolveBindings(scope, bindings, false, false); // look for parameterized type patterns which are not supported... HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); typePattern.traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.WITHIN_PCD_DOESNT_SUPPORT_PARAMETERS), getSourceLocation())); } } public void postRead(ResolvedType enclosingType) { typePattern.postRead(enclosingType); } public boolean couldEverMatchSameJoinPointsAs(WithinPointcut other) { return typePattern.couldEverMatchSameTypesAs(other.typePattern); } public boolean equals(Object other) { if (!(other instanceof WithinPointcut)) return false; WithinPointcut o = (WithinPointcut)other; return o.typePattern.equals(this.typePattern); } public int hashCode() { int result = 43; result = 37*result + typePattern.hashCode(); return result; } public String toString() { return "within(" + typePattern + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new WithinPointcut(typePattern); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,117
Bug 108117 Complete implementation of abstract generic aspects
this requires 1/ completion of the parameterizeWith implementation in the pointcut AST nodes 2/ a much more exhaustive test suite around it.
resolved fixed
451fea8
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T11:54:49Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/WithincodePointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class WithincodePointcut extends Pointcut { private SignaturePattern signature; private static final Set matchedShadowKinds = new HashSet(); static { matchedShadowKinds.addAll(Shadow.ALL_SHADOW_KINDS); for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (Shadow.SHADOW_KINDS[i].isEnclosingKind()) matchedShadowKinds.remove(Shadow.SHADOW_KINDS[i]); } // these next two are needed for inlining of field initializers matchedShadowKinds.add(Shadow.ConstructorExecution); matchedShadowKinds.add(Shadow.Initialization); } public WithincodePointcut(SignaturePattern signature) { this.signature = signature; this.pointcutKind = WITHINCODE; } public SignaturePattern getSignature() { return signature; } public Set couldMatchKinds() { return matchedShadowKinds; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //This will not match code in local or anonymous classes as if //they were withincode of the outer signature return FuzzyBoolean.fromBoolean( signature.matches(shadow.getEnclosingCodeSignature(), shadow.getIWorld(), false)); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.WITHINCODE); signature.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { WithincodePointcut ret = new WithincodePointcut(SignaturePattern.read(s, context)); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { signature = signature.resolveBindings(scope, bindings); // look for inappropriate use of parameterized types and tell user... HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.WITHINCODE_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES), getSourceLocation())); } visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getThrowsPattern().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES), getSourceLocation())); } } public void postRead(ResolvedType enclosingType) { signature.postRead(enclosingType); } public boolean equals(Object other) { if (!(other instanceof WithincodePointcut)) return false; WithincodePointcut o = (WithincodePointcut)other; return o.signature.equals(this.signature); } public int hashCode() { int result = 43; result = 37*result + signature.hashCode(); return result; } public String toString() { return "withincode(" + signature + ")"; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE; } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new WithincodePointcut(signature); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation * David Knibb weaving context enhancments *******************************************************************************/ package org.aspectj.weaver.loadtime; import org.aspectj.asm.IRelationship; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.ICrossReferenceHandler; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.loadtime.definition.DocumentParser; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.tools.GeneratedClassHandler; import org.aspectj.weaver.tools.WeavingAdaptor; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; /** * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { private final static String AOP_XML = "META-INF/aop.xml"; private List m_dumpTypePattern = new ArrayList(); private List m_includeTypePattern = new ArrayList(); private List m_excludeTypePattern = new ArrayList(); private List m_aspectExcludeTypePattern = new ArrayList(); private StringBuffer namespace; private IWeavingContext weavingContext; public ClassLoaderWeavingAdaptor(final ClassLoader loader, IWeavingContext wContext) { super(null);// at this stage we don't have yet a generatedClassHandler to define to the VM the closures this.generatedClassHandler = new GeneratedClassHandler() { /** * Callback when we need to define a Closure in the JVM * * @param name * @param bytes */ public void acceptClass(String name, byte[] bytes) { //TODO av make dump configurable try { if (shouldDump(name.replace('/', '.'))) { Aj.dump(name, bytes); } } catch (Throwable throwable) { throwable.printStackTrace(); } Aj.defineClass(loader, name, bytes);// could be done lazily using the hook } }; if(wContext==null){ weavingContext = new DefaultWeavingContext(loader); }else{ weavingContext = wContext ; } bcelWorld = new BcelWorld( loader, messageHandler, new ICrossReferenceHandler() { public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) { ;// for tools only } } ); // //TODO this AJ code will call // //org.aspectj.apache.bcel.Repository.setRepository(this); // //ie set some static things // //==> bogus as Bcel is expected to be // org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader)); weaver = new BcelWeaver(bcelWorld); // register the definitions registerDefinitions(weaver, loader); messageHandler = bcelWorld.getMessageHandler(); // after adding aspects weaver.prepareForWeave(); } /** * Load and cache the aop.xml/properties according to the classloader visibility rules * * @param weaver * @param loader */ private void registerDefinitions(final BcelWeaver weaver, final ClassLoader loader) { try { MessageUtil.info(messageHandler, "register classloader " + ((loader!=null)?loader.getClass().getName()+"@"+loader.hashCode():"null")); //TODO av underoptimized: we will parse each XML once per CL that see it List definitions = new ArrayList(); //TODO av dev mode needed ? TBD -Daj5.def=... if (ClassLoader.getSystemClassLoader().equals(loader)) { String file = System.getProperty("aj5.def", null); if (file != null) { MessageUtil.info(messageHandler, "using (-Daj5.def) " + file); definitions.add(DocumentParser.parse((new File(file)).toURL())); } } String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration",AOP_XML); StringTokenizer st = new StringTokenizer(resourcePath,";"); while(st.hasMoreTokens()){ Enumeration xmls = weavingContext.getResources(st.nextToken()); // System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader); while (xmls.hasMoreElements()) { URL xml = (URL) xmls.nextElement(); MessageUtil.info(messageHandler, "using " + xml.getFile()); definitions.add(DocumentParser.parse(xml)); } } // still go thru if definitions is empty since we will configure // the default message handler in there registerOptions(weaver, loader, definitions); registerAspectExclude(weaver, loader, definitions); registerAspects(weaver, loader, definitions); registerIncludeExclude(weaver, loader, definitions); registerDump(weaver, loader, definitions); } catch (Exception e) { weaver.getWorld().getMessageHandler().handleMessage( new Message("Register definition failed", IMessage.WARNING, e, null) ); } } /** * Configure the weaver according to the option directives * TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW * * @param weaver * @param loader * @param definitions */ private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { StringBuffer allOptions = new StringBuffer(); for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); allOptions.append(definition.getWeaverOptions()).append(' '); } Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader); // configure the weaver and world // AV - code duplicates AspectJBuilder.initWorldAndWeaver() World world = weaver.getWorld(); world.setMessageHandler(weaverOption.messageHandler); world.setXlazyTjp(weaverOption.lazyTjp); world.setXHasMemberSupportEnabled(weaverOption.hasMember); world.setPinpointMode(weaverOption.pinpoint); weaver.setReweavableMode(weaverOption.reWeavable, false); world.setXnoInline(weaverOption.noInline); world.setBehaveInJava5Way(weaverOption.java5);//TODO should be autodetected ? //-Xlintfile: first so that lint wins if (weaverOption.lintFile != null) { InputStream resource = null; try { resource = loader.getResourceAsStream(weaverOption.lintFile); Exception failure = null; if (resource != null) { try { Properties properties = new Properties(); properties.load(resource); world.getLint().setFromProperties(properties); } catch (IOException e) { failure = e; } } if (failure != null || resource == null) { world.getMessageHandler().handleMessage(new Message( "Cannot access resource for -Xlintfile:"+weaverOption.lintFile, IMessage.WARNING, failure, null)); } } finally { try { resource.close(); } catch (Throwable t) {;} } } if (weaverOption.lint != null) { if (weaverOption.lint.equals("default")) {//FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps.. bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(weaverOption.lint); } } //TODO proceedOnError option } private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) { String exclude = (String) iterator1.next(); TypePattern excludePattern = new PatternParser(exclude).parseTypePattern(); m_aspectExcludeTypePattern.add(excludePattern); } } } /** * Register the aspect, following include / exclude rules * * @param weaver * @param loader * @param definitions */ private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { //TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ?? // if not, review the getResource so that we track which resource is defined by which CL //it aspectClassNames //exclude if in any of the exclude list for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) { String aspectClassName = (String) aspects.next(); if (acceptAspect(aspectClassName)) { weaver.addLibraryAspect(aspectClassName); //generate key for SC String aspectCode = readAspect(aspectClassName, loader); if(namespace==null){ namespace=new StringBuffer(aspectCode); }else{ namespace = namespace.append(";"+aspectCode); } } } } //it concreteAspects //exclude if in any of the exclude list //TODO } /** * Register the include / exclude filters * * @param weaver * @param loader * @param definitions */ private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) { String include = (String) iterator1.next(); TypePattern includePattern = new PatternParser(include).parseTypePattern(); m_includeTypePattern.add(includePattern); } for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) { String exclude = (String) iterator1.next(); TypePattern excludePattern = new PatternParser(exclude).parseTypePattern(); m_excludeTypePattern.add(excludePattern); } } } /** * Register the dump filter * * @param weaver * @param loader * @param definitions */ private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) { String dump = (String) iterator1.next(); TypePattern pattern = new PatternParser(dump).parseTypePattern(); m_dumpTypePattern.add(pattern); } } } protected boolean accept(String className) { // avoid ResolvedType if not needed if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) { return true; } //TODO AV - optimize for className.startWith only ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true); //exclude are "AND"ed for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // exclude match - skip return false; } } //include are "OR"ed boolean accept = true;//defaults to true if no include for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); accept = typePattern.matchesStatically(classInfo); if (accept) { break; } // goes on if this include did not match ("OR"ed) } return accept; } private boolean acceptAspect(String aspectClassName) { // avoid ResolvedType if not needed if (m_aspectExcludeTypePattern.isEmpty()) { return true; } //TODO AV - optimize for className.startWith only ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true); //exclude are "AND"ed for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // exclude match - skip return false; } } return true; } public boolean shouldDump(String className) { // avoid ResolvedType if not needed if (m_dumpTypePattern.isEmpty()) { return false; } //TODO AV - optimize for className.startWith only ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true); //dump for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // dump match return true; } } return false; } /* * shared classes methods */ /** * @return Returns the key. */ public String getNamespace() { if(namespace==null) return ""; else return new String(namespace); } /** * Check to see if any classes are stored in the generated classes cache. * Then flush the cache if it is not empty * @return true if a class has been generated and is stored in the cache */ public boolean generatedClassesExist(){ if(generatedClasses.size()>0) { return true; } return false; } /** * Flush the generated classes cache */ public void flushGeneratedClasses(){ generatedClasses = new HashMap(); } /** * Read in an aspect from the disk and return its bytecode as a String * @param name the name of the aspect to read in * @return the bytecode representation of the aspect */ private String readAspect(String name, ClassLoader loader){ try { String result = ""; InputStream is = loader.getResourceAsStream(name.replace('.','/')+".class"); int b = is.read(); while(b!=-1){ result = result + b; b=is.read(); } is.close(); return result; } catch (IOException e) { e.printStackTrace(); return ""; }catch (NullPointerException e) { //probably tried to read in a "non aspect @missing@" aspect System.err.println("ClassLoaderWeavingAdaptor.readAspect() name: "+name+" Exception: "+e); return ""; } } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
loadtime/src/org/aspectj/weaver/loadtime/Options.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package org.aspectj.weaver.loadtime; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.Message; import org.aspectj.util.LangUtil; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * A class that hanldes LTW options. * Note: AV - I choosed to not reuse AjCompilerOptions and alike since those implies too many dependancies on * jdt and ajdt modules. * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class Options { private final static String OPTION_15 = "-1.5"; private final static String OPTION_lazyTjp = "-XlazyTjp"; private final static String OPTION_noWarn = "-nowarn"; private final static String OPTION_noWarnNone = "-warn:none"; private final static String OPTION_proceedOnError = "-proceedOnError"; private final static String OPTION_verbose = "-verbose"; private final static String OPTION_reweavable = "-Xreweavable"; private final static String OPTION_noinline = "-Xnoinline"; private final static String OPTION_hasMember = "-XhasMember"; private final static String OPTION_pinpoint = "-Xdev:pinpoint"; private final static String OPTION_showWeaveInfo = "-showWeaveInfo"; private final static String OPTIONVALUED_messageHandler = "-XmessageHandlerClass:"; private static final String OPTIONVALUED_Xlintfile = "-Xlintfile:"; private static final String OPTIONVALUED_Xlint = "-Xlint:"; public static WeaverOption parse(String options, ClassLoader laoder) { if (LangUtil.isEmpty(options)) { return new WeaverOption(); } // the first option wins List flags = LangUtil.anySplit(options, " "); Collections.reverse(flags); WeaverOption weaverOption = new WeaverOption(); // do a first round on the message handler since it will report the options themselves for (Iterator iterator = flags.iterator(); iterator.hasNext();) { String arg = (String) iterator.next(); if (arg.startsWith(OPTIONVALUED_messageHandler)) { if (arg.length() > OPTIONVALUED_messageHandler.length()) { String handlerClass = arg.substring(OPTIONVALUED_messageHandler.length()).trim(); try { Class handler = Class.forName(handlerClass, false, laoder); weaverOption.messageHandler = ((IMessageHandler) handler.newInstance()); } catch (Throwable t) { weaverOption.messageHandler.handleMessage( new Message( "Cannot instantiate message handler " + handlerClass, IMessage.ERROR, t, null ) ); } } } } // configure the other options for (Iterator iterator = flags.iterator(); iterator.hasNext();) { String arg = (String) iterator.next(); if (arg.equals(OPTION_15)) { weaverOption.java5 = true; } else if (arg.equalsIgnoreCase(OPTION_lazyTjp)) { weaverOption.lazyTjp = true; } else if (arg.equalsIgnoreCase(OPTION_noinline)) { weaverOption.noInline = true; } else if (arg.equalsIgnoreCase(OPTION_noWarn) || arg.equalsIgnoreCase(OPTION_noWarnNone)) { weaverOption.noWarn = true; } else if (arg.equalsIgnoreCase(OPTION_proceedOnError)) { weaverOption.proceedOnError = true; } else if (arg.equalsIgnoreCase(OPTION_reweavable)) { weaverOption.reWeavable = true; } else if (arg.equalsIgnoreCase(OPTION_showWeaveInfo)) { weaverOption.showWeaveInfo = true; } else if (arg.equalsIgnoreCase(OPTION_hasMember)) { weaverOption.hasMember = true; } else if (arg.equalsIgnoreCase(OPTION_verbose)) { weaverOption.verbose = true; } else if (arg.equalsIgnoreCase(OPTION_pinpoint)) { weaverOption.pinpoint = true; } else if (arg.startsWith(OPTIONVALUED_messageHandler)) { ;// handled in first round } else if (arg.startsWith(OPTIONVALUED_Xlintfile)) { if (arg.length() > OPTIONVALUED_Xlintfile.length()) { weaverOption.lintFile = arg.substring(OPTIONVALUED_Xlintfile.length()).trim(); } } else if (arg.startsWith(OPTIONVALUED_Xlint)) { if (arg.length() > OPTIONVALUED_Xlint.length()) { weaverOption.lint = arg.substring(OPTIONVALUED_Xlint.length()).trim(); } } else { weaverOption.messageHandler.handleMessage( new Message( "Cannot configure weaver with option '" + arg + "': unknown option", IMessage.WARNING, null, null ) ); } } // refine message handler configuration if (weaverOption.noWarn) { weaverOption.messageHandler.dontIgnore(IMessage.WARNING); } if (weaverOption.verbose) { weaverOption.messageHandler.dontIgnore(IMessage.DEBUG); } if (weaverOption.showWeaveInfo) { weaverOption.messageHandler.dontIgnore(IMessage.WEAVEINFO); } return weaverOption; } public static class WeaverOption { boolean java5; boolean lazyTjp; boolean hasMember; boolean noWarn; boolean proceedOnError; boolean verbose; boolean reWeavable; boolean noInline; boolean showWeaveInfo; boolean pinpoint; IMessageHandler messageHandler; String lint; String lintFile; public WeaverOption() { messageHandler = new DefaultMessageHandler();//default } } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.ajc; import java.io.*; import java.util.*; import org.aspectj.ajdt.internal.core.builder.*; import org.aspectj.bridge.*; import org.aspectj.util.*; import org.aspectj.weaver.Dump; import org.aspectj.weaver.WeaverMessages; import org.aspectj.org.eclipse.jdt.core.compiler.InvalidInputException; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.Main; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; public class BuildArgParser extends Main { private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages"; private static boolean LOADED_BUNDLE = false; static { bundle = ResourceBundle.getBundle(BUNDLE_NAME); if (!LOADED_BUNDLE) { LOADED_BUNDLE = true; } } /** to initialize super's PrintWriter but refer to underlying StringWriter */ private static class StringPrintWriter extends PrintWriter { public final StringWriter stringWriter; StringPrintWriter(StringWriter sw) { super(sw); this.stringWriter = sw; } } /** @return multi-line String usage for the compiler */ public static String getUsage() { return Main.bind("misc.usage",Main.bind("compiler.name")); } public static String getXOptionUsage() { return Main.bind("xoption.usage",Main.bind("compiler.name")); } /** * StringWriter sink for some errors. * This only captures errors not handled by any IMessageHandler parameter * and only when no PrintWriter is set in the constructor. * XXX This relies on (Sun's) implementation of StringWriter, * which returns the actual (not copy) internal StringBuffer. */ private final StringBuffer errorSink; private IMessageHandler handler; /** * Overrides super's bundle. */ public BuildArgParser(PrintWriter writer, IMessageHandler handler) { super(writer, writer, false); if (writer instanceof StringPrintWriter) { errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer(); } else { errorSink = null; } this.handler = handler; } /** Set up to capture messages using getOtherMessages(boolean) */ public BuildArgParser(IMessageHandler handler) { this(new StringPrintWriter(new StringWriter()),handler); } /** * Generate build configuration for the input args, * passing to handler any error messages. * @param args the String[] arguments for the build configuration * @return AjBuildConfig per args, * which will be invalid unless there are no handler errors. */ public AjBuildConfig genBuildConfig(String[] args) { AjBuildConfig config = new AjBuildConfig(); populateBuildConfig(config, args, true, null); return config; } /** * Generate build configuration for the input args, * passing to handler any error messages. * @param args the String[] arguments for the build configuration * @param setClasspath determines if the classpath should be parsed and set on the build configuration * @param configFile can be null * @return AjBuildConfig per args, * which will be invalid unless there are no handler errors. */ public AjBuildConfig populateBuildConfig(AjBuildConfig buildConfig, String[] args, boolean setClasspath, File configFile) { Dump.saveCommandLine(args); buildConfig.setConfigFile(configFile); try { // sets filenames to be non-null in order to make sure that file paramters are ignored super.filenames = new String[] { "" }; AjcConfigParser parser = new AjcConfigParser(buildConfig, handler); parser.parseCommandLine(args); boolean swi = buildConfig.getShowWeavingInformation(); // Now jump through firey hoops to turn them on/off if (handler instanceof CountingMessageHandler) { IMessageHandler delegate = ((CountingMessageHandler)handler).delegate; // Without dontIgnore() on the IMessageHandler interface, we have to do this *blurgh* if (delegate instanceof MessageHandler) { if (swi) ((MessageHandler)delegate).dontIgnore(IMessage.WEAVEINFO); else ((MessageHandler)delegate).ignore(IMessage.WEAVEINFO); } } boolean incrementalMode = buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode(); List fileList = new ArrayList(); List files = parser.getFiles(); if (!LangUtil.isEmpty(files)) { if (incrementalMode) { MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots"); } else { fileList.addAll(files); } } List javaArgList = new ArrayList(); // disable all special eclipse warnings by default - why??? //??? might want to instead override getDefaultOptions() javaArgList.add("-warn:none"); // these next four lines are some nonsense to fool the eclipse batch compiler // without these it will go searching for reasonable values from properties //TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed javaArgList.add("-classpath"); javaArgList.add(System.getProperty("user.dir")); javaArgList.add("-bootclasspath"); javaArgList.add(System.getProperty("user.dir")); javaArgList.addAll(parser.getUnparsedArgs()); super.configure((String[])javaArgList.toArray(new String[javaArgList.size()])); if (!proceed) { buildConfig.doNotProceed(); return buildConfig; } if (buildConfig.getSourceRoots() != null) { for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) { fileList.addAll(collectSourceRootFiles((File)i.next())); } } buildConfig.setFiles(fileList); if (destinationPath != null) { // XXX ?? unparsed but set? buildConfig.setOutputDir(new File(destinationPath)); } if (setClasspath) { buildConfig.setClasspath(getClasspath(parser)); buildConfig.setBootclasspath(getBootclasspath(parser)); } if (incrementalMode && (0 == buildConfig.getSourceRoots().size())) { MessageUtil.error(handler, "specify a source root when in incremental mode"); } /* * Ensure we don't overwrite injars, inpath or aspectpath with outjar * bug-71339 */ File outjar = buildConfig.getOutputJar(); if (outjar != null) { /* Search injars */ for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File injar = (File)i.next(); if (injar.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } /* Search inpath */ for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory() && inPathElement.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } /* Search aspectpath */ for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext(); ) { File pathElement = (File)i.next(); if (!pathElement.isDirectory() && pathElement.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } } setDebugOptions(); buildConfig.getOptions().set(options); } catch (InvalidInputException iie) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location); handler.handleMessage(m); } return buildConfig; } // from super... public void printVersion() { System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$ System.err.flush(); } public void printUsage() { System.out.println(bind("misc.usage")); //$NON-NLS-1$ System.out.flush(); } /** * Get messages not dumped to handler or any PrintWriter. * @param flush if true, empty errors * @return null if none, String otherwise * @see BuildArgParser() */ public String getOtherMessages(boolean flush) { if (null == errorSink) { return null; } String result = errorSink.toString().trim(); if (0 == result.length()) { result = null; } if (flush) { errorSink.setLength(0); } return result; } private void setDebugOptions() { options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); } private Collection collectSourceRootFiles(File dir) { return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter)); } public List getBootclasspath(AjcConfigParser parser) { List ret = new ArrayList(); if (parser.bootclasspath == null) { addClasspath(System.getProperty("sun.boot.class.path", ""), ret); } else { addClasspath(parser.bootclasspath, ret); } return ret; } /** * If the classpath is not set, we use the environment's java.class.path, but remove * the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues * (refer to bug#39959). */ public List getClasspath(AjcConfigParser parser) { List ret = new ArrayList(); // if (parser.bootclasspath == null) { // addClasspath(System.getProperty("sun.boot.class.path", ""), ret); // } else { // addClasspath(parser.bootclasspath, ret); // } String extdirs = parser.extdirs; if (extdirs == null) { extdirs = System.getProperty("java.ext.dirs", ""); } addExtDirs(extdirs, ret); if (parser.classpath == null) { addClasspath(System.getProperty("java.class.path", ""), ret); List fixedList = new ArrayList(); for (Iterator it = ret.iterator(); it.hasNext(); ) { String entry = (String)it.next(); if (!entry.endsWith("aspectjtools.jar")) { fixedList.add(entry); } } ret = fixedList; } else { addClasspath(parser.classpath, ret); } //??? eclipse seems to put outdir on the classpath //??? we're brave and believe we don't need it return ret; } private void addExtDirs(String extdirs, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator); while (tokenizer.hasMoreTokens()) { // classpathCollector.add(tokenizer.nextToken()); File dirFile = new File((String)tokenizer.nextToken()); if (dirFile.canRead() && dirFile.isDirectory()) { File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER); for (int i = 0; i < files.length; i++) { classpathCollector.add(files[i].getAbsolutePath()); } } else { // XXX alert on invalid -extdirs entries } } } private void addClasspath(String classpath, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { classpathCollector.add(tokenizer.nextToken()); } } private class AjcConfigParser extends ConfigParser { private String bootclasspath = null; private String classpath = null; private String extdirs = null; private List unparsedArgs = new ArrayList(); private AjBuildConfig buildConfig; private IMessageHandler handler; public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) { this.buildConfig = buildConfig; this.handler = handler; } public List getUnparsedArgs() { return unparsedArgs; } /** * Extract AspectJ-specific options (except for argfiles). * Caller should warn when sourceroots is empty but in * incremental mode. * Signals warnings or errors through handler set in constructor. */ public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove() int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique // trim arg? if (LangUtil.isEmpty(arg)) { showWarning("empty arg found"); } else if (arg.equals("-inpath")) {; if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE); List inPath = buildConfig.getInpath(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File file = makeFile(filename); if (file.exists() && FileUtil.hasZipSuffix(filename)) { inPath.add(file); } else { if (file.isDirectory()) { inPath.add(file); } else showError("bad inpath component: " + filename); } } buildConfig.setInPath(inPath); args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-injars")) {; if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) { buildConfig.getInJars().add(jarFile); } else { File dirFile = makeFile(filename); if (dirFile.isDirectory()) { buildConfig.getInJars().add(dirFile); } else showError("bad injar: " + filename); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-aspectpath")) {; if (args.size() > nextArgIndex) { StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (jarFile.exists() && (FileUtil.hasZipSuffix(filename) || jarFile.isDirectory())) { buildConfig.getAspectpath().add(jarFile); } else { showError("bad aspectpath: " + filename); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-sourceroots")) { if (args.size() > nextArgIndex) { List sourceRoots = new ArrayList(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { File f = makeFile(st.nextToken()); if (f.isDirectory() && f.canRead()) { sourceRoots.add(f); } else { showError("bad sourceroot: " + f); } } if (0 < sourceRoots.size()) { buildConfig.setSourceRoots(sourceRoots); } args.remove(args.get(nextArgIndex)); } else { showError("-sourceroots requires list of directories"); } } else if (arg.equals("-outjar")) { if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE); File jarFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); if (FileUtil.hasZipSuffix(jarFile)) { try { if (!jarFile.exists()) { jarFile.createNewFile(); } buildConfig.setOutputJar(jarFile); } catch (IOException ioe) { showError("unable to create outjar file: " + jarFile); } } else { showError("invalid -outjar file: " + jarFile); } args.remove(args.get(nextArgIndex)); } else { showError("-outjar requires jar path argument"); } } else if (arg.equals("-log")){ // remove it as it's already been handled in org.aspectj.tools.ajc.Main args.remove(args.get(nextArgIndex)); } else if (arg.equals("-incremental")) { buildConfig.setIncrementalMode(true); } else if (arg.equals("-XincrementalFile")) { if (args.size() > nextArgIndex) { File file = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); buildConfig.setIncrementalFile(file); if (!file.canRead()) { showError("bad -XincrementalFile : " + file); // if not created before recompile test, stop after first compile } args.remove(args.get(nextArgIndex)); } else { showError("-XincrementalFile requires file argument"); } } else if (arg.equals("-emacssym")) { buildConfig.setEmacsSymMode(true); buildConfig.setGenerateModelMode(true); } else if (arg.equals("-XjavadocsInModel")) { buildConfig.setGenerateModelMode(true); buildConfig.setGenerateJavadocsInModelMode(true); } else if (arg.equals("-Xdev:NoAtAspectJProcessing")) { buildConfig.setNoAtAspectJAnnotationProcessing(true); } else if (arg.equals("-Xdev:Pinpoint")) { buildConfig.setXdevPinpointMode(true); } else if (arg.equals("-noweave") || arg.equals( "-XnoWeave")) { buildConfig.setNoWeave(true); } else if (arg.equals("-XserializableAspects")) { buildConfig.setXserializableAspects(true); } else if (arg.equals("-XlazyTjp")) { buildConfig.setXlazyTjp(true); } else if (arg.startsWith("-Xreweavable")) { buildConfig.setXreweavable(true); if (arg.endsWith(":compress")) { buildConfig.setXreweavableCompressClasses(true); } } else if (arg.equals("-XnoInline")) { buildConfig.setXnoInline(true); } else if (arg.equals("-XhasMember")) { buildConfig.setXHasMemberSupport(true); } else if (arg.startsWith("-showWeaveInfo")) { buildConfig.setShowWeavingInformation(true); } else if (arg.equals("-Xlintfile")) { if (args.size() > nextArgIndex) { File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); // XXX relax restriction on props file suffix? if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) { buildConfig.setLintSpecFile(lintSpecFile); } else { showError("bad -Xlintfile file: " + lintSpecFile); buildConfig.setLintSpecFile(null); } args.remove(args.get(nextArgIndex)); } else { showError("-Xlintfile requires .properties file argument"); } } else if (arg.equals("-Xlint")) { // buildConfig.getAjOptions().put( // AjCompilerOptions.OPTION_Xlint, // CompilerOptions.GENERATE); buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT); } else if (arg.startsWith("-Xlint:")) { if (7 < arg.length()) { buildConfig.setLintMode(arg.substring(7)); } else { showError("invalid lint option " + arg); } } else if (arg.equals("-bootclasspath")) { if (args.size() > nextArgIndex) { String bcpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer bcp = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator); while (strTok.hasMoreTokens()) { bcp.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { bcp.append(File.pathSeparator); } } bootclasspath = bcp.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-bootclasspath requires classpath entries"); } } else if (arg.equals("-classpath") || arg.equals("-cp")) { if (args.size() > nextArgIndex) { String cpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer cp = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator); while (strTok.hasMoreTokens()) { cp.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { cp.append(File.pathSeparator); } } classpath = cp.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-classpath requires classpath entries"); } } else if (arg.equals("-extdirs")) { if (args.size() > nextArgIndex) { String extdirsArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer ed = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator); while (strTok.hasMoreTokens()) { ed.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { ed.append(File.pathSeparator); } } extdirs = ed.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-extdirs requires list of external directories"); } // error on directory unless -d, -{boot}classpath, or -extdirs } else if (arg.equals("-d")) { dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-classpath")) { // dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-bootclasspath")) { // dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-extdirs")) { // dirLookahead(arg, args, nextArgIndex); } else if (arg.equals("-proceedOnError")) { buildConfig.setProceedOnError(true); } else if (new File(arg).isDirectory()) { showError("dir arg not permitted: " + arg); } else if (arg.equals("-1.5")) { buildConfig.setBehaveInJava5Way(true); unparsedArgs.add("-1.5"); // this would enable the '-source 1.5' to do the same as '-1.5' but doesnt sound quite right as // as an option right now as it doesnt mean we support 1.5 source code - people will get confused... } else if (arg.equals("-source")) { if (args.size() > nextArgIndex) { String level = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); if (level.equals("1.5")){ buildConfig.setBehaveInJava5Way(true); } unparsedArgs.add("-source"); unparsedArgs.add(level); args.remove(args.get(nextArgIndex)); } } else { // argfile, @file parsed by superclass // no eclipse options parsed: // -d args, -help (handled), // -classpath, -target, -1.3, -1.4, -source [1.3|1.4] // -nowarn, -warn:[...], -deprecation, -noImportError, // -g:[...], -preserveAllLocals, // -referenceInfo, -encoding, -verbose, -log, -time // -noExit, -repeat // (Actually, -noExit grabbed by Main) unparsedArgs.add(arg); } } protected void dirLookahead(String arg, LinkedList argList, int nextArgIndex) { unparsedArgs.add(arg); ConfigParser.Arg next = (ConfigParser.Arg) argList.get(nextArgIndex); String value = next.getValue(); if (!LangUtil.isEmpty(value)) { if (new File(value).isDirectory()) { unparsedArgs.add(value); argList.remove(next); return; } } } public void showError(String message) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.ERROR, null, location); handler.handleMessage(errorMessage); // MessageUtil.error(handler, CONFIG_MSG + message); } protected void showWarning(String message) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location); handler.handleMessage(errorMessage); // MessageUtil.warn(handler, message); } protected File makeFile(File dir, String name) { name = name.replace('/', File.separatorChar); File ret = new File(name); if (dir == null || ret.isAbsolute()) return ret; try { dir = dir.getCanonicalFile(); } catch (IOException ioe) { } return new File(dir, name); } } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/core/AspectJCore.java
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.ajdt.core; import java.util.Map; import org.aspectj.ajdt.internal.core.builder.AjCompilerOptions; import org.aspectj.org.eclipse.jdt.core.JavaCore; /** * This is the plugin class for AspectJ. */ public class AspectJCore extends JavaCore { public static final String COMPILER_PB_INVALID_ABSOLUTE_TYPE_NAME = AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName; public static final String COMPILER_PB_INVALID_WILDCARD_TYPE_NAME = AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName; public static final String COMPILER_PB_UNRESOLVABLE_MEMBER = AjCompilerOptions.OPTION_ReportUnresolvableMember; public static final String COMPILER_PB_TYPE_NOT_EXPOSED_TO_WEAVER = AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver; public static final String COMPILER_PB_SHADOW_NOT_IN_STRUCTURE = AjCompilerOptions.OPTION_ReportShadowNotInStructure; public static final String COMPILER_PB_UNMATCHED_SUPERTYPE_IN_CALL = AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall; public static final String COMPILER_PB_CANNOT_IMPLEMENT_LAZY_TJP = AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP; public static final String COMPILER_PB_NEED_SERIAL_VERSION_UID = AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField; public static final String COMPILER_PB_INCOMPATIBLE_SERIAL_VERSION = AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion; public static final String COMPILER_NO_WEAVE = AjCompilerOptions.OPTION_NoWeave; public static final String COMPILER_SERIALIZABLE_ASPECTS = AjCompilerOptions.OPTION_XSerializableAspects; public static final String COMPILER_LAZY_TJP = AjCompilerOptions.OPTION_XLazyThisJoinPoint; public static final String COMPILER_NO_ADVICE_INLINE = AjCompilerOptions.OPTION_XNoInline; public static final String COMPILER_REWEAVABLE = AjCompilerOptions.OPTION_XReweavable; public static final String COMPILER_REWEAVABLE_COMPRESS = AjCompilerOptions.OPTION_XReweavableCompress; public AspectJCore() { super(); } public static AspectJCore getAspectJCore() { return (AspectJCore) getPlugin(); } /* (non-Javadoc) * @see org.eclipse.jdt.core.JavaCore#getCompilerOptions() */ protected Map getCompilerOptions() { return new AjCompilerOptions().getMap(); } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer added constructor to populate javaOptions with * default settings - 01.20.2003 * Bugzilla #29768, 29769 * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.util.FileUtil; /** * All configuration information needed to run the AspectJ compiler. * Compiler options (as opposed to path information) are held in an AjCompilerOptions instance */ public class AjBuildConfig { private boolean shouldProceed = true; public static final String AJLINT_IGNORE = "ignore"; public static final String AJLINT_WARN = "warn"; public static final String AJLINT_ERROR = "error"; public static final String AJLINT_DEFAULT = "default"; private File outputDir; private File outputJar; private List/*File*/ sourceRoots = new ArrayList(); private List/*File*/ files = new ArrayList(); private List /*File*/ binaryFiles = new ArrayList(); // .class files in indirs... private List/*File*/ inJars = new ArrayList(); private List/*File*/ inPath = new ArrayList(); private Map/*String->File*/ sourcePathResources = new HashMap(); private List/*File*/ aspectpath = new ArrayList(); private List/*String*/ classpath = new ArrayList(); private List/*String*/ bootclasspath = new ArrayList(); private File configFile; private String lintMode = AJLINT_DEFAULT; private File lintSpecFile = null; private AjCompilerOptions options; /** if true, then global values override local when joining */ private boolean override = true; // incremental variants handled by the compiler client, but parsed here private boolean incrementalMode; private File incrementalFile; public String toString() { StringBuffer sb = new StringBuffer(); sb.append("BuildConfig["+(configFile==null?"null":configFile.getAbsoluteFile().toString())+"] #Files="+files.size()); return sb.toString(); } public static class BinarySourceFile { public BinarySourceFile(File dir, File src) { this.fromInPathDirectory = dir; this.binSrc = src; } public File fromInPathDirectory; public File binSrc; public boolean equals(Object obj) { if ((obj instanceof BinarySourceFile) && (obj != null)) { BinarySourceFile other = (BinarySourceFile)obj; return(binSrc.equals(other.binSrc)); } return false; } public int hashCode() { return binSrc != null ? binSrc.hashCode() : 0; } } /** * Intialises the javaOptions Map to hold the default * JDT Compiler settings. Added by AMC 01.20.2003 in reponse * to bug #29768 and enh. 29769. * The settings here are duplicated from those set in * org.eclipse.jdt.internal.compiler.batch.Main, but I've elected to * copy them rather than refactor the JDT class since this keeps * integration with future JDT releases easier (?). */ public AjBuildConfig( ) { options = new AjCompilerOptions(); } /** * returned files includes <ul> * <li>files explicitly listed on command-line</li> * <li>files listed by reference in argument list files</li> * <li>files contained in sourceRootDir if that exists</li> * </ul> * * @return all source files that should be compiled. */ public List/*File*/ getFiles() { return files; } /** * returned files includes all .class files found in * a directory on the inpath, but does not include * .class files contained within jars. */ public List/*BinarySourceFile*/ getBinaryFiles() { return binaryFiles; } public File getOutputDir() { return outputDir; } public void setFiles(List files) { this.files = files; } public void setOutputDir(File outputDir) { this.outputDir = outputDir; } public AjCompilerOptions getOptions() { return options; } /** * This does not include -bootclasspath but includes -extdirs and -classpath */ public List getClasspath() { // XXX setters don't respect javadoc contract... return classpath; } public void setClasspath(List classpath) { this.classpath = classpath; } public List getBootclasspath() { return bootclasspath; } public void setBootclasspath(List bootclasspath) { this.bootclasspath = bootclasspath; } public File getOutputJar() { return outputJar; } public List/*File*/ getInpath() { // Elements of the list are either archives (jars/zips) or directories return inPath; } public List/*File*/ getInJars() { return inJars; } public Map getSourcePathResources() { return sourcePathResources; } public void setOutputJar(File outputJar) { this.outputJar = outputJar; } public void setInJars(List sourceJars) { this.inJars = sourceJars; } public void setInPath(List dirsOrJars) { inPath = dirsOrJars; // remember all the class files in directories on the inpath binaryFiles = new ArrayList(); FileFilter filter = new FileFilter() { public boolean accept(File pathname) { return pathname.getPath().endsWith(".class"); }}; for (Iterator iter = dirsOrJars.iterator(); iter.hasNext();) { File inpathElement = (File) iter.next(); if (inpathElement.isDirectory()) { File[] files = FileUtil.listFiles(inpathElement, filter); for (int i = 0; i < files.length; i++) { binaryFiles.add(new BinarySourceFile(inpathElement,files[i])); } } } } public List getSourceRoots() { return sourceRoots; } public void setSourceRoots(List sourceRootDir) { this.sourceRoots = sourceRootDir; } public File getConfigFile() { return configFile; } public void setConfigFile(File configFile) { this.configFile = configFile; } public void setIncrementalMode(boolean incrementalMode) { this.incrementalMode = incrementalMode; } public boolean isIncrementalMode() { return incrementalMode; } public void setIncrementalFile(File incrementalFile) { this.incrementalFile = incrementalFile; } public boolean isIncrementalFileMode() { return (null != incrementalFile); } /** * @return List (String) classpath of bootclasspath, injars, inpath, aspectpath * entries, specified classpath (extdirs, and classpath), and output dir or jar */ public List getFullClasspath() { List full = new ArrayList(); full.addAll(getBootclasspath()); // XXX Is it OK that boot classpath overrides inpath/injars/aspectpath? for (Iterator i = inJars.iterator(); i.hasNext(); ) { full.add(((File)i.next()).getAbsolutePath()); } for (Iterator i = inPath.iterator();i.hasNext();) { full.add(((File)i.next()).getAbsolutePath()); } for (Iterator i = aspectpath.iterator(); i.hasNext(); ) { full.add(((File)i.next()).getAbsolutePath()); } full.addAll(getClasspath()); // if (null != outputDir) { // full.add(outputDir.getAbsolutePath()); // } else if (null != outputJar) { // full.add(outputJar.getAbsolutePath()); // } return full; } public File getLintSpecFile() { return lintSpecFile; } public void setLintSpecFile(File lintSpecFile) { this.lintSpecFile = lintSpecFile; } public List getAspectpath() { return aspectpath; } public void setAspectpath(List aspectpath) { this.aspectpath = aspectpath; } /** @return true if any config file, sourceroots, sourcefiles, injars or inpath */ public boolean hasSources() { return ((null != configFile) || (0 < sourceRoots.size()) || (0 < files.size()) || (0 < inJars.size()) || (0 < inPath.size()) ); } // /** @return null if no errors, String errors otherwise */ // public String configErrors() { // StringBuffer result = new StringBuffer(); // // ok, permit both. sigh. //// if ((null != outputDir) && (null != outputJar)) { //// result.append("specified both outputDir and outputJar"); //// } // // incremental => only sourceroots // // // return (0 == result.length() ? null : result.toString()); // } /** * Install global values into local config * unless values conflict: * <ul> * <li>Collections are unioned</li> * <li>values takes local value unless default and global set</li> * <li>this only sets one of outputDir and outputJar as needed</li> * <ul> * This also configures super if javaOptions change. * @param global the AjBuildConfig to read globals from */ public void installGlobals(AjBuildConfig global) { // XXX relies on default values // don't join the options - they already have defaults taken care of. // Map optionsMap = options.getMap(); // join(optionsMap,global.getOptions().getMap()); // options.set(optionsMap); join(aspectpath, global.aspectpath); join(classpath, global.classpath); if (null == configFile) { configFile = global.configFile; // XXX correct? } if (!isEmacsSymMode() && global.isEmacsSymMode()) { setEmacsSymMode(true); } join(files, global.files); if (!isGenerateModelMode() && global.isGenerateModelMode()) { setGenerateModelMode(true); } if (null == incrementalFile) { incrementalFile = global.incrementalFile; } if (!incrementalMode && global.incrementalMode) { incrementalMode = true; } join(inJars, global.inJars); join(inPath, global.inPath); if ((null == lintMode) || (AJLINT_DEFAULT.equals(lintMode))) { setLintMode(global.lintMode); } if (null == lintSpecFile) { lintSpecFile = global.lintSpecFile; } if (!isNoWeave() && global.isNoWeave()) { setNoWeave(true); } if ((null == outputDir) && (null == outputJar)) { if (null != global.outputDir) { outputDir = global.outputDir; } if (null != global.outputJar) { outputJar = global.outputJar; } } join(sourceRoots, global.sourceRoots); if (!isXnoInline() && global.isXnoInline()) { setXnoInline(true); } if (!isXserializableAspects() && global.isXserializableAspects()) { setXserializableAspects(true); } if (!isXlazyTjp() && global.isXlazyTjp()) { setXlazyTjp(true); } if (!isXreweavable() && global.isXreweavable()) { setXreweavable(true); } if (!getXreweavableCompressClasses() && global.getXreweavableCompressClasses()) { setXreweavableCompressClasses(true); } } void join(Collection local, Collection global) { for (Iterator iter = global.iterator(); iter.hasNext();) { Object next = iter.next(); if (!local.contains(next)) { local.add(next); } } } void join(Map local, Map global) { for (Iterator iter = global.keySet().iterator(); iter.hasNext();) { Object key = iter.next(); if (override || (null == local.get(key))) { // Object value = global.get(key); if (null != value) { local.put(key, value); } } } } public void setSourcePathResources(Map map) { sourcePathResources = map; } /** * used to indicate whether to proceed after parsing config */ public boolean shouldProceed() { return shouldProceed; } public void doNotProceed() { shouldProceed = false; } public String getLintMode() { return lintMode; } // options... public void setLintMode(String lintMode) { this.lintMode = lintMode; String lintValue = null; if (AJLINT_IGNORE.equals(lintMode)) { lintValue = AjCompilerOptions.IGNORE; } else if (AJLINT_WARN.equals(lintMode)) { lintValue = AjCompilerOptions.WARNING; } else if (AJLINT_ERROR.equals(lintMode)) { lintValue = AjCompilerOptions.ERROR; } if (lintValue != null) { Map lintOptions = new HashMap(); lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportUnresolvableMember,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion,lintValue); options.set(lintOptions); } } public boolean isNoWeave() { return options.noWeave; } public void setNoWeave(boolean noWeave) { options.noWeave = noWeave; } public boolean isXserializableAspects() { return options.xSerializableAspects; } public void setXserializableAspects(boolean xserializableAspects) { options.xSerializableAspects = xserializableAspects; } public boolean isXnoInline() { return options.xNoInline; } public void setXnoInline(boolean xnoInline) { options.xNoInline = xnoInline; } public boolean isXlazyTjp() { return options.xLazyThisJoinPoint; } public void setXlazyTjp(boolean b) { options.xLazyThisJoinPoint = b; } public void setXreweavable(boolean b) { options.xReweavable = b; } public void setXHasMemberSupport(boolean enabled) { options.xHasMember = enabled; } public boolean isXHasMemberEnabled() { return options.xHasMember; } public void setXdevPinpointMode(boolean enabled) { options.xdevPinpoint = enabled; } public boolean isXdevPinpoint() { return options.xdevPinpoint; } public boolean isXreweavable() { return options.xReweavable; } public void setXreweavableCompressClasses(boolean b) { options.xReweavableCompress = b; } public boolean getXreweavableCompressClasses() { return options.xReweavableCompress; } public boolean isGenerateJavadocsInModelMode() { return options.generateJavaDocsInModel; } public void setGenerateJavadocsInModelMode( boolean generateJavadocsInModelMode) { options.generateJavaDocsInModel = generateJavadocsInModelMode; } public boolean isEmacsSymMode() { return options.generateEmacsSymFiles; } public void setEmacsSymMode(boolean emacsSymMode) { options.generateEmacsSymFiles = emacsSymMode; } public boolean isGenerateModelMode() { return options.generateModel; } public void setGenerateModelMode(boolean structureModelMode) { options.generateModel = structureModelMode; } public boolean isNoAtAspectJAnnotationProcessing() { return options.noAtAspectJProcessing; } public void setNoAtAspectJAnnotationProcessing(boolean noProcess) { options.noAtAspectJProcessing = noProcess; } public void setShowWeavingInformation(boolean b) { options.showWeavingInformation = true; } public boolean getShowWeavingInformation() { return options.showWeavingInformation; } public void setProceedOnError(boolean b) { options.proceedOnError = b; } public boolean getProceedOnError() { return options.proceedOnError; } public void setBehaveInJava5Way(boolean b) { options.behaveInJava5Way = b; } public boolean getBehaveInJava5Way() { return options.behaveInJava5Way; } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.ICompilerAdapter; import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.CountingMessageHandler; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.Version; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextFormatter; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathDirectory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.util.FileUtil; import org.aspectj.weaver.Dump; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.core.runtime.OperationCanceledException; //import org.aspectj.org.eclipse.jdt.internal.compiler.util.HashtableOfObject; public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory { private static final String CANT_WRITE_RESULT = "unable to write compilation result"; private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; static final boolean COPY_INPATH_DIR_RESOURCES = false; static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false; private static final FileFilter binarySourceFilter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".class"); }}; /** * This builder is static so that it can be subclassed and reset. However, note * that there is only one builder present, so if two extendsion reset it, only * the latter will get used. */ private static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder(); static { CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter()); CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter()); } private IProgressListener progressListener = null; private int compiledCount; private int sourceFileCount; private JarOutputStream zos; private boolean batchCompile = true; private INameEnvironment environment; private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap(); // FIXME asc should this really be in here? private IHierarchy structureModel; public AjBuildConfig buildConfig; AjState state = new AjState(this); public BcelWeaver getWeaver() { return state.getWeaver();} public BcelWorld getBcelWorld() { return state.getBcelWorld();} public CountingMessageHandler handler; public AjBuildManager(IMessageHandler holder) { super(); this.handler = CountingMessageHandler.makeCountingMessageHandler(holder); } /** @return true if we should generate a model as a side-effect */ public boolean doGenerateModel() { return buildConfig.isGenerateModelMode(); } public boolean batchBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, true); } public boolean incrementalBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, false); } /** @throws AbortException if check for runtime fails */ protected boolean doBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler, boolean batch) throws IOException, AbortException { boolean ret = true; batchCompile = batch; int phase = batch ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD; ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase ,buildConfig); try { if (batch) { this.state = new AjState(this); } boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !batch) { // retry as batch? CompilationAndWeavingContext.leavingPhase(ct); return doBuild(buildConfig, baseHandler, true); } this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler); // XXX duplicate, no? remove? String check = checkRtJar(buildConfig); if (check != null) { if (FAIL_IF_RUNTIME_NOT_FOUND) { MessageUtil.error(handler, check); CompilationAndWeavingContext.leavingPhase(ct); return false; } else { MessageUtil.warn(handler, check); } } // if (batch) { setBuildConfig(buildConfig); //} if (batch || !AsmManager.attemptIncrementalModelRepairs) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(buildConfig); // } } if (batch) { initBcelWorld(handler); } if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } } if (batch) { // System.err.println("XXXX batch: " + buildConfig.getFiles()); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { getWorld().setModel(AsmManager.getDefault().getHierarchy()); // in incremental build, only get updated model? } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); performCompilation(buildConfig.getFiles()); if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After a batch build"); } else { // done already? // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { // bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel()); // } // System.err.println("XXXX start inc "); binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); List files = state.getFilesToCompile(true); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles); boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); for (int i = 0; (i < 5) && hereWeGoAgain; i++) { // System.err.println("XXXX inc: " + files); performCompilation(files); if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false); files = state.getFilesToCompile(false); hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); // TODO Andy - Needs some thought here... // I think here we might want to pass empty addedFiles/deletedFiles as they were // dealt with on the first call to processDelta - we are going through this loop // again because in compiling something we found something else we needed to // rebuild. But what case causes this? if (hereWeGoAgain) if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles); } if (!files.isEmpty()) { CompilationAndWeavingContext.leavingPhase(ct); return batchBuild(buildConfig, baseHandler); } else { if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After an incremental build"); } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(); } // have to tell state we succeeded or next is not incremental state.successfulCompile(buildConfig,batch); copyResourcesToDestination(); /*boolean weaved = *///weaveAndGenerateClassFiles(); // if not weaved, then no-op build, no model changes // but always returns true // XXX weaved not in Mik's incremental if (buildConfig.isGenerateModelMode()) { AsmManager.getDefault().fireModelUpdated(); } CompilationAndWeavingContext.leavingPhase(ct); } finally { if (zos != null) { closeOutputStream(buildConfig.getOutputJar()); } ret = !handler.hasErrors(); getBcelWorld().tidyUp(); // bug 59895, don't release reference to handler as may be needed by a nested call //handler = null; } return ret; } private boolean openOutputStream(File outJar) { try { OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar()); zos = new JarOutputStream(os,getWeaver().getManifest(true)); } catch (IOException ex) { IMessage message = new Message("Unable to open outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); return false; } return true; } private void closeOutputStream(File outJar) { try { if (zos != null) zos.close(); zos = null; /* Ensure we don't write an incomplete JAR bug-71339 */ if (handler.hasErrors()) { outJar.delete(); } } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); } } private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); copyResourcesFromJarFile(inJar); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (inPathElement.isDirectory()) { copyResourcesFromDirectory(inPathElement); } else { copyResourcesFromJarFile(inPathElement); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) { String resource = (String)i.next(); File from = (File)buildConfig.getSourcePathResources().get(resource); copyResourcesFromFile(from,resource,from); } } writeManifest(); } private void copyResourcesFromJarFile(File jarFile) throws IOException { JarInputStream inStream = null; try { inStream = new JarInputStream(new FileInputStream(jarFile)); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; String filename = entry.getName(); // System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'"); if (!entry.isDirectory() && acceptResource(filename)) { byte[] bytes = FileUtil.readAsByteArray(inStream); writeResource(filename,bytes,jarFile); } inStream.closeEntry(); } } finally { if (inStream != null) inStream.close(); } } private void copyResourcesFromDirectory(File dir) throws IOException { if (!COPY_INPATH_DIR_RESOURCES) return; // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(dir,new FileFilter() { public boolean accept(File f) { boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ; return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = files[i].getAbsolutePath().substring( dir.getAbsolutePath().length()+1); copyResourcesFromFile(files[i],filename,dir); } } private void copyResourcesFromFile(File f,String filename,File src) throws IOException { if (!acceptResource(filename)) return; FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); writeResource(filename,bytes,src); } finally { if (fis != null) fis.close(); } } private void writeResource(String filename, byte[] content, File srcLocation) throws IOException { if (state.resources.contains(filename)) { IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); return; } if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(content); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename)); fos.write(content); fos.close(); } state.resources.add(filename); } /* * If we are writing to an output directory copy the manifest but only * if we already have one */ private void writeManifest () throws IOException { Manifest manifest = getWeaver().getManifest(false); if (manifest != null && zos == null) { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME)); manifest.write(fos); fos.close(); } } private boolean acceptResource(String resourceName) { if ( (resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS")) || (resourceName.endsWith(".class")) || (resourceName.toUpperCase().equals(MANIFEST_NAME)) ) { return false; } else { return true; } } // public static void dumprels() { // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); // int ctr = 1; // Set entries = irm.getEntries(); // for (Iterator iter = entries.iterator(); iter.hasNext();) { // String hid = (String) iter.next(); // List rels = irm.get(hid); // for (Iterator iterator = rels.iterator(); iterator.hasNext();) { // IRelationship ir = (IRelationship) iterator.next(); // List targets = ir.getTargets(); // for (Iterator iterator2 = targets.iterator(); // iterator2.hasNext(); // ) { // String thid = (String) iterator2.next(); // System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid); // } // } // } // } /** * Responsible for managing the ASM model between builds. Contains the policy for * maintaining the persistance of elements in the model. * * This code is driven before each 'fresh' (batch) build to create * a new model. */ private void setupModel(AjBuildConfig config) { AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode()); if (!AsmManager.isCreatingModel()) return; AsmManager.getDefault().createNewASM(); // AsmManager.getDefault().getRelationshipMap().clear(); IHierarchy model = AsmManager.getDefault().getHierarchy(); String rootLabel = "<root>"; IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA; if (buildConfig.getConfigFile() != null) { rootLabel = buildConfig.getConfigFile().getName(); model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath()); kind = IProgramElement.Kind.FILE_LST; } model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList())); model.setFileMap(new HashMap()); setStructureModel(model); state.setStructureModel(model); state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap()); } // // private void dumplist(List l) { // System.err.println("---- "+l.size()); // for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i)); // } // private void accumulateFileNodes(IProgramElement ipe,List store) { // if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA || // ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) { // if (!ipe.getName().equals("<root>")) { // store.add(ipe); // return; // } // } // for (Iterator i = ipe.getChildren().iterator();i.hasNext();) { // accumulateFileNodes((IProgramElement)i.next(),store); // } // } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { List cp = buildConfig.getBootclasspath(); cp.addAll(buildConfig.getClasspath()); BcelWorld bcelWorld = new BcelWorld(cp, handler, null); bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way()); bcelWorld.setXnoInline(buildConfig.isXnoInline()); bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp()); bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled()); bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint()); BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld); state.setWorld(bcelWorld); state.setWeaver(bcelWeaver); state.binarySourceFiles = new HashMap(); for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) { File f = (File) i.next(); bcelWeaver.addLibraryJarFile(f); } // String lintMode = buildConfig.getLintMode(); if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) { bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(buildConfig.getLintMode()); } if (buildConfig.getLintSpecFile() != null) { bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile()); } //??? incremental issues for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false); state.binarySourceFiles.put(inJar.getPath(), unwovenClasses); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory()) { // its a jar file on the inpath // the weaver method can actually handle dirs, but we don't call it, see next block List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true); state.binarySourceFiles.put(inPathElement.getPath(),unwovenClasses); } else { // add each class file in an in-dir individually, this gives us the best error reporting // (they are like 'source' files then), and enables a cleaner incremental treatment of // class file changes in indirs. File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter); for (int j = 0; j < binSrcs.length; j++) { UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, buildConfig.getOutputDir()); List ucfl = new ArrayList(); ucfl.add(ucf); state.binarySourceFiles.put(binSrcs[j].getPath(),ucfl); } } } bcelWeaver.setReweavableMode(buildConfig.isXreweavable(),buildConfig.getXreweavableCompressClasses()); //check for org.aspectj.runtime.JoinPoint ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint"); if (joinPoint.isMissing()) { IMessage message = new Message("classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)", null, true); handler.handleMessage(message); } } public World getWorld() { return getBcelWorld(); } void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException { for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); getWeaver().addClassFile(classFile); } } // public boolean weaveAndGenerateClassFiles() throws IOException { // handler.handleMessage(MessageUtil.info("weaving")); // if (progressListener != null) progressListener.setText("weaving aspects"); // bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size()); // //!!! doesn't provide intermediate progress during weaving // // XXX add all aspects even during incremental builds? // addAspectClassFilesToWeaver(state.addedClassFiles); // if (buildConfig.isNoWeave()) { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.dumpUnwoven(buildConfig.getOutputJar()); // } else { // bcelWeaver.dumpUnwoven(); // bcelWeaver.dumpResourcesToOutPath(); // } // } else { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.weave(buildConfig.getOutputJar()); // } else { // bcelWeaver.weave(); // bcelWeaver.dumpResourcesToOutPath(); // } // } // if (progressListener != null) progressListener.setProgress(1.0); // return true; // //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors(); // } public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) { String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ // Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every // element of the classpath is likely to be a directory. If we ensure every element of the array is set to // only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build // a classpathDirectory object that will attempt to look for source when it can't find binary. int[] classpathModes = new int[classpaths.length]; for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY; return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes); } public IProblemFactory getProblemFactory() { return new DefaultProblemFactory(Locale.getDefault()); } /* * Build the set of compilation source units */ public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) { int fileCount = filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; // HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ for (int i = 0; i < fileCount; i++) { String encoding = encodings[i]; if (encoding == null) encoding = defaultEncoding; units[i] = new CompilationUnit(null, filenames[i], encoding); } return units; } public String extractDestinationPathFromSourceFile(CompilationResult result) { ICompilationUnit compilationUnit = result.compilationUnit; if (compilationUnit != null) { char[] fileName = compilationUnit.getFileName(); int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName); if (lastIndex == -1) { return System.getProperty("user.dir"); //$NON-NLS-1$ } return new String(CharOperation.subarray(fileName, 0, lastIndex)); } return System.getProperty("user.dir"); //$NON-NLS-1$ } public void performCompilation(List files) { if (progressListener != null) { compiledCount=0; sourceFileCount = files.size(); progressListener.setText("compiling source files"); } //System.err.println("got files: " + files); String[] filenames = new String[files.size()]; String[] encodings = new String[files.size()]; //System.err.println("filename: " + this.filenames); for (int i=0; i < files.size(); i++) { filenames[i] = ((File)files.get(i)).getPath(); } List cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i=0; i < cps.size(); i++) { classpaths[i] = (String)cps.get(i); } //System.out.println("compiling"); environment = getLibraryAccess(classpaths, filenames); if (!state.classesFromName.isEmpty()) { environment = new StatefulNameEnvironment(environment, state.classesFromName); } org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this); org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(), getBatchRequestor(), getProblemFactory()); CompilerOptions options = compiler.options; options.produceReferenceInfo = true; //TODO turn off when not needed try { compiler.compile(getCompilationUnits(filenames, encodings)); } catch (OperationCanceledException oce) { handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null)); } // cleanup environment.cleanup(); environment = null; } /* * Answer the component to which will be handed back compilation results from the compiler */ public IIntermediateResultsRequestor getInterimResultRequestor() { return new IIntermediateResultsRequestor() { public void acceptResult(InterimCompilationResult result) { if (progressListener != null) { compiledCount++; progressListener.setProgress((compiledCount/2.0)/sourceFileCount); progressListener.setText("compiled: " + result.fileName()); } state.noteResult(result); if (progressListener!=null && progressListener.isCancelledRequested()) { throw new AbortCompilation(true, new OperationCanceledException("Compilation cancelled as requested")); } } }; } public ICompilerRequestor getBatchRequestor() { return new ICompilerRequestor() { public void acceptResult(CompilationResult unitResult) { // end of compile, must now write the results to the output destination // this is either a jar file or a file in a directory if (!(unitResult.hasErrors() && !proceedOnError())) { Collection classFiles = unitResult.compiledTypes.values(); for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile classFile = (ClassFile) iter.next(); String filename = new String(classFile.fileName()); filename = filename.replace('/', File.separatorChar) + ".class"; try { if (buildConfig.getOutputJar() == null) { writeDirectoryEntry(unitResult, classFile,filename); } else { writeZipEntry(classFile,filename); } } catch (IOException ex) { IMessage message = EclipseAdapterUtils.makeErrorMessage( new String(unitResult.fileName), CANT_WRITE_RESULT, ex); handler.handleMessage(message); } } } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); for (int i=0; i < problems.length; i++) { IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i]); handler.handleMessage(message); } } } private void writeDirectoryEntry( CompilationResult unitResult, ClassFile classFile, String filename) throws IOException { File destinationPath = buildConfig.getOutputDir(); String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); } private void writeZipEntry(ClassFile classFile, String name) throws IOException { name = name.replace(File.separatorChar,'/'); ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(classFile.getBytes()); zos.closeEntry(); } }; } protected boolean proceedOnError() { return buildConfig.getProceedOnError(); } // public void noteClassFiles(AjCompiler.InterimResult result) { // if (result == null) return; // CompilationResult unitResult = result.result; // String sourceFileName = result.fileName(); // if (!(unitResult.hasErrors() && !proceedOnError())) { // List unwovenClassFiles = new ArrayList(); // Enumeration classFiles = unitResult.compiledTypes.elements(); // while (classFiles.hasMoreElements()) { // ClassFile classFile = (ClassFile) classFiles.nextElement(); // String filename = new String(classFile.fileName()); // filename = filename.replace('/', File.separatorChar) + ".class"; // // File destinationPath = buildConfig.getOutputDir(); // if (destinationPath == null) { // filename = new File(filename).getName(); // filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath(); // } else { // filename = new File(destinationPath, filename).getPath(); // } // // //System.out.println("classfile: " + filename); // unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes())); // } // state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles); //// System.out.println("file: " + sourceFileName); //// for (int i=0; i < unitResult.simpleNameReferences.length; i++) { //// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i])); //// } //// for (int i=0; i < unitResult.qualifiedReferences.length; i++) { //// System.out.println("qualified: " + //// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/'))); //// } // } else { // state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST); // } // } // private void setBuildConfig(AjBuildConfig buildConfig) { this.buildConfig = buildConfig; handler.reset(); } String makeClasspathString(AjBuildConfig buildConfig) { if (buildConfig == null || buildConfig.getFullClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. * Otherwise it will return a string message indicating the problem. */ public String checkRtJar(AjBuildConfig buildConfig) { // omitting dev info if (Version.text.equals(Version.DEVELOPMENT)) { // in the development version we can't do this test usefully // MessageUtil.info(holder, "running development version of aspectj compiler"); return null; } if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified"; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { File p = new File( (String)it.next() ); if (p.isFile() && p.getName().equals("aspectjrt.jar")) { try { String version = null; Manifest manifest = new JarFile(p).getManifest(); if (manifest == null) { return "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text; } Attributes attr = manifest.getAttributes("org/aspectj/lang/"); if (null != attr) { version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (null != version) { version = version.trim(); } } // assume that users of development aspectjrt.jar know what they're doing if (Version.DEVELOPMENT.equals(version)) { // MessageUtil.info(holder, // "running with development version of aspectjrt.jar in " + // p.getAbsolutePath()); return null; } else if (!Version.text.equals(version)) { return "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found " + version; } } catch (IOException ioe) { return "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; } return null; } else { // might want to catch other classpath errors } } return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("AjBuildManager("); buf.append(")"); return buf.toString(); } public void setStructureModel(IHierarchy structureModel) { this.structureModel = structureModel; } /** * Returns null if there is no structure model */ public IHierarchy getStructureModel() { return structureModel; } public IProgressListener getProgressListener() { return progressListener; } public void setProgressListener(IProgressListener progressListener) { this.progressListener = progressListener; } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[]) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { String filename = new String(eclipseClassFileName); filename = filename.replace('/', File.separatorChar) + ".class"; File destinationPath = buildConfig.getOutputDir(); String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } return outFile; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, getProblemFactory()); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment); EclipseFactory factory = new EclipseFactory(le,this); le.factory = factory; pr.factory = factory; forCompiler.lookupEnvironment = le; forCompiler.parser = new Parser( pr, forCompiler.options.parseLiteralExpressionsAsConstants); return new AjCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.binarySourceFiles, state.resultsFromFile.values(), buildConfig.isNoWeave(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing()); } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return binarySourcesForTheNextCompile; } public static AsmHierarchyBuilder getAsmHierarchyBuilder() { return asmHierarchyBuilder; } /** * Override the the default hierarchy builder. */ public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) { asmHierarchyBuilder = newBuilder; } public AjState getState() { return state; } public void setState(AjState buildState) { state = buildState; } private static class AjBuildContexFormatter implements ContextFormatter { public String formatEntry(int phaseId, Object data) { StringBuffer sb = new StringBuffer(); if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) { sb.append("batch building "); } else { sb.append("incrementally building "); } AjBuildConfig config = (AjBuildConfig) data; List classpath = config.getClasspath(); sb.append("with classpath: "); for (Iterator iter = classpath.iterator(); iter.hasNext();) { sb.append(iter.next().toString()); sb.append(File.pathSeparator); } return sb.toString(); } } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjCompilerOptions.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.util.Map; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; /** * Compiler options used by Eclipse integration (AJDT) */ public class AjCompilerOptions extends CompilerOptions { // AspectJ Lint options public static final String OPTION_ReportInvalidAbsoluteTypeName = "org.aspectj.ajdt.core.compiler.lint.InvalidAbsoluteTypeName"; public static final String OPTION_ReportInvalidWildcardTypeName = "org.aspectj.ajdt.core.compiler.lint.WildcardTypeName"; public static final String OPTION_ReportUnresolvableMember = "org.aspectj.ajdt.core.compiler.lint.UnresolvableMember"; public static final String OPTION_ReportTypeNotExposedToWeaver = "org.aspectj.ajdt.core.compiler.lint.TypeNotExposedToWeaver"; public static final String OPTION_ReportShadowNotInStructure = "org.aspectj.ajdt.core.compiler.lint.ShadowNotInStructure"; public static final String OPTION_ReportUnmatchedSuperTypeInCall = "org.aspectj.ajdt.core.compiler.list.UnmatchedSuperTypeInCall"; public static final String OPTION_ReportCannotImplementLazyTJP = "org.aspectj.ajdt.core.compiler.lint.CannotImplementLazyTJP"; public static final String OPTION_ReportNeedSerialVersionUIDField = "org.aspectj.ajdt.core.compiler.lint.NeedSerialVersionUIDField"; public static final String OPTION_ReportIncompatibleSerialVersion = "org.aspectj.ajdt.core.compiler.lint.BrokeSerialVersionCompatibility"; // General AspectJ Compiler options (excludes paths etc, these are handled separately) public static final String OPTION_NoWeave = "org.aspectj.ajdt.core.compiler.weaver.NoWeave"; public static final String OPTION_XSerializableAspects = "org.aspectj.ajdt.core.compiler.weaver.XSerializableAspects"; public static final String OPTION_XLazyThisJoinPoint = "org.aspectj.ajdt.core.compiler.weaver.XLazyThisJoinPoint"; public static final String OPTION_XNoInline = "org.aspectj.ajdt.core.compiler.weaver.XNoInline"; public static final String OPTION_XReweavable = "org.aspectj.ajdt.core.compiler.weaver.XReweavable"; public static final String OPTION_XReweavableCompress = "org.aspectj.ajdt.core.compiler.weaver.XReweavableCompress"; public static final String OPTION_XHasMember = "org.aspectj.ajdt.core.compiler.weaver.XHasMember"; public static final String OPTION_XdevPinpoint = "org.aspectj.ajdt.core.compiler.weaver.XdevPinpoint"; // these next four not exposed by IDEs public static final String OPTION_XDevNoAtAspectJProcessing = "org.aspectj.ajdt.core.compiler.ast.NoAtAspectJProcessing"; public static final String OPTION_GenerateModel = "org.aspectj.ajdt.core.compiler.model.GenerateModel"; public static final String OPTION_GenerateJavaDocsInModel = "org.aspectj.ajdt.core.compiler.model.GenerateJavaDocsInModel"; public static final String OPTION_Emacssym = "org.aspectj.ajdt.core.compiler.model.Emacssym"; // constants for irritant levels public static final long InvalidAbsoluteTypeName = ASTNode.Bit45L; public static final long InvalidWildCardTypeName = ASTNode.Bit46L; public static final long UnresolvableMember = ASTNode.Bit47L; public static final long TypeNotExposedToWeaver = ASTNode.Bit48L; public static final long ShadowNotInStructure = ASTNode.Bit49L; public static final long UnmatchedSuperTypeInCall = ASTNode.Bit50L; public static final long CannotImplementLazyTJP = ASTNode.Bit51L; public static final long NeedSerialVersionUIDField = ASTNode.Bit52L; public static final long IncompatibleSerialVersion = ASTNode.Bit53L; public boolean noWeave = false; public boolean xSerializableAspects = false; public boolean xLazyThisJoinPoint = false; public boolean xNoInline = false; public boolean xReweavable = false; public boolean xReweavableCompress = false; public boolean xHasMember = false; public boolean xdevPinpoint = false; public boolean showWeavingInformation = false; // If true - autoboxing behaves differently ... public boolean behaveInJava5Way = false; // these next four not exposed by IDEs public boolean generateModel = false; public boolean generateJavaDocsInModel = false; public boolean generateEmacsSymFiles = false; public boolean noAtAspectJProcessing = false; public boolean proceedOnError = false; /** * Initializing the compiler options with defaults */ public AjCompilerOptions(){ super(); setAspectJWarningDefaults(); } /** * Initializing the compiler options with external settings * @param settings */ public AjCompilerOptions(Map settings){ setAspectJWarningDefaults(); if (settings == null) return; set(settings); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.impl.CompilerOptions#getMap() */ public Map getMap() { Map map = super.getMap(); // now add AspectJ additional options map.put(OPTION_ReportInvalidAbsoluteTypeName,getSeverityString(InvalidAbsoluteTypeName)); map.put(OPTION_ReportInvalidWildcardTypeName,getSeverityString(InvalidWildCardTypeName)); map.put(OPTION_ReportUnresolvableMember,getSeverityString(UnresolvableMember)); map.put(OPTION_ReportTypeNotExposedToWeaver,getSeverityString(TypeNotExposedToWeaver)); map.put(OPTION_ReportShadowNotInStructure,getSeverityString(ShadowNotInStructure)); map.put(OPTION_ReportUnmatchedSuperTypeInCall,getSeverityString(UnmatchedSuperTypeInCall)); map.put(OPTION_ReportCannotImplementLazyTJP,getSeverityString(CannotImplementLazyTJP)); map.put(OPTION_ReportNeedSerialVersionUIDField,getSeverityString(NeedSerialVersionUIDField)); map.put(OPTION_ReportIncompatibleSerialVersion,getSeverityString(IncompatibleSerialVersion)); map.put(OPTION_NoWeave, this.noWeave ? ENABLED : DISABLED); map.put(OPTION_XSerializableAspects,this.xSerializableAspects ? ENABLED : DISABLED); map.put(OPTION_XLazyThisJoinPoint,this.xLazyThisJoinPoint ? ENABLED : DISABLED); map.put(OPTION_XNoInline,this.xNoInline ? ENABLED : DISABLED); map.put(OPTION_XReweavable,this.xReweavable ? ENABLED : DISABLED); map.put(OPTION_XReweavableCompress,this.xReweavableCompress ? ENABLED : DISABLED); map.put(OPTION_XHasMember, this.xHasMember ? ENABLED : DISABLED); map.put(OPTION_XdevPinpoint, this.xdevPinpoint ? ENABLED : DISABLED); map.put(OPTION_GenerateModel,this.generateModel ? ENABLED : DISABLED); map.put(OPTION_GenerateJavaDocsInModel,this.generateJavaDocsInModel ? ENABLED : DISABLED); map.put(OPTION_Emacssym,this.generateEmacsSymFiles ? ENABLED : DISABLED); map.put(OPTION_XDevNoAtAspectJProcessing,this.noAtAspectJProcessing ? ENABLED : DISABLED); return map; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.impl.CompilerOptions#set(java.util.Map) */ public void set(Map optionsMap) { super.set(optionsMap); Object optionValue; if ((optionValue = optionsMap.get(OPTION_ReportInvalidAbsoluteTypeName)) != null) updateSeverity(InvalidAbsoluteTypeName, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportInvalidWildcardTypeName)) != null) updateSeverity(InvalidWildCardTypeName, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportUnresolvableMember)) != null) updateSeverity(UnresolvableMember, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportTypeNotExposedToWeaver)) != null) updateSeverity(TypeNotExposedToWeaver, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportShadowNotInStructure)) != null) updateSeverity(ShadowNotInStructure, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportUnmatchedSuperTypeInCall)) != null) updateSeverity(UnmatchedSuperTypeInCall, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportCannotImplementLazyTJP)) != null) updateSeverity(CannotImplementLazyTJP, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportNeedSerialVersionUIDField)) != null) updateSeverity(NeedSerialVersionUIDField, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportIncompatibleSerialVersion)) != null) updateSeverity(IncompatibleSerialVersion, optionValue); if ((optionValue = optionsMap.get(OPTION_NoWeave)) != null) { if (ENABLED.equals(optionValue)) { this.noWeave = true; } else if (DISABLED.equals(optionValue)) { this.noWeave = false; } } if ((optionValue = optionsMap.get(OPTION_XSerializableAspects)) != null) { if (ENABLED.equals(optionValue)) { this.xSerializableAspects = true; } else if (DISABLED.equals(optionValue)) { this.xSerializableAspects = false; } } if ((optionValue = optionsMap.get(OPTION_XLazyThisJoinPoint)) != null) { if (ENABLED.equals(optionValue)) { this.xLazyThisJoinPoint = true; } else if (DISABLED.equals(optionValue)) { this.xLazyThisJoinPoint = false; } } if ((optionValue = optionsMap.get(OPTION_XNoInline)) != null) { if (ENABLED.equals(optionValue)) { this.xNoInline = true; } else if (DISABLED.equals(optionValue)) { this.xNoInline = false; } } if ((optionValue = optionsMap.get(OPTION_XReweavable)) != null) { if (ENABLED.equals(optionValue)) { this.xReweavable = true; } else if (DISABLED.equals(optionValue)) { this.xReweavable = false; } } if ((optionValue = optionsMap.get(OPTION_XReweavableCompress)) != null) { if (ENABLED.equals(optionValue)) { this.xReweavableCompress = true; } else if (DISABLED.equals(optionValue)) { this.xReweavableCompress = false; } } if ((optionValue = optionsMap.get(OPTION_XHasMember)) != null) { if (ENABLED.equals(optionValue)) { this.xHasMember = true; } else if (DISABLED.equals(optionValue)) { this.xHasMember = false; } } if ((optionValue = optionsMap.get(OPTION_XdevPinpoint)) != null) { if (ENABLED.equals(optionValue)) { this.xdevPinpoint = true; } else if (DISABLED.equals(optionValue)) { this.xdevPinpoint = false; } } if ((optionValue = optionsMap.get(OPTION_GenerateModel)) != null) { if (ENABLED.equals(optionValue)) { this.generateModel = true; } else if (DISABLED.equals(optionValue)) { this.generateModel = false; } } if ((optionValue = optionsMap.get(OPTION_GenerateJavaDocsInModel)) != null) { if (ENABLED.equals(optionValue)) { this.generateJavaDocsInModel = true; } else if (DISABLED.equals(optionValue)) { this.generateJavaDocsInModel = false; } } if ((optionValue = optionsMap.get(OPTION_Emacssym)) != null) { if (ENABLED.equals(optionValue)) { this.generateEmacsSymFiles = true; } else if (DISABLED.equals(optionValue)) { this.generateEmacsSymFiles = false; } } if ((optionValue = optionsMap.get(OPTION_XDevNoAtAspectJProcessing)) != null) { if (ENABLED.equals(optionValue)) { this.noAtAspectJProcessing = true; } else if (DISABLED.equals(optionValue)) { this.noAtAspectJProcessing = false; } } } /** * Add these warnings to the default set... */ private void setAspectJWarningDefaults() { super.warningThreshold = super.warningThreshold | InvalidAbsoluteTypeName | UnresolvableMember | TypeNotExposedToWeaver | UnmatchedSuperTypeInCall | CannotImplementLazyTJP; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer( super.toString() ); // now add AspectJ additional options buf.append("\n\tAspectJ Specific Options:"); buf.append("\n\t- no weave: ").append(this.noWeave ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- no inline (X option): ").append(this.xNoInline ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate serializable aspects (X option): ").append(this.xSerializableAspects ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- lazy thisJoinPoint (X option): ").append(this.xLazyThisJoinPoint ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate reweavable class files (X option): ").append(this.xReweavable ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- compress reweavable class files (X option): ").append(this.xReweavableCompress ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- has member support (X option): ").append(this.xHasMember ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate AJDE model: ").append(this.generateModel ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate Javadocs in AJDE model: ").append(this.generateJavaDocsInModel ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate Emacs symbol files: ").append(this.generateEmacsSymFiles ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- suppress @AspectJ processing: ").append(this.noAtAspectJProcessing ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- invalid absolute type name (XLint): ").append(getSeverityString(InvalidAbsoluteTypeName)); //$NON-NLS-1$ buf.append("\n\t- invalid wildcard type name (XLint): ").append(getSeverityString(InvalidWildCardTypeName)); //$NON-NLS-1$ buf.append("\n\t- unresolvable member (XLint): ").append(getSeverityString(UnresolvableMember)); //$NON-NLS-1$ buf.append("\n\t- type not exposed to weaver (XLint): ").append(getSeverityString(TypeNotExposedToWeaver)); //$NON-NLS-1$ buf.append("\n\t- shadow not in structure (XLint): ").append(getSeverityString(ShadowNotInStructure)); //$NON-NLS-1$ buf.append("\n\t- unmatched super type in call (XLint): ").append(getSeverityString(UnmatchedSuperTypeInCall)); //$NON-NLS-1$ buf.append("\n\t- cannot implement lazy thisJoinPoint (XLint): ").append(getSeverityString(CannotImplementLazyTJP)); //$NON-NLS-1$ buf.append("\n\t- need serialVersionUID field (XLint): ").append(getSeverityString(NeedSerialVersionUIDField)); //$NON-NLS-1$ buf.append("\n\t- incompatible serial version (XLint): ").append(getSeverityString(IncompatibleSerialVersion)); //$NON-NLS-1$ return buf.toString(); } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AspectJBuilder.java
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import org.aspectj.ajdt.core.AspectJCore; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.ICompilerAdapter; import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.ajdt.internal.compiler.CompilerAdapter; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.weaver.Lint; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.aspectj.org.eclipse.jdt.core.IJavaModelMarker; import org.aspectj.org.eclipse.jdt.core.JavaCore; import org.aspectj.org.eclipse.jdt.core.JavaModelException; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.Compiler; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.org.eclipse.jdt.internal.core.builder.BatchImageBuilder; import org.aspectj.org.eclipse.jdt.internal.core.builder.BuildNotifier; import org.aspectj.org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder; import org.aspectj.org.eclipse.jdt.internal.core.builder.JavaBuilder; /** * @author colyer * * This is the builder class used by AJDT, and that the org.eclipse.ajdt.core * plugin references. */ public class AspectJBuilder extends JavaBuilder implements ICompilerAdapterFactory { // One builder instance per project (important) private BcelWeaver myWeaver = null; private BcelWorld myBcelWorld = null; private EclipseClassPathManager cpManager = null; private UnwovenResultCollector unwovenResultCollector = null; private OutputFileNameProvider fileNameProvider = null; private boolean isBatchBuild = false; /* (non-Javadoc) * @see org.eclipse.core.internal.events.InternalBuilder#build(int, java.util.Map, org.eclipse.core.runtime.IProgressMonitor) */ protected IProject[] build(int kind, Map ignored, IProgressMonitor monitor) throws CoreException { // super method always causes construction of a new XXXImageBuilder, which // causes construction of a new Compiler, so we will be detected as the // adapter. CompilerAdapter.setCompilerAdapterFactory(this); return super.build(kind, ignored, monitor); } protected BatchImageBuilder getBatchImageBuilder() { isBatchBuild = true; return new AjBatchImageBuilder(this); } protected IncrementalImageBuilder getIncrementalImageBuilder() { isBatchBuild = false; return new AjIncrementalImageBuilder(this); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(Compiler forCompiler) { Map javaOptions = forCompiler.options.getMap(); // TODO get aspectj options from project and add into map before... AjCompilerOptions ajOptions = new AjCompilerOptions(javaOptions); forCompiler.options = ajOptions; if (isBatchBuild || myBcelWorld == null || myWeaver == null) { initWorldAndWeaver(ajOptions); } else { // update the nameEnvironment each time we compile... cpManager.setNameEnvironment(nameEnvironment); } // * an eclipse factory -- create from AjLookupEnvironment, need to hide AjBuildManager field AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, new DefaultProblemFactory(Locale.getDefault())); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr,nameEnvironment); EclipseFactory eFactory = new EclipseFactory(le,myBcelWorld,ajOptions.xSerializableAspects); le.factory = eFactory; forCompiler.lookupEnvironment = le; AjBuildNotifier ajNotifier = (AjBuildNotifier) notifier; if (fileNameProvider == null ) fileNameProvider = new OutputFileNameProvider(getProject()); // * the set of binary source entries for this compile -- from analyzing deltas, or everything if batch // * the full set of binary source entries for the project -- from IAspectJProject // TODO deal with inpath, injars here... IBinarySourceProvider bsProvider = new NullBinarySourceProvider(); Map fullBinarySourceEntries = new HashMap(); // * the intermediate result set from the last batch compile if (isBatchBuild) { unwovenResultCollector = new UnwovenResultCollector(); } Collection resultSetForFullWeave = unwovenResultCollector.getIntermediateResults(); return new AjCompilerAdapter(forCompiler,isBatchBuild,myBcelWorld, myWeaver,eFactory,unwovenResultCollector,ajNotifier,fileNameProvider,bsProvider, fullBinarySourceEntries,resultSetForFullWeave, ajOptions.noWeave,ajOptions.proceedOnError,ajOptions.noAtAspectJProcessing); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.core.builder.JavaBuilder#createBuildNotifier(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.resources.IProject) */ protected BuildNotifier createBuildNotifier(IProgressMonitor monitor, IProject currentProject) { return new AjBuildNotifier(monitor, currentProject); } private void initWorldAndWeaver(AjCompilerOptions options) { cpManager = new EclipseClassPathManager(nameEnvironment); myBcelWorld = new BcelWorld(cpManager,new UnhandledMessageHandler(getProject()),null /*(xrefHandler)*/); myBcelWorld.setBehaveInJava5Way(options.behaveInJava5Way); myBcelWorld.setXnoInline(options.xNoInline); myBcelWorld.setXlazyTjp(options.xLazyThisJoinPoint); myBcelWorld.setXHasMemberSupportEnabled(options.xHasMember); myBcelWorld.setPinpointMode(options.xdevPinpoint); setLintProperties(myBcelWorld,options); myWeaver = new BcelWeaver(myBcelWorld); myWeaver.setReweavableMode(options.xReweavable,options.xReweavableCompress); // TODO deal with injars, inpath, and aspectpath here... } private void setLintProperties(BcelWorld world, AjCompilerOptions options) { Properties p = new Properties(); Lint lintSettings = world.getLint(); Map map = options.getMap(); p.put(lintSettings.invalidAbsoluteTypeName.getName(),map.get(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName)); p.put(lintSettings.invalidWildcardTypeName.getName(),map.get(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName)); p.put(lintSettings.unresolvableMember.getName(),map.get(AjCompilerOptions.OPTION_ReportUnresolvableMember)); p.put(lintSettings.typeNotExposedToWeaver.getName(),map.get(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver)); p.put(lintSettings.shadowNotInStructure.getName(),map.get(AjCompilerOptions.OPTION_ReportShadowNotInStructure)); p.put(lintSettings.unmatchedSuperTypeInCall.getName(),map.get(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall)); p.put(lintSettings.canNotImplementLazyTjp.getName(),map.get(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP)); p.put(lintSettings.needsSerialVersionUIDField.getName(),map.get(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField)); p.put(lintSettings.serialVersionUIDBroken.getName(),map.get(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion)); lintSettings.setFromProperties(p); } private static class UnwovenResultCollector implements IIntermediateResultsRequestor { private Collection results = new ArrayList(); /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor#acceptResult(org.aspectj.ajdt.internal.compiler.InterimCompilationResult) */ public void acceptResult(InterimCompilationResult intRes) { results.add(intRes); } public Collection getIntermediateResults() { return results; } } // this class will only get messages that the weaver adapter couldn't tie into // an originating resource in the project - make them messages on the project // itself. private static class UnhandledMessageHandler implements IMessageHandler { private IProject project; public UnhandledMessageHandler(IProject p) { this.project = p; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage) */ public boolean handleMessage(IMessage message) throws AbortException { try { IMarker marker = project.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, message.getMessage()); marker.setAttribute(IMarker.SEVERITY, message.isError() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING); } catch (CoreException e) { AspectJCore.getPlugin().getLog().log(e.getStatus()); } return true; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) */ public boolean isIgnoring(Kind kind) { if (kind == IMessage.DEBUG || kind == IMessage.INFO) return true; return false; } /** * No-op * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) * @param kind */ public void dontIgnore(IMessage.Kind kind) { ; } } private static class OutputFileNameProvider implements IOutputClassFileNameProvider { private IPath outputLocation; public OutputFileNameProvider(IProject p) { try { outputLocation = JavaCore.create(p).getOutputLocation(); } catch (JavaModelException e) { outputLocation = new Path("."); AspectJCore.getPlugin().getLog().log(e.getStatus()); } } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider#getOutputClassFileName(char[], org.eclipse.jdt.internal.compiler.CompilationResult) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { // In the AJDT implementation, the name provided here will be ignored, we write the results // out in xxxImageBuilder.acceptResult() instead. // simply return the default output directory for the project. String filename = new String(eclipseClassFileName); IPath out = outputLocation.append(filename); out.addFileExtension(".class"); return out.toOSString(); } } // default impl class until the implementation is extended to cope with inpath, injars private static class NullBinarySourceProvider implements IBinarySourceProvider { /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return new HashMap(); } } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/BinaryFormsTestCase.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.batch; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.aspectj.ajdt.ajc.AjdtAjcTests; import org.aspectj.testing.util.TestUtil; import org.aspectj.tools.ajc.AjcTests; public class BinaryFormsTestCase extends CommandTestCase { public BinaryFormsTestCase(String name) { super(name); } public void testJar1() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("out/lib.jar"); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath()); args.add("-d"); args.add("out"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/lib/ConcreteA.aj"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/lib/AbstractA.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); args = new ArrayList(); args.add("-aspectpath"); args.add("out/lib.jar"); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath()); args.add("-d"); args.add("out"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/client/Client.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/client/Client1.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); TestUtil.runMain("out" + File.pathSeparator + "out/lib.jar", "client.Client"); TestUtil.runMain("out" + File.pathSeparator + "out/lib.jar", "client.Client1"); args = new ArrayList(); args.add("-aspectpath"); args.add("out/lib.jar"); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath()); args.add("-d"); args.add("out"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/client/MyAspect.aj"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/client/Client1.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); TestUtil.runMain("out" + File.pathSeparator + "out/lib.jar", "client.Client1"); args = new ArrayList(); args.add("-aspectpath"); args.add("out/lib.jar"); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath()); args.add("-d"); args.add("out"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/client/MyAspect1.aj"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/client/Client1.java"); CommandTestCase.runCompiler(args, new int[] {24, 30}); args = new ArrayList(); args.add("-classpath"); args.add("out/lib.jar" + File.pathSeparator + AjcTests.aspectjrtClasspath()); args.add("-d"); args.add("out"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/client/Client1.java"); CommandTestCase.runCompiler(args, new int[] {15, 17, 22}); args = new ArrayList(); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath() + File.pathSeparator + "out/lib.jar"); args.add("-Xlint:error"); args.add("-d"); args.add("out"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/client/MyAspect.aj"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/binary/client/Client1.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/core/builder/AjCompilerOptionsTest.java
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.util.HashMap; import java.util.Map; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import junit.framework.TestCase; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class AjCompilerOptionsTest extends TestCase { private AjCompilerOptions options; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); options = new AjCompilerOptions(); } public void testDefaultValues() { assertFalse(options.noWeave); assertFalse(options.xSerializableAspects); assertFalse(options.xLazyThisJoinPoint); assertFalse(options.xNoInline); assertFalse(options.xReweavable); assertFalse(options.xReweavableCompress); assertFalse(options.generateModel); assertFalse(options.generateJavaDocsInModel); assertFalse(options.generateEmacsSymFiles); assertFalse(options.noAtAspectJProcessing); Map map = options.getMap(); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportUnresolvableMember)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportShadowNotInStructure)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion)); } public void testDirectSet() { options.noWeave = true; options.xSerializableAspects = true; options.xLazyThisJoinPoint = true; options.xNoInline = true; options.xReweavable = true; options.xReweavableCompress = true; options.generateModel = true; options.generateJavaDocsInModel = true; options.generateEmacsSymFiles = true; options.noAtAspectJProcessing = true; Map map = options.getMap(); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_NoWeave)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XSerializableAspects)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XLazyThisJoinPoint)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XNoInline)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XReweavable)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XReweavableCompress)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_GenerateModel)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_GenerateJavaDocsInModel)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_Emacssym)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XDevNoAtAspectJProcessing)); } public void testMapSet() { Map map = new HashMap(); map.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportUnresolvableMember,CompilerOptions.IGNORE); map.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure,CompilerOptions.WARNING); map.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField,CompilerOptions.WARNING); map.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_NoWeave,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XSerializableAspects,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XLazyThisJoinPoint,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XNoInline,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XReweavable,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XReweavableCompress,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_GenerateModel,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_GenerateJavaDocsInModel,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_Emacssym,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XDevNoAtAspectJProcessing,CompilerOptions.ENABLED); options.set(map); assertTrue(options.noWeave); assertTrue(options.xSerializableAspects); assertTrue(options.xLazyThisJoinPoint); assertTrue(options.xNoInline); assertTrue(options.xReweavable); assertTrue(options.xReweavableCompress); assertTrue(options.generateModel); assertTrue(options.generateJavaDocsInModel); assertTrue(options.generateEmacsSymFiles); assertTrue(options.noAtAspectJProcessing); Map newMap = options.getMap(); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName)); assertEquals(CompilerOptions.IGNORE,newMap.get(AjCompilerOptions.OPTION_ReportUnresolvableMember)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver)); assertEquals(CompilerOptions.WARNING,newMap.get(AjCompilerOptions.OPTION_ReportShadowNotInStructure)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP)); assertEquals(CompilerOptions.WARNING,newMap.get(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion)); } /* * Class to test for String toString() */ public void testToString() { String s = options.toString(); assertTrue("Should have info on AspectJ options",s.indexOf("AspectJ Specific Options:") > 0); } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
taskdefs/src/org/aspectj/tools/ant/taskdefs/AjcTask.java
/* ******************************************************************* * Copyright (c) 2001-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC) * 2003-2004 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Wes Isberg 2003-2004 changes * ******************************************************************/ package org.aspectj.tools.ant.taskdefs; import java.io.*; import java.util.*; import org.apache.tools.ant.*; import org.apache.tools.ant.taskdefs.*; import org.apache.tools.ant.types.*; import org.aspectj.bridge.*; import org.aspectj.tools.ajc.Main; import org.aspectj.tools.ajc.Main.MessagePrinter; import org.aspectj.util.*; /** * This runs the AspectJ 1.1 compiler, * supporting all the command-line options. * In 1.1.1, ajc copies resources from input jars, * but you can copy resources from the source directories * using sourceRootCopyFilter. * When not forking, things will be copied as needed * for each iterative compile, * but when forking things are only copied at the * completion of a successful compile. * <p> * See the development environment guide for * usage documentation. * * @since AspectJ 1.1, Ant 1.5 */ public class AjcTask extends MatchingTask { /* * This task mainly converts ant specification for ajc, * verbosely ignoring improper input. * It also has some special features for non-obvious clients: * (1) Javac compiler adapter supported in * <code>setupAjc(AjcTask, Javac, File)</code> * and * <code>readArguments(String[])</code>; * (2) testing is supported by * (a) permitting the same specification to be re-run * with added flags (settings once made cannot be * removed); and * (b) permitting recycling the task with * <code>reset()</code> (untested). * * The parts that do more than convert ant specs are * (a) code for forking; * (b) code for copying resources. * * If you maintain/upgrade this task, keep in mind: * (1) changes to the semantics of ajc (new options, new * values permitted, etc.) will have to be reflected here. * (2) the clients: * the iajc ant script, Javac compiler adapter, * maven clients of iajc, and testing code. */ // XXX move static methods after static initializer /** * This method extracts javac arguments to ajc, * and add arguments to make ajc behave more like javac * in copying resources. * <p> * Pass ajc-specific options using compilerarg sub-element: * <pre> * &lt;javac srcdir="src"> * &lt;compilerarg compiler="..." line="-argfile src/args.lst"/> * &lt;javac> * </pre> * Some javac arguments are not supported in this component (yet): * <pre> * String memoryInitialSize; * boolean includeAntRuntime = true; * boolean includeJavaRuntime = false; * </pre> * Other javac arguments are not supported in ajc 1.1: * <pre> * boolean optimize; * String forkedExecutable; * FacadeTaskHelper facade; * boolean depend; * String debugLevel; * Path compileSourcepath; * </pre> * @param javac the Javac command to implement (not null) * @param ajc the AjcTask to adapt (not null) * @param destDir the File class destination directory (may be null) * @return null if no error, or String error otherwise */ public String setupAjc(Javac javac) { if (null == javac) { return "null javac"; } AjcTask ajc = this; // no null checks b/c AjcTask handles null input gracefully ajc.setProject(javac.getProject()); ajc.setLocation(javac.getLocation()); ajc.setTaskName("javac-iajc"); ajc.setDebug(javac.getDebug()); ajc.setDeprecation(javac.getDeprecation()); ajc.setFailonerror(javac.getFailonerror()); final boolean fork = javac.isForkedJavac(); ajc.setFork(fork); if (fork) { ajc.setMaxmem(javac.getMemoryMaximumSize()); } ajc.setNowarn(javac.getNowarn()); ajc.setListFileArgs(javac.getListfiles()); ajc.setVerbose(javac.getVerbose()); ajc.setTarget(javac.getTarget()); ajc.setSource(javac.getSource()); ajc.setEncoding(javac.getEncoding()); File javacDestDir = javac.getDestdir(); if (null != javacDestDir) { ajc.setDestdir(javacDestDir); // filter requires dest dir // mimic Javac task's behavior in copying resources, ajc.setSourceRootCopyFilter("**/CVS/*,**/*.java,**/*.aj"); } ajc.setBootclasspath(javac.getBootclasspath()); ajc.setExtdirs(javac.getExtdirs()); ajc.setClasspath(javac.getClasspath()); // ignore srcDir -- all files picked up in recalculated file list // ajc.setSrcDir(javac.getSrcdir()); ajc.addFiles(javac.getFileList()); // arguments can override the filter, add to paths, override options ajc.readArguments(javac.getCurrentCompilerArgs()); return null; } /** * Find aspectjtools.jar on the task or system classpath. * Accept <code>aspectj{-}tools{...}.jar</code> * mainly to support build systems using maven-style * re-naming * (e.g., <code>aspectj-tools-1.1.0.jar</code>. * Note that we search the task classpath first, * though an entry on the system classpath would be loaded first, * because it seems more correct as the more specific one. * @return readable File for aspectjtools.jar, or null if not found. */ public static File findAspectjtoolsJar() { File result = null; ClassLoader loader = AjcTask.class.getClassLoader(); if (loader instanceof AntClassLoader) { AntClassLoader taskLoader = (AntClassLoader) loader; String cp = taskLoader.getClasspath(); String[] cps = LangUtil.splitClasspath(cp); for (int i = 0; (i < cps.length) && (null == result); i++) { result = isAspectjtoolsjar(cps[i]); } } if (null == result) { final Path classpath = Path.systemClasspath; final String[] paths = classpath.list(); for (int i = 0; (i < paths.length) && (null == result); i++) { result = isAspectjtoolsjar(paths[i]); } } return (null == result? null : result.getAbsoluteFile()); } /** @return File if readable jar with aspectj tools name, or null */ private static File isAspectjtoolsjar(String path) { if (null == path) { return null; } final String prefix = "aspectj"; final String infix = "tools"; final String altInfix = "-tools"; final String suffix = ".jar"; final int prefixLength = 7; // prefix.length(); final int minLength = 16; // prefixLength + infix.length() + suffix.length(); if (!path.endsWith(suffix)) { return null; } int loc = path.lastIndexOf(prefix); if ((-1 != loc) && ((loc + minLength) <= path.length())) { String rest = path.substring(loc+prefixLength); if (-1 != rest.indexOf(File.pathSeparator)) { return null; } if (rest.startsWith(infix) || rest.startsWith(altInfix)) { File result = new File(path); if (result.canRead() && result.isFile()) { return result; } } } return null; } /** * Maximum length (in chars) of command line * before converting to an argfile when forking */ private static final int MAX_COMMANDLINE = 4096; private static final File DEFAULT_DESTDIR = new File(".") { public String toString() { return "(no destination dir specified)"; } }; /** do not throw BuildException on fail/abort message with usage */ private static final String USAGE_SUBSTRING = "AspectJ-specific options"; /** valid -X[...] options other than -Xlint variants */ private static final List VALID_XOPTIONS; /** valid warning (-warn:[...]) variants */ private static final List VALID_WARNINGS; /** valid debugging (-g:[...]) variants */ private static final List VALID_DEBUG; /** * -Xlint variants (error, warning, ignore) * @see org.aspectj.weaver.Lint */ private static final List VALID_XLINT; public static final String COMMAND_EDITOR_NAME = AjcTask.class.getName() + ".COMMAND_EDITOR"; static final String[] TARGET_INPUTS = new String [] { "1.1", "1.2", "1.3", "1.4", "1.5" }; static final String[] SOURCE_INPUTS = new String [] { "1.3", "1.4", "1.5" }; static final String[] COMPLIANCE_INPUTS = new String [] { "-1.3", "-1.4", "-1.5" }; private static final ICommandEditor COMMAND_EDITOR; static { String[] xs = new String[] { "serializableAspects", "incrementalFile", "lazyTjp", "reweavable", "reweavable:compress", "noInline" //, "targetNearSource", "OcodeSize", }; VALID_XOPTIONS = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] {"constructorName", "packageDefaultMethod", "deprecation", "maskedCatchBlocks", "unusedLocals", "unusedArguments", "unusedImports", "syntheticAccess", "assertIdentifier", "none" }; VALID_WARNINGS = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] {"none", "lines", "vars", "source" }; VALID_DEBUG = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] { "error", "warning", "ignore"}; VALID_XLINT = Collections.unmodifiableList(Arrays.asList(xs)); ICommandEditor editor = null; try { String editorClassName = System.getProperty(COMMAND_EDITOR_NAME); if (null != editorClassName) { ClassLoader cl = AjcTask.class.getClassLoader(); Class editorClass = cl.loadClass(editorClassName); editor = (ICommandEditor) editorClass.newInstance(); } } catch (Throwable t) { System.err.println("Warning: unable to load command editor"); t.printStackTrace(System.err); } COMMAND_EDITOR = editor; } // ---------------------------- state and Ant interface thereto private boolean verbose; private boolean listFileArgs; private boolean failonerror; private boolean fork; private String maxMem; // ------- single entries dumped into cmd protected GuardedCommand cmd; // ------- lists resolved in addListArgs() at execute() time private Path srcdir; private Path injars; private Path inpath; private Path classpath; private Path bootclasspath; private Path forkclasspath; private Path extdirs; private Path aspectpath; private Path argfiles; private List ignored; private Path sourceRoots; private File xweaveDir; private String xdoneSignal; // ----- added by adapter - integrate better? private List /* File */ adapterFiles; private String[] adapterArguments; private IMessageHolder messageHolder; private ICommandEditor commandEditor; // -------- resource-copying /** true if copying injar non-.class files to the output jar */ private boolean copyInjars; private boolean copyInpath; /** non-null if copying all source root files but the filtered ones */ private String sourceRootCopyFilter; /** non-null if copying all inpath dir files but the filtered ones */ private String inpathDirCopyFilter; /** directory sink for classes */ private File destDir; /** zip file sink for classes */ private File outjar; /** track whether we've supplied any temp outjar */ private boolean outjarFixedup; /** * When possibly copying resources to the output jar, * pass ajc a fake output jar to copy from, * so we don't change the modification time of the output jar * when copying injars/inpath into the actual outjar. */ private File tmpOutjar; private boolean executing; /** non-null only while executing in same vm */ private Main main; /** true only when executing in other vm */ private boolean executingInOtherVM; /** true if -incremental */ private boolean inIncrementalMode; /** true if -XincrementalFile (i.e, setTagFile)*/ private boolean inIncrementalFileMode; // also note MatchingTask grabs source files... public AjcTask() { reset(); } /** to use this same Task more than once (testing) */ public void reset() { // XXX possible to reset MatchingTask? // need declare for "all fields initialized in ..." adapterArguments = null; adapterFiles = new ArrayList(); argfiles = null; executing = false; aspectpath = null; bootclasspath = null; classpath = null; cmd = new GuardedCommand(); copyInjars = false; copyInpath = false; destDir = DEFAULT_DESTDIR; executing = false; executingInOtherVM = false; extdirs = null; failonerror = true; // non-standard default forkclasspath = null; inIncrementalMode = false; inIncrementalFileMode = false; ignored = new ArrayList(); injars = null; inpath = null; listFileArgs = false; maxMem = null; messageHolder = null; outjar = null; sourceRootCopyFilter = null; inpathDirCopyFilter = null; sourceRoots = null; srcdir = null; tmpOutjar = null; verbose = false; xweaveDir = null; xdoneSignal = null; } protected void ignore(String ignored) { this.ignored.add(ignored + " at " + getLocation()); } //---------------------- option values // used by entries with internal commas protected String validCommaList(String list, List valid, String label) { return validCommaList(list, valid, label, valid.size()); } protected String validCommaList(String list, List valid, String label, int max) { StringBuffer result = new StringBuffer(); StringTokenizer st = new StringTokenizer(list, ","); int num = 0; while (st.hasMoreTokens()) { String token = st.nextToken().trim(); num++; if (num > max) { ignore("too many entries for -" + label + ": " + token); break; } if (!valid.contains(token)) { ignore("bad commaList entry for -" + label + ": " + token); } else { if (0 < result.length()) { result.append(","); } result.append(token); } } return (0 == result.length() ? null : result.toString()); } public void setIncremental(boolean incremental) { cmd.addFlag("-incremental", incremental); inIncrementalMode = incremental; } public void setHelp(boolean help) { cmd.addFlag("-help", help); } public void setVersion(boolean version) { cmd.addFlag("-version", version); } public void setXNoweave(boolean noweave) { cmd.addFlag("-XnoWeave", noweave); } public void setXReweavable(boolean reweavable) { cmd.addFlag("-Xreweavable",reweavable); } public void setXNoInline(boolean noInline) { cmd.addFlag("-XnoInline",noInline); } public void setShowWeaveInfo(boolean showweaveinfo) { cmd.addFlag("-showWeaveInfo",showweaveinfo); } public void setNowarn(boolean nowarn) { cmd.addFlag("-nowarn", nowarn); } public void setDeprecation(boolean deprecation) { cmd.addFlag("-deprecation", deprecation); } public void setWarn(String warnings) { warnings = validCommaList(warnings, VALID_WARNINGS, "warn"); cmd.addFlag("-warn:" + warnings, (null != warnings)); } public void setDebug(boolean debug) { cmd.addFlag("-g", debug); } public void setDebugLevel(String level) { level = validCommaList(level, VALID_DEBUG, "g"); cmd.addFlag("-g:" + level, (null != level)); } public void setEmacssym(boolean emacssym) { cmd.addFlag("-emacssym", emacssym); } /** * -Xlint - set default level of -Xlint messages to warning * (same as </code>-Xlint:warning</code>) */ public void setXlintwarnings(boolean xlintwarnings) { cmd.addFlag("-Xlint", xlintwarnings); } /** -Xlint:{error|warning|info} - set default level for -Xlint messages * @param xlint the String with one of error, warning, ignored */ public void setXlint(String xlint) { xlint = validCommaList(xlint, VALID_XLINT, "Xlint", 1); cmd.addFlag("-Xlint:" + xlint, (null != xlint)); } /** * -Xlintfile {lint.properties} - enable or disable specific forms * of -Xlint messages based on a lint properties file * (default is * <code>org/aspectj/weaver/XLintDefault.properties</code>) * @param xlintFile the File with lint properties */ public void setXlintfile(File xlintFile) { cmd.addFlagged("-Xlintfile", xlintFile.getAbsolutePath()); } public void setPreserveAllLocals(boolean preserveAllLocals) { cmd.addFlag("-preserveAllLocals", preserveAllLocals); } public void setNoImportError(boolean noImportError) { cmd.addFlag("-warn:-unusedImport", noImportError); } public void setEncoding(String encoding) { cmd.addFlagged("-encoding", encoding); } public void setLog(File file) { cmd.addFlagged("-log", file.getAbsolutePath()); } public void setProceedOnError(boolean proceedOnError) { cmd.addFlag("-proceedOnError", proceedOnError); } public void setVerbose(boolean verbose) { cmd.addFlag("-verbose", verbose); this.verbose = verbose; } public void setListFileArgs(boolean listFileArgs) { this.listFileArgs = listFileArgs; } public void setReferenceInfo(boolean referenceInfo) { cmd.addFlag("-referenceInfo", referenceInfo); } public void setTime(boolean time) { cmd.addFlag("-time", time); } public void setNoExit(boolean noExit) { cmd.addFlag("-noExit", noExit); } public void setFailonerror(boolean failonerror) { this.failonerror = failonerror; } /** * @return true if fork was set */ public boolean isForked() { return fork; } public void setFork(boolean fork) { this.fork = fork; } public void setMaxmem(String maxMem) { this.maxMem = maxMem; } // ---------------- public void setTagFile(File file) { inIncrementalMode = true; cmd.addFlagged(Main.CommandController.TAG_FILE_OPTION, file.getAbsolutePath()); inIncrementalFileMode = true; } public void setOutjar(File file) { if (DEFAULT_DESTDIR != destDir) { String e = "specifying both output jar (" + file + ") and destination dir (" + destDir + ")"; throw new BuildException(e); } outjar = file; outjarFixedup = false; tmpOutjar = null; } public void setDestdir(File dir) { if (null != outjar) { String e = "specifying both output jar (" + outjar + ") and destination dir (" + dir + ")"; throw new BuildException(e); } cmd.addFlagged("-d", dir.getAbsolutePath()); destDir = dir; } /** * @param input a String in TARGET_INPUTS */ public void setTarget(String input) { String ignore = cmd.addOption("-target", TARGET_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Language compliance level. * If not set explicitly, eclipse default holds. * @param input a String in COMPLIANCE_INPUTS */ public void setCompliance(String input) { String ignore = cmd.addOption(null, COMPLIANCE_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Source compliance level. * If not set explicitly, eclipse default holds. * @param input a String in SOURCE_INPUTS */ public void setSource(String input) { String ignore = cmd.addOption("-source", SOURCE_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Flag to copy all non-.class contents of injars * to outjar after compile completes. * Requires both injars and outjar. * @param doCopy */ public void setCopyInjars(boolean doCopy){ ignore("copyInJars"); log("copyInjars not required since 1.1.1.\n", Project.MSG_WARN); //this.copyInjars = doCopy; } /** * Option to copy all files from * all source root directories * except those specified here. * If this is specified and sourceroots are specified, * then this will copy all files except * those specified in the filter pattern. * Requires sourceroots. * * @param filter a String acceptable as an excludes * filter for an Ant Zip fileset. */ public void setSourceRootCopyFilter(String filter){ this.sourceRootCopyFilter = filter; } /** * Option to copy all files from * all inpath directories * except the files specified here. * If this is specified and inpath directories are specified, * then this will copy all files except * those specified in the filter pattern. * Requires inpath. * If the input does not contain "**\/*.class", then * this prepends it, to avoid overwriting woven classes * with unwoven input. * @param filter a String acceptable as an excludes * filter for an Ant Zip fileset. */ public void setInpathDirCopyFilter(String filter){ if (null != filter) { if (-1 == filter.indexOf("**/*.class")) { filter = "**/*.class," + filter; } } this.inpathDirCopyFilter = filter; } public void setX(String input) { // ajc-only eajc-also docDone StringTokenizer tokens = new StringTokenizer(input, ",", false); while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); if (1 < token.length()) { if (VALID_XOPTIONS.contains(token)) { cmd.addFlag("-X" + token, true); } else { ignore("-X" + token); } } } } public void setXDoneSignal(String doneSignal) { this.xdoneSignal = doneSignal; } /** direct API for testing */ public void setMessageHolder(IMessageHolder holder) { this.messageHolder = holder; } /** * Setup custom message handling. * @param className the String fully-qualified-name of a class * reachable from this object's class loader, * implementing IMessageHolder, and * having a public no-argument constructor. * @throws BuildException if unable to create instance of className */ public void setMessageHolderClass(String className) { try { Class mclass = Class.forName(className); IMessageHolder holder = (IMessageHolder) mclass.newInstance(); setMessageHolder(holder); } catch (Throwable t) { String m = "unable to instantiate message holder: " + className; throw new BuildException(m, t); } } /** direct API for testing */ public void setCommandEditor(ICommandEditor editor) { this.commandEditor = editor; } /** * Setup command-line filter. * To do this staticly, define the environment variable * <code>org.aspectj.tools.ant.taskdefs.AjcTask.COMMAND_EDITOR</code> * with the <code>className</code> parameter. * @param className the String fully-qualified-name of a class * reachable from this object's class loader, * implementing ICommandEditor, and * having a public no-argument constructor. * @throws BuildException if unable to create instance of className */ public void setCommandEditorClass(String className) { // skip Ant interface? try { Class mclass = Class.forName(className); setCommandEditor((ICommandEditor) mclass.newInstance()); } catch (Throwable t) { String m = "unable to instantiate command editor: " + className; throw new BuildException(m, t); } } //---------------------- Path lists /** * Add path elements to source path and return result. * Elements are added even if they do not exist. * @param source the Path to add to - may be null * @param toAdd the Path to add - may be null * @return the (never-null) Path that results */ protected Path incPath(Path source, Path toAdd) { if (null == source) { source = new Path(project); } if (null != toAdd) { source.append(toAdd); } return source; } public void setSourcerootsref(Reference ref) { createSourceRoots().setRefid(ref); } public void setSourceRoots(Path roots) { sourceRoots = incPath(sourceRoots, roots); } public Path createSourceRoots() { if (sourceRoots == null) { sourceRoots = new Path(project); } return sourceRoots.createPath(); } public void setXWeaveDir(File file) { if ((null != file) && file.isDirectory() && file.canRead()) { xweaveDir = file; } } public void setInjarsref(Reference ref) { createInjars().setRefid(ref); } public void setInpathref(Reference ref) { createInpath().setRefid(ref); } public void setInjars(Path path) { injars = incPath(injars, path); } public void setInpath(Path path) { inpath = incPath(inpath,path); } public Path createInjars() { if (injars == null) { injars = new Path(project); } return injars.createPath(); } public Path createInpath() { if (inpath == null) { inpath = new Path(project); } return inpath.createPath(); } public void setClasspath(Path path) { classpath = incPath(classpath, path); } public void setClasspathref(Reference classpathref) { createClasspath().setRefid(classpathref); } public Path createClasspath() { if (classpath == null) { classpath = new Path(project); } return classpath.createPath(); } public void setBootclasspath(Path path) { bootclasspath = incPath(bootclasspath, path); } public void setBootclasspathref(Reference bootclasspathref) { createBootclasspath().setRefid(bootclasspathref); } public Path createBootclasspath() { if (bootclasspath == null) { bootclasspath = new Path(project); } return bootclasspath.createPath(); } public void setForkclasspath(Path path) { forkclasspath = incPath(forkclasspath, path); } public void setForkclasspathref(Reference forkclasspathref) { createForkclasspath().setRefid(forkclasspathref); } public Path createForkclasspath() { if (forkclasspath == null) { forkclasspath = new Path(project); } return forkclasspath.createPath(); } public void setExtdirs(Path path) { extdirs = incPath(extdirs, path); } public void setExtdirsref(Reference ref) { createExtdirs().setRefid(ref); } public Path createExtdirs() { if (extdirs == null) { extdirs = new Path(project); } return extdirs.createPath(); } public void setAspectpathref(Reference ref) { createAspectpath().setRefid(ref); } public void setAspectpath(Path path) { aspectpath = incPath(aspectpath, path); } public Path createAspectpath() { if (aspectpath == null) { aspectpath = new Path(project); } return aspectpath.createPath(); } public void setSrcDir(Path path) { srcdir = incPath(srcdir, path); } public Path createSrc() { return createSrcdir(); } public Path createSrcdir() { if (srcdir == null) { srcdir = new Path(project); } return srcdir.createPath(); } /** @return true if in incremental mode (command-line or file) */ public boolean isInIncrementalMode() { return inIncrementalMode; } /** @return true if in incremental file mode */ public boolean isInIncrementalFileMode() { return inIncrementalFileMode; } public void setArgfilesref(Reference ref) { createArgfiles().setRefid(ref); } public void setArgfiles(Path path) { // ajc-only eajc-also docDone argfiles = incPath(argfiles, path); } public Path createArgfiles() { if (argfiles == null) { argfiles = new Path(project); } return argfiles.createPath(); } // ------------------------------ run /** * Compile using ajc per settings. * @exception BuildException if the compilation has problems * or if there were compiler errors and failonerror is true. */ public void execute() throws BuildException { if (executing) { throw new IllegalStateException("already executing"); } else { executing = true; } setupOptions(); verifyOptions(); try { String[] args = makeCommand(); if (verbose || listFileArgs) { // XXX if listFileArgs, only do that log("ajc " + Arrays.asList(args), Project.MSG_VERBOSE); } if (!fork) { executeInSameVM(args); } else { // when forking, Adapter handles failonerror executeInOtherVM(args); } } catch (BuildException e) { throw e; } catch (Throwable x) { System.err.println(Main.renderExceptionForUser(x)); throw new BuildException("IGNORE -- See " + LangUtil.unqualifiedClassName(x) + " rendered to System.err"); } finally { executing = false; if (null != tmpOutjar) { tmpOutjar.delete(); } } } /** * Halt processing. * This tells main in the same vm to quit. * It fails when running in forked mode. * @return true if not in forked mode * and main has quit or been told to quit */ public boolean quit() { if (executingInOtherVM) { return false; } Main me = main; if (null != me) { me.quit(); } return true; } // package-private for testing String[] makeCommand() { ArrayList result = new ArrayList(); if (0 < ignored.size()) { for (Iterator iter = ignored.iterator(); iter.hasNext();) { log("ignored: " + iter.next(), Project.MSG_INFO); } } // when copying resources, use temp jar for class output // then copy temp jar contents and resources to output jar if ((null != outjar) && !outjarFixedup) { if (copyInjars || copyInpath || (null != sourceRootCopyFilter) || (null != inpathDirCopyFilter)) { String path = outjar.getAbsolutePath(); int len = FileUtil.zipSuffixLength(path); if (len < 1) { log("not copying resources - weird outjar: " + path); } else { path = path.substring(0, path.length()-len) + ".tmp.jar"; tmpOutjar = new File(path); } } if (null == tmpOutjar) { cmd.addFlagged("-outjar", outjar.getAbsolutePath()); } else { cmd.addFlagged("-outjar", tmpOutjar.getAbsolutePath()); } outjarFixedup = true; } result.addAll(cmd.extractArguments()); addListArgs(result); String[] command = (String[]) result.toArray(new String[0]); if (null != commandEditor) { command = commandEditor.editCommand(command); } else if (null != COMMAND_EDITOR) { command = COMMAND_EDITOR.editCommand(command); } return command; } /** * Create any pseudo-options required to implement * some of the macro options * @throws BuildException if options conflict */ protected void setupOptions() { if (null != xweaveDir) { if (DEFAULT_DESTDIR != destDir) { throw new BuildException("weaveDir forces destdir"); } if (null != outjar) { throw new BuildException("weaveDir forces outjar"); } if (null != injars) { throw new BuildException("weaveDir incompatible with injars now"); } if (null != inpath) { throw new BuildException("weaveDir incompatible with inpath now"); } File injar = zipDirectory(xweaveDir); setInjars(new Path(getProject(), injar.getAbsolutePath())); setDestdir(xweaveDir); } } protected File zipDirectory(File dir) { File tempDir = new File("."); try { tempDir = File.createTempFile("AjcTest", ".tmp"); tempDir.mkdirs(); tempDir.deleteOnExit(); // XXX remove zip explicitly.. } catch (IOException e) { // ignore } // File result = new File(tempDir, String filename = "AjcTask-" + System.currentTimeMillis() + ".zip"; File result = new File(filename); Zip zip = new Zip(); zip.setProject(getProject()); zip.setDestFile(result); zip.setTaskName(getTaskName() + " - zip"); FileSet fileset = new FileSet(); fileset.setDir(dir); zip.addFileset(fileset); zip.execute(); Delete delete = new Delete(); delete.setProject(getProject()); delete.setTaskName(getTaskName() + " - delete"); delete.setDir(dir); delete.execute(); Mkdir mkdir = new Mkdir(); mkdir.setProject(getProject()); mkdir.setTaskName(getTaskName() + " - mkdir"); mkdir.setDir(dir); mkdir.execute(); return result; } /** * @throw BuildException if options conflict */ protected void verifyOptions() { StringBuffer sb = new StringBuffer(); if (fork && isInIncrementalMode() && !isInIncrementalFileMode()) { sb.append("can fork incremental only using tag file.\n"); } if (((null != inpathDirCopyFilter) || (null != sourceRootCopyFilter)) && (null == outjar) && (DEFAULT_DESTDIR == destDir)) { final String REQ = " requires dest dir or output jar.\n"; if (null == inpathDirCopyFilter) { sb.append("sourceRootCopyFilter"); } else if (null == sourceRootCopyFilter) { sb.append("inpathDirCopyFilter"); } else { sb.append("sourceRootCopyFilter and inpathDirCopyFilter"); } sb.append(REQ); } if (0 < sb.length()) { throw new BuildException(sb.toString()); } } /** * Run the compile in the same VM by * loading the compiler (Main), * setting up any message holders, * doing the compile, * and converting abort/failure and error messages * to BuildException, as appropriate. * @throws BuildException if abort or failure messages * or if errors and failonerror. * */ protected void executeInSameVM(String[] args) { if (null != maxMem) { log("maxMem ignored unless forked: " + maxMem, Project.MSG_WARN); } IMessageHolder holder = messageHolder; int numPreviousErrors; if (null == holder) { MessageHandler mhandler = new MessageHandler(true); final IMessageHandler delegate; delegate = verbose ? MessagePrinter.VERBOSE: MessagePrinter.TERSE; mhandler.setInterceptor(delegate); if (!verbose) { mhandler.ignore(IMessage.INFO); } holder = mhandler; numPreviousErrors = 0; } else { numPreviousErrors = holder.numMessages(IMessage.ERROR, true); } { Main newmain = new Main(); newmain.setHolder(holder); newmain.setCompletionRunner(new Runnable() { public void run() { doCompletionTasks(); } }); if (null != main) { MessageUtil.fail(holder, "still running prior main"); return; } main = newmain; } main.runMain(args, false); if (failonerror) { int errs = holder.numMessages(IMessage.ERROR, false); errs -= numPreviousErrors; if (0 < errs) { String m = errs + " errors"; MessageUtil.print(System.err, holder, "", MessageUtil.MESSAGE_ALL, MessageUtil.PICK_ERROR, true); throw new BuildException(m); } } // Throw BuildException if there are any fail or abort // messages. // The BuildException message text has a list of class names // for the exceptions found in the messages, or the // number of fail/abort messages found if there were // no exceptions for any of the fail/abort messages. // The interceptor message handler should have already // printed the messages, including any stack traces. // HACK: this ignores the Usage message { IMessage[] fails = holder.getMessages(IMessage.FAIL, true); if (!LangUtil.isEmpty(fails)) { StringBuffer sb = new StringBuffer(); String prefix = "fail due to "; int numThrown = 0; for (int i = 0; i < fails.length; i++) { String message = fails[i].getMessage(); if (LangUtil.isEmpty(message)) { message = "<no message>"; } else if (-1 != message.indexOf(USAGE_SUBSTRING)) { continue; } Throwable t = fails[i].getThrown(); if (null != t) { numThrown++; sb.append(prefix); sb.append(LangUtil.unqualifiedClassName(t.getClass())); String thrownMessage = t.getMessage(); if (!LangUtil.isEmpty(thrownMessage)) { sb.append(" \"" + thrownMessage + "\""); } } sb.append("\"" + message + "\""); prefix = ", "; } if (0 < sb.length()) { sb.append(" (" + numThrown + " exceptions)"); throw new BuildException(sb.toString()); } } } } /** * Execute in a separate VM. * Differences from normal same-VM execution: * <ul> * <li>ignores any message holder {class} set</li> * <li>No resource-copying between interative runs</li> * <li>failonerror fails when process interface fails * to return negative values</li> * </ul> * @param args String[] of the complete compiler command to execute * * @see DefaultCompilerAdapter#executeExternalCompile(String[], int) * @throws BuildException if ajc aborts (negative value) * or if failonerror and there were compile errors. */ protected void executeInOtherVM(String[] args) { if (null != messageHolder) { log("message holder ignored when forking: " + messageHolder.getClass().getName(), Project.MSG_WARN); } CommandlineJava javaCmd = new CommandlineJava(); javaCmd.setClassname(org.aspectj.tools.ajc.Main.class.getName()); final Path vmClasspath = javaCmd.createClasspath(getProject()); { File aspectjtools = null; int vmClasspathSize = vmClasspath.size(); if ((null != forkclasspath) && (0 != forkclasspath.size())) { vmClasspath.addExisting(forkclasspath); } else { aspectjtools = findAspectjtoolsJar(); if (null != aspectjtools) { vmClasspath.createPathElement().setLocation(aspectjtools); } } int newVmClasspathSize = vmClasspath.size(); if (vmClasspathSize == newVmClasspathSize) { String m = "unable to find aspectjtools to fork - "; if (null != aspectjtools) { m += "tried " + aspectjtools.toString(); } else if (null != forkclasspath) { m += "tried " + forkclasspath.toString(); } else { m += "define forkclasspath or put aspectjtools on classpath"; } throw new BuildException(m); } } if (null != maxMem) { javaCmd.setMaxmemory(maxMem); } File tempFile = null; int numArgs = args.length; args = GuardedCommand.limitTo(args, MAX_COMMANDLINE, getLocation()); if (args.length != numArgs) { tempFile = new File(args[1]); } try { String[] javaArgs = javaCmd.getCommandline(); String[] both = new String[javaArgs.length + args.length]; System.arraycopy(javaArgs,0,both,0,javaArgs.length); System.arraycopy(args,0,both,javaArgs.length,args.length); // try to use javaw instead on windows if (both[0].endsWith("java.exe")) { String path = both[0]; path = path.substring(0, path.length()-4); path = path + "w.exe"; File javaw = new File(path); if (javaw.canRead() && javaw.isFile()) { both[0] = path; } } if (verbose) { // XXX also when ant is verbose... log("forking " + Arrays.asList(both)); } int result = execInOtherVM(both); if (0 > result) { throw new BuildException("failure[" + result + "] running ajc"); } else if (failonerror && (0 < result)) { throw new BuildException("compile errors: " + result); } // when forking, do completion only at end and when successful doCompletionTasks(); } finally { if (null != tempFile) { tempFile.delete(); } } } /** * Execute in another process using the same JDK * and the base directory of the project. XXX correct? * @param args * @return */ protected int execInOtherVM(String[] args) { try { Project project = getProject(); PumpStreamHandler handler = new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN); // replace above two lines with what follows as an aid to debugging when running the unit tests.... // LogStreamHandler handler = new LogStreamHandler(this, // Project.MSG_INFO, Project.MSG_WARN) { // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // /* (non-Javadoc) // * @see org.apache.tools.ant.taskdefs.PumpStreamHandler#createProcessOutputPump(java.io.InputStream, java.io.OutputStream) // */ // protected void createProcessErrorPump(InputStream is, // OutputStream os) { // super.createProcessErrorPump(is, baos); // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.taskdefs.LogStreamHandler#stop() // */ // public void stop() { // byte[] written = baos.toByteArray(); // System.err.print(new String(written)); // super.stop(); // } // }; Execute exe = new Execute(handler); exe.setAntRun(project); exe.setWorkingDirectory(project.getBaseDir()); exe.setCommandline(args); try { if (executingInOtherVM) { String s = "already running in other vm?"; throw new BuildException(s, location); } executingInOtherVM = true; exe.execute(); } finally { executingInOtherVM = false; } return exe.getExitValue(); } catch (IOException e) { String m = "Error executing command " + Arrays.asList(args); throw new BuildException(m, e, location); } } // ------------------------------ setup and reporting /** @return null if path null or empty, String rendition otherwise */ protected static void addFlaggedPath(String flag, Path path, List list) { if (!LangUtil.isEmpty(flag) && ((null != path) && (0 < path.size()))) { list.add(flag); list.add(path.toString()); } } /** * Add to list any path or plural arguments. */ protected void addListArgs(List list) throws BuildException { addFlaggedPath("-classpath", classpath, list); addFlaggedPath("-bootclasspath", bootclasspath, list); addFlaggedPath("-extdirs", extdirs, list); addFlaggedPath("-aspectpath", aspectpath, list); addFlaggedPath("-injars", injars, list); addFlaggedPath("-inpath", inpath, list); addFlaggedPath("-sourceroots", sourceRoots, list); if (argfiles != null) { String[] files = argfiles.list(); for (int i = 0; i < files.length; i++) { File argfile = project.resolveFile(files[i]); if (check(argfile, files[i], false, location)) { list.add("-argfile"); list.add(argfile.getAbsolutePath()); } } } if (srcdir != null) { // todo: ignore any srcdir if any argfiles and no explicit includes String[] dirs = srcdir.list(); for (int i = 0; i < dirs.length; i++) { File dir = project.resolveFile(dirs[i]); check(dir, dirs[i], true, location); // relies on compiler to prune non-source files String[] files = getDirectoryScanner(dir).getIncludedFiles(); for (int j = 0; j < files.length; j++) { File file = new File(dir, files[j]); if (FileUtil.hasSourceSuffix(file)) { list.add(file.getAbsolutePath()); } } } } if (0 < adapterFiles.size()) { for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) { File file = (File) iter.next(); if (file.canRead() && FileUtil.hasSourceSuffix(file)) { list.add(file.getAbsolutePath()); } else { log("skipping file: " + file, Project.MSG_WARN); } } } } /** * Throw BuildException unless file is valid. * @param file the File to check * @param name the symbolic name to print on error * @param isDir if true, verify file is a directory * @param loc the Location used to create sensible BuildException * @return * @throws BuildException unless file valid */ protected final boolean check(File file, String name, boolean isDir, Location loc) { loc = loc != null ? loc : location; if (file == null) { throw new BuildException(name + " is null!", loc); } if (!file.exists()) { throw new BuildException(file + " doesn't exist!", loc); } if (isDir ^ file.isDirectory()) { String e = file + " should" + (isDir ? "" : "n't") + " be a directory!"; throw new BuildException(e, loc); } return true; } /** * Called when compile or incremental compile is completing, * this completes the output jar or directory * by copying resources if requested. * Note: this is a callback run synchronously by the compiler. * That means exceptions thrown here are caught by Main.run(..) * and passed to the message handler. */ protected void doCompletionTasks() { if (!executing) { throw new IllegalStateException("should be executing"); } if (null != outjar) { completeOutjar(); } else { completeDestdir(); } if (null != xdoneSignal) { MessageUtil.info(messageHolder, xdoneSignal); } } /** * Complete the destination directory * by copying resources from the source root directories * (if the filter is specified) * and non-.class files from the input jars * (if XCopyInjars is enabled). */ private void completeDestdir() { if (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter)) { return; } else if ((destDir == DEFAULT_DESTDIR) || !destDir.canWrite()) { String s = "unable to copy resources to destDir: " + destDir; throw new BuildException(s); } final Project project = getProject(); if (copyInjars) { // XXXX remove as unused since 1.1.1 if (null != inpath) { log("copyInjars does not support inpath.\n", Project.MSG_WARN); } String taskName = getTaskName() + " - unzip"; String[] paths = injars.list(); if (!LangUtil.isEmpty(paths)) { PatternSet patternSet = new PatternSet(); patternSet.setProject(project); patternSet.setIncludes("**/*"); patternSet.setExcludes("**/*.class"); for (int i = 0; i < paths.length; i++) { Expand unzip = new Expand(); unzip.setProject(project); unzip.setTaskName(taskName); unzip.setDest(destDir); unzip.setSrc(new File(paths[i])); unzip.addPatternset(patternSet); unzip.execute(); } } } if ((null != sourceRootCopyFilter) && (null != sourceRoots)) { String[] paths = sourceRoots.list(); if (!LangUtil.isEmpty(paths)) { Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destDir); for (int i = 0; i < paths.length; i++) { FileSet fileSet = new FileSet(); fileSet.setDir(new File(paths[i])); fileSet.setIncludes("**/*"); fileSet.setExcludes(sourceRootCopyFilter); copy.addFileset(fileSet); } copy.execute(); } } if ((null != inpathDirCopyFilter) && (null != inpath)) { String[] paths = inpath.list(); if (!LangUtil.isEmpty(paths)) { Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destDir); boolean gotDir = false; for (int i = 0; i < paths.length; i++) { File inpathDir = new File(paths[i]); if (inpathDir.isDirectory() && inpathDir.canRead()) { if (!gotDir) { gotDir = true; } FileSet fileSet = new FileSet(); fileSet.setDir(inpathDir); fileSet.setIncludes("**/*"); fileSet.setExcludes(inpathDirCopyFilter); copy.addFileset(fileSet); } } if (gotDir) { copy.execute(); } } } } /** * Complete the output jar * by copying resources from the source root directories * if the filter is specified. * and non-.class files from the input jars if enabled. */ private void completeOutjar() { if (((null == tmpOutjar) || !tmpOutjar.canRead()) || (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter))) { return; } Zip zip = new Zip(); Project project = getProject(); zip.setProject(project); zip.setTaskName(getTaskName() + " - zip"); zip.setDestFile(outjar); ZipFileSet zipfileset = new ZipFileSet(); zipfileset.setProject(project); zipfileset.setSrc(tmpOutjar); zipfileset.setIncludes("**/*.class"); zip.addZipfileset(zipfileset); if (copyInjars) { String[] paths = injars.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File jarFile = new File(paths[i]); zipfileset = new ZipFileSet(); zipfileset.setProject(project); zipfileset.setSrc(jarFile); zipfileset.setIncludes("**/*"); zipfileset.setExcludes("**/*.class"); zip.addZipfileset(zipfileset); } } } if ((null != sourceRootCopyFilter) && (null != sourceRoots)) { String[] paths = sourceRoots.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File srcRoot = new File(paths[i]); FileSet fileset = new FileSet(); fileset.setProject(project); fileset.setDir(srcRoot); fileset.setIncludes("**/*"); fileset.setExcludes(sourceRootCopyFilter); zip.addFileset(fileset); } } } if ((null != inpathDirCopyFilter) && (null != inpath)) { String[] paths = inpath.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File inpathDir = new File(paths[i]); if (inpathDir.isDirectory() && inpathDir.canRead()) { FileSet fileset = new FileSet(); fileset.setProject(project); fileset.setDir(inpathDir); fileset.setIncludes("**/*"); fileset.setExcludes(inpathDirCopyFilter); zip.addFileset(fileset); } } } } zip.execute(); } // -------------------------- compiler adapter interface extras /** * Add specified source files. */ void addFiles(File[] paths) { for (int i = 0; i < paths.length; i++) { addFile(paths[i]); } } /** * Add specified source file. */ void addFile(File path) { if (null != path) { adapterFiles.add(path); } } /** * Read arguments in as if from a command line, * mainly to support compiler adapter compilerarg subelement. * * @param args the String[] of arguments to read */ public void readArguments(String[] args) { // XXX slow, stupid, unmaintainable if ((null == args) || (0 == args.length)) { return; } /** String[] wrapper with increment, error reporting */ class Args { final String[] args; int index = 0; Args(String[] args) { this.args = args; // not null or empty } boolean hasNext() { return index < args.length; } String next() { String err = null; if (!hasNext()) { err = "need arg for flag " + args[args.length-1]; } else { String s = args[index++]; if (null == s) { err = "null value"; } else { s = s.trim(); if (0 == s.trim().length()) { err = "no value"; } else { return s; } } } err += " at [" + index + "] of " + Arrays.asList(args); throw new BuildException(err); } } // class Args Args in = new Args(args); String flag; while (in.hasNext()) { flag = in.next(); if ("-1.3".equals(flag)) { setCompliance(flag); } else if ("-1.4".equals(flag)) { setCompliance(flag); } else if ("-1.5".equals(flag)) { setCompliance("1.5"); } else if ("-argfile".equals(flag)) { setArgfiles(new Path(project, in.next())); } else if ("-aspectpath".equals(flag)) { setAspectpath(new Path(project, in.next())); } else if ("-classpath".equals(flag)) { setClasspath(new Path(project, in.next())); } else if ("-extdirs".equals(flag)) { setExtdirs(new Path(project, in.next())); } else if ("-Xcopyinjars".equals(flag)) { setCopyInjars(true); // ignored - will be flagged by setter } else if ("-g".equals(flag)) { setDebug(true); } else if (flag.startsWith("-g:")) { setDebugLevel(flag.substring(2)); } else if ("-deprecation".equals(flag)) { setDeprecation(true); } else if ("-d".equals(flag)) { setDestdir(new File(in.next())); } else if ("-emacssym".equals(flag)) { setEmacssym(true); } else if ("-encoding".equals(flag)) { setEncoding(in.next()); } else if ("-Xfailonerror".equals(flag)) { setFailonerror(true); } else if ("-fork".equals(flag)) { setFork(true); } else if ("-forkclasspath".equals(flag)) { setForkclasspath(new Path(project, in.next())); } else if ("-help".equals(flag)) { setHelp(true); } else if ("-incremental".equals(flag)) { setIncremental(true); } else if ("-injars".equals(flag)) { setInjars(new Path(project, in.next())); } else if ("-inpath".equals(flag)) { setInpath(new Path(project,in.next())); } else if ("-Xlistfileargs".equals(flag)) { setListFileArgs(true); } else if ("-Xmaxmem".equals(flag)) { setMaxmem(in.next()); } else if ("-Xmessageholderclass".equals(flag)) { setMessageHolderClass(in.next()); } else if ("-noexit".equals(flag)) { setNoExit(true); } else if ("-noimport".equals(flag)) { setNoExit(true); } else if ("-noExit".equals(flag)) { setNoExit(true); } else if ("-noImportError".equals(flag)) { setNoImportError(true); } else if ("-noWarn".equals(flag)) { setNowarn(true); } else if ("-noexit".equals(flag)) { setNoExit(true); } else if ("-outjar".equals(flag)) { setOutjar(new File(in.next())); } else if ("-preserveAllLocals".equals(flag)) { setPreserveAllLocals(true); } else if ("-proceedOnError".equals(flag)) { setProceedOnError(true); } else if ("-referenceInfo".equals(flag)) { setReferenceInfo(true); } else if ("-source".equals(flag)) { setSource(in.next()); } else if ("-Xsourcerootcopyfilter".equals(flag)) { setSourceRootCopyFilter(in.next()); } else if ("-sourceroots".equals(flag)) { setSourceRoots(new Path(project, in.next())); } else if ("-Xsrcdir".equals(flag)) { setSrcDir(new Path(project, in.next())); } else if ("-Xtagfile".equals(flag)) { setTagFile(new File(in.next())); } else if ("-target".equals(flag)) { setTarget(in.next()); } else if ("-time".equals(flag)) { setTime(true); } else if ("-time".equals(flag)) { setTime(true); } else if ("-verbose".equals(flag)) { setVerbose(true); } else if ("-showWeaveInfo".equals(flag)) { setShowWeaveInfo(true); } else if ("-version".equals(flag)) { setVersion(true); } else if ("-warn".equals(flag)) { setWarn(in.next()); } else if (flag.startsWith("-warn:")) { setWarn(flag.substring(6)); } else if ("-Xlint".equals(flag)) { setXlintwarnings(true); } else if (flag.startsWith("-Xlint:")) { setXlint(flag.substring(7)); } else if ("-Xlintfile".equals(flag)) { setXlintfile(new File(in.next())); } else if ("-Xnoweave".equals(flag)) { setXNoweave(true); } else if ("-Xreweavable".equals(flag)) { setXReweavable(true); } else if (flag.startsWith("@")) { File file = new File(flag.substring(1)); if (file.canRead()) { setArgfiles(new Path(project, file.getPath())); } else { ignore(flag); } } else { File file = new File(flag); if (file.isFile() && file.canRead() && FileUtil.hasSourceSuffix(file)) { addFile(file); } else { ignore(flag); } } } } /** * Commandline wrapper that * only permits addition of non-empty values * and converts to argfile form if necessary. */ public static class GuardedCommand { Commandline command; //int size; static boolean isEmpty(String s) { return ((null == s) || (0 == s.trim().length())); } GuardedCommand() { command = new Commandline(); } void addFlag(String flag, boolean doAdd) { if (doAdd && !isEmpty(flag)) { command.createArgument().setValue(flag); //size += 1 + flag.length(); } } /** @return null if added or ignoreString otherwise */ String addOption(String prefix, String[] validOptions, String input) { if (isEmpty(input)) { return null; } for (int i = 0; i < validOptions.length; i++) { if (input.equals(validOptions[i])) { if (isEmpty(prefix)) { addFlag(input, true); } else { addFlagged(prefix, input); } return null; } } return (null == prefix ? input : prefix + " " + input); } void addFlagged(String flag, String argument) { if (!isEmpty(flag) && !isEmpty(argument)) { command.addArguments(new String[] {flag, argument}); //size += 1 + flag.length() + argument.length(); } } // private void addFile(File file) { // if (null != file) { // String path = file.getAbsolutePath(); // addFlag(path, true); // } // } List extractArguments() { ArrayList result = new ArrayList(); String[] cmds = command.getArguments(); if (!LangUtil.isEmpty(cmds)) { result.addAll(Arrays.asList(cmds)); } return result; } /** * Adjust args for size if necessary by creating * an argument file, which should be deleted by the client * after the compiler run has completed. * @param max the int maximum length of the command line (in char) * @return the temp File for the arguments (if generated), * for deletion when done. * @throws IllegalArgumentException if max is negative */ static String[] limitTo(String[] args, int max, Location location) { if (max < 0) { throw new IllegalArgumentException("negative max: " + max); } // sigh - have to count anyway for now int size = 0; for (int i = 0; (i < args.length) && (size < max); i++) { size += 1 + (null == args[i] ? 0 : args[i].length()); } if (size <= max) { return args; } File tmpFile = null; PrintWriter out = null; // adapted from DefaultCompilerAdapter.executeExternalCompile try { String userDirName = System.getProperty("user.dir"); File userDir = new File(userDirName); tmpFile = File.createTempFile("argfile", "", userDir); out = new PrintWriter(new FileWriter(tmpFile)); for (int i = 0; i < args.length; i++) { out.println(args[i]); } out.flush(); return new String[] {"-argfile", tmpFile.getAbsolutePath()}; } catch (IOException e) { throw new BuildException("Error creating temporary file", e, location); } finally { if (out != null) { try {out.close();} catch (Throwable t) {} } } } } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
testing/newsrc/org/aspectj/testing/WeaveSpec.java
/* ******************************************************************* * Copyright (c) 2005 IBM Corporation * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Adrian Colyer, * ******************************************************************/ package org.aspectj.testing; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import org.aspectj.tools.ajc.AjcTestCase; import org.aspectj.tools.ajc.CompilationResult; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class WeaveSpec extends CompileSpec { private String classesFiles; private String aspectsFiles; private List classFilesFromClasses; /* (non-Javadoc) * @see org.aspectj.testing.ITestStep#execute(org.aspectj.tools.ajc.AjcTestCase) */ public void execute(AjcTestCase inTestCase) { String failMessage = "test \"" + getTest().getTitle() + "\" failed"; try { File base = new File(getBaseDir()); classFilesFromClasses = new ArrayList(); setFiles(classesFiles); String[] args = buildArgs(); CompilationResult result = inTestCase.ajc(base,args); inTestCase.assertNoMessages(result,failMessage); File sandbox = inTestCase.getSandboxDirectory(); createJar(sandbox,"classes.jar",true); inTestCase.setShouldEmptySandbox(false); setFiles(aspectsFiles); String options = getOptions(); if (options == null) { setOptions("-Xreweavable"); } else if (options.indexOf("-Xreweavable") == -1) { setOptions(options + ",-Xreweavable"); } setClasspath("classes.jar"); args = buildArgs(); result = inTestCase.ajc(base,args); inTestCase.assertNoMessages(result,failMessage); createJar(sandbox,"aspects.jar",false); args = buildWeaveArgs(); inTestCase.setShouldEmptySandbox(false); result = inTestCase.ajc(base,args); AjcTestCase.MessageSpec messageSpec = buildMessageSpec(); inTestCase.assertMessages(result,failMessage,messageSpec); inTestCase.setShouldEmptySandbox(false); // so subsequent steps in same test see my results } catch (IOException e) { AjcTestCase.fail(failMessage + " " + e); } } public void setClassesFiles(String files) { this.classesFiles = files; } public void setAspectsFiles(String files) { this.aspectsFiles = files; } /** * Find all the .class files under the dir, package them into a jar file, * and then delete them. * @param inDir * @param name */ private void createJar(File inDir, String name, boolean isClasses) throws IOException { File outJar = new File(inDir,name); FileOutputStream fos = new FileOutputStream(outJar); JarOutputStream jarOut = new JarOutputStream(fos); List classFiles = new ArrayList(); List toExclude = isClasses ? Collections.EMPTY_LIST : classFilesFromClasses; collectClassFiles(inDir,classFiles,toExclude); if (isClasses) classFilesFromClasses = classFiles; String prefix = inDir.getPath() + File.separator; for (Iterator iter = classFiles.iterator(); iter.hasNext();) { File f = (File) iter.next(); String thisPath = f.getPath(); if (thisPath.startsWith(prefix)) { thisPath = thisPath.substring(prefix.length()); } JarEntry entry = new JarEntry(thisPath); jarOut.putNextEntry(entry); copyFile(f,jarOut); jarOut.closeEntry(); } jarOut.flush(); jarOut.close(); } private void collectClassFiles(File inDir, List inList, List toExclude) { File[] contents = inDir.listFiles(); for (int i = 0; i < contents.length; i++) { if (contents[i].getName().endsWith(".class")) { if (!toExclude.contains(contents[i])) { inList.add(contents[i]); } } else if (contents[i].isDirectory()) { collectClassFiles(contents[i],inList, toExclude); } } } private void copyFile(File f, OutputStream dest) throws IOException { FileInputStream fis = new FileInputStream(f); byte[] buf = new byte[4096]; int read = -1; while((read = fis.read(buf)) != -1) { dest.write(buf,0,read); } } private String[] buildWeaveArgs() { StringBuffer args = new StringBuffer(); if (getOptions() != null) { StringTokenizer strTok = new StringTokenizer(getOptions(),","); while (strTok.hasMoreTokens()) { args.append(strTok.nextToken()); args.append(" "); } } args.append("-inpath "); args.append("classes.jar"); args.append(File.pathSeparator); args.append("aspects.jar"); args.append(" "); args.append("-aspectpath "); args.append("aspects.jar"); String argumentString = args.toString(); StringTokenizer strTok = new StringTokenizer(argumentString," "); String[] ret = new String[strTok.countTokens()]; for (int i = 0; i < ret.length; i++) { ret[i] = strTok.nextToken(); } return ret; } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
testing/src/org/aspectj/testing/harness/bridge/CompilerRun.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC), * 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Wes Isberg 2003 updates * ******************************************************************/ package org.aspectj.testing.harness.bridge; import java.io.*; import java.util.*; import org.aspectj.bridge.*; import org.aspectj.testing.ajde.CompileCommand; import org.aspectj.testing.run.*; import org.aspectj.testing.taskdefs.AjcTaskCompileCommand; import org.aspectj.testing.util.options.*; import org.aspectj.testing.util.options.Option.*; import org.aspectj.testing.xml.*; import org.aspectj.util.*; /** * Run the compiler once. * The lifecycle is as follows: * <ul> * <li>Spec (specification) is created.</li> * <li>This is created using the Spec.</li> * <li>setupAjcRun(Sandbox, Validator) is invoked, * at which point this populates the shared sandbox * with values derived from the spec and also * sets up internal state based on both the sandbox * and the spec.</li> * <li>run(IRunStatus) is invoked, and this runs the compiler * based on internal state, the spec, and the sandbox.</li> * </ul> * Programmer notes: * <ul> * <li>Paths are resolved absolutely, which fails to test the * compiler's ability to find files relative to a source base</li> * <li>This does not enforce the lifecycle.</li> * <li>This must be used as the initial compile * before doing an incremental compile. * In that case, staging must be enabled.</li> * </ul> */ public class CompilerRun implements IAjcRun { // static final String JAVAC_COMPILER // = JavacCompileCommand.class.getName(); static final String[] RA_String = new String[0]; static final String[] JAR_SUFFIXES = new String[] { ".jar", ".zip" }; static final String[] SOURCE_SUFFIXES = (String[]) FileUtil.SOURCE_SUFFIXES.toArray(new String[0]); /** specifications, set on construction */ Spec spec; //------------ calculated during setup /** get shared stuff during setup */ Sandbox sandbox; /** * During run, these String are passed as the source and arg files to compile. * The list is set up in setupAjcRun(..), when arg files are prefixed with "@". */ final List /*String*/ arguments; /** * During run, these String are collapsed and passed as the injar option. * The list is set up in setupAjcRun(..). */ final List /*String*/ injars; /** * During run, these String are collapsed and passed as the inpath option. * The list is set up in setupAjcRun(..), * which extracts only directories from the files attribute. */ final List inpaths; private CompilerRun(Spec spec) { if (null == spec) { throw new IllegalArgumentException("null spec"); } this.spec = spec; arguments = new ArrayList(); injars = new ArrayList(); inpaths = new ArrayList(); } /** * This checks that the spec is reasonable and does setup: * <ul> * <li>calculate and set sandbox testBaseSrcDir as {Sandbox.testBaseDir}/ * {Spec.testSrcDirOffset}/<li> * <li>get the list of source File to compile as {Sandbox.testBaseSrcDir} / * {Spec.getPaths..}</li> * <li>get the list of extraClasspath entries to add to default classpath as * {Sandbox.testBaseSrcDir} / {Spec.classpath..}</li> * <li>get the list of aspectpath entries to use as the aspectpath as * {Sandbox. testBaseSrcDir} / {Spec.aspectpath..}</li> * </ul> * All sources must be readable at this time, * unless spec.badInput is true (for invalid-input tests). * If staging, the source files and source roots are copied * to a separate staging directory so they can be modified * for incremental tests. Note that (as of this writing) the * compiler only handles source roots for incremental tests. * @param classesDir the File * @see org.aspectj.testing.harness.bridge.AjcTest.IAjcRun#setup(File, File) * @throws AbortException containing IOException or IllegalArgumentException * if the staging operations fail */ public boolean setupAjcRun(Sandbox sandbox, Validator validator) { if (!validator.nullcheck(spec.getOptionsArray(), "localOptions") || !validator.nullcheck(sandbox, "sandbox") || !validator.nullcheck(spec.compiler, "compilerName") || !validator.canRead(Globals.F_aspectjrt_jar, "aspectjrt.jar") || !validator.canRead( Globals.F_testingclient_jar, "testing-client.jar")) { return false; } this.sandbox = sandbox; String rdir = spec.testSrcDirOffset; File testBaseSrcDir; if ((null == rdir) || (0 == rdir.length())) { testBaseSrcDir = sandbox.testBaseDir; } else { testBaseSrcDir = new File(sandbox.testBaseDir, rdir); // XXX what if rdir is two levels deep? if (!validator .canReadDir(testBaseSrcDir, "sandbox.testBaseSrcDir")) { return false; } } // Sources come as relative paths - check read, copy if staging. // This renders paths absolute before run(RunStatusI) is called. // For a compile run to support relative paths + source base, // change so the run calculates the paths (differently when staging) final String[] inpathPaths; final String[] injarPaths; final String[] srcPaths; { final String[] paths = spec.getPathsArray(); srcPaths = LangUtil.endsWith( paths, CompilerRun.SOURCE_SUFFIXES, true); injarPaths = LangUtil.endsWith(paths, CompilerRun.JAR_SUFFIXES, true); inpathPaths = LangUtil.selectDirectories(paths, testBaseSrcDir); if (!spec.badInput) { int found = inpathPaths.length + injarPaths.length + srcPaths.length; if (paths.length != found) { validator.fail("found " + found + " of " + paths.length + " sources"); } } } // validate readable for sources if (!spec.badInput) { if (!validator.canRead(testBaseSrcDir, srcPaths, "sources") // see validation of inpathPaths below due to ambiguous base dir || !validator.canRead( testBaseSrcDir, spec.argfiles, "argfiles") || !validator.canRead( testBaseSrcDir, spec.classpath, "classpath") || !validator.canRead( testBaseSrcDir, spec.aspectpath, "aspectpath") || !validator.canRead( testBaseSrcDir, spec.sourceroots, "sourceroots") || !validator.canRead( testBaseSrcDir, spec.extdirs, "extdirs")) { return false; } } int numSources = srcPaths.length + injarPaths.length + inpathPaths.length + spec.argfiles.length + spec.sourceroots.length; if (!spec.badInput && (numSources < 1)) { validator.fail( "no input jars, arg files, or source files or roots"); return false; } final File[] argFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, spec.argfiles); final File[] injarFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, injarPaths); final File[] inpathFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, inpathPaths); final File[] aspectFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, spec.aspectpath); final File[] extdirFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, spec.extdirs); final File[] classFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, spec.classpath); final File[] xlintFiles = (null == spec.xlintfile ? new File[0] : FileUtil.getBaseDirFiles(testBaseSrcDir, new String[] {spec.xlintfile})); // injars might be outjars in the classes dir... for (int i = 0; i < injarFiles.length; i++) { if (!injarFiles[i].exists()) { injarFiles[i] = new File(sandbox.classesDir, injarPaths[i]); } } for (int i = 0; i < inpathFiles.length; i++) { if (!inpathFiles[i].exists()) { inpathFiles[i] = new File(sandbox.classesDir, inpathPaths[i]); } } // moved after solving any injars that were outjars if (!validator.canRead(injarFiles, "injars") || !validator.canRead(injarFiles, "injars")) { return false; } // hmm - duplicates validation above, verifying getBaseDirFiles? if (!spec.badInput) { if (!validator.canRead(argFiles, "argFiles") || !validator.canRead(injarFiles, "injarFiles") || !validator.canRead(inpathFiles, "inpathFiles") || !validator.canRead(aspectFiles, "aspectFiles") || !validator.canRead(classFiles, "classFiles") || !validator.canRead(xlintFiles, "xlintFiles")) { return false; } } final File[] srcFiles; File[] sourcerootFiles = new File[0]; // source text files are copied when staging incremental tests if (!spec.isStaging()) { // XXX why this? was always? || (testBaseSrcDir != sandbox.stagingDir))) { srcFiles = FileUtil.getBaseDirFiles( testBaseSrcDir, srcPaths, CompilerRun.SOURCE_SUFFIXES); if (!LangUtil.isEmpty(spec.sourceroots)) { sourcerootFiles = FileUtil.getBaseDirFiles( testBaseSrcDir, spec.sourceroots, null); } } else { // staging - copy files if (spec.badInput) { validator.info( "badInput ignored - files checked when staging"); } try { // copy all files, then remove tagged ones // XXX make copyFiles support a filter? srcFiles = FileUtil.copyFiles( testBaseSrcDir, srcPaths, sandbox.stagingDir); if (!LangUtil.isEmpty(spec.sourceroots)) { sourcerootFiles = FileUtil.copyFiles( testBaseSrcDir, spec.sourceroots, sandbox.stagingDir); // delete incremental files in sourceroot after copying // XXX inefficient // an incremental file has an extra "." in name // most .java files don't, because they are named after // the principle type they contain, and simple type names // have no dots. FileFilter pickIncFiles = new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) { // continue recursion return true; } String path = file.getPath(); // only source files are relevant to staging if (!FileUtil.hasSourceSuffix(path)) { return false; } int first = path.indexOf("."); int last = path.lastIndexOf("."); return (first != last); } }; for (int i = 0; i < sourcerootFiles.length; i++) { FileUtil.deleteContents( sourcerootFiles[i], pickIncFiles, false); } if (0 < sourcerootFiles.length) { FileUtil.sleepPastFinalModifiedTime( sourcerootFiles); } } File[] files = FileUtil.getBaseDirFiles(sandbox.stagingDir, srcPaths); if (0 < files.length) { FileUtil.sleepPastFinalModifiedTime(files); } } catch (IllegalArgumentException e) { validator.fail("staging - bad input", e); return false; } catch (IOException e) { validator.fail("staging - operations", e); return false; } } if (!spec.badInput && !validator.canRead(srcFiles, "copied paths")) { return false; } arguments.clear(); if (!LangUtil.isEmpty(xlintFiles)) { arguments.add("-Xlintfile"); String sr = FileUtil.flatten(xlintFiles, null); arguments.add(sr); } if (spec.outjar != null) { arguments.add("-outjar"); arguments.add(new File(sandbox.classesDir,spec.outjar).getPath()); } if (!LangUtil.isEmpty(extdirFiles)) { arguments.add("-extdirs"); String sr = FileUtil.flatten(extdirFiles, null); arguments.add(sr); } if (!LangUtil.isEmpty(sourcerootFiles)) { arguments.add("-sourceroots"); String sr = FileUtil.flatten(sourcerootFiles, null); arguments.add(sr); } if (!LangUtil.isEmpty(srcFiles)) { arguments.addAll(Arrays.asList(FileUtil.getPaths(srcFiles))); } injars.clear(); if (!LangUtil.isEmpty(injarFiles)) { injars.addAll(Arrays.asList(FileUtil.getPaths(injarFiles))); } inpaths.clear(); if (!LangUtil.isEmpty(inpathFiles)) { inpaths.addAll(Arrays.asList(FileUtil.getPaths(inpathFiles))); } if (!LangUtil.isEmpty(argFiles)) { String[] ra = FileUtil.getPaths(argFiles); for (int j = 0; j < ra.length; j++) { arguments.add("@" + ra[j]); } if (!spec.badInput && spec.isStaging) { validator.fail( "warning: files listed in argfiles not staged"); } } // save classpath and aspectpath in sandbox for this and other clients final boolean checkReadable = !spec.badInput; int size = spec.includeClassesDir ? 3 : 2; File[] cp = new File[size + classFiles.length]; System.arraycopy(classFiles, 0, cp, 0, classFiles.length); int index = classFiles.length; if (spec.includeClassesDir) { cp[index++] = sandbox.classesDir; } cp[index++] = Globals.F_aspectjrt_jar; cp[index++] = Globals.F_testingclient_jar; sandbox.compilerRunInit(this, testBaseSrcDir, aspectFiles, checkReadable, cp, checkReadable, null); // XXX todo set bootclasspath if set for forking? return true; } /** * Setup result evaluation and command line, run, and evaluate result. * <li>setup an AjcMessageHandler using the expected messages from * {@link Spec#getMessages()}.<li> * <li>heed any globals interpreted into a TestSetup by reading * {@link Spec@getOptions()}. For a list of supported globals, see * {@link setupArgs(ArrayList, IMessageHandler}.</li> * <li>construct a command line, using as classpath * {@link Sandbox.classpathToString()}<li> * <li>construct a compiler using {@link Spec#compiler} * or any overriding value set in TestSetup.<li> * <li>Just before running, set the compiler in the sandbox using * {@link Sandbox.setCompiler(ICommand)}.<li> * <li>After running, report AjcMessageHandler results to the status parameter. * If the AjcMessageHandler reports a failure, then send info messages * for the Spec, TestSetup, and command line.<li> * @see org.aspectj.testing.run.IRun#run(IRunStatus) */ public boolean run(IRunStatus status) { if (null == spec.testSetup) { MessageUtil.abort( status, "no test setup - adoptParentValues not called"); return false; } else if (!spec.testSetup.result) { MessageUtil.abort(status, spec.testSetup.failureReason); return false; } AjcMessageHandler handler = new AjcMessageHandler(spec.getMessages()); handler.init(); boolean handlerResult = false; boolean result = false; boolean commandResult = false; ArrayList argList = new ArrayList(); final Spec.TestSetup setupResult = spec.testSetup; try { if (spec.outjar == null) { argList.add("-d"); String outputDirPath = sandbox.classesDir.getAbsolutePath(); try { // worth it to try for canonical? outputDirPath = sandbox.classesDir.getCanonicalPath(); } catch (IOException e) { MessageUtil.abort( status, "canonical " + sandbox.classesDir, e); } argList.add(outputDirPath); } String path = sandbox.classpathToString(this); if (!LangUtil.isEmpty(path)) { argList.add("-classpath"); argList.add(path); } path = sandbox.getBootclasspath(this); if (!LangUtil.isEmpty(path)) { argList.add("-bootclasspath"); argList.add(path); } path = sandbox.aspectpathToString(this); if (!LangUtil.isEmpty(path)) { argList.add("-aspectpath"); argList.add(path); } if (0 < injars.size()) { argList.add("-injars"); argList.add( FileUtil.flatten( (String[]) injars.toArray(new String[0]), null)); } if (0 < inpaths.size()) { argList.add("-inpath"); argList.add( FileUtil.flatten( (String[]) inpaths.toArray(new String[0]), null)); } // put specified arguments last, for better badInput tests argList.addAll(setupResult.commandOptions); // add both java/aspectj and argfiles argList.addAll(arguments); // XXX hack - seek on request as a side effect. reimplement as listener if (null != setupResult.seek) { String slopPrefix = Spec.SEEK_MESSAGE_PREFIX + " slop - "; PrintStream slop = MessageUtil.handlerPrintStream( status, IMessage.INFO, System.err, slopPrefix); List found = FileUtil.lineSeek( setupResult.seek, arguments, false, slop); if (!LangUtil.isEmpty(found)) { for (Iterator iter = found.iterator(); iter.hasNext(); ) { MessageUtil.info( status, Spec.SEEK_MESSAGE_PREFIX + iter.next()); } } } ICommand compiler = spec.reuseCompiler // throws IllegalStateException if null ? sandbox.getCommand(this) : ReflectionFactory.makeCommand(setupResult.compilerName, status); DirChanges dirChanges = null; if (null == compiler) { MessageUtil.fail( status, "unable to make compiler " + setupResult.compilerName); return false; } else { if (setupResult.compilerName != Spec.DEFAULT_COMPILER) { MessageUtil.info( status, "compiler: " + setupResult.compilerName); } if (status.aborted()) { MessageUtil.debug( status, "aborted, but compiler valid?: " + compiler); } else { // same DirChanges handling for JavaRun, CompilerRun, IncCompilerRun // XXX around advice or template method/class if (!LangUtil.isEmpty(spec.dirChanges)) { LangUtil.throwIaxIfFalse( 1 == spec.dirChanges.size(), "expecting 0..1 dirChanges"); dirChanges = new DirChanges( (DirChanges.Spec) spec.dirChanges.get(0)); if (!dirChanges .start(status, sandbox.classesDir)) { return false; // setup failed } } MessageUtil.info( status, compiler + "(" + argList + ")"); sandbox.setCommand(compiler, this); String[] args = (String[]) argList.toArray(RA_String); commandResult = compiler.runCommand(args, handler); } } handlerResult = handler.passed(); if (!handlerResult) { return false; } else { result = (commandResult == handler.expectingCommandTrue()); if (!result) { String m = commandResult ? "compile did not fail as expected" : "compile failed unexpectedly"; MessageUtil.fail(status, m); } else if (null != dirChanges) { result = dirChanges.end(status, sandbox.testBaseDir); } } return result; } finally { if (!handlerResult) { // more debugging context in case of failure MessageUtil.info(handler, spec.toLongString()); MessageUtil.info(handler, "" + argList); if (null != setupResult) { MessageUtil.info(handler, "" + setupResult); } } handler.report(status); // XXX weak - actual messages not reported in real-time, no fast-fail } } public String toString() { return "CompilerRun(" + spec + ")"; } /** * Initializer/factory for CompilerRun * any path or file is relative to this test base dir */ public static class Spec extends AbstractRunSpec { public static final String XMLNAME = "compile"; public static final String DEFAULT_COMPILER = ReflectionFactory.ECLIPSE; static final String SEEK_PREFIX = "-seek:"; static final String SEEK_MESSAGE_PREFIX = "found: "; private static final CRSOptions CRSOPTIONS = new CRSOptions(); /** * Retitle description to title, paths to files, do comment, * staging, badInput, * do dirChanges, and print no chidren. */ private static final AbstractRunSpec.XMLNames NAMES = new AbstractRunSpec.XMLNames( AbstractRunSpec.XMLNames.DEFAULT, "title", null, null, null, "files", null, null, null, false, false, true); /** * If the source version warrants, add a -bootclasspath * entry to the list of arguments to add. * This will fail and return an error String if the * required library is not found. * @param sourceVersion the String (if any) describing the -source option * (expecting one of [null, "1.3", "1.4", "1.5"]. * @param compilerName the String name of the target compiler * @param toAdd the ArrayList to add -bootclasspath to * @return the String describing any errors, or null if no errors */ private static String updateBootclasspathForSourceVersion( String sourceVersion, String compilerName, ArrayList toAdd) { if (null == sourceVersion) { return null; } if (3 != sourceVersion.length()) { throw new IllegalArgumentException( "bad version: " + sourceVersion); } if (null == toAdd) { throw new IllegalArgumentException("null toAdd"); } int version = sourceVersion.charAt(2) - '0'; switch (version) { case (3) : if (LangUtil.supportsJava("1.4")) { if (!FileUtil.canReadFile(Globals.J2SE13_RTJAR)) { return "no 1.3 libraries to handle -source 1.3"; } toAdd.add("-bootclasspath"); toAdd.add(Globals.J2SE13_RTJAR.getAbsolutePath()); } break; case (4) : if (!LangUtil.supportsJava("1.4")) { if (ReflectionFactory .ECLIPSE .equals(compilerName)) { return "run eclipse under 1.4 to handle -source 1.4"; } if (!FileUtil.canReadFile(Globals.J2SE14_RTJAR)) { return "no 1.4 libraries to handle -source 1.4"; } toAdd.add("-bootclasspath"); toAdd.add(Globals.J2SE14_RTJAR.getAbsolutePath()); } break; case (5) : return "1.5 not supported in CompilerRun"; case (0) : // ignore - no version specified break; default : throw new Error("unexpected version: " + version); } return null; } static CRSOptions testAccessToCRSOptions() { return CRSOPTIONS; } static Options testAccessToOptions() { return CRSOPTIONS.getOptions(); } private static String[] copy(String[] input) { if (null == input) { return null; } String[] result = new String[input.length]; System.arraycopy(input, 0, result, 0, input.length); return result; } protected String compiler; // use same command - see also IncCompiler.Spec.fresh protected boolean reuseCompiler; protected boolean permitAnyCompiler; protected boolean includeClassesDir; protected TestSetup testSetup; protected String[] argfiles = new String[0]; protected String[] aspectpath = new String[0]; protected String[] classpath = new String[0]; protected String[] sourceroots = new String[0]; protected String[] extdirs = new String[0]; /** src path = {suiteParentDir}/{testBaseDirOffset}/{testSrcDirOffset}/{path} */ protected String testSrcDirOffset; protected String xlintfile; protected String outjar; public Spec() { super(XMLNAME); setXMLNames(NAMES); compiler = DEFAULT_COMPILER; } protected void initClone(Spec spec) throws CloneNotSupportedException { super.initClone(spec); spec.argfiles = copy(argfiles); spec.aspectpath = copy(aspectpath); spec.classpath = copy(classpath); spec.compiler = compiler; spec.includeClassesDir = includeClassesDir; spec.reuseCompiler = reuseCompiler; spec.permitAnyCompiler = permitAnyCompiler; spec.sourceroots = copy(sourceroots); spec.extdirs = copy(extdirs); spec.outjar = outjar; spec.testSetup = null; if (null != testSetup) { spec.testSetup = (TestSetup) testSetup.clone(); } spec.testSrcDirOffset = testSrcDirOffset; } public Object clone() throws CloneNotSupportedException { Spec result = new Spec(); initClone(result); return result; } public void setIncludeClassesDir(boolean include) { this.includeClassesDir = include; } public void setReuseCompiler(boolean reuse) { this.reuseCompiler = reuse; } public void setPermitAnyCompiler(boolean permitAny) { this.permitAnyCompiler = permitAny; } public void setCompiler(String compilerName) { this.compiler = compilerName; } public void setTestSrcDirOffset(String s) { if (null != s) { testSrcDirOffset = s; } } /** override to set dirToken to Sandbox.CLASSES and default suffix to ".class" */ public void addDirChanges(DirChanges.Spec spec) { if (null == spec) { return; } spec.setDirToken(Sandbox.CLASSES_DIR); spec.setDefaultSuffix(".class"); super.addDirChanges(spec); } public String toLongString() { return getPrintName() + "(" + super.containedSummary() + ")"; } public String toString() { return getPrintName() + "(" + super.containedSummary() + ")"; } /** bean mapping for writers */ public void setFiles(String paths) { addPaths(paths); } /** * Add to default classpath * (which includes aspectjrt.jar and testing-client.jar). * @param files comma-delimited list of classpath entries - ignored if * null or empty */ public void setClasspath(String files) { if (!LangUtil.isEmpty(files)) { classpath = XMLWriter.unflattenList(files); } } /** * Set source roots, deleting any old ones * @param files comma-delimited list of directories * - ignored if null or empty */ public void setSourceroots(String dirs) { if (!LangUtil.isEmpty(dirs)) { sourceroots = XMLWriter.unflattenList(dirs); } } public void setXlintfile(String path) { xlintfile = path; } public void setOutjar(String path) { outjar = path; } /** * Set extension dirs, deleting any old ones * @param files comma-delimited list of directories * - ignored if null or empty */ public void setExtdirs(String dirs) { if (!LangUtil.isEmpty(dirs)) { extdirs = XMLWriter.unflattenList(dirs); } } /** * Set aspectpath, deleting any old ones * @param files comma-delimited list of aspect jars - ignored if null or * empty */ public void setAspectpath(String files) { if (!LangUtil.isEmpty(files)) { aspectpath = XMLWriter.unflattenList(files); } } /** * Set argfiles, deleting any old ones * @param files comma-delimited list of argfiles - ignored if null or empty */ public void setArgfiles(String files) { if (!LangUtil.isEmpty(files)) { argfiles = XMLWriter.unflattenList(files); } } /** @return String[] copy of argfiles array */ public String[] getArgfilesArray() { String[] argfiles = this.argfiles; if (LangUtil.isEmpty(argfiles)) { return new String[0]; } return (String[]) LangUtil.copy(argfiles); } /** * This implementation skips if: * <ul> * <li>incremental test, but using ajc (not eclipse)</li> * <li>usejavac, but javac is not available on the classpath</li> * <li>eclipse, but -usejavac or -preprocess test</li> * <li>-source 1.4, but running under 1.2 (XXX design)</li> * <li>local/global option conflicts (-lenient/-strict)</li> * <li>semantic conflicts (e.g., -lenient/-strict)</li> * </ul> * @return false if this wants to be skipped, true otherwise */ protected boolean doAdoptParentValues( RT parentRuntime, IMessageHandler handler) { if (!super.doAdoptParentValues(parentRuntime, handler)) { return false; } testSetup = setupArgs(handler); if (!testSetup.result) { skipMessage(handler, testSetup.failureReason); } return testSetup.result; } private String getShortCompilerName() { String compilerClassName = compiler; if (null != testSetup) { compilerClassName = testSetup.compilerName; } if (null != compilerClassName) { int loc = compilerClassName.lastIndexOf("."); if (-1 != loc) { compilerClassName = compilerClassName.substring(loc + 1); } } return compilerClassName; } /** @return a CompilerRun with this as spec if setup completes successfully. */ public IRunIterator makeRunIterator( Sandbox sandbox, Validator validator) { CompilerRun run = new CompilerRun(this); if (run.setupAjcRun(sandbox, validator)) { // XXX need name for compilerRun return new WrappedRunIterator(this, run); } return null; } protected String getPrintName() { return "CompilerRun.Spec " + getShortCompilerName(); } /** * Each non-incremental run, fold the global flags in with * the run flags, which may involve adding or removing from * either list, depending on the flag prefix: * <ul> * <li>-foo: use -foo unless forced off.<li> * <li>^foo: (force off) remove any -foo option from the run flags</li> * <li>!foo: (force on) require the -foo flag </li> * </ul> * If there is a force conflict, then the test is skipped * ("skipping" info message, TestSetup.result is false). * This means an option local to the test which was specified * without forcing may be overridden by a globally-forced option. * <p> * There are some flags which are interpreted by the test * and removed from the list of flags passed to the command * (see testFlag()): * <ul> * <li>eclipse: use the new eclipse compiler (can force)</li> * <li>ajc: use the old ajc compiler (can force)</li> * <li>ignoreWarnings: ignore warnings in result evaluations (no force)</li> * </ul> * <p> * There are some flags which are inconsistent with each other. * These are treated as conflicts and the test is skipped: * <ul> * <li>lenient, strict</li> * </ul> * <p> * <p> * This also interprets any relevant System properties, * e.g., from <code>JavaRun.BOOTCLASSPATH_KEY</code>. * <p> * Finally, compiler limitations are enforced here by skipping * tests which the compiler cannot do: * <ul> * <li>eclipse does not do -lenient, -strict, -usejavac, -preprocess, * -XOcodeSize, -XSerializable, XaddSafePrefix, * -XserializableAspects,-XtargetNearSource</li> * <li>ajc does not run in incremental (staging) mode, * nor with -usejavac if javac is not on the classpath</li> * </ul> * <u>Errors</u>:This will remove an arg not prefixed by [-|!|^] after * providing an info message. * <u>TestSetup Result</u>: * If this completes successfully, then TestSetup.result is true, * and commandOptions is not null, and any test flags (ignore warning, * compiler) are reflected in the TestSetup. * If this fails, then TestSetup.result is false, * and a TestSetup.failreason is set. * This means the test is skipped. * @return TestSetup with results * (TestSetup result=false if the run should not continue) */ protected TestSetup setupArgs(IMessageHandler handler) { // warning: HarnessSelectionTest checks for specific error wording final Spec spec = this; final TestSetup result = new TestSetup(); result.compilerName = spec.compiler; // urk - s.b. null, but expected Values values = gatherValues(result); if ((null == values) || (null != result.failureReason)) { return checkResult(result); } // send info messages about // forced staging when -incremental // or staging but no -incremental flag Option.Family getFamily = CRSOPTIONS.crsIncrementalOption.getFamily(); final boolean haveIncrementalFlag = (null != values.firstInFamily(getFamily)); if (spec.isStaging()) { if (!haveIncrementalFlag) { MessageUtil.info( handler, "staging but no -incremental flag"); } } else if (haveIncrementalFlag) { spec.setStaging(true); MessageUtil.info(handler, "-incremental forcing staging"); } if (hasInvalidOptions(values, result)) { return checkResult(result); } // set compiler in result getFamily = CRSOPTIONS.ajccompilerOption.getFamily(); Option.Value compiler = values.firstInFamily(getFamily); if (null != compiler) { result.compilerName = CRSOPTIONS.compilerClassName(compiler.option); if (null == result.compilerName) { result.failureReason = "unable to get class name for " + compiler; return checkResult(result); } } String compilerName = (null == result.compilerName ? spec.compiler : result.compilerName); // check compiler semantics if (hasCompilerSpecErrors(compilerName, values, result)) { return checkResult(result); } // add toadd and finish result ArrayList args = new ArrayList(); String[] rendered = values.render(); if (!LangUtil.isEmpty(rendered)) { args.addAll(Arrays.asList(rendered)); } // update bootclasspath getFamily = CRSOPTIONS.crsSourceOption.getFamily(); Option.Value source = values.firstInFamily(getFamily); if (null != source) { String sourceVersion = source.unflatten()[1]; ArrayList toAdd = new ArrayList(); /*String err =*/ updateBootclasspathForSourceVersion( sourceVersion, spec.compiler, toAdd); args.addAll(toAdd); } result.commandOptions = args; result.result = true; return checkResult(result); } /** * Ensure exit invariant: * <code>result.result == (null == result.failureReason) * == (null != result.commandOptions)</code> * @param result the TestSetup to verify * @return result * @throws Error if invariant is not true */ TestSetup checkResult(TestSetup result) { String err = null; if (null == result) { err = "null result"; } else if (result.result != (null == result.failureReason)) { err = result.result ? "expected no failure: " + result.failureReason : "fail for no reason"; } else if (result.result != (null != result.commandOptions)) { err = result.result ? "expected command options" : "unexpected command options"; } if (null != err) { throw new Error(err); } return result; } boolean hasInvalidOptions(Values values, TestSetup result) { // not supporting 1.0 options any more for (Iterator iter = CRSOPTIONS.invalidOptions.iterator(); iter.hasNext(); ) { Option option = (Option) iter.next(); if (null != values.firstOption(option)) { result.failureReason = "invalid option in harness: " + option; return true; } } return false; } boolean hasCompilerSpecErrors( String compilerName, Values values, TestSetup result) { /* * Describe any semantic conflicts between options. * This skips: * - old 1.0 options, including lenient v. strict * - old ajc options, include !incremental and usejavac w/o javac * - invalid eclipse options (mostly ajc) * @param compilerName the String name of the target compiler * @return a String describing any conflicts, or null if none */ if (!permitAnyCompiler && (!(ReflectionFactory.ECLIPSE.equals(compilerName) || ReflectionFactory.OLD_AJC.equals(compilerName) || CRSOptions.AJDE_COMPILER.equals(compilerName) || CRSOptions.AJCTASK_COMPILER.equals(compilerName) || permitAnyCompiler ))) { //|| BUILDER_COMPILER.equals(compilerName)) result.failureReason = "unrecognized compiler: " + compilerName; return true; } // not supporting ajc right now if (null != values.firstOption(CRSOPTIONS.ajccompilerOption)) { result.failureReason = "ajc not supported"; return true; } // not supporting 1.0 options any more for (Iterator iter = CRSOPTIONS.ajc10Options.iterator(); iter.hasNext(); ) { Option option = (Option) iter.next(); if (null != values.firstOption(option)) { result.failureReason = "old ajc 1.0 option: " + option; return true; } } return false; } protected Values gatherValues(TestSetup result) { final Spec spec = this; // ---- local option values final Values localValues; final Options options = CRSOPTIONS.getOptions(); try { String[] input = getOptionsArray(); // this handles reading options, // flattening two-String options, etc. localValues = options.acceptInput(input); // all local values should be picked up String err = Options.missedMatchError(input, localValues); if (!LangUtil.isEmpty(err)) { result.failureReason = err; return null; } } catch (InvalidInputException e) { result.failureReason = e.getFullMessage(); return null; } // ---- global option values StringBuffer errs = new StringBuffer(); final Values globalValues = spec.runtime.extractOptions(options, true, errs); if (errs.length() > 0) { result.failureReason = errs.toString(); return null; } final Values combined = Values.wrapValues( new Values[] { localValues, globalValues }); String err = combined.resolve(); if (null != err) { result.failureReason = err; return null; } return handleTestArgs(combined, result); } // final int len = globalValues.length() + localValues.length(); // final Option.Value[] combinedValues = new Option.Value[len]; // System.arraycopy( // globalValues, // 0, // combinedValues, // 0, // globalValues.length()); // System.arraycopy( // localValues, // 0, // combinedValues, // globalValues.length(), // localValues.length()); // // result.compilerName = spec.compiler; // if (0 < combinedValues.length) { // // this handles option forcing, etc. // String err = Options.resolve(combinedValues); // if (null != err) { // result.failureReason = err; // return null; // } // if (!handleTestArgs(combinedValues, result)) { // return null; // } // } // return Values.wrapValues(combinedValues); // } /** * This interprets and nullifies values for the test. * @param values the Option.Value[] being processed * @param result the TestSetup to modify * @return false if error (caller should return), true otherwise */ Values handleTestArgs(Values values, final TestSetup result) { final Option.Family compilerFamily = CRSOPTIONS.ajccompilerOption.getFamily(); Values.Selector selector = new Values.Selector() { protected boolean accept(Option.Value value) { if (null == value) { return false; } Option option = value.option; if (compilerFamily.sameFamily(option.getFamily())) { if (value.prefix.isSet()) { String compilerClass = CRSOPTIONS.compilerClassName(option); if (null == compilerClass) { result.failureReason = "unrecognized compiler: " + value; throw Values.Selector.STOP; } if (!CRSOPTIONS.compilerIsLoadable(option)) { result.failureReason = "unable to load compiler: " + option; throw Values.Selector.STOP; } result.compilerName = compilerClass; } return true; } else if ( CRSOPTIONS.crsIgnoreWarnings.sameOptionIdentifier( option)) { result.ignoreWarnings = value.prefix.isSet(); result.ignoreWarningsSet = true; return true; } return false; } }; return values.nullify(selector); } // /** // * This interprets and nullifies values for the test. // * @param values the Option.Value[] being processed // * @param result the TestSetup to modify // * @return false if error (caller should return), true otherwise // */ // boolean handleTestArgs(Option.Value[] values, TestSetup result) { // if (!LangUtil.isEmpty(values)) { // for (int i = 0; i < values.length; i++) { // Option.Value value = values[i]; // if (null == value) { // continue; // } // Option option = value.option; // if (option.sameOptionFamily(ECLIPSE_OPTION)) { // if (!value.prefix.isSet()) { // values[i] = null; // continue; // } // String compilerClass = // (String) COMPILER_OPTION_TO_CLASSNAME.get( // option); // if (null == compilerClass) { // result.failureReason = // "unrecognized compiler: " + value; // return false; // } // result.compilerName = compilerClass; // values[i] = null; // } else if ( // option.sameOptionFamily(crsIgnoreWarnings)) { // result.ignoreWarnings = value.prefix.isSet(); // result.ignoreWarningsSet = true; // values[i] = null; // } // } // } // return true; // } // XXX need keys, cache... /** @return index of global in argList, ignoring first char */ protected int indexOf(String global, ArrayList argList) { int max = argList.size(); for (int i = 0; i < max; i++) { if (global .equals(((String) argList.get(i)).substring(1))) { return i; } } return -1; } /** * Write this out as a compile element as defined in * AjcSpecXmlReader.DOCTYPE. * @see AjcSpecXmlReader#DOCTYPE * @see IXmlWritable#writeXml(XMLWriter) */ public void writeXml(XMLWriter out) { out.startElement(xmlElementName, false); if (!LangUtil.isEmpty(testSrcDirOffset)) { out.printAttribute("dir", testSrcDirOffset); } super.writeAttributes(out); if (!DEFAULT_COMPILER.equals(compiler)) { out.printAttribute("compiler", compiler); } if (reuseCompiler) { out.printAttribute("reuseCompiler", "true"); } // test-only feature // if (permitAnyCompiler) { // out.printAttribute("permitAnyCompiler", "true"); // } if (includeClassesDir) { out.printAttribute("includeClassesDir", "true"); } if (!LangUtil.isEmpty(argfiles)) { out.printAttribute( "argfiles", XMLWriter.flattenFiles(argfiles)); } if (!LangUtil.isEmpty(aspectpath)) { out.printAttribute( "aspectpath", XMLWriter.flattenFiles(aspectpath)); } if (!LangUtil.isEmpty(sourceroots)) { out.printAttribute( "sourceroots", XMLWriter.flattenFiles(sourceroots)); } if (!LangUtil.isEmpty(extdirs)) { out.printAttribute( "extdirs", XMLWriter.flattenFiles(extdirs)); } out.endAttributes(); if (!LangUtil.isEmpty(dirChanges)) { DirChanges.Spec.writeXml(out, dirChanges); } SoftMessage.writeXml(out, getMessages()); out.endElement(xmlElementName); } /** * Encapsulate the directives that can be set using * global arguments supplied in {@link Spec.getOptions()}. * This supports changing the compiler and ignoring warnings. */ class TestSetup { /** null unless overriding the compiler to be used */ String compilerName; /** * true if we should tell AjcMessageHandler whether * to ignore warnings in its result evaluation */ boolean ignoreWarningsSet; /** if telling AjcMessageHandler, what we tell it */ boolean ignoreWarnings; /** false if setup failed */ boolean result; /** if setup failed, this has the reason why */ String failureReason; /** beyond running test, also seek text in sources */ String seek; /** if setup completed, this has the combined global/local options */ ArrayList commandOptions; public Object clone() { TestSetup testSetup = new TestSetup(); testSetup.compilerName = compilerName; testSetup.ignoreWarnings = ignoreWarnings; testSetup.ignoreWarningsSet = ignoreWarningsSet; testSetup.result = result; testSetup.failureReason = failureReason; testSetup.seek = seek; if (null != commandOptions) { testSetup.commandOptions = new ArrayList(); testSetup.commandOptions.addAll(commandOptions); } return testSetup; } public String toString() { return "TestSetup(" + (null == compilerName ? "" : compilerName + " ") + (!ignoreWarningsSet ? "" : (ignoreWarnings ? "" : "do not ") + "ignore warnings ") + (result ? "" : "setup failed") + ")"; } } /** * Options-related stuff in the spec. */ static class CRSOptions { // static final String BUILDER_COMPILER = // "org.aspectj.ajdt.internal.core.builder.Builder.Command"; static final String AJDE_COMPILER = CompileCommand.class.getName(); static final String AJCTASK_COMPILER = AjcTaskCompileCommand.class.getName(); private final Map compilerOptionToLoadable = new TreeMap(); /* * The options field in a compiler test permits some arbitrary * command-line options to be set. It does not permit things * like classpath, aspectpath, files, etc. which are set * using other fields in the test specification, so the options * permitted are a subset of those permitted on the command-line. * * Global options specified on the harness command-line are * adopted for the compiler command-line if they are permitted * in the options field. That means we have to detect each * permitted option, rather than just letting all through * for the compiler. * * Conversely, some options are targeted not at the compiler, * but at the test itself (e.g., to ignore warnings, or to * select a compiler. * * The harness can run many compilers, and they differ in * which options are permitted. You can specify a compiler * as an option (e.g., -eclipse). So the set of constraints * on the list of permitted options can differ from test to test. * * The following code sets up the lists of permitted options * and breaks out subsets for different compiler-variant checks. * Most options are created but not named, but some options * are named to detect corresponding values for further * processing. e.g., the compiler options are saved so * we can do per-compiler option verification. * */ private final Options crsOptions; private final Family compilerFamily; private final Option crsIncrementalOption; private final Option crsSourceOption; // these are options handled/absorbed by CompilerRun private final Option crsIgnoreWarnings; private final Option eclipseOption; private final Option buildercompilerOption; private final Option ajdecompilerOption; private final Option javacOption; private final Option ajctaskcompilerOption; private final Option ajccompilerOption; private final Map compilerOptionToClassname; private final Set compilerOptions; // compiler verification - permit but flag ajc 1.0 options private final List ajc10Options; private final List invalidOptions; private CRSOptions() { crsOptions = new Options(true); Option.Factory factory = new Option.Factory("CompilerRun"); // compiler options go in map eclipseOption = factory.create( "eclipse", "compiler", Option.FORCE_PREFIXES, false); compilerFamily = eclipseOption.getFamily(); buildercompilerOption = factory.create( "builderCompiler", "compiler", Option.FORCE_PREFIXES, false); ajctaskcompilerOption = factory.create( "ajctaskCompiler", "compiler", Option.FORCE_PREFIXES, false); ajdecompilerOption = factory.create( "ajdeCompiler", "compiler", Option.FORCE_PREFIXES, false); ajccompilerOption = factory.create( "ajc", "compiler", Option.FORCE_PREFIXES, false); javacOption = factory.create( "javac", "compiler", Option.FORCE_PREFIXES, false); Map map = new TreeMap(); map.put(eclipseOption, ReflectionFactory.ECLIPSE); //map.put(BUILDERCOMPILER_OPTION, BUILDER_COMPILER); map.put( ajctaskcompilerOption, AJCTASK_COMPILER); map.put(ajdecompilerOption, AJDE_COMPILER); map.put(ajccompilerOption, ReflectionFactory.OLD_AJC); //map.put(JAVAC_OPTION, "XXX javac option not supported"); compilerOptionToClassname = Collections.unmodifiableMap(map); compilerOptions = Collections.unmodifiableSet( compilerOptionToClassname.keySet()); // options not permitted in the harness List list = new ArrayList(); list.add(factory.create("workingdir")); list.add(factory.create("argfile")); list.add(factory.create("sourceroots")); list.add(factory.create("outjar")); invalidOptions = Collections.unmodifiableList(list); // other options added directly crsIncrementalOption = factory.create("incremental"); crsIgnoreWarnings = factory.create("ignoreWarnings"); crsSourceOption = factory .create( "source", "source", Option.FORCE_PREFIXES, false, new String[][] { new String[] { "1.3", "1.4", "1.5" } }); // ajc 1.0 options // workingdir above in invalid options list = new ArrayList(); list.add(factory.create("usejavac")); list.add(factory.create("preprocess")); list.add(factory.create("nocomment")); list.add(factory.create("porting")); list.add(factory.create("XOcodeSize")); list.add(factory.create("XTargetNearSource")); list.add(factory.create("XaddSafePrefix")); list.add( factory.create( "lenient", "lenient", Option.FORCE_PREFIXES, false)); list.add( factory.create( "strict", "lenient", Option.FORCE_PREFIXES, false)); ajc10Options = Collections.unmodifiableList(list); // -warn:.. and -g/-g:.. are not exclusive if (!(factory.setupFamily("debug", true) && factory.setupFamily("warning", true))) { System.err.println("CompilerRun debug/warning fail!"); } Option[] options = new Option[] { crsIncrementalOption, crsIgnoreWarnings, crsSourceOption, factory.create( "Xlint", "XLint", Option.FORCE_PREFIXES, true), factory.create("verbose"), factory.create("emacssym"), factory.create("referenceInfo"), factory.create("nowarn"), factory.create("deprecation"), factory.create("noImportError"), factory.create("proceedOnError"), factory.create("preserveAllLocals"), factory.create( "warn", "warning", Option.STANDARD_PREFIXES, true), factory.create( "g", "debug", Option.STANDARD_PREFIXES, false), factory.create( "g:", "debug", Option.STANDARD_PREFIXES, true), factory.create( "1.3", "compliance", Option.FORCE_PREFIXES, false), factory.create( "1.4", "compliance", Option.FORCE_PREFIXES, false), factory.create( "1.5", "compliance", Option.FORCE_PREFIXES, false), factory .create( "target", "target", Option.FORCE_PREFIXES, false, new String[][] { new String[] { "1.1", "1.2", "1.3", "1.4", "1.5" }}), factory.create("XnoInline"), factory.create("XnoWeave"), factory.create("Xreweavable"), factory.create("XserializableAspects") }; // among options not permitted: extdirs... for (int i = 0; i < options.length; i++) { crsOptions.addOption(options[i]); } for (Iterator iter = compilerOptions.iterator(); iter.hasNext(); ) { crsOptions.addOption((Option) iter.next()); } // these are recognized but records with them are skipped for (Iterator iter = ajc10Options.iterator(); iter.hasNext(); ) { crsOptions.addOption((Option) iter.next()); } crsOptions.freeze(); } Options getOptions() { return crsOptions; } /** * @return unmodifiable Set of options sharing the * family "compiler". */ Set compilerOptions() { return compilerOptions; } /** * @param option the compiler Option to get name for * @return null if option is null or not a compiler option, * or the fully-qualified classname of the ICommand * implementing the compiler. */ String compilerClassName(Option option) { if ((null == option) || (!compilerFamily.sameFamily(option.getFamily()))) { return null; } return (String) compilerOptionToClassname.get(option); } /** * Check that the compiler class associated with a compiler * option can be loaded. This check only happens once; * the result is cached (by compilerOption key) for later calls. * @param compilerOption the Option (family compiler) to check * @return true if compiler class for this option can be loaded */ boolean compilerIsLoadable(Option compilerOption) { LangUtil.throwIaxIfNull(compilerOption, "compilerName"); synchronized (compilerOptionToLoadable) { Boolean result = (Boolean) compilerOptionToLoadable.get( compilerOption); if (null == result) { MessageHandler sink = new MessageHandler(); String compilerClassname = (String) compilerOptionToClassname.get( compilerOption); if (null == compilerClassname) { result = Boolean.FALSE; } else { ICommand c = ReflectionFactory.makeCommand( compilerClassname, sink); if ((null == c) || sink.hasAnyMessage( IMessage.ERROR, true)) { result = Boolean.FALSE; } else { result = Boolean.TRUE; } } compilerOptionToLoadable.put( compilerOption, result); } return result.booleanValue(); } } } // CompilerRun.Spec.CRSOptions } // CompilerRun.Spec } // CompilerRun
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
tests/java5/ataspectj/ataspectj/ltwlog/MainVerboseAndShow.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package ataspectj.ltwlog; import java.util.ArrayList; import java.util.Arrays; /** * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class MainVerboseAndShow { void target() {}; public static void main(String args[]) throws Throwable { new MainVerboseAndShow().target(); if (!MessageHolder.startsAs(Arrays.asList(new String[]{ "info weaving 'ataspectj/ltwlog/MainVerboseAndShow'", "weaveinfo Join point 'method-execution(void ataspectj.ltwlog.MainVerboseAndShow.target())' in Type 'ataspectj.ltwlog.MainVerboseAndShow' (MainVerboseAndShow.java:22) advised by before advice from 'ataspectj.ltwlog.Aspect1' (Aspect1.java)", "info weaving 'ataspectj/ltwlog/Aspect1'"}))) { MessageHolder.dump(); throw new RuntimeException("failed"); } } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
tests/src/org/aspectj/systemtest/ajc150/ataspectj/AtAjLTWTests.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150.ataspectj; import org.aspectj.testing.XMLBasedAjcTestCase; import junit.framework.Test; import java.io.File; /** * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class AtAjLTWTests extends XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(org.aspectj.systemtest.ajc150.ataspectj.AtAjLTWTests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ataspectj/ltw.xml"); } public void testRunThemAllWithJavacCompiledAndLTW() { runTest("RunThemAllWithJavacCompiledAndLTW"); } public void testAjcLTWPerClauseTest_XnoWeave() { runTest("AjcLTW PerClauseTest -XnoWeave"); } public void testAjcLTWPerClauseTest_Xreweavable() { runTest("AjcLTW PerClauseTest -Xreweavable"); } public void testJavaCAjcLTWPerClauseTest() { runTest("JavaCAjcLTW PerClauseTest"); } public void testAjcLTWAroundInlineMungerTest_XnoWeave() { runTest("AjcLTW AroundInlineMungerTest -XnoWeave"); } public void testAjcLTWAroundInlineMungerTest_Xreweavable() { runTest("AjcLTW AroundInlineMungerTest -Xreweavable"); } public void testAjcLTWAroundInlineMungerTest() { runTest("AjcLTW AroundInlineMungerTest"); } public void testAjcLTWAroundInlineMungerTest_XnoInline_Xreweavable() { runTest("AjcLTW AroundInlineMungerTest -XnoInline -Xreweavable"); } public void testAjcLTWAroundInlineMungerTest2() { runTest("AjcLTW AroundInlineMungerTest2"); } public void testLTWDump() { runTest("LTW DumpTest"); } public void testAjcAspect1LTWAspect2_Xreweavable() { runTest("Ajc Aspect1 LTW Aspect2 -Xreweavable"); } public void testLTWLog() { runTest("LTW Log"); } public void testLTWUnweavable() { // actually test that we do LTW proxy and jit classes runTest("LTW Unweavable"); } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
weaver/src/org/aspectj/weaver/WeaverStateInfo.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.bridge.IMessage; import org.aspectj.weaver.bcel.BcelTypeMunger; /** * WeaverStateInfo represents how a type was processed. It is used by the weaver to determine how a type * was previously treated and whether reweaving is allowed. * The format in the data stream is: * * Byte: Kind. UNTOUCHED|WOVEN|EXTENDED - If extended it can have two extra bits set 'REWEAVABLE' and 'REWEAVABLE_COMPRESSION_BIT' * Short: typeMungerCount - how many type mungers have affected this type * <UnresolvedType & ResolvedTypeMunger>: The type mungers themselves * If we are reweavable then we also have: * Short: Number of aspects that touched this type in some way when it was previously woven * <String> The fully qualified name of each type * Int: Length of class file data (i.e. the unwovenclassfile) * Byte[]: The class file data, compressed if REWEAVABLE_COMPRESSION_BIT set. */ public class WeaverStateInfo { private List/*Entry*/ typeMungers; private boolean oldStyle; private boolean reweavable; private boolean reweavableCompressedMode; // If true, unwovenClassFile is compressed on write and uncompressed on read private Set /*String*/ aspectsAffectingType; // These must exist in the world for reweaving to be valid private byte[] unwovenClassFile; // Original 'untouched' class file private static boolean reweavableDefault = false; private static boolean reweavableCompressedModeDefault = false; public WeaverStateInfo() { this(new ArrayList(), false,reweavableDefault,reweavableCompressedModeDefault); } private WeaverStateInfo(List typeMungers, boolean oldStyle,boolean reweavableMode,boolean reweavableCompressedMode) { this.typeMungers = typeMungers; this.oldStyle = oldStyle; this.reweavable = reweavableMode; this.reweavableCompressedMode = reweavableCompressedMode; this.aspectsAffectingType= new HashSet(); this.unwovenClassFile = null; } public static void setReweavableModeDefaults(boolean mode, boolean compress) { reweavableDefault = mode; reweavableCompressedModeDefault = compress; } private static final int UNTOUCHED=0, WOVEN=2, EXTENDED=3; // Use 'bits' for these capabilities - only valid in EXTENDED mode private static final byte REWEAVABLE_BIT = 1<<4; private static final byte REWEAVABLE_COMPRESSION_BIT = 1<<5; public static final WeaverStateInfo read(VersionedDataInputStream s, ISourceContext context) throws IOException { byte b = s.readByte(); boolean isReweavable = ((b&REWEAVABLE_BIT)!=0); if (isReweavable) b=(byte) (b-REWEAVABLE_BIT); boolean isReweavableCompressed = ((b&REWEAVABLE_COMPRESSION_BIT)!=0); if (isReweavableCompressed) b=(byte) (b-REWEAVABLE_COMPRESSION_BIT); switch(b) { case UNTOUCHED: throw new RuntimeException("unexpected UNWOVEN"); case WOVEN: return new WeaverStateInfo(Collections.EMPTY_LIST, true,isReweavable,isReweavableCompressed); case EXTENDED: int n = s.readShort(); List l = new ArrayList(); for (int i=0; i < n; i++) { UnresolvedType aspectType = UnresolvedType.read(s); ResolvedTypeMunger typeMunger = ResolvedTypeMunger.read(s, context); l.add(new Entry(aspectType, typeMunger)); } WeaverStateInfo wsi = new WeaverStateInfo(l,false,isReweavable,isReweavableCompressed); readAnyReweavableData(wsi,s); return wsi; } throw new RuntimeException("bad WeaverState.Kind: " + b); } private static class Entry { public UnresolvedType aspectType; public ResolvedTypeMunger typeMunger; public Entry(UnresolvedType aspectType, ResolvedTypeMunger typeMunger) { this.aspectType = aspectType; this.typeMunger = typeMunger; } public String toString() { return "<" + aspectType + ", " + typeMunger + ">"; } } public void write(DataOutputStream s) throws IOException { if (oldStyle) throw new RuntimeException("shouldn't be writing this"); byte weaverStateInfoKind = EXTENDED; if (reweavable) weaverStateInfoKind |= REWEAVABLE_BIT; if (reweavableCompressedMode) weaverStateInfoKind |= REWEAVABLE_COMPRESSION_BIT; s.writeByte(weaverStateInfoKind); int n = typeMungers.size(); s.writeShort(n); for (int i=0; i < n; i++) { Entry e = (Entry)typeMungers.get(i); e.aspectType.write(s); e.typeMunger.write(s); } writeAnyReweavableData(this,s); } public void addConcreteMunger(ConcreteTypeMunger munger) { typeMungers.add(new Entry(munger.getAspectType(), munger.getMunger())); } public String toString() { return "WeaverStateInfo(" + typeMungers + ", " + oldStyle + ")"; } public List getTypeMungers(ResolvedType onType) { World world = onType.getWorld(); List ret = new ArrayList(); for (Iterator i = typeMungers.iterator(); i.hasNext();) { Entry entry = (Entry) i.next(); ResolvedType aspectType = world.resolve(entry.aspectType, true); if (aspectType == ResolvedType.MISSING) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ASPECT_NEEDED,entry.aspectType,onType), onType.getSourceLocation(), null); continue; } ret.add(new BcelTypeMunger(entry.typeMunger, aspectType)); } return ret; } public boolean isOldStyle() { return oldStyle; } public byte[] getUnwovenClassFileData() { return unwovenClassFile; } public void setUnwovenClassFileData(byte[] data) { unwovenClassFile = data; } public boolean isReweavable() { return reweavable; } public void setReweavable(boolean rw,boolean compressData) { reweavable = rw; reweavableCompressedMode = compressData; } public void addAspectsAffectingType(Collection /*String*/ aspects) { aspectsAffectingType.addAll(aspects); } public void addAspectAffectingType(String aspectType) { aspectsAffectingType.add(aspectType); } public Set /*String*/ getAspectsAffectingType() { return this.aspectsAffectingType; } //// private static void readAnyReweavableData(WeaverStateInfo wsi,DataInputStream s) throws IOException { if (wsi.isReweavable()) { // Load list of aspects that need to exist in the world for reweaving to be 'legal' int numberAspectsAffectingType = s.readShort(); for (int i=0; i < numberAspectsAffectingType; i++) {wsi.addAspectAffectingType(s.readUTF());} int unwovenClassFileSize = s.readInt(); byte[] classData = null; // The data might or might not be compressed: if (!wsi.reweavableCompressedMode) { // Read it straight in classData = new byte[unwovenClassFileSize]; int bytesread = s.read(classData); if (bytesread!=unwovenClassFileSize) throw new IOException("ERROR whilst reading reweavable data, expected "+ unwovenClassFileSize+" bytes, only found "+bytesread); } else { // Decompress it classData = new byte[unwovenClassFileSize]; ZipInputStream zis = new ZipInputStream(s); ZipEntry zen = zis.getNextEntry(); int current = 0; int bytesToGo=unwovenClassFileSize; while (bytesToGo>0) { int amount = zis.read(classData,current,bytesToGo); current+=amount; bytesToGo-=amount; } zis.closeEntry(); if (bytesToGo!=0) throw new IOException("ERROR whilst reading compressed reweavable data, expected "+ unwovenClassFileSize+" bytes, only found "+current); } wsi.setUnwovenClassFileData(classData); } } private static void writeAnyReweavableData(WeaverStateInfo wsi,DataOutputStream s) throws IOException { if (wsi.isReweavable()) { // Write out list of aspects that must exist next time we try and weave this class s.writeShort(wsi.aspectsAffectingType.size()); if (wsi.aspectsAffectingType.size()>0) { for (Iterator iter = wsi.aspectsAffectingType.iterator(); iter.hasNext();) { String type = (String) iter.next(); s.writeUTF(type); } } byte[] data = wsi.unwovenClassFile; s.writeInt(data.length); // Do we need to compress the data? if (!wsi.reweavableCompressedMode) { s.write(wsi.unwovenClassFile); } else { ZipOutputStream zos = new ZipOutputStream(s); ZipEntry ze = new ZipEntry("data"); zos.putNextEntry(ze); zos.write(wsi.unwovenClassFile,0,wsi.unwovenClassFile.length); zos.closeEntry(); } } } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.IndexedInstruction; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.NEW; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUTFIELD; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.RET; import org.aspectj.apache.bcel.generic.ReturnInstruction; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.PartialOrder; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IClassWeaver; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.DeclareAnnotation; class BcelClassWeaver implements IClassWeaver { /** * This is called from {@link BcelWeaver} to perform the per-class weaving process. */ public static boolean weave( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers).weave(); //System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState()); //clazz.print(); return b; } // -------------------------------------------- private final LazyClassGen clazz; private final List shadowMungers; private final List typeMungers; private final List lateTypeMungers; private final BcelObjectType ty; // alias of clazz.getType() private final BcelWorld world; // alias of ty.getWorld() private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen() private final InstructionFactory fact; // alias of clazz.getFactory(); private final List addedLazyMethodGens = new ArrayList(); private final Set addedDispatchTargets = new HashSet(); // Static setting across BcelClassWeavers private static boolean inReweavableMode = false; private static boolean compressReweavableAttributes = false; private List addedSuperInitializersAsList = null; // List<IfaceInitList> private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger> private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger> private Map mapToAnnotations = new HashMap(); private BcelShadow clinitShadow = null; /** * This holds the initialization and pre-initialization shadows for this class * that were actually matched by mungers (if no match, then we don't even create the * shadows really). */ private final List initializationShadows = new ArrayList(1); private BcelClassWeaver( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { super(); // assert world == clazz.getType().getWorld() this.world = world; this.clazz = clazz; this.shadowMungers = shadowMungers; this.typeMungers = typeMungers; this.lateTypeMungers = lateTypeMungers; this.ty = clazz.getBcelObjectType(); this.cpg = clazz.getConstantPoolGen(); this.fact = clazz.getFactory(); fastMatchShadowMungers(shadowMungers); initializeSuperInitializerMap(ty.getResolvedTypeX()); } private List[] perKindShadowMungers; private boolean canMatchBodyShadows = false; private boolean canMatchInitialization = false; private void fastMatchShadowMungers(List shadowMungers) { // beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) ! perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1]; for (int i = 0; i < perKindShadowMungers.length; i++) { perKindShadowMungers[i] = new ArrayList(0); } for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Set couldMatchKinds = munger.getPointcut().couldMatchKinds(); for (Iterator kindIterator = couldMatchKinds.iterator(); kindIterator.hasNext();) { Shadow.Kind aKind = (Shadow.Kind) kindIterator.next(); perKindShadowMungers[aKind.getKey()].add(munger); } } if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty()) canMatchInitialization = true; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (!kind.isEnclosingKind() && !perKindShadowMungers[i+1].isEmpty()) { canMatchBodyShadows = true; } if (perKindShadowMungers[i+1].isEmpty()) { perKindShadowMungers[i+1] = null; } } } private boolean canMatch(Shadow.Kind kind) { return perKindShadowMungers[kind.getKey()] != null; } // private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) { // FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind); // for (Iterator i = shadowMungers.iterator(); i.hasNext();) { // ShadowMunger munger = (ShadowMunger) i.next(); // FuzzyBoolean fb = munger.getPointcut().fastMatch(info); // WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString() // if (fb.maybeTrue()) mungers.add(munger); // } // } private void initializeSuperInitializerMap(ResolvedType child) { ResolvedType[] superInterfaces = child.getDeclaredInterfaces(); for (int i=0, len=superInterfaces.length; i < len; i++) { if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) { if (addSuperInitializer(superInterfaces[i])) { initializeSuperInitializerMap(superInterfaces[i]); } } } } private boolean addSuperInitializer(ResolvedType onType) { if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); if (l != null) return false; l = new IfaceInitList(onType); addedSuperInitializers.put(onType, l); return true; } public void addInitializer(ConcreteTypeMunger cm) { NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger(); ResolvedType onType = m.getSignature().getDeclaringType().resolve(world); if (onType.isRawType()) onType = onType.getGenericType(); if (m.getSignature().isStatic()) { addedClassInitializers.add(cm); } else { if (onType == ty.getResolvedTypeX()) { addedThisInitializers.add(cm); } else { IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); l.list.add(cm); } } } private static class IfaceInitList implements PartialOrder.PartialComparable { final ResolvedType onType; List list = new ArrayList(); IfaceInitList(ResolvedType onType) { this.onType = onType; } public int compareTo(Object other) { IfaceInitList o = (IfaceInitList)other; if (onType.isAssignableFrom(o.onType)) return +1; else if (o.onType.isAssignableFrom(onType)) return -1; else return 0; } public int fallbackCompareTo(Object other) { return 0; } } // XXX this is being called, but the result doesn't seem to be being used public boolean addDispatchTarget(ResolvedMember m) { return addedDispatchTargets.add(m); } public void addLazyMethodGen(LazyMethodGen gen) { addedLazyMethodGens.add(gen); } public void addOrReplaceLazyMethodGen(LazyMethodGen mg) { if (alreadyDefined(clazz, mg)) return; for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (existing.definingType == null) { // this means existing was introduced on the class itself return; } else if (mg.definingType.isAssignableFrom(existing.definingType)) { // existing is mg's subtype and dominates mg return; } else if (existing.definingType.isAssignableFrom(mg.definingType)) { // mg is existing's subtype and dominates existing i.remove(); addedLazyMethodGens.add(mg); return; } else { throw new BCException("conflict between: " + mg + " and " + existing); } } } addedLazyMethodGens.add(mg); } private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) { for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (!mg.isAbstract() && existing.isAbstract()) { i.remove(); return false; } return true; } } return false; } private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) { return mg.getName().equals(existing.getName()) && mg.getSignature().equals(existing.getSignature()); } // ---- public boolean weave() { if (clazz.isWoven() && !clazz.isReweavable()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()), ty.getSourceLocation(), null); return false; } Set aspectsAffectingType = null; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType = new HashSet(); boolean isChanged = false; // we want to "touch" all aspects if (clazz.getType().isAspect()) isChanged = true; // start by munging all typeMungers for (Iterator i = typeMungers.iterator(); i.hasNext(); ) { Object o = i.next(); if ( !(o instanceof BcelTypeMunger) ) { //???System.err.println("surprising: " + o); continue; } BcelTypeMunger munger = (BcelTypeMunger)o; boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } // Weave special half type/half shadow mungers... isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged; isChanged = weaveDeclareAtField(clazz) || isChanged; // XXX do major sort of stuff // sort according to: Major: type hierarchy // within each list: dominates // don't forget to sort addedThisInitialiers according to dominates addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values()); addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList); if (addedSuperInitializersAsList == null) { throw new BCException("circularity in inter-types"); } // this will create a static initializer if there isn't one // this is in just as bad taste as NOPs LazyMethodGen staticInit = clazz.getStaticInitializer(); staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true)); // now go through each method, and match against each method. This // sets up each method's {@link LazyMethodGen#matchedShadows} field, // and it also possibly adds to {@link #initializationShadows}. List methodGens = new ArrayList(clazz.getMethodGens()); for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; boolean shadowMungerMatched = match(mg); if (shadowMungerMatched) { // For matching mungers, add their declaring aspects to the list that affected this type if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.addAll(findAspectsForMungers(mg)); isChanged = true; } } // now we weave all but the initialization shadows for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; implement(mg); } // if we matched any initialization shadows, we inline and weave if (! initializationShadows.isEmpty()) { // Repeat next step until nothing left to inline...cant go on // infinetly as compiler will have detected and reported // "Recursive constructor invocation" while (inlineSelfConstructors(methodGens)); positionAndImplement(initializationShadows); } // now proceed with late type mungers if (lateTypeMungers != null) { for (Iterator i = lateTypeMungers.iterator(); i.hasNext(); ) { BcelTypeMunger munger = (BcelTypeMunger)i.next(); if (munger.matches(clazz.getType())) { boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } } } //FIXME AV - see #75442, for now this is not enough to fix the bug, comment that out until we really fix it // // flush to save some memory // PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType()); // finally, if we changed, we add in the introduced methods. if (isChanged) { clazz.getOrCreateWeaverStateInfo(); weaveInAddedMethods(); // FIXME asc are these potentially affected by declare annotation? } if (inReweavableMode || clazz.getType().isAspect()) { WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(); wsi.addAspectsAffectingType(aspectsAffectingType); wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes()); wsi.setReweavable(true,compressReweavableAttributes); } else { clazz.getOrCreateWeaverStateInfo().setReweavable(false,false); } return isChanged; } /** * Weave any declare @method/@ctor statements into the members of the supplied class */ private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) { List reportedProblems = new ArrayList(); List allDecams = world.getDeclareAnnotationOnMethods(); if (allDecams.isEmpty()) return false; // nothing to do boolean isChanged = false; // deal with ITDs List itdMethodsCtors = getITDSubset(clazz,ResolvedTypeMunger.Method); itdMethodsCtors.addAll(getITDSubset(clazz,ResolvedTypeMunger.Constructor)); if (!itdMethodsCtors.isEmpty()) { // Can't use the subset called 'decaMs' as it won't be right for ITDs... isChanged = weaveAtMethodOnITDSRepeatedly(allDecams,itdMethodsCtors,reportedProblems); } // deal with all the other methods... List members = clazz.getMethodGens(); List decaMs = getMatchingSubset(allDecams,clazz.getType()); if (decaMs.isEmpty()) return false; // nothing to do if (!members.isEmpty()) { for (int memberCounter = 0;memberCounter<members.size();memberCounter++) { LazyMethodGen mg = (LazyMethodGen)members.get(memberCounter); if (!mg.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter = decaMs.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) continue; // skip this one... Annotation a = decaM.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); Method oldMethod = mg.getMethod(); MethodGen myGen = new MethodGen(oldMethod,clazz.getClassName(),clazz.getConstantPoolGen()); myGen.addAnnotation(ag); Method newMethod = myGen.getMethod(); mg.addAnnotation(decaM.getAnnotationX()); members.set(memberCounter,new LazyMethodGen(newMethod,clazz)); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); reportMethodCtorWeavingMessage(clazz, mg, decaM); isChanged = true; modificationOccured = true; } else { if (!decaM.isStarredAnnotationPattern()) worthRetrying.add(decaM); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) continue; // skip this one... mg.addAnnotation(decaM.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); isChanged = true; modificationOccured = true; forRemoval.add(decaM); } } worthRetrying.removeAll(forRemoval); } } } } return isChanged; } // TAG: WeavingMessage private void reportMethodCtorWeavingMessage(LazyClassGen clazz, LazyMethodGen mg, DeclareAnnotation decaM) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ StringBuffer parmString = new StringBuffer("("); Type[] args = mg.getMethod().getArgumentTypes(); for (int i = 0; i < args.length; i++) { Type type2 = args[i]; String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type2.getSignature()); if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1); parmString.append(s); if ((i+1)<args.length) parmString.append(","); } parmString.append(")"); String methodName = mg.getMethod().getName(); StringBuffer sig = new StringBuffer(); sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(mg.getMethod().getAccessFlags()) ); sig.append(" "); sig.append(mg.getMethod().getReturnType().toString()); sig.append(" "); sig.append(clazz.getName()); sig.append("."); sig.append(methodName.equals("<init>")?"new":methodName); sig.append(parmString); StringBuffer loc = new StringBuffer(); if (clazz.getFileName()==null) { loc.append("no debug info available"); } else { loc.append(clazz.getFileName()); if (mg.getDeclarationLineNumber()!=-1) { loc.append(":"+mg.getDeclarationLineNumber()); } } getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ sig.toString(), loc.toString(), decaM.getAnnotationString(), methodName.startsWith("<init>")?"constructor":"method", decaM.getAspect().toString(), Utility.beautifyLocation(decaM.getSourceLocation()) })); } } /** * Looks through a list of declare annotation statements and only returns * those that could possibly match on a field/method/ctor in type. */ private List getMatchingSubset(List declareAnnotations, ResolvedType type) { List subset = new ArrayList(); for (Iterator iter = declareAnnotations.iterator(); iter.hasNext();) { DeclareAnnotation da = (DeclareAnnotation) iter.next(); if (da.couldEverMatch(type)) { subset.add(da); } } return subset; } /** * Get a subset of all the type mungers defined on this aspect */ private List getITDSubset(LazyClassGen clazz,ResolvedTypeMunger.Kind wantedKind) { List subset = new ArrayList(); Collection c = clazz.getBcelObjectType().getTypeMungers(); for (Iterator iter = c.iterator();iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger)iter.next(); if (typeMunger.getMunger().getKind()==wantedKind) subset.add(typeMunger); } return subset; } public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz,BcelTypeMunger fieldMunger) { NewFieldTypeMunger nftm = (NewFieldTypeMunger)fieldMunger.getMunger(); ResolvedMember lookingFor =AjcMemberMaker.interFieldInitializer(nftm.getSignature(),clazz.getType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName())) return element; } return null; } // FIXME asc refactor this to neaten it up public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz,BcelTypeMunger methodCtorMunger) { if (methodCtorMunger.getMunger() instanceof NewMethodTypeMunger) { NewMethodTypeMunger nftm = (NewMethodTypeMunger)methodCtorMunger.getMunger(); ResolvedMember lookingFor = AjcMemberMaker.interMethodDispatcher(nftm.getSignature(),methodCtorMunger.getAspectType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element; } return null; } else if (methodCtorMunger.getMunger() instanceof NewConstructorTypeMunger) { NewConstructorTypeMunger nftm = (NewConstructorTypeMunger)methodCtorMunger.getMunger(); ResolvedMember lookingFor =AjcMemberMaker.postIntroducedConstructor(methodCtorMunger.getAspectType(),nftm.getSignature().getDeclaringType(),nftm.getSignature().getParameterTypes()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element; } return null; } else { throw new RuntimeException("Not sure what this is: "+methodCtorMunger); } } /** * Applies some set of declare @field constructs (List<DeclareAnnotation>) to some bunch * of ITDfields (List<BcelTypeMunger>. It will iterate over the fields repeatedly until * everything has been applied. * */ private boolean weaveAtFieldRepeatedly(List decaFs, List itdFields,List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdFields.iterator(); iter.hasNext();) { BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next(); ResolvedMember itdIsActually = fieldMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaFs.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaF); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } /** * Applies some set of declare @method/@ctor constructs (List<DeclareAnnotation>) to some bunch * of ITDmembers (List<BcelTypeMunger>. It will iterate over the fields repeatedly until * everything has been applied. */ private boolean weaveAtMethodOnITDSRepeatedly(List decaMCs, List itdMethodsCtors,List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdMethodsCtors.iterator(); iter.hasNext();) { BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next(); ResolvedMember unMangledInterMethod = methodctorMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaMCs.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz,methodctorMunger); if (annotationHolder == null || doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)){ continue; // skip this one... } annotationHolder.addAnnotation(decaMC.getAnnotationX()); isChanged=true; AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation()); modificationOccured = true; } else { if (!decaMC.isStarredAnnotationPattern()) worthRetrying.add(decaMC); // an annotation is specified that might be put on by a subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,methodctorMunger); if (doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaMC.getAnnotationX()); unMangledInterMethod.addAnnotation(decaMC.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaMC); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } private boolean dontAddTwice(DeclareAnnotation decaF, Annotation [] dontAddMeTwice){ for (int i = 0; i < dontAddMeTwice.length; i++){ Annotation ann = dontAddMeTwice[i]; if (ann != null && decaF.getAnnotationX().getTypeName().equals(ann.getTypeName())){ dontAddMeTwice[i] = null; // incase it really has been added twice! return true; } } return false; } /** * Weave any declare @field statements into the fields of the supplied class * * Interesting case relating to public ITDd fields. The annotations are really stored against * the interfieldinit method in the aspect, but the public field is placed in the target * type and then is processed in the 2nd pass over fields that occurs. I think it would be * more expensive to avoid putting the annotation on that inserted public field than just to * have it put there as well as on the interfieldinit method. */ private boolean weaveDeclareAtField(LazyClassGen clazz) { // BUGWARNING not getting enough warnings out on declare @field ? // There is a potential problem here with warnings not coming out - this // will occur if they are created on the second iteration round this loop. // We currently deactivate error reporting for the second time round. // A possible solution is to record what annotations were added by what // decafs and check that to see if an error needs to be reported - this // would be expensive so lets skip it for now List reportedProblems = new ArrayList(); List allDecafs = world.getDeclareAnnotationOnFields(); if (allDecafs.isEmpty()) return false; // nothing to do boolean isChanged = false; List itdFields = getITDSubset(clazz,ResolvedTypeMunger.Field); if (itdFields!=null) { isChanged = weaveAtFieldRepeatedly(allDecafs,itdFields,reportedProblems); } List decaFs = getMatchingSubset(allDecafs,clazz.getType()); if (decaFs.isEmpty()) return false; // nothing more to do Field[] fields = clazz.getFieldGens(); if (fields!=null) { for (int fieldCounter = 0;fieldCounter<fields.length;fieldCounter++) { BcelField aBcelField = new BcelField(clazz.getBcelObjectType(),fields[fieldCounter]); if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; Annotation [] dontAddMeTwice = fields[fieldCounter].getAnnotations(); // go through all the declare @field statements for (Iterator iter = decaFs.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { if (!dontAddTwice(decaF,dontAddMeTwice)){ if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)){ continue; } if(decaF.getAnnotationX().isRuntimeVisible()){ // isAnnotationWithRuntimeRetention(clazz.getJavaClass(world))){ //if(decaF.getAnnotationTypeX().isAnnotationWithRuntimeRetention(world)){ // it should be runtime visible, so put it on the Field Annotation a = decaF.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); FieldGen myGen = new FieldGen(fields[fieldCounter],clazz.getConstantPoolGen()); myGen.addAnnotation(ag); Field newField = myGen.getField(); aBcelField.addAnnotation(decaF.getAnnotationX()); clazz.replaceField(fields[fieldCounter],newField); fields[fieldCounter]=newField; } else{ aBcelField.addAnnotation(decaF.getAnnotationX()); } } AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); reportFieldAnnotationWeavingMessage(clazz, fields, fieldCounter, decaF); isChanged = true; modificationOccured = true; } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { // below code is for recursive things if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) continue; // skip this one... aBcelField.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); isChanged = true; modificationOccured = true; forRemoval.add(decaF); } } worthRetrying.removeAll(forRemoval); } } } } return isChanged; } // TAG: WeavingMessage private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, Field[] fields, int fieldCounter, DeclareAnnotation decaF) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ Field theField = fields[fieldCounter]; world.getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ theField.toString() + "' of type '" + clazz.getName(), clazz.getFileName(), decaF.getAnnotationString(), "field", decaF.getAspect().toString(), Utility.beautifyLocation(decaF.getSourceLocation())})); } } /** * Check if a resolved member (field/method/ctor) already has an annotation, if it * does then put out a warning and return true */ private boolean doesAlreadyHaveAnnotation(ResolvedMember rm,DeclareAnnotation deca,List reportedProblems) { if (rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); world.getLint().elementAlreadyAnnotated.signal( new String[]{rm.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } } return true; } return false; } private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm,ResolvedMember itdfieldsig,DeclareAnnotation deca,List reportedProblems) { if (rm != null && rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); reportedProblems.add(new Integer(itdfieldsig.hashCode()*deca.hashCode())); world.getLint().elementAlreadyAnnotated.signal( new String[]{rm.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } } return true; } return false; } private Set findAspectsForMungers(LazyMethodGen mg) { Set aspectsAffectingType = new HashSet(); for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) { BcelShadow aShadow = (BcelShadow) iter.next(); // Mungers in effect on that shadow for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) { ShadowMunger aMunger = (ShadowMunger) iter2.next(); if (aMunger instanceof BcelAdvice) { BcelAdvice bAdvice = (BcelAdvice)aMunger; aspectsAffectingType.add(bAdvice.getConcreteAspect().getName()); } else { // It is a 'Checker' - we don't need to remember aspects that only contributed Checkers... } } } return aspectsAffectingType; } private boolean inlineSelfConstructors(List methodGens) { boolean inlinedSomething = false; for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); if (! mg.getName().equals("<init>")) continue; InstructionHandle ih = findSuperOrThisCall(mg); if (ih != null && isThisCall(ih)) { LazyMethodGen donor = getCalledMethod(ih); inlineMethod(donor, mg, ih); inlinedSomething = true; } } return inlinedSomething; } private void positionAndImplement(List initializationShadows) { for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) { BcelShadow s = (BcelShadow) i.next(); positionInitializationShadow(s); //s.getEnclosingMethod().print(); s.implement(); } } private void positionInitializationShadow(BcelShadow s) { LazyMethodGen mg = s.getEnclosingMethod(); InstructionHandle call = findSuperOrThisCall(mg); InstructionList body = mg.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow((BcelShadow) s); if (s.getKind() == Shadow.PreInitialization) { // XXX assert first instruction is an ALOAD_0. // a pre shadow goes from AFTER the first instruction (which we believe to // be an ALOAD_0) to just before the call to super r.associateWithTargets( Range.genStart(body, body.getStart().getNext()), Range.genEnd(body, call.getPrev())); } else { // assert s.getKind() == Shadow.Initialization r.associateWithTargets( Range.genStart(body, call.getNext()), Range.genEnd(body)); } } private boolean isThisCall(InstructionHandle ih) { INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction(); return inst.getClassName(cpg).equals(clazz.getName()); } /** inline a particular call in bytecode. * * @param donor the method we want to inline * @param recipient the method containing the call we want to inline * @param call the instructionHandle in recipient's body holding the call we want to * inline. */ public static void inlineMethod( LazyMethodGen donor, LazyMethodGen recipient, InstructionHandle call) { // assert recipient.contains(call) /* Implementation notes: * * We allocate two slots for every tempvar so we don't screw up * longs and doubles which may share space. This could be conservatively avoided * (no reference to a long/double instruction, don't do it) or packed later. * Right now we don't bother to pack. * * Allocate a new var for each formal param of the inlined. Fill with stack * contents. Then copy the inlined instructions in with the appropriate remap * table. Any framelocs used by locals in inlined are reallocated to top of * frame, */ final InstructionFactory fact = recipient.getEnclosingClass().getFactory(); IntMap frameEnv = new IntMap(); // this also sets up the initial environment InstructionList argumentStores = genArgumentStores(donor, recipient, frameEnv, fact); InstructionList inlineInstructions = genInlineInstructions(donor, recipient, frameEnv, fact, false); inlineInstructions.insert(argumentStores); recipient.getBody().append(call, inlineInstructions); Utility.deleteInstruction(call, recipient); } /** generate the instructions to be inlined. * * @param donor the method from which we will copy (and adjust frame and jumps) * instructions. * @param recipient the method the instructions will go into. Used to get the frame * size so we can allocate new frame locations for locals in donor. * @param frameEnv an environment to map from donor frame to recipient frame, * initially populated with argument locations. * @param fact an instruction factory for recipient */ static InstructionList genInlineInstructions( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact, boolean keepReturns) { InstructionList footer = new InstructionList(); InstructionHandle end = footer.append(InstructionConstants.NOP); InstructionList ret = new InstructionList(); InstructionList sourceList = donor.getBody(); Map srcToDest = new HashMap(); ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen(); ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen(); boolean isAcrossClass = donorCpg != recipientCpg; // first pass: copy the instructions directly, populate the srcToDest map, // fix frame instructions for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) { Instruction fresh = Utility.copyInstruction(src.getInstruction()); InstructionHandle dest; if (fresh instanceof CPInstruction) { // need to reset index to go to new constant pool. This is totally // a computation leak... we're testing this LOTS of times. Sigh. if (isAcrossClass) { CPInstruction cpi = (CPInstruction) fresh; cpi.setIndex( recipientCpg.addConstant( donorCpg.getConstant(cpi.getIndex()), donorCpg)); } } if (src.getInstruction() == Range.RANGEINSTRUCTION) { dest = ret.append(Range.RANGEINSTRUCTION); } else if (fresh instanceof ReturnInstruction) { if (keepReturns) { dest = ret.append(fresh); } else { dest = ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end)); } } else if (fresh instanceof BranchInstruction) { dest = ret.append((BranchInstruction) fresh); } else if ( fresh instanceof LocalVariableInstruction || fresh instanceof RET) { IndexedInstruction indexed = (IndexedInstruction) fresh; int oldIndex = indexed.getIndex(); int freshIndex; if (!frameEnv.hasKey(oldIndex)) { freshIndex = recipient.allocateLocal(2); frameEnv.put(oldIndex, freshIndex); } else { freshIndex = frameEnv.get(oldIndex); } indexed.setIndex(freshIndex); dest = ret.append(fresh); } else { dest = ret.append(fresh); } srcToDest.put(src, dest); } // second pass: retarget branch instructions, copy ranges and tags Map tagMap = new HashMap(); Map shadowMap = new HashMap(); for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src.getNext()) { Instruction inst = dest.getInstruction(); // retarget branches if (inst instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction) inst; InstructionHandle oldTarget = branch.getTarget(); InstructionHandle newTarget = (InstructionHandle) srcToDest.get(oldTarget); if (newTarget == null) { // assert this is a GOTO // this was a return instruction we previously replaced } else { branch.setTarget(newTarget); if (branch instanceof Select) { Select select = (Select) branch; InstructionHandle[] oldTargets = select.getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { select.setTarget( k, (InstructionHandle) srcToDest.get(oldTargets[k])); } } } } //copy over tags and range attributes InstructionTargeter[] srcTargeters = src.getTargeters(); if (srcTargeters != null) { for (int j = srcTargeters.length - 1; j >= 0; j--) { InstructionTargeter old = srcTargeters[j]; if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = (Tag) tagMap.get(oldTag); if (fresh == null) { fresh = oldTag.copy(); tagMap.put(oldTag, fresh); } dest.addTargeter(fresh); } else if (old instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) old; if (er.getStart() == src) { ExceptionRange freshEr = new ExceptionRange( recipient.getBody(), er.getCatchType(), er.getPriority()); freshEr.associateWithTargets( dest, (InstructionHandle)srcToDest.get(er.getEnd()), (InstructionHandle)srcToDest.get(er.getHandler())); } } else if (old instanceof ShadowRange) { ShadowRange oldRange = (ShadowRange) old; if (oldRange.getStart() == src) { BcelShadow oldShadow = oldRange.getShadow(); BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow()); BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing); ShadowRange freshRange = new ShadowRange(recipient.getBody()); freshRange.associateWithShadow(freshShadow); freshRange.associateWithTargets( dest, (InstructionHandle) srcToDest.get(oldRange.getEnd())); shadowMap.put(oldRange, freshRange); //recipient.matchedShadows.add(freshShadow); // XXX should go through the NEW copied shadow and update // the thisVar, targetVar, and argsVar // ??? Might want to also go through at this time and add // "extra" vars to the shadow. } } } } } if (!keepReturns) ret.append(footer); return ret; } /** generate the argument stores in preparation for inlining. * * @param donor the method we will inline from. Used to get the signature. * @param recipient the method we will inline into. Used to get the frame size * so we can allocate fresh locations. * @param frameEnv an empty environment we populate with a map from donor frame to * recipient frame. * @param fact an instruction factory for recipient */ private static InstructionList genArgumentStores( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact) { InstructionList ret = new InstructionList(); int donorFramePos = 0; // writing ret back to front because we're popping. if (! donor.isStatic()) { int targetSlot = recipient.allocateLocal(Type.OBJECT); ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot)); frameEnv.put(donorFramePos, targetSlot); donorFramePos += 1; } Type[] argTypes = donor.getArgumentTypes(); for (int i = 0, len = argTypes.length; i < len; i++) { Type argType = argTypes[i]; int argSlot = recipient.allocateLocal(argType); ret.insert(InstructionFactory.createStore(argType, argSlot)); frameEnv.put(donorFramePos, argSlot); donorFramePos += argType.getSize(); } return ret; } /** get a called method: Assumes the called method is in this class, * and the reference to it is exact (a la INVOKESPECIAL). * * @param ih The InvokeInstruction instructionHandle pointing to the called method. */ private LazyMethodGen getCalledMethod( InstructionHandle ih) { InvokeInstruction inst = (InvokeInstruction) ih.getInstruction(); String methodName = inst.getName(cpg); String signature = inst.getSignature(cpg); return clazz.getLazyMethodGen(methodName, signature); } private void weaveInAddedMethods() { Collections.sort(addedLazyMethodGens, new Comparator() { public int compare(Object a, Object b) { LazyMethodGen aa = (LazyMethodGen) a; LazyMethodGen bb = (LazyMethodGen) b; int i = aa.getName().compareTo(bb.getName()); if (i != 0) return i; return aa.getSignature().compareTo(bb.getSignature()); } } ); for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { clazz.addMethodGen((LazyMethodGen)i.next()); } } void addPerSingletonField(Member field) { ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType()); String aspectName = field.getReturnType().getName(); LazyMethodGen clinit = clazz.getStaticInitializer(); InstructionList setup = new InstructionList(); InstructionFactory fact = clazz.getFactory(); setup.append(fact.createNew(aspectType)); setup.append(InstructionFactory.createDup(1)); setup.append(fact.createInvoke( aspectName, "<init>", Type.VOID, new Type[0], Constants.INVOKESPECIAL)); setup.append( fact.createFieldAccess( aspectName, field.getName(), aspectType, Constants.PUTSTATIC)); clinit.getBody().insert(setup); } /** * Returns null if this is not a Java constructor, and then we won't * weave into it at all */ private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) { int depth = 1; InstructionHandle start = mg.getBody().getStart(); while (true) { if (start == null) return null; Instruction inst = start.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth--; if (depth == 0) return start; } else if (inst instanceof NEW) { depth++; } start = start.getNext(); } } // ---- private boolean match(LazyMethodGen mg) { BcelShadow enclosingShadow; List shadowAccumulator = new ArrayList(); // we want to match ajsynthetic constructors... if (mg.getName().equals("<init>")) { return matchInit(mg, shadowAccumulator); } else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) { return false; } else { if (mg.getName().equals("<clinit>")) { clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg); //System.err.println(enclosingShadow); } else if (mg.isAdviceMethod()) { enclosingShadow = BcelShadow.makeAdviceExecution(world, mg); } else { AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature(); if (effective == null) { enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows); } else if (effective.isWeaveBody()) { ResolvedMember rm = effective.getEffectiveSignature(); // Annotations for things with effective signatures are never stored in the effective // signature itself - we have to hunt for them. Storing them in the effective signature // would mean keeping two sets up to date (no way!!) fixAnnotationsForResolvedMember(rm,mg.getMemberView()); enclosingShadow = BcelShadow.makeShadowForMethod(world,mg,effective.getShadowKind(),rm); } else { return false; } } if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { match(mg, h, enclosingShadow, shadowAccumulator); } } // FIXME asc change from string match if we can, rather brittle. this check actually prevents field-exec jps if (canMatch(enclosingShadow.getKind()) && !mg.getName().startsWith("ajc$interFieldInit")) { if (match(enclosingShadow, shadowAccumulator)) { enclosingShadow.init(); } } mg.matchedShadows = shadowAccumulator; return !shadowAccumulator.isEmpty(); } } private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) { BcelShadow enclosingShadow; // XXX the enclosing join point is wrong for things before ignoreMe. InstructionHandle superOrThisCall = findSuperOrThisCall(mg); // we don't walk bodies of things where it's a wrong constructor thingie if (superOrThisCall == null) return false; enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall); if (mg.getEffectiveSignature() != null) { enclosingShadow.setMatchingSignature(mg.getEffectiveSignature().getEffectiveSignature()); } // walk the body boolean beforeSuperOrThisCall = true; if (shouldWeaveBody(mg)) { if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { if (h == superOrThisCall) { beforeSuperOrThisCall = false; continue; } match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator); } } if (canMatch(Shadow.ConstructorExecution)) match(enclosingShadow, shadowAccumulator); } // XXX we don't do pre-inits of interfaces // now add interface inits if (superOrThisCall != null && ! isThisCall(superOrThisCall)) { InstructionHandle curr = enclosingShadow.getRange().getStart(); for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) { IfaceInitList l = (IfaceInitList) i.next(); Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType); BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig); // insert code in place InstructionList inits = genInitInstructions(l.list, false); if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) { initShadow.initIfaceInitializer(curr); initShadow.getRange().insert(inits, Range.OutsideBefore); } } // now we add our initialization code InstructionList inits = genInitInstructions(addedThisInitializers, false); enclosingShadow.getRange().insert(inits, Range.OutsideBefore); } // actually, you only need to inline the self constructors that are // in a particular group (partition the constructors into groups where members // call or are called only by those in the group). Then only inline // constructors // in groups where at least one initialization jp matched. Future work. boolean addedInitialization = match( BcelShadow.makeUnfinishedInitialization(world, mg), initializationShadows); addedInitialization |= match( BcelShadow.makeUnfinishedPreinitialization(world, mg), initializationShadows); mg.matchedShadows = shadowAccumulator; return addedInitialization || !shadowAccumulator.isEmpty(); } private boolean shouldWeaveBody(LazyMethodGen mg) { if (mg.isBridgeMethod()) return false; if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>"); AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature(); if (a != null) return a.isWeaveBody(); return true; } /** * first sorts the mungers, then gens the initializers in the right order */ private InstructionList genInitInstructions(List list, boolean isStatic) { list = PartialOrder.sort(list); if (list == null) { throw new BCException("circularity in inter-types"); } InstructionList ret = new InstructionList(); for (Iterator i = list.iterator(); i.hasNext();) { ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next(); NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger(); ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType()); if (!isStatic) ret.append(InstructionConstants.ALOAD_0); ret.append(Utility.createInvoke(fact, world, initMethod)); } return ret; } private void match( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { Instruction i = ih.getInstruction(); if ((i instanceof FieldInstruction) && (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) ) { FieldInstruction fi = (FieldInstruction) i; if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) { // check for sets of constant fields. We first check the previous // instruction. If the previous instruction is a LD_WHATEVER (push // constant on the stack) then we must resolve the field to determine // if it's final. If it is final, then we don't generate a shadow. InstructionHandle prevHandle = ih.getPrev(); Instruction prevI = prevHandle.getInstruction(); if (Utility.isConstantPushInstruction(prevI)) { Member field = BcelWorld.makeFieldJoinPointSignature(clazz, (FieldInstruction) i); ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. } else if (Modifier.isFinal(resolvedField.getModifiers())) { // it's final, so it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldGet)) matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else if (i instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction) i; if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) { if (canMatch(Shadow.ConstructorCall)) match( BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow), shadowAccumulator); } else if (ii instanceof INVOKESPECIAL) { String onTypeName = ii.getClassName(cpg); if (onTypeName.equals(mg.getEnclosingClass().getName())) { // we are private matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } else { // we are a super call, and this is not a join point in AspectJ-1.{0,1} } } else { matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } } // performance optimization... we only actually care about ASTORE instructions, // since that's what every javac type thing ever uses to start a handler, but for // now we'll do this for everybody. if (!canMatch(Shadow.ExceptionHandler)) return; if (Range.isRangeHandle(ih)) return; InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int j = 0; j < targeters.length; j++) { InstructionTargeter t = targeters[j]; if (t instanceof ExceptionRange) { // assert t.getHandler() == ih ExceptionRange er = (ExceptionRange) t; if (er.getCatchType() == null) continue; if (isInitFailureHandler(ih)) return; match( BcelShadow.makeExceptionHandler( world, er, mg, ih, enclosingShadow), shadowAccumulator); } } } } private boolean isInitFailureHandler(InstructionHandle ih) { // Skip the astore_0 and aload_0 at the start of the handler and // then check if the instruction following these is // 'putstatic ajc$initFailureCause'. If it is then we are // in the handler we created in AspectClinit.generatePostSyntheticCode() InstructionHandle twoInstructionsAway = ih.getNext().getNext(); if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) { String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg); if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true; } return false; } private void matchSetInstruction( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if ( Modifier.isFinal(resolvedField.getModifiers()) && Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) { // it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { match( BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow), shadowAccumulator); } } private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { BcelShadow bs = BcelShadow.makeFieldGet(world,resolvedField,mg,ih,enclosingShadow); String cname = fi.getClassName(cpg); if (!resolvedField.getDeclaringType().getName().equals(cname)) { bs.setActualTargetType(cname); } match(bs, shadowAccumulator); } } /** * For a given resolvedmember, this will discover the real annotations for it. * <b>Should only be used when the resolvedmember is the contents of an effective signature * attribute, as thats the only time when the annotations aren't stored directly in the * resolvedMember</b> * @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing * @param declaredSig the real sig 'blah.ajc$xxx' */ private void fixAnnotationsForResolvedMember(ResolvedMember rm,ResolvedMember declaredSig) { try { UnresolvedType memberHostType = declaredSig.getDeclaringType(); ResolvedType[] annotations = (ResolvedType[])mapToAnnotations.get(rm); String methodName = declaredSig.getName(); // FIXME asc shouldnt really rely on string names ! if (annotations == null) { if (rm.getKind()==Member.FIELD) { if (methodName.startsWith("ajc$inlineAccessField")) { ResolvedMember resolvedDooberry = world.resolve(rm); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interFieldInitializer(rm,memberHostType); ResolvedMember resolvedDooberry = world.resolve(realthing); annotations = resolvedDooberry.getAnnotationTypes(); } } else if (rm.getKind()==Member.METHOD && !rm.isAbstract()) { if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) { ResolvedMember resolvedDooberry = world.resolve(declaredSig); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm,memberHostType); ResolvedMember resolvedDooberry = world.resolve(realthing); annotations = resolvedDooberry.getAnnotationTypes(); } } else if (rm.getKind()==Member.CONSTRUCTOR) { ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(),rm.getParameterTypes()); ResolvedMember resolvedDooberry = world.resolve(realThing); annotations = resolvedDooberry.getAnnotationTypes(); } if (annotations == null) annotations = new ResolvedType[0]; mapToAnnotations.put(rm,annotations); } rm.setAnnotationTypes(annotations); } catch (Throwable t) { //FIXME asc remove this catch after more testing has confirmed the above stuff is OK throw new BCException("Unexpectedly went bang when searching for annotations on "+rm,t); } } private void matchInvokeInstruction(LazyMethodGen mg, InstructionHandle ih, InvokeInstruction invoke, BcelShadow enclosingShadow, List shadowAccumulator) { String methodName = invoke.getName(cpg); if (methodName.startsWith(NameMangler.PREFIX)) { Member jpSig = world.makeJoinPointSignatureForMethodInvocation(clazz, invoke); ResolvedMember declaredSig = jpSig.resolve(world); //System.err.println(method + ", declaredSig: " +declaredSig); if (declaredSig == null) return; if (declaredSig.getKind() == Member.FIELD) { Shadow.Kind kind; if (jpSig.getReturnType().equals(ResolvedType.VOID)) { kind = Shadow.FieldSet; } else { kind = Shadow.FieldGet; } if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, kind, declaredSig), shadowAccumulator); } else { AjAttribute.EffectiveSignatureAttribute effectiveSig = declaredSig.getEffectiveSignature(); if (effectiveSig == null) return; //System.err.println("call to inter-type member: " + effectiveSig); if (effectiveSig.isWeaveBody()) return; ResolvedMember rm = effectiveSig.getEffectiveSignature(); fixAnnotationsForResolvedMember(rm,declaredSig); // abracadabra if (canMatch(effectiveSig.getShadowKind())) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, effectiveSig.getShadowKind(), rm), shadowAccumulator); } } else { if (canMatch(Shadow.MethodCall)) match( BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow), shadowAccumulator); } } private boolean match(BcelShadow shadow, List shadowAccumulator) { //System.err.println("match: " + shadow); ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_SHADOW, shadow); boolean isMatched = false; for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) { ShadowMunger munger = (ShadowMunger)i.next(); ContextToken mungerMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_POINTCUT, munger.getPointcut()); if (munger.match(shadow, world)) { WeaverMetrics.recordMatchResult(true);// Could pass: munger shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation()); } } else { WeaverMetrics.recordMatchResult(false); // Could pass: munger } CompilationAndWeavingContext.leavingPhase(mungerMatchToken); } if (isMatched) shadowAccumulator.add(shadow); CompilationAndWeavingContext.leavingPhase(shadowMatchToken); return isMatched; } // ---- private void implement(LazyMethodGen mg) { List shadows = mg.matchedShadows; if (shadows == null) return; // We depend on a partial order such that inner shadows are earlier on the list // than outer shadows. That's fine. This order is preserved if: // A preceeds B iff B.getStart() is LATER THAN A.getStart(). for (Iterator i = shadows.iterator(); i.hasNext(); ) { BcelShadow shadow = (BcelShadow)i.next(); ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.IMPLEMENTING_ON_SHADOW,shadow); shadow.implement(); CompilationAndWeavingContext.leavingPhase(tok); } mg.matchedShadows = null; } // ---- public LazyClassGen getLazyClassGen() { return clazz; } public List getShadowMungers() { return shadowMungers; } public BcelWorld getWorld() { return world; } // Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info public static void setReweavableMode(boolean mode,boolean compress) { inReweavableMode = mode; compressReweavableAttributes = compress; } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.PrivilegedAccessMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.Pointcut; //XXX addLazyMethodGen is probably bad everywhere public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { super(munger, aspectType); } public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } public boolean munge(BcelClassWeaver weaver) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MUNGING_WITH, this); boolean changed = false; boolean worthReporting = true; if (munger.getKind() == ResolvedTypeMunger.Field) { changed = mungeNewField(weaver, (NewFieldTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { changed = mungeNewMethod(weaver, (NewMethodTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) { changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) { // PTWIMPL Transform the target type (add the aspect instance field) changed = mungePerTypeWithinTransformer(weaver); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) { changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Parent) { changed = mungeNewParent(weaver, (NewParentTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) { changed = mungeNewAnnotationOnType(weaver,(AnnotationOnTypeMunger)munger); } else { throw new RuntimeException("unimplemented"); } if (changed && munger.changesPublicSignature()) { WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(); info.addConcreteMunger(this); } // Whilst type mungers aren't persisting their source locations, we add this relationship during // compilation time (see other reference to ResolvedTypeMunger.persist) if (ResolvedTypeMunger.persistSourceLocation) { if (changed && worthReporting) { if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } else { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } } } // TAG: WeavingMessage if (changed && worthReporting && munger!=null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName(); if (tName.indexOf("no debug info available")!=-1) tName = "no debug info available"; else tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath()); String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath()); if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { // This message could come out of AjLookupEnvironment.addParent if doing parents // munging at compile time only... NewParentTypeMunger parentTM = (NewParentTypeMunger)munger; if (parentTM.getNewParent().isInterface()) { weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName}, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } else { weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName })); // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } } else { weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[]{weaver.getLazyClassGen().getType().getName(), tName,munger.getKind().toString().toLowerCase(), getAspectType().getName(), fName+":'"+munger.getSignature()+"'"}, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } } CompilationAndWeavingContext.leavingPhase(tok); return changed; } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom+1); } private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver,AnnotationOnTypeMunger munger) { // FIXME asc this has already been done up front, need to do it here too? weaver.getLazyClassGen().addAnnotation(munger.getNewAnnotation().getBcelAnnotation()); return true; } /** * For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted * but could do with more testing! */ private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) { LazyClassGen newParentTarget = weaver.getLazyClassGen(); ResolvedType newParent = munger.getNewParent(); boolean cont = true; // Set to false when we error, so we don't actually *do* the munge cont = enforceDecpRule1_abstractMethodsImplemented(weaver, munger.getSourceLocation(),newParentTarget, newParent); cont = enforceDecpRule2_cantExtendFinalClass(weaver,munger.getSourceLocation(),newParentTarget,newParent) && cont; List methods = newParent.getMethodsWithoutIterator(false,true); for (Iterator iter = methods.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (!superMethod.getName().equals("<init>")) { LazyMethodGen subMethod = findMatchingMethod(newParentTarget, superMethod); if (subMethod!=null) { cont = enforceDecpRule3_visibilityChanges(weaver, newParent, superMethod, subMethod) && cont; cont = enforceDecpRule4_compatibleReturnTypes(weaver, superMethod, subMethod) && cont; cont = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver,munger.getSourceLocation(),superMethod,subMethod) && cont; } } } if (!cont) return false; // A rule was violated and an error message already reported if (newParent.isClass()) { // Changing the supertype if (!attemptToModifySuperCalls(weaver,newParentTarget,newParent)) return false; newParentTarget.setSuperClass(newParent); } else { // Adding a new interface newParentTarget.addInterface(newParent,getSourceLocation()); } return true; } /** * Rule 1: For the declare parents to be allowed, the target type must override and implement * inherited abstract methods (if the type is not declared abstract) */ private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc,LazyClassGen newParentTarget, ResolvedType newParent) { boolean ruleCheckingSucceeded = true; if (!(newParentTarget.isAbstract() || newParentTarget.isInterface())) { // Ignore abstract classes or interfaces List methods = newParent.getMethodsWithoutIterator(false,true); for (Iterator i = methods.iterator(); i.hasNext();) { ResolvedMember o = (ResolvedMember)i.next(); if (o.isAbstract() && !o.getName().startsWith("ajc$interField")) { // Ignore abstract methods of ajc$interField prefixed methods ResolvedMember discoveredImpl = null; List newParentTargetMethods = newParentTarget.getType().getMethodsWithoutIterator(false,true); for (Iterator ii = newParentTargetMethods.iterator(); ii.hasNext() && discoveredImpl==null;) { ResolvedMember gen2 = (ResolvedMember) ii.next(); if (gen2.getName().equals(o.getName()) && gen2.getParameterSignature().equals(o.getParameterSignature()) && !gen2.isAbstract()) { discoveredImpl = gen2; // Found a valid implementation ! } } if (discoveredImpl == null) { // didnt find a valid implementation, lets check the ITDs on this type to see if they satisfy it boolean satisfiedByITD = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next(); if (m.getMunger() instanceof NewMethodTypeMunger) { ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType .matches( AjcMemberMaker.interMethod( sig,m.getAspectType(),sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()),o)) { satisfiedByITD = true; } } } } if (!satisfiedByITD) { error(weaver, "The type " + newParentTarget.getName() + " must implement the inherited abstract method "+o.getDeclaringType()+"."+o.getName()+o.getParameterSignature(), newParentTarget.getType().getSourceLocation(),new ISourceLocation[]{o.getSourceLocation(),mungerLoc}); ruleCheckingSucceeded=false; } } } } } return ruleCheckingSucceeded; } /** * Rule 2. Can't extend final types */ private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { if (newParent.isFinal()) { error(weaver,"Cannot make type "+newParentTarget.getName()+" extend final class "+newParent.getName(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[]{mungerLoc}); return false; } return true; } /** * Rule 3. Can't narrow visibility of methods when overriding */ private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; if (superMethod.isPublic()) { if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } else if (superMethod.isProtected()) { if (subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } else if (superMethod.isDefault()) { if (subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } return cont; } /** * Rule 4. Can't have incompatible return types */ private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; String superReturnTypeSig = superMethod.getReturnType().getSignature(); String subReturnTypeSig = subMethod.getReturnType().getSignature(); if (!superReturnTypeSig.equals(subReturnTypeSig)) { // Allow for covariance - wish I could test this (need Java5...) ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType()); ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType()); if (!superType.isAssignableFrom(subType)) { ISourceLocation sloc = subMethod.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "The return type is incompatible with "+superMethod.getDeclaringType()+"."+superMethod.getName()+superMethod.getParameterSignature(), subMethod.getSourceLocation())); cont=false; } } return cont; } /** * Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance * method static or override and make a static method an instance method. */ private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver,ISourceLocation mungerLoc,ResolvedMember superMethod, LazyMethodGen subMethod ) { if (superMethod.isStatic() && !subMethod.isStatic()) { error(weaver,"This instance method "+subMethod.getName()+subMethod.getParameterSignature()+ " cannot override the static method from "+superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc}); return false; } else if (!superMethod.isStatic() && subMethod.isStatic()) { error(weaver,"The static method "+subMethod.getName()+subMethod.getParameterSignature()+ " cannot hide the instance method from "+superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc}); return false; } return true; } public void error(BcelClassWeaver weaver,String text,ISourceLocation primaryLoc,ISourceLocation[] extraLocs) { IMessage msg = new Message(text, primaryLoc, true, extraLocs); weaver.getWorld().getMessageHandler().handleMessage(msg); } private LazyMethodGen findMatchingMethod(LazyClassGen newParentTarget, ResolvedMember m) { LazyMethodGen found = null; // Search the type for methods overriding super methods (methods that come from the new parent) // Don't use the return value in the comparison as overriding doesnt for (Iterator i = newParentTarget.getMethodGens().iterator(); i.hasNext() && found==null;) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(m.getName()) && gen.getParameterSignature().equals(m.getParameterSignature())) { found = gen; } } return found; } /** * The main part of implementing declare parents extends. Modify super ctor calls to target the new type. */ public boolean attemptToModifySuperCalls(BcelClassWeaver weaver,LazyClassGen newParentTarget, ResolvedType newParent) { String currentParent = newParentTarget.getSuperClassname(); List mgs = newParentTarget.getMethodGens(); // Look for ctors to modify for (Iterator iter = mgs.iterator(); iter.hasNext();) { LazyMethodGen aMethod = (LazyMethodGen) iter.next(); if (aMethod.getName().equals("<init>")) { InstructionList insList = aMethod.getBody(); InstructionHandle handle = insList.getStart(); while (handle!= null) { if (handle.getInstruction() instanceof INVOKESPECIAL) { ConstantPoolGen cpg = newParentTarget.getConstantPoolGen(); INVOKESPECIAL invokeSpecial = (INVOKESPECIAL)handle.getInstruction(); if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) { // System.err.println("Transforming super call '<init>"+sp.getSignature(cpg)+"'"); // 1. Check there is a ctor in the new parent with the same signature ResolvedMember newCtor = getConstructorWithSignature(newParent,invokeSpecial.getSignature(cpg)); if (newCtor == null) { // 2. Check ITDCs to see if the necessary ctor is provided that way boolean satisfiedByITDC = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC; ) { ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next(); if (m.getMunger() instanceof NewConstructorTypeMunger) { if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) { satisfiedByITDC = true; } } } if (!satisfiedByITDC) { String csig = createReadableCtorSig(newParent, cpg, invokeSpecial); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Unable to modify hierarchy for "+newParentTarget.getClassName()+" - the constructor "+ csig+" is missing",this.getSourceLocation())); return false; } } int idx = cpg.addMethodref(newParent.getClassName(), invokeSpecial.getMethodName(cpg), invokeSpecial.getSignature(cpg)); invokeSpecial.setIndex(idx); } } handle = handle.getNext(); } } } return true; } /** * Creates a nice signature for the ctor, something like "(int,Integer,String)" */ private String createReadableCtorSig(ResolvedType newParent, ConstantPoolGen cpg, INVOKESPECIAL invokeSpecial) { StringBuffer sb = new StringBuffer(); Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg); sb.append(newParent.getClassName()); sb.append("("); for (int i = 0; i < ctorArgs.length; i++) { String argtype = ctorArgs[i].toString(); if (argtype.lastIndexOf(".")!=-1) sb.append(argtype.substring(argtype.lastIndexOf(".")+1)); else sb.append(argtype); if (i+1<ctorArgs.length) sb.append(","); } sb.append(")"); return sb.toString(); } private ResolvedMember getConstructorWithSignature(ResolvedType tx,String signature) { ResolvedMember[] mems = tx.getDeclaredJavaMethods(); for (int i = 0; i < mems.length; i++) { ResolvedMember rm = mems[i]; if (rm.getName().equals("<init>")) { if (rm.getSignature().equals(signature)) return rm; } } return null; } private boolean mungePrivilegedAccess( BcelClassWeaver weaver, PrivilegedAccessMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember member = munger.getMember(); ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); //System.out.println("munging: " + gen + " with " + member); if (onType.equals(gen.getType())) { if (member.getKind() == Member.FIELD) { //System.out.println("matched: " + gen); addFieldGetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member)); return true; } else if (member.getKind() == Member.METHOD) { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { for (Iterator i = gen.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen m = (LazyMethodGen)i.next(); if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); //return true; } } return true; //throw new BCException("no match for " + member + " in " + gen); } else if (member.getKind() == Member.STATIC_INITIALIZATION) { gen.forcePublic(); return true; } else { throw new RuntimeException("unimplemented"); } } return false; } private void addFieldGetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType()))); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addFieldSetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (field.isStatic()) { il.append(InstructionFactory.createLoad(fieldType, 0)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(fieldType, 1)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD)); } il.append(InstructionFactory.createReturn(Type.VOID)); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addMethodDispatch( LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); //Type fieldType = BcelWorld.makeBcelType(field.getType()); Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes()); int pos = 0; if (!method.isStatic()) { il.append(InstructionConstants.ALOAD_0); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; il.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } il.append(Utility.createInvoke(fact, (BcelWorld)aspectType.getWorld(), method)); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType()))); mg.getBody().insert(il); gen.addMethodGen(mg); } protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) { LazyMethodGen ret = new LazyMethodGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) { return new FieldGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), gen.getConstantPoolGen()); } private boolean mungePerObjectInterface( BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = new LazyMethodGen( Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType), new Type[]{fieldType,}, new String[0], gen); InstructionList il1 = new InstructionList(); il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); gen.addInterface(munger.getInterfaceType(),getSourceLocation()); return true; } else { return false; } } // PTWIMPL Add field to hold aspect instance and an accessor private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) { LazyClassGen gen = weaver.getLazyClassGen(); // if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { // Add (to the target type) the field that will hold the aspect instance // e.g ajc$com_blah_SecurityAspect$ptwAspectInstance FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); // Add an accessor for this new field, the ajc$<aspectname>$localAspectOf() method // e.g. "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()" Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC | Modifier.STATIC,fieldType, NameMangler.perTypeWithinLocalAspectOf(aspectType), new Type[0], new String[0],gen); InstructionList il = new InstructionList(); //PTWIMPL ?? Should check if it is null and throw NoAspectBoundException InstructionFactory fact = gen.getFactory(); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); return true; // } else { // return false; // } } // ??? Why do we have this method? I thought by now we would know if it matched or not private boolean couldMatch( BcelObjectType bcelObjectType, Pointcut pointcut) { return !bcelObjectType.isInterface(); } private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) { ResolvedMember unMangledInterMethod = munger.getSignature(); // do matching on the unMangled one, but actually add them to the mangled method ResolvedMember interMethodBody = munger.getInterMethodBody(aspectType); ResolvedMember interMethodDispatcher = munger.getInterMethodDispatcher(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); boolean mungingInterface = gen.isInterface(); ResolvedType onType = weaver.getWorld().resolve(unMangledInterMethod.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (onInterface && gen.getLazyMethodGen(unMangledInterMethod.getName(), unMangledInterMethod.getSignature(),true) != null) { // this is ok, we could be providing the default implementation of a method // that the target has already declared return false; } if (onType.equals(gen.getType())) { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface); LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all *implementors* of the // interface, but the method itself we add to the interface must be public abstract mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ AnnotationX annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,interMethodDispatcher); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ interMethodDispatcher+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();){ DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(unMangledInterMethod,weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotationX()); } } } if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) { InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); body.append( InstructionFactory.createReturn( BcelWorld.makeBcelType(mangledInterMethod.getReturnType()))); } else { //??? this is okay //if (!(mg.getBody() == null)) throw new RuntimeException("bas"); } // XXX make sure to check that we set exceptions properly on this guy. weaver.addLazyMethodGen(mg); weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(),getSignature().getSourceLocation()); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) { // This means the 'gen' should be the top most implementor // - if it is *not* then something went wrong after we worked // out that it was the top most implementor (see pr49657) if (!gen.getType().isTopmostImplementor(onType)) { ResolvedType rtx = gen.getType().getTopmostImplementor(onType); if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR,rtx,getAspectType().getName()), (sLoc==null?getAspectType().getSourceLocation():sLoc))); } else { // XXX what does this state mean? // We have incorrectly identified what is the top most implementor and its not because // a type wasn't exposed to the weaver } return false; } else { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false); LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all *implementors* of the // interface, but the method itself we add to the interface must be public abstract mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType()); InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!mangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); body.append(InstructionFactory.createReturn(returnType)); mg.definingType = onType; weaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } } else { return false; } } private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType,ResolvedMember lookingFor) { ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods(); UnresolvedType [] lookingForParams = lookingFor.getParameterTypes(); ResolvedMember realMember = null; for (int i = 0; realMember==null && i < aspectMethods.length; i++) { ResolvedMember member = aspectMethods[i]; if (member.getName().equals(lookingFor.getName())){ UnresolvedType [] memberParams = member.getParameterTypes(); if (memberParams.length == lookingForParams.length){ boolean matchOK = true; for (int j = 0; j < memberParams.length && matchOK; j++){ UnresolvedType memberParam = memberParams[j]; UnresolvedType lookingForParam = lookingForParams[j].resolve(aspectType.getWorld()); if (lookingForParam.isTypeVariableReference()) lookingForParam = lookingForParam.getUpperBound(); if (!memberParam.equals(lookingForParam)){ matchOK=false; } } if (matchOK) realMember = member; } } } return realMember; } private void addNeededSuperCallMethods( BcelClassWeaver weaver, ResolvedType onType, Set neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (weaver.addDispatchTarget(superMethod)) { //System.err.println("super type: " + superMethod.getDeclaringType() + ", " + gen.getType()); boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType()); String dispatchName; if (isSuper) dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName()); else dispatchName = NameMangler.protectedDispatchMethod( onType, superMethod.getName()); LazyMethodGen dispatcher = makeDispatcher( gen, dispatchName, superMethod, weaver.getWorld(), isSuper); weaver.addLazyMethodGen(dispatcher); } } } private void signalError(String msgid,BcelClassWeaver weaver,UnresolvedType onType) { IMessage msg = MessageUtil.error( WeaverMessages.format(msgid,onType.getName()),getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } private boolean mungeNewConstructor( BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) { final LazyClassGen currentClass = weaver.getLazyClassGen(); final InstructionFactory fact = currentClass.getFactory(); ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor(); ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld()); if (onType.isRawType()) onType = onType.getGenericType(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (! onType.equals(currentClass.getType())) return false; ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor(); //int declaredParameterCount = newConstructorTypeMunger.getDeclaredParameterCount(); LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember); mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(),Shadow.ConstructorExecution,true); // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ ResolvedMember interMethodDispatcher =AjcMemberMaker.postIntroducedConstructor(aspectType,onType,newConstructorTypeMunger.getSignature().getParameterTypes()); AnnotationX annotationsOnRealMember[] = null; ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType,interMethodDispatcher); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ interMethodDispatcher+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();){ DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(explicitConstructor,weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotationX()); } } } currentClass.addMethodGen(mg); //weaver.addLazyMethodGen(freshConstructor); InstructionList body = mg.getBody(); // add to body: push arts for call to pre, from actual args starting at 1 (skipping this), going to // declared argcount + 1 UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes(); Type[] paramTypes = mg.getArgumentTypes(); int frameIndex = 1; for (int i = 0, len = declaredParams.length; i < len; i++) { body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex)); frameIndex += paramTypes[i].getSize(); } // do call to pre Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams); body.append(Utility.createInvoke(fact, null, preMethod)); // create a local, and store return pre stuff into it. int arraySlot = mg.allocateLocal(1); body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot)); // put this on the stack body.append(InstructionConstants.ALOAD_0); // unpack pre args onto stack UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes(); for (int i = 0, len = superParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, i)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i]))); } // call super/this body.append(Utility.createInvoke(fact, null, explicitConstructor)); // put this back on the stack body.append(InstructionConstants.ALOAD_0); // unpack params onto stack Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams); UnresolvedType[] postParamTypes = postMethod.getParameterTypes(); for (int i = 1, len = postParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, superParamTypes.length + i-1)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i]))); } // call post body.append(Utility.createInvoke(fact, null, postMethod)); // don't forget to return!! body.append(InstructionConstants.RETURN); return true; } private static LazyMethodGen makeDispatcher( LazyClassGen onGen, String dispatchName, ResolvedMember superMethod, BcelWorld world, boolean isSuper) { Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType()); int modifiers = Modifier.PUBLIC; if (onGen.isInterface()) modifiers |= Modifier.ABSTRACT; LazyMethodGen mg = new LazyMethodGen( modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod.getExceptions()), onGen); InstructionList body = mg.getBody(); if (onGen.isInterface()) return mg; // assert (!superMethod.isStatic()) InstructionFactory fact = onGen.getFactory(); int pos = 0; body.append(InstructionFactory.createThis()); pos++; for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } if (isSuper) { body.append(Utility.createSuperInvoke(fact, world, superMethod)); } else { body.append(Utility.createInvoke(fact, world, superMethod)); } body.append(InstructionFactory.createReturn(returnType)); return mg; } private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) { /*ResolvedMember initMethod = */munger.getInitMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember field = munger.getSignature(); ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } ResolvedMember interMethodBody = munger.getInitMethod(aspectType); AnnotationX annotationsOnRealMember[] = null; // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ // the below line just gets the method with the same name in aspectType.getDeclaredMethods(); ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,interMethodBody); if (realMember==null) throw new BCException("Couldn't find ITD init member '"+ interMethodBody+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); } if (onType.equals(gen.getType())) { if (onInterface) { LazyMethodGen mg = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType)); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType)); gen.addMethodGen(mg1); } else { weaver.addInitializer(this); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldClassField(field, aspectType)); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); fg.addAnnotation(ag); } } gen.addField(fg.getField(),getSourceLocation()); } return true; } else if (onInterface && gen.getType().isTopmostImplementor(onType)) { // wew know that we can't be static since we don't allow statics on interfaces if (field.isStatic()) throw new RuntimeException("unimplemented"); weaver.addInitializer(this); //System.err.println("impl body on " + gen.getType() + " for " + munger); Type fieldType = BcelWorld.makeBcelType(field.getType()); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType)); gen.addField(fg.getField(),getSourceLocation()); //this uses a shadow munger to add init method to constructors //weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod)); LazyMethodGen mg = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType(), aspectType)); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType)); InstructionList il1 = new InstructionList(); if (field.isStatic()) { il1.append(InstructionFactory.createLoad(fieldType, 0)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTSTATIC)); } else { il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); } il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); return true; } else { return false; } } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.jar.Attributes.Name; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.CrosscuttingMembersSet; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.IWeaver; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.BindingAnnotationTypePattern; import org.aspectj.weaver.patterns.BindingTypePattern; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.ConcreteCflowPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NameBindingPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.patterns.WithinPointcut; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; public BcelWeaver(BcelWorld world) { super(); WeaverMetrics.reset(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List lateTypeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } /** * Add the given aspect to the weaver. * The type is resolved to support DOT for static inner classes as well as DOLLAR * * @param aspectName */ public void addLibraryAspect(String aspectName) { // 1 - resolve as is ResolvedType type = world.resolve(UnresolvedType.forName(aspectName), true); if (type.equals(ResolvedType.MISSING)) { // fallback on inner class lookup mechanism String fixedName = aspectName; int hasDot = fixedName.lastIndexOf('.'); while (hasDot > 0) { //System.out.println("BcelWeaver.addLibraryAspect " + fixedName); char[] fixedNameChars = fixedName.toCharArray(); fixedNameChars[hasDot] = '$'; fixedName = new String(fixedNameChars); hasDot = fixedName.lastIndexOf('.'); type = world.resolve(UnresolvedType.forName(fixedName), true); if (!type.equals(ResolvedType.MISSING)) { break; } } } //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { //TODO AV - happens to reach that a lot of time: for each type flagged reweavable X for each aspect in the weaverstate //=> mainly for nothing for LTW - pbly for something in incremental build... xcutSet.addOrReplaceAspect(type); } else { // FIXME : Alex: better warning upon no such aspect from aop.xml throw new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName); } } /** * * @param inFile File path to class directory or zip/jar class archive * @throws IOException */ public void addLibraryJarFile(File inFile) throws IOException { List addedAspects = null; if (inFile.isDirectory()) { addedAspects = addAspectsFromDirectory(inFile); } else { addedAspects = addAspectsFromJarFile(inFile); } for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedType aspectX = (ResolvedType) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } // FIXME ASC performance? of this alternative soln. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); return addedAspects; } private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{ List addedAspects = new ArrayList(); File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){ public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }); for (int i = 0; i < classFiles.length; i++) { FileInputStream fis = new FileInputStream(classFiles[i]); byte[] bytes = FileUtil.readAsByteArray(fis); addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects); } return addedAspects; } private void addIfAspect(byte[] bytes, String name, List toList) throws IOException { ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name); JavaClass jc = parser.parse(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { toList.add(type); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarFile inJar = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inJar = new JarFile(inFile); addManifest(inJar.getManifest()); Enumeration entries = inJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); InputStream inStream = inJar.getInputStream(entry); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); // System.out.println("? addJarFile() filename='" + filename + "'"); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.close(); } inJar.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inJar != null) { try {inJar.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(UnresolvedType.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void prepareForWeave() { needToReweaveWorld = false; CflowPointcut.clearCaches(); // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(UnresolvedType.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); rewritePointcuts(shadowMungerList); typeMungerList = xcutSet.getTypeMungers(); lateTypeMungerList = xcutSet.getLateTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); // The ordering here used to be based on a string compare on toString() for the two mungers - // that breaks for the @AJ style where advice names aren't programmatically generated. So we // have changed the sorting to be based on source location in the file - this is reliable, in // the case of source locations missing, we assume they are 'sorted' - i.e. the order in // which they were added to the collection is correct, this enables the @AJ stuff to work properly. // When @AJ processing starts filling in source locations for mungers, this code may need // a bit of alteration... Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { ShadowMunger sm1 = (ShadowMunger)o1; ShadowMunger sm2 = (ShadowMunger)o2; if (sm1.getSourceLocation()==null) return (sm2.getSourceLocation()==null?0:1); if (sm2.getSourceLocation()==null) return -1; return (sm2.getSourceLocation().getOffset()-sm1.getSourceLocation().getOffset()); } }); } /* * Rewrite all of the pointcuts in the world into their most efficient * form for subsequent matching. Also ensure that if pc1.equals(pc2) * then pc1 == pc2 (for non-binding pcds) by making references all * point to the same instance. * Since pointcuts remember their match decision on the last shadow, * this makes matching faster when many pointcuts share common elements, * or even when one single pointcut has one common element (which can * be a side-effect of DNF rewriting). */ private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) { PointcutRewriter rewriter = new PointcutRewriter(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = rewriter.rewrite(p); // validateBindings now whilst we still have around the pointcut // that resembles what the user actually wrote in their program // text. if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getSignature() != null) { final int numFormals; final String names[]; //ATAJ for @AJ aspect, the formal have to be checked according to the argument number // since xxxJoinPoint presence or not have side effects if (advice.getConcreteAspect().isAnnotationStyleAspect()) { numFormals = advice.getBaseParameterCount(); int numArgs = advice.getSignature().getParameterTypes().length; if (numFormals > 0) { names = advice.getSignature().getParameterNames(world); validateBindings(newP,p,numArgs,names); } } else { numFormals = advice.getBaseParameterCount(); if (numFormals > 0) { names = advice.getBaseParameterNames(world); validateBindings(newP,p,numFormals,names); } } } } munger.setPointcut(newP); } // now that we have optimized individual pointcuts, optimize // across the set of pointcuts.... // Use a map from key based on pc equality, to value based on // pc identity. Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); munger.setPointcut(shareEntriesFromMap(p,pcMap)); } } private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) { // some things cant be shared... if (p instanceof NameBindingPointcut) return p; if (p instanceof IfPointcut) return p; if (p instanceof ConcreteCflowPointcut) return p; if (p instanceof AndPointcut) { AndPointcut apc = (AndPointcut) p; Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap); return new AndPointcut(left,right); } else if (p instanceof OrPointcut) { OrPointcut opc = (OrPointcut) p; Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap); return new OrPointcut(left,right); } else if (p instanceof NotPointcut) { NotPointcut npc = (NotPointcut) p; Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap); return new NotPointcut(not); } else { // primitive pcd if (pcMap.containsKey(p)) { // based on equality return (Pointcut) pcMap.get(p); // same instance (identity) } else { pcMap.put(p,p); return p; } } } // userPointcut is the pointcut that the user wrote in the program text. // dnfPointcut is the same pointcut rewritten in DNF // numFormals is the number of formal parameters in the pointcut // if numFormals > 0 then every branch of a disjunction must bind each formal once and only once. // in addition, the left and right branches of a disjunction must hold on join point kinds in // common. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) { if (numFormals == 0) return; // nothing to check if (dnfPointcut.couldMatchKinds().isEmpty()) return; // cant have problems if you dont match! if (dnfPointcut instanceof OrPointcut) { OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut; Pointcut[] leftBindings = new Pointcut[numFormals]; Pointcut[] rightBindings = new Pointcut[numFormals]; validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings); } else { Pointcut[] bindings = new Pointcut[numFormals]; validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings); } } private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) { Pointcut left = pc.getLeft(); Pointcut right = pc.getRight(); if (left instanceof OrPointcut) { Pointcut[] newRightBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings); } else { if (left.couldMatchKinds().size() > 0) validateSingleBranch(left, userPointcut, numFormals, names, leftBindings); } if (right instanceof OrPointcut) { Pointcut[] newLeftBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings); } else { if (right.couldMatchKinds().size() > 0) validateSingleBranch(right, userPointcut, numFormals, names, rightBindings); } Set kindsInCommon = left.couldMatchKinds(); kindsInCommon.retainAll(right.couldMatchKinds()); if (!kindsInCommon.isEmpty() && couldEverMatchSameJoinPoints(left,right)) { // we know that every branch binds every formal, so there is no ambiguity // if each branch binds it in exactly the same way... List ambiguousNames = new ArrayList(); for (int i = 0; i < numFormals; i++) { if (!leftBindings[i].equals(rightBindings[i])) { ambiguousNames.add(names[i]); } } if (!ambiguousNames.isEmpty()) raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames); } } // pc is a pointcut that does not contain any disjunctions // check that every formal is bound (negation doesn't count). // we know that numFormals > 0 or else we would not be called private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) { boolean[] foundFormals = new boolean[numFormals]; for (int i = 0; i < foundFormals.length; i++) { foundFormals[i] = false; } validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings); for (int i = 0; i < foundFormals.length; i++) { if (!foundFormals[i]) { boolean ignore = false; // ATAJ soften the unbound error for implicit bindings like JoinPoint in @AJ style for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) { if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) { ignore = true; break; } } if (!ignore) { raiseUnboundFormalError(names[i],userPointcut); } } } } // each formal must appear exactly once private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) { if (pc instanceof NotPointcut) { // nots can only appear at leaves in DNF NotPointcut not = (NotPointcut) pc; if (not.getNegatedPointcut() instanceof NameBindingPointcut) { NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut(); if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) raiseNegationBindingError(userPointcut); } } else if (pc instanceof AndPointcut) { AndPointcut and = (AndPointcut) pc; validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings); validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings); } else if (pc instanceof NameBindingPointcut) { List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns(); for (Iterator iter = btps.iterator(); iter.hasNext();) { BindingTypePattern btp = (BindingTypePattern) iter.next(); int index = btp.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns(); for (Iterator iter = baps.iterator(); iter.hasNext();) { BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next(); int index = bap.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); for (int i = 0; i < slots.length; i++) { bindings[slots[i]] = cfp; if (foundFormals[slots[i]]) { raiseAmbiguousBindingError(names[slots[i]],userPointcut); } else { foundFormals[slots[i]] = true; } } } } // By returning false from this method, we are allowing binding of the same // variable on either side of an or. // Be conservative :- have to consider overriding, varargs, autoboxing, // the effects of itds (on within for example), interfaces, the fact that // join points can have multiple signatures and so on. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) { if (left instanceof OrPointcut) { OrPointcut leftOrPointcut = (OrPointcut)left; if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(),right)) return true; if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(),right)) return true; return false; } if (right instanceof OrPointcut) { OrPointcut rightOrPointcut = (OrPointcut)right; if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getLeft())) return true; if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getRight())) return true; return false; } // look for withins WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class); WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class); if ((leftWithin != null) && (rightWithin != null)) { if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false; } // look for kinded KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class); KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class); if ((leftKind != null) && (rightKind != null)) { if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false; } return true; } private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) { if (toSearch instanceof NotPointcut) return null; if (toLookFor.isInstance(toSearch)) return toSearch; if (toSearch instanceof AndPointcut) { AndPointcut apc = (AndPointcut) toSearch; Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor); if (left != null) return left; return findFirstPointcutIn(apc.getRight(),toLookFor); } return null; } /** * @param userPointcut */ private void raiseNegationBindingError(Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param userPointcut */ private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) { StringBuffer formalNames = new StringBuffer(names.get(0).toString()); for (int i = 1; i < names.size(); i++) { formalNames.append(", "); formalNames.append(names.get(i)); } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseUnboundFormalError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, ""); Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); requestor.processingReweavableState(); ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE,""); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); // null return from getClassType() means the delegate is an eclipse source type - so // there *cant* be any reweavable state... (he bravely claimed...) if (classType !=null) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className); processReweavableStateIfPresent(className, classType); CompilationAndWeavingContext.leavingPhase(tok); } } CompilationAndWeavingContext.leavingPhase(reweaveToken); ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,""); requestor.addingTypeMungers(); // We process type mungers in two groups, first mungers that change the type // hierarchy, then 'normal' ITD type mungers. // Process the types in a predictable order (rather than the order encountered). // For class A, the order is superclasses of A then superinterfaces of A // (and this mechanism is applied recursively) List typesToProcess = new ArrayList(); for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = (UnwovenClassFile) iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size()>0) { weaveParentsFor(typesToProcess,(String)typesToProcess.get(0)); } for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addNormalTypeMungers(className); } CompilationAndWeavingContext.leavingPhase(typeMungingToken); requestor.weavingAspects(); ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (classType.isAspect()) { weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(aspectToken); requestor.weavingClasses(); ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, ""); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (! classType.isAspect()) { weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(classToken); addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); warnOnUnmatchedAdvice(); requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(weaveToken); return wovenClassNames; } /** * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any * mungers that did not match anything. */ private void warnOnUnmatchedAdvice() { class AdviceLocation { private int lineNo; private UnresolvedType inAspect; public AdviceLocation(BcelAdvice advice) { this.lineNo = advice.getSourceLocation().getLine(); this.inAspect = advice.getDeclaringAspect(); } public boolean equals(Object obj) { if (!(obj instanceof AdviceLocation)) return false; AdviceLocation other = (AdviceLocation) obj; if (this.lineNo != other.lineNo) return false; if (!this.inAspect.equals(other.inAspect)) return false; return true; } public int hashCode() { return 37 + 17*lineNo + 17*inAspect.hashCode(); }; } // FIXME asc Should be factored out into Xlint code and done automatically for all xlint messages, ideally. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) { List l = world.getCrosscuttingMembersSet().getShadowMungers(); Set alreadyWarnedLocations = new HashSet(); for (Iterator iter = l.iterator(); iter.hasNext();) { ShadowMunger element = (ShadowMunger) iter.next(); if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers BcelAdvice ba = (BcelAdvice)element; if (!ba.hasMatchedSomething()) { // Because we implement some features of AJ itself by creating our own kind of mungers, you sometimes // find that ba.getSignature() is not a BcelMethod - for example it might be a cflow entry munger. if (ba.getSignature()!=null) { // check we haven't already warned on this advice and line // (cflow creates multiple mungers for the same advice) AdviceLocation loc = new AdviceLocation(ba); if (alreadyWarnedLocations.contains(loc)) { continue; } else { alreadyWarnedLocations.add(loc); } if (!(ba.getSignature() instanceof BcelMethod) || !Utility.isSuppressing((AnnotationX[])ba.getSignature().getAnnotations(),"adviceDidNotMatch")) { world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(),element.getSourceLocation()); } } } } } } } /** * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process * supertypes (classes/interfaces) of 'typeToWeave' that are in the * 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from * the 'typesForWeaving' list. * * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may * break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it * may choose to weave them in either order - but you'll probably have other problems if * you are supplying partial hierarchies like that ! */ private void weaveParentsFor(List typesForWeaving,String typeToWeave) { // Look at the supertype first ResolvedType rtx = world.resolve(typeToWeave); ResolvedType superType = rtx.getSuperclass(); if (superType!=null && typesForWeaving.contains(superType.getName())) { weaveParentsFor(typesForWeaving,superType.getName()); } // Then look at the superinterface list ResolvedType[] interfaceTypes = rtx.getDeclaredInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ResolvedType rtxI = interfaceTypes[i]; if (typesForWeaving.contains(rtxI.getName())) { weaveParentsFor(typesForWeaving,rtxI.getName()); } } ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,rtx.getName()); weaveParentTypeMungers(rtx); // Now do this type CompilationAndWeavingContext.leavingPhase(tok); typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process } public void prepareToProcessReweavableState() { if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()), null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { // keep track of them just to ensure unique missing aspect error reporting Set alreadyConfirmedReweavableState = new HashSet(); for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedType rtx = world.resolve(UnresolvedType.forName(requiredTypeName),true); boolean exists = rtx!=ResolvedType.MISSING; if (!exists) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className), classType.getSourceLocation(), null); } else { if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()), null,null); alreadyConfirmedReweavableState.add(requiredTypeName); } } } } classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); } else { classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType.getResolvedTypeX().getName()); LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } CompilationAndWeavingContext.leavingPhase(tok); } /** helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType */ public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addParentTypeMungers(String typeName) { weaveParentTypeMungers(world.resolve(typeName)); } public void addNormalTypeMungers(String typeName) { weaveNormalTypeMungers(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes()); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } /** * Weaves new parents and annotations onto a type ("declare parents" and "declare @type") * * Algorithm: * 1. First pass, do parents then do annotations. During this pass record: * - any parent mungers that don't match but have a non-wild annotation type pattern * - any annotation mungers that don't match * 2. Multiple subsequent passes which go over the munger lists constructed in the first * pass, repeatedly applying them until nothing changes. * FIXME asc confirm that algorithm is optimal ?? */ public void weaveParentTypeMungers(ResolvedType onType) { if (onType.isRawType()) onType = onType.getGenericType(); onType.clearInterTypeMungers(); List decpToRepeat = new ArrayList(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents decp = (DeclareParents)i.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { // Perhaps it would have matched if a 'dec @type' had modified the type if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation)i.next(); boolean typeChanged = applyDeclareAtType(decA,onType,true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List decpToRepeatNextTime = new ArrayList(); for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = (DeclareParents) iter.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA,onType,false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType,boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { // FIXME asc important this should be guarded by the 'already has annotation' check below but isn't since the compiler is producing classfiles with deca affected things in... AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation()); // FIXME asc same comment above applies here // TAG: WeavingMessage if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()), decA.getAnnotationString(), "type", decA.getAspect().toString(), Utility.beautifyLocation(decA.getSourceLocation()) })); } if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) { // FIXME asc Could put out a lint here for an already annotated type - the problem is that it may have // picked up the annotation during 'source weaving' in which case the message is misleading. Leaving it // off for now... // if (reportProblems) { // world.getLint().elementAlreadyAnnotated.signal( // new String[]{onType.toString(),decA.getAnnotationTypeX().toString()}, // onType.getSourceLocation(),new ISourceLocation[]{decA.getSourceLocation()}); // } return false; } AnnotationX annoX = decA.getAnnotationX(); // check the annotation is suitable for the target boolean problemReported = verifyTargetIsOK(decA, onType, annoX,reportProblems); if (!problemReported) { didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation * to be attached to the target type that matched. */ private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationX annoX,boolean outputProblems) { boolean problemReported = false; if (annoX.specifiesTarget()) { if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { if (outputProblems) { if (decA.isExactPattern()) { world.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation())); } else { if (world.getLint().invalidTargetForAnnotation.isEnabled()) { world.getLint().invalidTargetForAnnotation.signal( new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()}); } } } problemReported = true; } } return problemReported; } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType,true); if (!newParents.isEmpty()) { didSomething=true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedType newParent = (ResolvedType)j.next(); // We set it here so that the imminent matching for ITDs can succeed - we // still haven't done the necessary changes to the class file itself // (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent() classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } return didSomething; } public void weaveNormalTypeMungers(ResolvedType onType) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, onType.getName()); if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (m.matches(onType)) { onType.addInterTypeMunger(m); } } CompilationAndWeavingContext.leavingPhase(tok); } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { if (dump) dumpUnchanged(classFile); return null; } // JavaClass javaClass = classType.getJavaClass(); List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); LazyClassGen clazz = null; if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() || world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0 ) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList); if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { String messageText = "trouble in: \n" + clazz.toLongString(); getWorld().getMessageHandler().handleMessage( new Message(messageText,IMessage.ABORT,re,null) ); } catch (Error re) { String messageText = "trouble in: \n" + clazz.toLongString(); getWorld().getMessageHandler().handleMessage( new Message(messageText,IMessage.ABORT,re,null) ); } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { // ATAJ: the class was not weaved, but since it gets there early it may have new generated inner classes // attached to it to support LTW perX aspectOf support (see BcelPerClauseAspectAdder) // that aggressively defines the inner <aspect>$mayHaveAspect interface. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) { return clazz; } return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedType type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info if (fb.maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean mode,boolean compress) { inReweavableMode = mode; WeaverStateInfo.setReweavableModeDefaults(mode,compress); BcelClassWeaver.setReweavableMode(mode,compress); } public boolean isReweavable() { return inReweavableMode; } public World getWorld() { return world; } }
91,417
Bug 91417 -Xreweavable should be the default
In order to facilitate widespread use of LTW we need to ensure code is compiled with Xreweavable. However we cannot rely on developers to use this flag so it must be the default. Unfortunately the current code bloat is unacceptable for large projects.
resolved fixed
12e6334
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T12:23:52Z
2005-04-14T14:46:40Z
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.java
/* ******************************************************************* * Copyright (c) 2002 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Andy Clement 6Jul05 generics - signature attribute * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantUtf8; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.classfile.Unknown; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.ClassGen; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUSH; import org.aspectj.apache.bcel.generic.RETURN; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.CollectionUtil; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; /** * Lazy lazy lazy. * We don't unpack the underlying class unless necessary. Things * like new methods and annotations accumulate in here until they * must be written out, don't add them to the underlying MethodGen! * Things are slightly different if this represents an Aspect. */ public final class LazyClassGen { int highestLineNumber = 0; // ---- JSR 45 info private SortedMap /* <String, InlinedSourceFileInfo> */ inlinedFiles = new TreeMap(); private boolean regenerateGenericSignatureAttribute = false; private BcelObjectType myType; // XXX is not set for types we create private ClassGen myGen; private ConstantPoolGen constantPoolGen; private World world; private List /*LazyMethodGen*/ methodGens = new ArrayList(); private List /*LazyClassGen*/ classGens = new ArrayList(); private List /*AnnotationGen*/ annotations = new ArrayList(); private int childCounter = 0; private InstructionFactory fact; private boolean isSerializable = false; private boolean hasSerialVersionUIDField = false; private boolean hasClinit = false; // --- static class InlinedSourceFileInfo { int highestLineNumber; int offset; // calculated InlinedSourceFileInfo(int highestLineNumber) { this.highestLineNumber = highestLineNumber; } } void addInlinedSourceFileInfo(String fullpath, int highestLineNumber) { Object o = inlinedFiles.get(fullpath); if (o != null) { InlinedSourceFileInfo info = (InlinedSourceFileInfo) o; if (info.highestLineNumber < highestLineNumber) { info.highestLineNumber = highestLineNumber; } } else { inlinedFiles.put(fullpath, new InlinedSourceFileInfo(highestLineNumber)); } } void calculateSourceDebugExtensionOffsets() { int i = roundUpToHundreds(highestLineNumber); for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) { InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next(); element.offset = i; i = roundUpToHundreds(i + element.highestLineNumber); } } private static int roundUpToHundreds(int i) { return ((i / 100) + 1) * 100; } int getSourceDebugExtensionOffset(String fullpath) { return ((InlinedSourceFileInfo) inlinedFiles.get(fullpath)).offset; } private Unknown getSourceDebugExtensionAttribute() { int nameIndex = constantPoolGen.addUtf8("SourceDebugExtension"); String data = getSourceDebugExtensionString(); //System.err.println(data); byte[] bytes = Utility.stringToUTF(data); int length = bytes.length; return new Unknown(nameIndex, length, bytes, constantPoolGen.getConstantPool()); } // private LazyClassGen() {} // public static void main(String[] args) { // LazyClassGen m = new LazyClassGen(); // m.highestLineNumber = 37; // m.inlinedFiles.put("boo/baz/foo.java", new InlinedSourceFileInfo( 83)); // m.inlinedFiles.put("boo/barz/foo.java", new InlinedSourceFileInfo(292)); // m.inlinedFiles.put("boo/baz/moo.java", new InlinedSourceFileInfo(128)); // m.calculateSourceDebugExtensionOffsets(); // System.err.println(m.getSourceDebugExtensionString()); // } // For the entire pathname, we're using package names. This is probably wrong. private String getSourceDebugExtensionString() { StringBuffer out = new StringBuffer(); String myFileName = getFileName(); // header section out.append("SMAP\n"); out.append(myFileName); out.append("\nAspectJ\n"); // stratum section out.append("*S AspectJ\n"); // file section out.append("*F\n"); out.append("1 "); out.append(myFileName); out.append("\n"); int i = 2; for (Iterator iter = inlinedFiles.keySet().iterator(); iter.hasNext();) { String element = (String) iter.next(); int ii = element.lastIndexOf('/'); if (ii == -1) { out.append(i++); out.append(' '); out.append(element); out.append('\n'); } else { out.append("+ "); out.append(i++); out.append(' '); out.append(element.substring(ii+1)); out.append('\n'); out.append(element); out.append('\n'); } } // emit line section out.append("*L\n"); out.append("1#1,"); out.append(highestLineNumber); out.append(":1,1\n"); i = 2; for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) { InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next(); out.append("1#"); out.append(i++); out.append(','); out.append(element.highestLineNumber); out.append(":"); out.append(element.offset + 1); out.append(",1\n"); } // end section out.append("*E\n"); // and finish up... return out.toString(); } // ---- end JSR45-related stuff /** Emit disassembled class and newline to out */ public static void disassemble(String path, String name, PrintStream out) throws IOException { if (null == out) { return; } //out.println("classPath: " + classPath); BcelWorld world = new BcelWorld(path); LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(name))); clazz.print(out); out.println(); } public int getNewGeneratedNameTag() { return childCounter++; } // ---- public LazyClassGen( String class_name, String super_class_name, String file_name, int access_flags, String[] interfaces, World world) { myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces); constantPoolGen = myGen.getConstantPool(); fact = new InstructionFactory(myGen, constantPoolGen); regenerateGenericSignatureAttribute = true; this.world = world; } //Non child type, so it comes from a real type in the world. public LazyClassGen(BcelObjectType myType) { myGen = new ClassGen(myType.getJavaClass()); constantPoolGen = myGen.getConstantPool(); fact = new InstructionFactory(myGen, constantPoolGen); this.myType = myType; this.world = myType.getResolvedTypeX().getWorld(); /* Does this class support serialization */ if (implementsSerializable(getType())) { isSerializable = true; // ResolvedMember[] fields = getType().getDeclaredFields(); // for (int i = 0; i < fields.length; i++) { // ResolvedMember field = fields[i]; // if (field.getName().equals("serialVersionUID") // && field.isStatic() && field.getType().equals(ResolvedType.LONG)) { // hasSerialVersionUIDField = true; // } // } hasSerialVersionUIDField = hasSerialVersionUIDField(getType()); ResolvedMember[] methods = getType().getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { ResolvedMember method = methods[i]; if (method.getName().equals("<clinit>")) { hasClinit = true; } } } Method[] methods = myGen.getMethods(); for (int i = 0; i < methods.length; i++) { addMethodGen(new LazyMethodGen(methods[i], this)); } } public static boolean hasSerialVersionUIDField (ResolvedType type) { ResolvedMember[] fields = type.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { ResolvedMember field = fields[i]; if (field.getName().equals("serialVersionUID") && field.isStatic() && field.getType().equals(ResolvedType.LONG)) { return true; } } return false; } // public void addAttribute(Attribute i) { // myGen.addAttribute(i); // } // ---- public String getInternalClassName() { return getConstantPoolGen().getConstantPool().getConstantString( myGen.getClassNameIndex(), Constants.CONSTANT_Class); } public String getInternalFileName() { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) { return getFileName(); } else { return str.substring(0, index + 1) + getFileName(); } } public File getPackagePath(File root) { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) return root; return new File(root, str.substring(0, index)); } public String getClassId() { String str = getInternalClassName(); int index = str.lastIndexOf('/'); if (index == -1) return str; return str.substring(index + 1); } public void addMethodGen(LazyMethodGen gen) { //assert gen.getClassName() == super.getClassName(); methodGens.add(gen); if (highestLineNumber < gen.highestLineNumber) highestLineNumber = gen.highestLineNumber; } public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) { addMethodGen(gen); if (!gen.getMethod().isPrivate()) { warnOnAddedMethod(gen.getMethod(),sourceLocation); } } public void errorOnAddedField (Field field, ISourceLocation sourceLocation) { if (isSerializable && !hasSerialVersionUIDField) { getWorld().getLint().serialVersionUIDBroken.signal( new String[] { myType.getResolvedTypeX().getName().toString(), field.getName() }, sourceLocation, null); } } public void warnOnAddedInterface (String name, ISourceLocation sourceLocation) { warnOnModifiedSerialVersionUID(sourceLocation,"added interface " + name); } public void warnOnAddedMethod (Method method, ISourceLocation sourceLocation) { warnOnModifiedSerialVersionUID(sourceLocation,"added non-private method " + method.getName()); } public void warnOnAddedStaticInitializer (Shadow shadow, ISourceLocation sourceLocation) { if (!hasClinit) { warnOnModifiedSerialVersionUID(sourceLocation,"added static initializer"); } } public void warnOnModifiedSerialVersionUID (ISourceLocation sourceLocation, String reason) { if (isSerializable && !hasSerialVersionUIDField) getWorld().getLint().needsSerialVersionUIDField.signal( new String[] { myType.getResolvedTypeX().getName().toString(), reason }, sourceLocation, null); } public World getWorld () { return world; } public List getMethodGens() { return methodGens; //???Collections.unmodifiableList(methodGens); } // FIXME asc Should be collection returned here public Field[] getFieldGens() { return myGen.getFields(); } // FIXME asc How do the ones on the underlying class surface if this just returns new ones added? // FIXME asc ...although no one calls this right now ! public List getAnnotations() { return annotations; } private void writeBack(BcelWorld world) { if (getConstantPoolGen().getSize() > Short.MAX_VALUE) { reportClassTooBigProblem(); return; } if (annotations.size()>0) { for (Iterator iter = annotations.iterator(); iter.hasNext();) { AnnotationGen element = (AnnotationGen) iter.next(); myGen.addAnnotation(element); } // Attribute[] annAttributes = org.aspectj.apache.bcel.classfile.Utility.getAnnotationAttributes(getConstantPoolGen(),annotations); // for (int i = 0; i < annAttributes.length; i++) { // Attribute attribute = annAttributes[i]; // System.err.println("Adding attribute for "+attribute); // myGen.addAttribute(attribute); // } } // Add a weaver version attribute to the file being produced (if necessary...) boolean hasVersionAttribute = false; Attribute[] attrs = myGen.getAttributes(); for (int i = 0; i < attrs.length && !hasVersionAttribute; i++) { Attribute attribute = attrs[i]; if (attribute.getName().equals("org.aspectj.weaver.WeaverVersion")) hasVersionAttribute=true; } if (!hasVersionAttribute) myGen.addAttribute(BcelAttributes.bcelAttribute(new AjAttribute.WeaverVersionInfo(),getConstantPoolGen())); if (myType != null && myType.getWeaverState() != null) { myGen.addAttribute(BcelAttributes.bcelAttribute( new AjAttribute.WeaverState(myType.getWeaverState()), getConstantPoolGen())); } //FIXME ATAJ needed only for slow Aspects.aspectOf() - keep or remove //make a lot of test fail since the test compare weaved class file // based on some test data as text files... // if (!myGen.isInterface()) { // addAjClassField(); // } addAjcInitializers(); int len = methodGens.size(); myGen.setMethods(new Method[0]); calculateSourceDebugExtensionOffsets(); for (int i = 0; i < len; i++) { LazyMethodGen gen = (LazyMethodGen) methodGens.get(i); // we skip empty clinits if (isEmptyClinit(gen)) continue; myGen.addMethod(gen.getMethod()); } if (inlinedFiles.size() != 0) { if (hasSourceDebugExtensionAttribute(myGen)) { world.showMessage( IMessage.WARNING, WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45,getFileName()), null, null); } // 17Feb05 - ASC - Skip this for now - it crashes IBM 1.4.2 jvms (pr80430). Will be revisited when contents // of attribute are confirmed to be correct. // myGen.addAttribute(getSourceDebugExtensionAttribute()); } fixupGenericSignatureAttribute(); } /** * When working with 1.5 generics, a signature attribute is attached to the type which indicates * how it was declared. This routine ensures the signature attribute for what we are about * to write out is correct. Basically its responsibilities are: * 1. Checking whether the attribute needs changing (i.e. did weaving change the type hierarchy) * 2. If it did, removing the old attribute * 3. Check if we need an attribute at all, are we generic? are our supertypes parameterized/generic? * 4. Build the new attribute which includes all typevariable, supertype and superinterface information */ private void fixupGenericSignatureAttribute () { if (getWorld() != null && !getWorld().isInJava5Mode()) return; // TODO asc generics Temporarily assume that types we generate dont need a signature attribute (closure/etc).. will need revisiting no doubt... if (myType==null) return; // 1. Has anything changed that would require us to modify this attribute? if (!regenerateGenericSignatureAttribute) return; // 2. Find the old attribute Signature sigAttr = null; if (myType!=null) { // if null, this is a type built from scratch, it won't already have a sig attribute Attribute[] as = myGen.getAttributes(); for (int i = 0; i < as.length; i++) { Attribute attribute = as[i]; if (attribute.getName().equals("Signature")) sigAttr = (Signature)attribute; } } // 3. Do we need an attribute? boolean needAttribute = false; if (sigAttr!=null) needAttribute = true; // If we had one before, we definetly still need one as types can't be 'removed' from the hierarchy // check the interfaces if (!needAttribute) { if (myType==null) { boolean stop = true; } ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces(); for (int i = 0; i < interfaceRTXs.length; i++) { ResolvedType typeX = interfaceRTXs[i]; if (typeX.isGenericType() || typeX.isParameterizedType()) needAttribute = true; } // check the supertype ResolvedType superclassRTX = myType.getSuperclass(); if (superclassRTX.isGenericType() || superclassRTX.isParameterizedType()) needAttribute = true; } if (needAttribute) { StringBuffer signature = new StringBuffer(); // first, the type variables... TypeVariable[] tVars = myType.getTypeVariables(); if (tVars.length>0) { signature.append("<"); for (int i = 0; i < tVars.length; i++) { TypeVariable variable = tVars[i]; if (i!=0) signature.append(","); signature.append(variable.getSignature()); } signature.append(">"); } // now the supertype signature.append(myType.getSuperclass().getSignature()); ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces(); for (int i = 0; i < interfaceRTXs.length; i++) { String s = interfaceRTXs[i].getSignatureForAttribute(); signature.append(s); } myGen.addAttribute(createSignatureAttribute(signature.toString())); } // TODO asc generics The 'old' signature is left in the constant pool - I wonder how safe it would be to // remove it since we don't know what else (if anything) is referring to it } /** * Helper method to create a signature attribute based on a string signature: * e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;" */ private Signature createSignatureAttribute(String signature) { int nameIndex = constantPoolGen.addUtf8("Signature"); int sigIndex = constantPoolGen.addUtf8(signature); return new Signature(nameIndex,2,sigIndex,constantPoolGen.getConstantPool()); } /** * */ private void reportClassTooBigProblem() { // PR 59208 // we've generated a class that is just toooooooooo big (you've been generating programs // again haven't you? come on, admit it, no-one writes classes this big by hand). // create an empty myGen so that we can give back a return value that doesn't upset the // rest of the process. myGen = new ClassGen(myGen.getClassName(), myGen.getSuperclassName(), myGen.getFileName(), myGen.getAccessFlags(), myGen.getInterfaceNames()); // raise an error against this compilation unit. getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CLASS_TOO_BIG, this.getClassName()), new SourceLocation(new File(myGen.getFileName()),0), null ); } private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) { ConstantPoolGen pool = gen.getConstantPool(); Attribute[] attrs = gen.getAttributes(); for (int i = 0; i < attrs.length; i++) { if ("SourceDebugExtension" .equals(((ConstantUtf8) pool.getConstant(attrs[i].getNameIndex())).getBytes())) { return true; } } return false; } public JavaClass getJavaClass(BcelWorld world) { writeBack(world); return myGen.getJavaClass(); } public void addGeneratedInner(LazyClassGen newClass) { classGens.add(newClass); } public void addInterface(UnresolvedType typeX, ISourceLocation sourceLocation) { regenerateGenericSignatureAttribute = true; myGen.addInterface(typeX.getRawName()); if (!typeX.equals(UnresolvedType.SERIALIZABLE)) warnOnAddedInterface(typeX.getName(),sourceLocation); } public void setSuperClass(UnresolvedType typeX) { regenerateGenericSignatureAttribute = true; myGen.setSuperclassName(typeX.getName()); } public String getSuperClassname() { return myGen.getSuperclassName(); } // non-recursive, may be a bug, ha ha. private List getClassGens() { List ret = new ArrayList(); ret.add(this); ret.addAll(classGens); return ret; } public List getChildClasses(BcelWorld world) { if (classGens.isEmpty()) return Collections.EMPTY_LIST; List ret = new ArrayList(); for (Iterator i = classGens.iterator(); i.hasNext();) { LazyClassGen clazz = (LazyClassGen) i.next(); byte[] bytes = clazz.getJavaClass(world).getBytes(); String name = clazz.getName(); int index = name.lastIndexOf('$'); // XXX this could be bad, check use of dollar signs. name = name.substring(index+1); ret.add(new UnwovenClassFile.ChildClass(name, bytes)); } return ret; } public String toString() { return toShortString(); } public String toShortString() { String s = org.aspectj.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true); if (s != "") s += " "; s += org.aspectj.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags()); s += " "; s += myGen.getClassName(); return s; } public String toLongString() { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s)); return new String(s.toByteArray()); } public void print() { print(System.out); } public void print(PrintStream out) { List classGens = getClassGens(); for (Iterator iter = classGens.iterator(); iter.hasNext();) { LazyClassGen element = (LazyClassGen) iter.next(); element.printOne(out); if (iter.hasNext()) out.println(); } } private void printOne(PrintStream out) { out.print(toShortString()); out.print(" extends "); out.print( org.aspectj.apache.bcel.classfile.Utility.compactClassName( myGen.getSuperclassName(), false)); int size = myGen.getInterfaces().length; if (size > 0) { out.print(" implements "); for (int i = 0; i < size; i++) { out.print(myGen.getInterfaceNames()[i]); if (i < size - 1) out.print(", "); } } out.print(":"); out.println(); // XXX make sure to pass types correctly around, so this doesn't happen. if (myType != null) { myType.printWackyStuff(out); } Field[] fields = myGen.getFields(); for (int i = 0, len = fields.length; i < len; i++) { out.print(" "); out.println(fields[i]); } List methodGens = getMethodGens(); for (Iterator iter = methodGens.iterator(); iter.hasNext();) { LazyMethodGen gen = (LazyMethodGen) iter.next(); // we skip empty clinits if (isEmptyClinit(gen)) continue; gen.print(out, (myType != null ? myType.getWeaverVersionAttribute() : WeaverVersionInfo.UNKNOWN)); if (iter.hasNext()) out.println(); } // out.println(" ATTRIBS: " + Arrays.asList(myGen.getAttributes())); out.println("end " + toShortString()); } private boolean isEmptyClinit(LazyMethodGen gen) { if (!gen.getName().equals("<clinit>")) return false; //System.err.println("checking clinig: " + gen); InstructionHandle start = gen.getBody().getStart(); while (start != null) { if (Range.isRangeHandle(start) || (start.getInstruction() instanceof RETURN)) { start = start.getNext(); } else { return false; } } return true; } public ConstantPoolGen getConstantPoolGen() { return constantPoolGen; } public String getName() { return myGen.getClassName(); } public boolean isWoven() { return myType.getWeaverState() != null; } public boolean isReweavable() { if (myType.getWeaverState()==null) return false; return myType.getWeaverState().isReweavable(); } public Set getAspectsAffectingType() { if (myType.getWeaverState()==null) return null; return myType.getWeaverState().getAspectsAffectingType(); } public WeaverStateInfo getOrCreateWeaverStateInfo() { WeaverStateInfo ret = myType.getWeaverState(); if (ret != null) return ret; ret = new WeaverStateInfo(); myType.setWeaverState(ret); return ret; } public InstructionFactory getFactory() { return fact; } public LazyMethodGen getStaticInitializer() { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals("<clinit>")) return gen; } LazyMethodGen clinit = new LazyMethodGen( Modifier.STATIC, Type.VOID, "<clinit>", new Type[0], CollectionUtil.NO_STRINGS, this); clinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(clinit); return clinit; } public LazyMethodGen getAjcPreClinit() { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(NameMangler.AJC_PRE_CLINIT_NAME)) return gen; } LazyMethodGen ajcClinit = new LazyMethodGen( Modifier.STATIC, Type.VOID, NameMangler.AJC_PRE_CLINIT_NAME, new Type[0], CollectionUtil.NO_STRINGS, this); ajcClinit.getBody().insert(InstructionConstants.RETURN); methodGens.add(ajcClinit); getStaticInitializer().getBody().insert(Utility.createInvoke(getFactory(), ajcClinit)); return ajcClinit; } // reflective thisJoinPoint support Map/*BcelShadow, Field*/ tjpFields = new HashMap(); public static final ObjectType proceedingTjpType = new ObjectType("org.aspectj.lang.ProceedingJoinPoint"); public static final ObjectType tjpType = new ObjectType("org.aspectj.lang.JoinPoint"); public static final ObjectType staticTjpType = new ObjectType("org.aspectj.lang.JoinPoint$StaticPart"); public static final ObjectType enclosingStaticTjpType = new ObjectType("org.aspectj.lang.JoinPoint$EnclosingStaticPart"); private static final ObjectType sigType = new ObjectType("org.aspectj.lang.Signature"); // private static final ObjectType slType = // new ObjectType("org.aspectj.lang.reflect.SourceLocation"); private static final ObjectType factoryType = new ObjectType("org.aspectj.runtime.reflect.Factory"); private static final ObjectType classType = new ObjectType("java.lang.Class"); public Field getTjpField(BcelShadow shadow, final boolean isEnclosingJp) { Field ret = (Field)tjpFields.get(shadow); if (ret != null) return ret; int modifiers = Modifier.STATIC | Modifier.FINAL; // XXX - Do we ever inline before or after advice? If we do, then we // better include them in the check below. (or just change it to // shadow.getEnclosingMethod().getCanInline()) // If the enclosing method is around advice, we could inline the join point // that has led to this shadow. If we do that then the TJP we are creating // here must be PUBLIC so it is visible to the type in which the // advice is inlined. (PR71377) LazyMethodGen encMethod = shadow.getEnclosingMethod(); boolean shadowIsInAroundAdvice = false; if (encMethod!=null && encMethod.getName().startsWith(NameMangler.PREFIX+"around")) { shadowIsInAroundAdvice = true; } if (getType().isInterface() || shadowIsInAroundAdvice) { modifiers |= Modifier.PUBLIC; } else { modifiers |= Modifier.PRIVATE; } ret = new FieldGen(modifiers, isEnclosingJp?enclosingStaticTjpType:staticTjpType, "ajc$tjp_" + tjpFields.size(), getConstantPoolGen()).getField(); addField(ret); tjpFields.put(shadow, ret); return ret; } //FIXME ATAJ needed only for slow Aspects.aspectOf - keep or remove // private void addAjClassField() { // // Andy: Why build it again?? // Field ajClassField = new FieldGen( // Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, // classType, // "aj$class", // getConstantPoolGen()).getField(); // addField(ajClassField); // // InstructionList il = new InstructionList(); // il.append(new PUSH(getConstantPoolGen(), getClassName())); // il.append(fact.createInvoke("java.lang.Class", "forName", classType, // new Type[] {Type.STRING}, Constants.INVOKESTATIC)); // il.append(fact.createFieldAccess(getClassName(), ajClassField.getName(), // classType, Constants.PUTSTATIC)); // // getStaticInitializer().getBody().insert(il); // } private void addAjcInitializers() { if (tjpFields.size() == 0) return; InstructionList il = initializeAllTjps(); getStaticInitializer().getBody().insert(il); } private InstructionList initializeAllTjps() { InstructionList list = new InstructionList(); InstructionFactory fact = getFactory(); // make a new factory list.append(fact.createNew(factoryType)); list.append(InstructionFactory.createDup(1)); list.append(new PUSH(getConstantPoolGen(), getFileName())); // load the current Class object //XXX check that this works correctly for inners/anonymous list.append(new PUSH(getConstantPoolGen(), getClassName())); //XXX do we need to worry about the fact the theorectically this could throw //a ClassNotFoundException list.append(fact.createInvoke("java.lang.Class", "forName", classType, new Type[] {Type.STRING}, Constants.INVOKESTATIC)); list.append(fact.createInvoke(factoryType.getClassName(), "<init>", Type.VOID, new Type[] {Type.STRING, classType}, Constants.INVOKESPECIAL)); list.append(InstructionFactory.createStore(factoryType, 0)); List entries = new ArrayList(tjpFields.entrySet()); Collections.sort(entries, new Comparator() { public int compare(Object a, Object b) { Map.Entry ae = (Map.Entry) a; Map.Entry be = (Map.Entry) b; return ((Field) ae.getValue()) .getName() .compareTo(((Field)be.getValue()).getName()); } }); for (Iterator i = entries.iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry)i.next(); initializeTjp(fact, list, (Field)entry.getValue(), (BcelShadow)entry.getKey()); } return list; } private void initializeTjp(InstructionFactory fact, InstructionList list, Field field, BcelShadow shadow) { Member sig = shadow.getSignature(); //ResolvedMember mem = shadow.getSignature().resolve(shadow.getWorld()); // load the factory list.append(InstructionFactory.createLoad(factoryType, 0)); // load the kind list.append(new PUSH(getConstantPoolGen(), shadow.getKind().getName())); // create the signature list.append(InstructionFactory.createLoad(factoryType, 0)); if (sig.getKind().equals(Member.METHOD)) { BcelWorld w = shadow.getWorld(); // For methods, push the parts of the signature on. list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w)))); list.append(new PUSH(getConstantPoolGen(),sig.getName())); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getReturnType()))); // And generate a call to the variant of makeMethodSig() that takes 7 strings list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING }, Constants.INVOKEVIRTUAL)); } else if (sig.getKind().equals(Member.HANDLER)) { BcelWorld w = shadow.getWorld(); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w)))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING, Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else if(sig.getKind().equals(Member.CONSTRUCTOR)) { BcelWorld w = shadow.getWorld(); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w)))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else if(sig.getKind().equals(Member.FIELD)) { BcelWorld w = shadow.getWorld(); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w)))); list.append(new PUSH(getConstantPoolGen(),sig.getName())); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getReturnType()))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else if(sig.getKind().equals(Member.ADVICE)) { BcelWorld w = shadow.getWorld(); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w)))); list.append(new PUSH(getConstantPoolGen(),sig.getName())); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes()))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w)))); list.append(new PUSH(getConstantPoolGen(),makeString((sig.getReturnType())))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else if(sig.getKind().equals(Member.STATIC_INITIALIZATION)) { BcelWorld w = shadow.getWorld(); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w)))); list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType()))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING, Type.STRING }, Constants.INVOKEVIRTUAL)); } else { list.append(new PUSH(getConstantPoolGen(), sig.getSignatureString(shadow.getWorld()))); list.append(fact.createInvoke(factoryType.getClassName(), sig.getSignatureMakerName(), new ObjectType(sig.getSignatureType()), new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL)); } //XXX should load source location from shadow list.append(Utility.createConstant(fact, shadow.getSourceLine())); final String factoryMethod; if (staticTjpType.equals(field.getType())) { factoryMethod = "makeSJP"; } else if (enclosingStaticTjpType.equals(field.getType())) { factoryMethod = "makeESJP"; } else { throw new Error("should not happen"); } list.append(fact.createInvoke(factoryType.getClassName(), factoryMethod, field.getType(), new Type[] { Type.STRING, sigType, Type.INT}, Constants.INVOKEVIRTUAL)); // put it in the field list.append(fact.createFieldAccess(getClassName(), field.getName(), field.getType(), Constants.PUTSTATIC)); } protected String makeString(int i) { return Integer.toString(i, 16); //??? expensive } protected String makeString(UnresolvedType t) { // this is the inverse of the odd behavior for Class.forName w/ arrays if (t.isArray()) { // this behavior matches the string used by the eclipse compiler for Foo.class literals return t.getSignature().replace('/', '.'); } else { return t.getName(); } } protected String makeString(UnresolvedType[] types) { if (types == null) return ""; StringBuffer buf = new StringBuffer(); for (int i = 0, len=types.length; i < len; i++) { buf.append(makeString(types[i])); buf.append(':'); } return buf.toString(); } protected String makeString(String[] names) { if (names == null) return ""; StringBuffer buf = new StringBuffer(); for (int i = 0, len=names.length; i < len; i++) { buf.append(names[i]); buf.append(':'); } return buf.toString(); } public ResolvedType getType() { if (myType == null) return null; return myType.getResolvedTypeX(); } public BcelObjectType getBcelObjectType() { return myType; } public String getFileName() { return myGen.getFileName(); } private void addField(Field field) { myGen.addField(field); } public void replaceField(Field oldF, Field newF){ myGen.removeField(oldF); myGen.addField(newF); } public void addField(Field field, ISourceLocation sourceLocation) { addField(field); if (!(field.isPrivate() && (field.isStatic() || field.isTransient()))) { errorOnAddedField(field,sourceLocation); } } public String getClassName() { return myGen.getClassName(); } public boolean isInterface() { return myGen.isInterface(); } public boolean isAbstract() { return myGen.isAbstract(); } public LazyMethodGen getLazyMethodGen(Member m) { return getLazyMethodGen(m.getName(), m.getSignature(),false); } public LazyMethodGen getLazyMethodGen(String name, String signature) { return getLazyMethodGen(name,signature,false); } public LazyMethodGen getLazyMethodGen(String name, String signature,boolean allowMissing) { for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(name) && gen.getSignature().equals(signature)) return gen; } if (!allowMissing) { throw new BCException("Class " + this.getName() + " does not have a method " + name + " with signature " + signature); } return null; } public void forcePublic() { myGen.setAccessFlags(Utility.makePublic(myGen.getAccessFlags())); } public boolean hasAnnotation(UnresolvedType t) { // annotations on the real thing AnnotationGen agens[] = myGen.getAnnotations(); if (agens==null) return false; for (int i = 0; i < agens.length; i++) { AnnotationGen gen = agens[i]; if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) return true; } // annotations added during this weave return false; } public void addAnnotation(Annotation a) { if (!hasAnnotation(UnresolvedType.forSignature(a.getTypeSignature()))) { annotations.add(new AnnotationGen(a,getConstantPoolGen(),true)); } } // this test is like asking: // if (UnresolvedType.SERIALIZABLE.resolve(getType().getWorld()).isAssignableFrom(getType())) { // only we don't do that because this forces us to find all the supertypes of the type, // and if one of them is missing we fail, and it's not worth failing just to put out // a warning message! private boolean implementsSerializable(ResolvedType aType) { ResolvedType[] interfaces = aType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].getSignature().equals(UnresolvedType.SERIALIZABLE.getSignature())) { return true; } else { if (interfaces[i].isMissing()) continue; ResolvedType superInterface = interfaces[i].getSuperclass(); if (superInterface != null && !superInterface.isMissing()) { if (implementsSerializable(superInterface)) return true; } } } ResolvedType superType = aType.getSuperclass(); if (superType != null && !superType.isMissing()) { return implementsSerializable(superType); } return false; } }
92,837
Bug 92837 [inc-compilation] Incremental Compilation Fails for ITD's on Aspects
On my project, when I save an aspect that calls an inter-type declaration defined on itself, the incremental compiler gives a message like this: The method logError(String, Exception) is undefined for the type Foo Foo.java Running a full build clears the error. This might be a compiler bug, or it might be AJDT (I never run command-line incremental compilation, so I don't know :-)). Unfortunately, simple test cases or extracts of just the 2 aspects aren't reproducing the issue, so let me know if you need me to spend some time trying to create a small isolated version of the issue.
resolved fixed
727b0f5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T14:01:43Z
2005-04-26T21:13:20Z
tests/multiIncremental/PR92837/base/sample/AbstractDerived.java
92,837
Bug 92837 [inc-compilation] Incremental Compilation Fails for ITD's on Aspects
On my project, when I save an aspect that calls an inter-type declaration defined on itself, the incremental compiler gives a message like this: The method logError(String, Exception) is undefined for the type Foo Foo.java Running a full build clears the error. This might be a compiler bug, or it might be AJDT (I never run command-line incremental compilation, so I don't know :-)). Unfortunately, simple test cases or extracts of just the 2 aspects aren't reproducing the issue, so let me know if you need me to spend some time trying to create a small isolated version of the issue.
resolved fixed
727b0f5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T14:01:43Z
2005-04-26T21:13:20Z
tests/multiIncremental/PR92837/base/sample/Holder.java
92,837
Bug 92837 [inc-compilation] Incremental Compilation Fails for ITD's on Aspects
On my project, when I save an aspect that calls an inter-type declaration defined on itself, the incremental compiler gives a message like this: The method logError(String, Exception) is undefined for the type Foo Foo.java Running a full build clears the error. This might be a compiler bug, or it might be AJDT (I never run command-line incremental compilation, so I don't know :-)). Unfortunately, simple test cases or extracts of just the 2 aspects aren't reproducing the issue, so let me know if you need me to spend some time trying to create a small isolated version of the issue.
resolved fixed
727b0f5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T14:01:43Z
2005-04-26T21:13:20Z
tests/multiIncremental/PR92837/inc1/sample/AbstractDerived.java
92,837
Bug 92837 [inc-compilation] Incremental Compilation Fails for ITD's on Aspects
On my project, when I save an aspect that calls an inter-type declaration defined on itself, the incremental compiler gives a message like this: The method logError(String, Exception) is undefined for the type Foo Foo.java Running a full build clears the error. This might be a compiler bug, or it might be AJDT (I never run command-line incremental compilation, so I don't know :-)). Unfortunately, simple test cases or extracts of just the 2 aspects aren't reproducing the issue, so let me know if you need me to spend some time trying to create a small isolated version of the issue.
resolved fixed
727b0f5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T14:01:43Z
2005-04-26T21:13:20Z
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.systemtest.incremental.tools; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.aspectj.ajdt.internal.core.builder.AjState; import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.testing.util.FileUtil; /** * The superclass knows all about talking through Ajde to the compiler. * The superclass isn't in charge of knowing how to simulate overlays * for incremental builds, that is in here. As is the ability to * generate valid build configs based on a directory structure. To * support this we just need access to a sandbox directory - this * sandbox is managed by the superclass (it only assumes all builds occur * in <sandboxDir>/<projectName>/ ) * * The idea is you can initialize multiple projects in the sandbox and * they can all be built independently, hopefully exploiting * incremental compilation. Between builds you can alter the contents * of a project using the alter() method that overlays some set of * new files onto the current set (adding new files/changing existing * ones) - you can then drive a new build and check it behaves as * expected. */ public class MultiProjectIncrementalTests extends AjdeInteractionTestbed { private static boolean VERBOSE = false; protected void setUp() throws Exception { super.setUp(); } // Compile a single simple project public void testTheBasics() { initialiseProject("P1"); build("P1"); // This first build will be batch build("P1"); checkWasntFullBuild(); checkCompileWeaveCount(0,0); } // Make simple changes to a project, adding a class public void testSimpleChanges() { initialiseProject("P1"); build("P1"); // This first build will be batch alter("P1","inc1"); // adds a single class build("P1"); checkCompileWeaveCount(1,-1); build("P1"); checkCompileWeaveCount(0,-1); } // Make simple changes to a project, adding a class and an aspect public void testAddingAnAspect() { initialiseProject("P1"); build("P1"); alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); long timeTakenForFullBuildAndWeave = getTimeTakenForBuild(); checkWasntFullBuild(); checkCompileWeaveCount(2,3); build("P1"); long timeTakenForSimpleIncBuild = getTimeTakenForBuild(); // I don't think this test will have timing issues as the times should be *RADICALLY* different // On my config, first build time is 2093ms and the second is 30ms assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+ "ms second="+timeTakenForSimpleIncBuild+"ms", timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave); } public void testBuildingTwoProjectsInTurns() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); } /** * In order for this next test to run, I had to move the weaver/world pair we keep in the * AjBuildManager instance down into the state object - this makes perfect sense - otherwise * when reusing the state for another project we'd not be switching to the right weaver/world * for that project. */ public void testBuildingTwoProjectsMakingSmallChanges() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); checkWasntFullBuild(); } /** * Setup up two simple projects and build them in turn - check the * structure model is right after each build */ public void testBuildingTwoProjectsAndVerifyingModel() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } // Setup up two simple projects and build them in turn - check the // structure model is right after each build public void testBuildingTwoProjectsAndVerifyingStuff() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, adding a new method and check structural changes is 1. */ public void testStateManagement1() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be a state object for project P1",ajs!=null); assertTrue("Should be no structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc3"); // adds a method to the class C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Should be one structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, changing body of a method, not the structure and * check struc changes is still 0. */ public void testStateManagement2() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making // it a structural change build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be state for project P1",ajs!=null); assertTrue("Should be no struc changes as its a full build: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); } /** * Now the most complex test. Create a dependancy between two projects. Building * one may affect whether the other does an incremental or full build. The * structural information recorded in the state object should be getting used * to control whether a full build is necessary... */ public void testBuildingDependantProjects() { initialiseProject("P1"); initialiseProject("P2"); configureNewProjectDependency("P2","P1"); build("P1"); build("P2"); // now everything is consistent and compiled alter("P1","inc1"); // adds a second class build("P1"); build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :) checkWasntFullBuild(); alter("P1","inc3"); // structurally changes one of the classes build("P1"); build("P2"); // build notices the structural change checkWasFullBuild(); alter("P1","inc4"); build("P1"); build("P2"); // build sees a change but works out its not structural checkWasntFullBuild(); } // other possible tests: // - memory usage (freemem calls?) // - relationship map // public void testPr85132() { // super.VERBOSE=true; // initialiseProject("PR85132"); // build("PR85132"); // alter("PR85132","inc1"); // build("PR85132"); // } // --------------------------------------------------------------------------------------------------- /** * Check we compiled/wove the right number of files, passing '-1' indicates you don't care about * that number. */ private void checkCompileWeaveCount(int expCompile,int expWoven) { if (expCompile!=-1 && getCompiledFiles().size()!=expCompile) fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+ "\n"+printCompiledAndWovenFiles()); if (expWoven!=-1 && getWovenClasses().size()!=expWoven) fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+ "\n"+printCompiledAndWovenFiles()); } private void checkWasntFullBuild() { assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild()); } private void checkWasFullBuild() { assertTrue("Should have been a full (batch) build",wasFullBuild()); } private void checkForNode(String packageName,String typeName,boolean shouldBeFound) { IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName); if (shouldBeFound) { if (ipe==null) printModel(); assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null); } else { if (ipe!=null) printModel(); assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null); } } private void printModel() { try { AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0); } catch (IOException e) { e.printStackTrace(); } } public void build(String projectName) { constructUpToDateLstFile(projectName,"build.lst"); build(projectName,"build.lst"); if (AjdeInteractionTestbed.VERBOSE) printBuildReport(); } private void constructUpToDateLstFile(String pname,String configname) { File projectBase = new File(sandboxDir,pname); File toConstruct = new File(projectBase,configname); List filesForCompilation = new ArrayList(); collectUpFiles(projectBase,projectBase,filesForCompilation); try { FileOutputStream fos = new FileOutputStream(toConstruct); DataOutputStream dos = new DataOutputStream(fos); for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) { String file = (String) iter.next(); dos.writeBytes(file+"\n"); } dos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } private void collectUpFiles(File location,File base,List collectionPoint) { String contents[] = location.list(); if (contents==null) return; for (int i = 0; i < contents.length; i++) { String string = contents[i]; File f = new File(location,string); if (f.isDirectory()) { collectUpFiles(f,base,collectionPoint); } else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) { String fileFound; try { fileFound = f.getCanonicalPath(); String toRemove = base.getCanonicalPath(); if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove); collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator } catch (IOException e) { e.printStackTrace(); } } } } /** * Fill in the working directory with the project base files, * from the 'base' folder. */ private void initialiseProject(String p) { File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base"); File destination=new File(getWorkingDir(),p); if (!destination.exists()) {destination.mkdir();} copy(projectSrc,destination);//,false); } /* * Applies an overlay onto the project being tested - copying * the contents of the specified overlay directory. */ private void alter(String projectName,String overlayDirectory) { File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+ File.separatorChar+overlayDirectory); File destination=new File(getWorkingDir(),projectName); copy(projectSrc,destination); } /** * Copy the contents of some directory to another location - the * copy is recursive. */ private void copy(File from, File to) { String contents[] = from.list(); if (contents==null) return; for (int i = 0; i < contents.length; i++) { String string = contents[i]; File f = new File(from,string); File t = new File(to,string); if (f.isDirectory() && !f.getName().startsWith("inc")) { t.mkdir(); copy(f,t); } else if (f.isFile()) { StringBuffer sb = new StringBuffer(); //if (VERBOSE) System.err.println("Copying "+f+" to "+t); FileUtil.copyFile(f,t,sb); if (sb.length()!=0) { System.err.println(sb.toString());} } } } private static void log(String msg) { if (VERBOSE) System.out.println(msg); } }
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/src/org/aspectj/tools/ajdoc/HtmlDecorator.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.*; import java.util.*; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; /** * @author Mik Kersten */ class HtmlDecorator { static List visibleFileList = new ArrayList(); static Hashtable declIDTable = null; static SymbolManager symbolManager = null; static File rootDir = null; static String docVisibilityModifier; static void decorateHTMLFromInputFiles(Hashtable table, File newRootDir, SymbolManager sm, File[] inputFiles, String docModifier ) throws IOException { rootDir = newRootDir; declIDTable = table; symbolManager = sm; docVisibilityModifier = docModifier; for (int i = 0; i < inputFiles.length; i++) { decorateHTMLFromDecls(symbolManager.getDeclarations(inputFiles[i].getCanonicalPath()), rootDir.getCanonicalPath() + Config.DIR_SEP_CHAR, docModifier, false); } } static void decorateHTMLFromDecls(Declaration[] decls, String base, String docModifier, boolean exceededNestingLevel) throws IOException { if ( decls != null ) { for (int i = 0; i < decls.length; i++) { Declaration decl = decls[i]; decorateHTMLFromDecl(decl, base, docModifier, exceededNestingLevel); } } } /** * Before attempting to decorate the HTML file we have to verify that it exists, * which depends on the documentation visibility specified to c. * * Depending on docModifier, can document * - public: only public * - protected: protected and public (default) * - package: package protected and public * - private: everything */ static void decorateHTMLFromDecl(Declaration decl, String base, String docModifier, boolean exceededNestingLevel ) throws IOException { boolean nestedClass = false; if ( decl.isType() ) { boolean decorateFile = true; if (isAboveVisibility(decl.getNode())) { visibleFileList.add(decl.getSignature()); String packageName = decl.getPackageName(); String filename = ""; if ( packageName != null ) { int index1 = base.lastIndexOf(Config.DIR_SEP_CHAR); int index2 = base.lastIndexOf("."); String currFileClass = ""; if (index1 > -1 && index2 > 0 && index1 < index2) { currFileClass = base.substring(index1+1, index2); } // XXX only one level of nexting if (currFileClass.equals(decl.getDeclaringType())) { nestedClass = true; packageName = packageName.replace( '.','/' ); String newBase = ""; if ( base.lastIndexOf(Config.DIR_SEP_CHAR) > 0 ) { newBase = base.substring(0, base.lastIndexOf(Config.DIR_SEP_CHAR)); } String signature = constructNestedTypeName(decl.getNode()); filename = newBase + Config.DIR_SEP_CHAR + packageName + Config.DIR_SEP_CHAR + currFileClass + //"." + signature + ".html"; } else { packageName = packageName.replace( '.','/' ); filename = base + packageName + Config.DIR_SEP_CHAR + decl.getSignature() + ".html"; } } else { filename = base + decl.getSignature() + ".html"; } if (!exceededNestingLevel) { decorateHTMLFile(new File(filename)); decorateHTMLFromDecls(decl.getDeclarations(), base + decl.getSignature() + ".", docModifier, nestedClass); } else { System.out.println("Warning: can not generate documentation for nested " + "inner class: " + decl.getSignature() ); } } } } private static String constructNestedTypeName(IProgramElement node) { if (node.getParent().getKind().isSourceFile()) { return node.getName(); } else { String nodeName = ""; if (node.getKind().isType()) nodeName += '.' + node.getName(); return constructNestedTypeName(node.getParent()) + nodeName; } } /** * Skips files that are public in the model but not public in the source, * e.g. nested aspects. */ static void decorateHTMLFile(File file) throws IOException { if (!file.exists()) return; System.out.println( "> Decorating " + file.getCanonicalPath() + "..." ); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuffer fileContents = new StringBuffer(); String line = reader.readLine(); while( line != null ) { fileContents.append(line + "\n"); line = reader.readLine(); } boolean isSecond = false; int index = 0; IProgramElement decl; while ( true ) { //---this next part is an inlined procedure that returns two values--- //---the next declaration and the index at which that declaration's--- //---DeclID sits in the .html file --- String contents = fileContents.toString(); int start = contents.indexOf( Config.DECL_ID_STRING, index); int end = contents.indexOf( Config.DECL_ID_TERMINATOR, index ); if ( start == -1 ) decl = null; else if ( end == -1 ) throw new Error("Malformed DeclID."); else { String tid = contents.substring(start + Config.DECL_ID_STRING.length(), end); decl = (IProgramElement)declIDTable.get(tid); index = start; } //--- --- //--- --- if ( decl == null ) break; fileContents.delete(start, end + Config.DECL_ID_TERMINATOR.length()); if ( decl.getKind().isType() ) { isSecond = true; // addIntroductionDocumentation(decl, fileContents, index); // addAdviceDocumentation(decl, fileContents, index); // addPointcutDocumentation(decl, fileContents, index); addAspectDocumentation(decl, fileContents, index); } else { decorateMemberDocumentation(decl, fileContents, index); } } // Change "Class" to "Aspect" // HACK: depends on matching presence of advice or pointcut summary int classStartIndex = fileContents.toString().indexOf("<BR>\nClass "); int pointcutSummaryIndex = fileContents.toString().indexOf("Pointcut Summary"); int adviceSummaryIndex = fileContents.toString().indexOf("Advice Summary"); if (classStartIndex != -1 && (adviceSummaryIndex != -1 || pointcutSummaryIndex != -1)) { int classEndIndex = fileContents.toString().indexOf("</H2>", classStartIndex); if (classStartIndex != -1 && classEndIndex != -1) { String classLine = fileContents.toString().substring(classStartIndex, classEndIndex); String aspectLine = "<BR>\n" + "Aspect " + classLine.substring(11, classLine.length()); fileContents.delete(classStartIndex, classEndIndex); fileContents.insert(classStartIndex, aspectLine); } } file.delete(); FileOutputStream fos = new FileOutputStream( file ); fos.write( fileContents.toString().getBytes() ); } static void addAspectDocumentation(IProgramElement node, StringBuffer fileBuffer, int index ) { List pointcuts = new ArrayList(); List advice = new ArrayList(); for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { IProgramElement member = (IProgramElement)it.next(); if (member.getKind().equals(IProgramElement.Kind.POINTCUT)) { pointcuts.add(member); } else if (member.getKind().equals(IProgramElement.Kind.ADVICE)) { advice.add(member); } } if (pointcuts.size() > 0) { insertDeclarationsSummary(fileBuffer, pointcuts, "Pointcut Summary", index); insertDeclarationsDetails(fileBuffer, pointcuts, "Pointcut Detail", index); } if (advice.size() > 0) { insertDeclarationsSummary(fileBuffer, advice, "Advice Summary", index); insertDeclarationsDetails(fileBuffer, advice, "Advice Detail", index); } } // static void addIntroductionDocumentation(IProgramElement decl, // StringBuffer fileBuffer, // int index ) { // Declaration[] introductions = decl.getIntroductionDeclarations(); // if ( introductions.length > 0 ) { // insertDeclarationsSummary(fileBuffer, // introductions, // "Introduction Summary", // index); // insertDeclarationsDetails(fileBuffer, // introductions, // "Introduction Detail", // index); // } // } static void insertDeclarationsSummary(StringBuffer fileBuffer, List decls, String kind, int index) { if (!declsAboveVisibilityExist(decls)) return; int insertIndex = findSummaryIndex(fileBuffer, index); // insert the head of the table String tableHead = "<!-- ======== " + kind.toUpperCase() + " ======= -->\n\n" + "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"1\"" + "CELLSPACING=\"0\"><TR><TD COLSPAN=2 BGCOLOR=\"#CCCCFF\">" + "<FONT SIZE=\"+2\"><B>" + kind + "</B></FONT></TD></TR>\n"; fileBuffer.insert(insertIndex, tableHead); insertIndex += tableHead.length(); // insert the body of the table for ( int i = 0; i < decls.size(); i++ ) { IProgramElement decl = (IProgramElement)decls.get(i); if (isAboveVisibility(decl)) { // insert the table row accordingly String comment = generateSummaryComment(decl); String entry = ""; if ( kind.equals( "Advice Summary" ) ) { entry += "<TR><TD>" + "<A HREF=\"#" + generateHREFName(decl) + "\">" + "<TT>" + generateAdviceSignatures(decl) + "</TT></A><BR>&nbsp;"; if (!comment.equals("")) { entry += comment + "<P>"; } entry += generateAffects(decl, false) + "</TD>" + "</TR><TD>\n"; } else if ( kind.equals( "Pointcut Summary" ) ) { entry += "<TR><TD WIDTH=\"1%\">" + "<FONT SIZE=-1><TT>" + genAccessibility(decl) + "</TT></FONT>" + "</TD>\n" + "<TD>" + "<TT><A HREF=\"#" + generateHREFName(decl) + "\">" + decl.toLabelString() + "</A></TT><BR>&nbsp;"; if (!comment.equals("")) { entry += comment + "<P>"; } entry += "</TR></TD>\n"; } else if ( kind.equals( "Introduction Summary" ) ) { entry += "<TR><TD WIDTH=\"1%\">" + "<FONT SIZE=-1><TT>" + decl.getModifiers() + "</TT></FONT>" + "</TD>" + "<TD>" + "<A HREF=\"#" + generateHREFName(decl) + "\">" + "<TT>introduction " + decl.toLabelString() + "</TT></A><P>" + generateIntroductionSignatures(decl, false) + generateAffects(decl, true); } // insert the entry fileBuffer.insert(insertIndex, entry); insertIndex += entry.length(); } } // insert the end of the table String tableTail = "</TABLE><P>&nbsp;\n"; fileBuffer.insert(insertIndex, tableTail); insertIndex += tableTail.length(); } private static boolean declsAboveVisibilityExist(List decls) { boolean exist = false; for (Iterator it = decls.iterator(); it.hasNext();) { IProgramElement element = (IProgramElement) it.next(); if (isAboveVisibility(element)) exist = true; } return exist; } private static boolean isAboveVisibility(IProgramElement element) { return (docVisibilityModifier.equals("private")) || // everything (docVisibilityModifier.equals("package") && element.getAccessibility().equals(IProgramElement.Accessibility.PACKAGE)) || // package (docVisibilityModifier.equals("protected") && (element.getAccessibility().equals(IProgramElement.Accessibility.PROTECTED) || element.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC))) || (docVisibilityModifier.equals("public") && element.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)); } private static String genAccessibility(IProgramElement decl) { if (decl.getAccessibility().equals(IProgramElement.Accessibility.PACKAGE)) { return "(package private)"; } else { return decl.getAccessibility().toString(); } } static void insertDeclarationsDetails(StringBuffer fileBuffer, List decls, String kind, int index) { if (!declsAboveVisibilityExist(decls)) return; int insertIndex = findDetailsIndex(fileBuffer, index); // insert the table heading String detailsHeading = "<P>&nbsp;\n" + "<!-- ======== " + kind.toUpperCase() + " SUMMARY ======= -->\n\n" + "<TABLE BORDER=\"1\" CELLPADDING=\"3\" CELLSPACING=\"0\" WIDTH=\"100%\">\n" + "<TR BGCOLOR=\"#CCCCFF\" CLASS=\"TableHeadingColor\">\n" + "<TD COLSPAN=1><FONT SIZE=\"+2\">\n" + "<B>" + kind + "</B></FONT></TD>\n" + "</TR>\n" + "</TABLE>"; fileBuffer.insert(insertIndex, detailsHeading); insertIndex += detailsHeading.length(); // insert the details for ( int i = 0; i < decls.size(); i++ ) { IProgramElement decl = (IProgramElement)decls.get(i); if (isAboveVisibility(decl)) { String entry = ""; // insert the table row accordingly entry += "<A NAME=\"" + generateHREFName(decl) + "\"><!-- --></A>\n"; if ( kind.equals( "Advice Detail" ) ) { entry += "<H3>" + decl.getName() + "</H3><P>"; entry += "<TT>" + generateAdviceSignatures(decl) + "</TT>\n" + "<P>" + generateDetailsComment(decl) + "<P>" + generateAffects(decl, false); } else if (kind.equals("Pointcut Detail")) { entry += "<H3>" + decl.toLabelString() + "</H3><P>" + generateDetailsComment(decl); } else if (kind.equals("Introduction Detail")) { entry += "<H3>introduction " + decl.toLabelString() + "</H3><P>"; entry += generateIntroductionSignatures(decl, true) + generateAffects(decl, true) + generateDetailsComment(decl); } // insert the entry if (i != decls.size()-1) { entry += "<P><HR>\n"; } else { entry += "<P>"; } fileBuffer.insert(insertIndex, entry); insertIndex += entry.length(); } } } /** * TODO: don't place the summary first. */ static int findSummaryIndex(StringBuffer fileBuffer, int index) { String fbs = fileBuffer.toString(); String MARKER_1 = "<!-- =========== FIELD SUMMARY =========== -->"; String MARKER_2 = "<!-- ======== CONSTRUCTOR SUMMARY ======== -->"; int index1 = fbs.indexOf(MARKER_1, index); int index2 = fbs.indexOf(MARKER_2, index); if (index1 < index2 && index1 != -1) { return index1; } else if (index2 != -1){ return index2; } else { return index; } } static int findDetailsIndex(StringBuffer fileBuffer, int index) { String fbs = fileBuffer.toString(); String MARKER_1 = "<!-- ========= CONSTRUCTOR DETAIL ======== -->"; String MARKER_2 = "<!-- ============ FIELD DETAIL =========== -->"; String MARKER_3 = "<!-- ============ METHOD DETAIL ========== -->"; int index1 = fbs.indexOf(MARKER_1, index); int index2 = fbs.indexOf(MARKER_2, index); int index3 = fbs.indexOf(MARKER_3, index); if (index1 != -1 && index1 < index2 && index1 < index3) { return index1; } else if (index2 != -1 && index2 < index1 && index2 < index3) { return index2; } else if (index3 != -1) { return index3; } else { return index; } } static void decorateMemberDocumentation(IProgramElement node, StringBuffer fileContentsBuffer, int index ) { List targets = StructureUtil.getTargets(node, IRelationship.Kind.ADVICE); if (targets != null && !targets.isEmpty()) { String prevName = ""; String adviceDoc = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>" + "<TD width=\"15%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>&nbsp;Advised&nbsp;by:</font></b></td><td>"; String relativePackagePath = getRelativePathFromHere( node.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR); List addedNames = new ArrayList(); for (Iterator it = targets.iterator(); it.hasNext(); ) { String currHandle = (String)it.next(); IProgramElement currDecl = AsmManager.getDefault().getHierarchy().findElementForHandle(currHandle); String packagePath = ""; if (currDecl.getPackageName() != null && !currDecl.getPackageName().equals("")) { packagePath = currDecl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR; } String hrefName = ""; String hrefLink = ""; // Start the hRefLink with the relative path based on where // *this* type (i.e. the advised) is in the package structure. hrefLink = relativePackagePath + packagePath; if (currDecl.getPackageName() != null ) { hrefName = currDecl.getPackageName().replace('.', '/'); // hrefLink = "";//+ currDecl.getPackageName() + Config.DIR_SEP_CHAR; } hrefName += Config.DIR_SEP_CHAR + currDecl.getParent().toLinkLabelString() + "." + currDecl.getName(); hrefLink += currDecl.getParent().toLinkLabelString() + ".html" + "#" + currDecl.toLabelString(); if (!addedNames.contains(hrefName)) { adviceDoc = adviceDoc + "<A HREF=\"" + hrefLink + "\"><tt>" + hrefName.replace('/', '.') + "</tt></A>"; if (it.hasNext()) adviceDoc += ", "; addedNames.add(hrefName); } } adviceDoc += "</TR></TD></TABLE>\n"; fileContentsBuffer.insert( index, adviceDoc ); } } /** * TODO: probably want to make this the same for intros and advice. */ static String generateAffects(IProgramElement decl, boolean isIntroduction) { List targets = StructureUtil.getTargets(decl, IRelationship.Kind.ADVICE); if (targets == null) return null; List packageList = new ArrayList(); String entry = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>" + "<TD width=\"10%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>&nbsp;Advises:</b></font></td><td>"; String relativePackagePath = getRelativePathFromHere( decl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR); List addedNames = new ArrayList(); // for ensuring that we don't add duplciates for (Iterator it = targets.iterator(); it.hasNext(); ) { String currHandle = (String)it.next(); IProgramElement currDecl = AsmManager.getDefault().getHierarchy().findElementForHandle(currHandle); if (currDecl.getKind().equals(IProgramElement.Kind.CODE)) { currDecl = currDecl.getParent(); // promote to enclosing } if (currDecl != null && !StructureUtil.isAnonymous(currDecl.getParent())) { String packagePath = ""; if (currDecl.getPackageName() != null && !currDecl.getPackageName().equals("")) { packagePath = currDecl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR; } String typeSignature = constructNestedTypeName(currDecl); String hrefName = packagePath + typeSignature; // Start the hRefLink with the relative path based on where // *this* type (i.e. the advisor) is in the package structure. String hrefLink = relativePackagePath + packagePath + typeSignature + ".html"; if (!currDecl.getKind().isType()) { hrefName += '.' + currDecl.getName(); hrefLink += "#" + currDecl.toLabelString(); } if (!addedNames.contains(hrefName)) { entry += "<A HREF=\"" + hrefLink + "\"><tt>" + hrefName.replace('/', '.') + "</tt></A>"; // !!! don't replace if (it.hasNext()) entry += ", "; addedNames.add(hrefName); } } } entry += "</B></FONT></TD></TR></TABLE>\n</TR></TD>\n"; return entry; } /** * Generates a relative directory path fragment that can be * used to navigate "upwards" from the directory location * implied by the argument. * @param packagePath * @return String consisting of multiple "../" parts, one for * each component part of the input <code>packagePath</code>. */ private static String getRelativePathFromHere(String packagePath) { StringBuffer result = new StringBuffer(""); if (packagePath != null && (packagePath.indexOf("/") != -1)) { StringTokenizer sTok = new StringTokenizer(packagePath, "/", false); while (sTok.hasMoreTokens()) { sTok.nextToken(); // don't care about the token value result.append(".." + Config.DIR_SEP_CHAR); }// end while }// end if return result.toString(); } static String generateIntroductionSignatures(IProgramElement decl, boolean isDetails) { return "<not implemented>"; // Declaration[] decls = decl.getDeclarations(); // String entry = ""; // for ( int j = 0; j < decls.length; j++ ) { // Declaration currDecl = decls[j]; // if ( currDecl != null ) { // entry += // "<TT><B>" + // currDecl.getSignature() + // "</B></TT><BR>"; // } // if (isDetails) { // entry += generateDetailsComment(currDecl) + "<P>"; // } // else { // entry += generateSummaryComment(currDecl) + "<P>"; // } // } // return entry; } static String generateAdviceSignatures(IProgramElement decl ) { return "<B>" + decl.toLabelString() + "</B>"; } static String generateSummaryComment(IProgramElement decl) { String COMMENT_INDENT = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; // !!! String formattedComment = getFormattedComment(decl); int periodIndex = formattedComment.indexOf( '.' ); if (formattedComment.equals("")) { return ""; } else if ( periodIndex != -1 ) { return COMMENT_INDENT + formattedComment.substring( 0, periodIndex+1 ) ; } else { return COMMENT_INDENT + formattedComment; } } static String generateDetailsComment(IProgramElement decl) { return getFormattedComment(decl); } static String generateHREFName(IProgramElement decl) { String hrefLink = decl.toLabelString(); // !!! return hrefLink; } /** * Figure out the link relative to the package. */ static String generateAffectsHREFLink(String declaringType) { String link = rootDir.getAbsolutePath() + "/" + declaringType + ".html"; return link; } /** * This formats a comment according to the rules in the Java Langauge Spec: * <I>The text of a docuemntation comment consists of the characters between * the /** that begins the comment and the 'star-slash' that ends it. The text is * devided into one or more lines. On each of these lines, the leading * * characters are ignored; for lines other than the first, blanks and * tabs preceding the initial * characters are also discarded.</I> * * TODO: implement formatting or linking for tags. */ static String getFormattedComment(IProgramElement decl) { String comment = decl.getFormalComment(); if (comment == null) return ""; String formattedComment = ""; // strip the comment markers int startIndex = comment.indexOf("/**"); int endIndex = comment.indexOf("*/"); if ( startIndex == -1 ) { startIndex = 0; } else { startIndex += 3; } if ( endIndex == -1 ) { endIndex = comment.length(); } comment = comment.substring( startIndex, endIndex ); // string the leading whitespace and '*' characters at the beginning of each line BufferedReader reader = new BufferedReader( new StringReader( comment ) ); try { for (String line = reader.readLine(); line != null; line = reader.readLine()) { line = line.trim(); for (int i = 0; i < line.length(); i++ ) { if ( line.charAt(0) == '*' ) { line = line.substring(1, line.length()); } else { break; } } // !!! remove any @see and @link tags from the line //int seeIndex = line.indexOf("@see"); //int linkIndex = line.indexOf("@link"); //if ( seeIndex != -1 ) { // line = line.substring(0, seeIndex) + line.substring(seeIndex); //} //if ( linkIndex != -1 ) { // line = line.substring(0, linkIndex) + line.substring(linkIndex); //} formattedComment += line; } } catch ( IOException ioe ) { throw new Error( "Couldn't format comment for declaration: " + decl.getName() ); } return formattedComment; } }
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/src/org/aspectj/tools/ajdoc/StructureUtil.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; /** * @author Mik Kersten */ public class StructureUtil { /** * @return null if a relationship of that kind is not found */ public static List/*IProgramElement*/ getTargets(IProgramElement node, IRelationship.Kind kind) { List relations = AsmManager.getDefault().getRelationshipMap().get(node); List targets = null; if (relations == null) return null; for (Iterator it = relations.iterator(); it.hasNext(); ) { IRelationship rtn = (IRelationship)it.next(); if (rtn.getKind().equals(kind)) { targets = rtn.getTargets(); } } return targets; } public static String getPackageDeclarationFromFile(File file) { IProgramElement fileNode = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(file.getAbsolutePath()); String packageName = ((IProgramElement)fileNode.getChildren().get(0)).getPackageName(); return packageName; } public static String genSignature(IProgramElement node) { StringBuffer sb = new StringBuffer(); String accessibility = node.getAccessibility().toString(); if (!accessibility.equals("package")) { sb.append(accessibility); sb.append(' '); } String modifiers = ""; for (Iterator modIt = node.getModifiers().iterator(); modIt.hasNext(); ) { modifiers += modIt.next() + " "; } if (node.getKind().equals(IProgramElement.Kind.METHOD) || node.getKind().equals(IProgramElement.Kind.FIELD)) { sb.append(node.getCorrespondingType()); sb.append(' '); } if (node.getKind().equals(IProgramElement.Kind.CLASS)) { sb.append("class "); } else if (node.getKind().equals(IProgramElement.Kind.INTERFACE)) { sb.append("interface "); } sb.append(node.getName()); if (node.getParameterTypes() != null ) { sb.append('('); for (int i = 0; i < node.getParameterTypes().size(); i++) { sb.append((String)node.getParameterTypes().get(i)); sb.append(' '); sb.append((String)node.getParameterNames().get(i)); if (i < node.getParameterTypes().size()-1) { sb.append(", "); } } sb.append(')'); } return sb.toString(); } public static boolean isAnonymous(IProgramElement node) { boolean isIntName = true; try { Integer.valueOf(node.getName()); } catch (NumberFormatException nfe) { // !!! using exceptions for logic, fix isIntName = false; } // System.err.println(">>>>>>>> " + node.getName()); return isIntName || node.getName().startsWith("new "); // return isIntName; // if (!isIntName) { // // return node.getName().startsWith("new "); // } else { // return false; // } } /** * @return same path, but ending in ".java" instead of ".aj" */ public static String translateAjPathName(String path) { if (path.endsWith(".aj")) { path = path.substring(0, path.lastIndexOf(".aj")) + ".java"; } return path; } }
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/src/org/aspectj/tools/ajdoc/StubFileGenerator.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.*; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; /** * @author Mik Kersten */ class StubFileGenerator{ static Hashtable declIDTable = null; static void doFiles (Hashtable table, SymbolManager symbolManager, File[] inputFiles, File[] signatureFiles) throws DocException { declIDTable = table; for (int i = 0; i < inputFiles.length; i++) { processFile(symbolManager, inputFiles[i], signatureFiles[i]); } } static void processFile(SymbolManager symbolManager, File inputFile, File signatureFile) throws DocException { try { String path = StructureUtil.translateAjPathName(signatureFile.getCanonicalPath()); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(path))); String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile); if (packageName != null && packageName != "") { writer.println( "package " + packageName + ";" ); } IProgramElement fileNode = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(inputFile.getAbsolutePath()); for (Iterator it = fileNode.getChildren().iterator(); it.hasNext(); ) { IProgramElement node = (IProgramElement)it.next(); if (node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) { processImportDeclaration(node, writer); } else { try { processTypeDeclaration(node, writer); } catch (DocException d){ throw new DocException("File name invalid: " + inputFile.toString()); } } } // if we got an error we don't want the contents of the file writer.close(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } private static void processImportDeclaration(IProgramElement node, PrintWriter writer) throws IOException { List imports = node.getChildren(); for (Iterator i = imports.iterator(); i.hasNext();) { IProgramElement importNode = (IProgramElement) i.next(); writer.print("import "); writer.print(importNode.getName()); writer.println(';'); } } private static void processTypeDeclaration(IProgramElement classNode, PrintWriter writer) throws DocException { String formalComment = addDeclID(classNode, classNode.getFormalComment()); writer.println(formalComment); String signature = genSourceSignature(classNode);// StructureUtil.genSignature(classNode); if (signature == null){ throw new DocException("The java file is invalid"); } // System.err.println("######" + signature + ", " + classNode.getName()); if (!StructureUtil.isAnonymous(classNode) && !classNode.getName().equals("<undefined>")) { writer.println(signature + " {" ); processMembers(classNode.getChildren(), writer, classNode.getKind().equals(IProgramElement.Kind.INTERFACE)); writer.println(); writer.println("}"); } } private static void processMembers(List/*IProgramElement*/ members, PrintWriter writer, boolean declaringTypeIsInterface) throws DocException { for (Iterator it = members.iterator(); it.hasNext();) { IProgramElement member = (IProgramElement) it.next(); if (member.getKind().isType()) { if (!member.getParent().getKind().equals(IProgramElement.Kind.METHOD) && !StructureUtil.isAnonymous(member)) {// don't print anonymous types // System.err.println(">>>>>>>>>>>>>" + member.getName() + "<<<<" + member.getParent()); processTypeDeclaration(member, writer); } } else { String formalComment = addDeclID(member, member.getFormalComment());; writer.println(formalComment); String signature = ""; if (!member.getKind().equals(IProgramElement.Kind.POINTCUT) && !member.getKind().equals(IProgramElement.Kind.ADVICE)) { signature = member.getSourceSignature();//StructureUtil.genSignature(member); if (member.getKind().equals(IProgramElement.Kind.ENUM_VALUE)){ if (((IProgramElement)members.get(members.indexOf(member)+1)).getKind().equals(IProgramElement.Kind.ENUM_VALUE)){ // if the next member is also an ENUM_VALUE: signature = signature + ","; } else { signature = signature + ";"; } } } if (member.getKind().isDeclare()) { System.err.println("> Skipping declare (ajdoc limitation): " + member.toLabelString()); } else if (signature != null && signature != "" && !member.getKind().isInterTypeMember() && !member.getKind().equals(IProgramElement.Kind.INITIALIZER) && !StructureUtil.isAnonymous(member)) { writer.print(signature); } else { // System.err.println(">> skipping: " + member.getKind()); } if (member.getKind().equals(IProgramElement.Kind.METHOD) || member.getKind().equals(IProgramElement.Kind.CONSTRUCTOR)) { if (member.getParent().getKind().equals(IProgramElement.Kind.INTERFACE) || signature.indexOf("abstract ") != -1) { writer.println(";"); } else { writer.println(" { }"); } } else if (member.getKind().equals(IProgramElement.Kind.FIELD)) { // writer.println(";"); } } } } /** * Translates "aspect" to "class", as long as its not ".aspect" */ private static String genSourceSignature(IProgramElement classNode) { String signature = classNode.getSourceSignature(); if (signature != null){ int index = signature.indexOf("aspect"); if (index != -1 && signature.charAt(index-1) != '.') { signature = signature.substring(0, index) + "class " + signature.substring(index + 6, signature.length()); } } return signature; } static int nextDeclID = 0; static String addDeclID(IProgramElement decl, String formalComment) { String declID = "" + ++nextDeclID; declIDTable.put(declID, decl); return addToFormal(formalComment, Config.DECL_ID_STRING + declID + Config.DECL_ID_TERMINATOR); } /** * We want to go: * just before the first period * just before the first @ * just before the end of the comment * * Adds a place holder for the period ('#') if one will need to be * replaced. */ static String addToFormal(String formalComment, String string) { boolean appendPeriod = true; if ( (formalComment == null) || formalComment.equals("")) { //formalComment = "/**\n * . \n */\n"; formalComment = "/**\n * \n */\n"; appendPeriod = false; } formalComment = formalComment.trim(); int atsignPos = formalComment.indexOf('@'); int endPos = formalComment.indexOf("*/"); int periodPos = formalComment.indexOf("/**")+2; int position = 0; String periodPlaceHolder = ""; if ( periodPos != -1 ) { position = periodPos+1; } else if ( atsignPos != -1 ) { string = string + "\n * "; position = atsignPos; } else if ( endPos != -1 ) { string = "* " + string + "\n"; position = endPos; } else { // !!! perhaps this error should not be silent throw new Error("Failed to append to formal comment for comment: " + formalComment ); } return formalComment.substring(0, position) + periodPlaceHolder + string + formalComment.substring(position); } }
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/testdata/declareForms/DeclareCoverage.java
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/AjdocTests.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Wes Isberg initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import org.aspectj.util.FileUtil; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class AjdocTests extends TestCase { public static File ASPECTJRT_PATH; static { String[] paths = { "sp:aspectjrt.path", "sp:aspectjrt.jar", "../lib/test/aspectjrt.jar", "../aj-build/jars/aspectj5rt-all.jar", "../aj-build/jars/runtime.jar", "../runtime/bin"}; ASPECTJRT_PATH = FileUtil.getBestFile(paths); } public static Test suite() { TestSuite suite = new TestSuite(AjdocTests.class.getName()); //$JUnit-BEGIN$ suite.addTestSuite(SpacewarTestCase.class); suite.addTestSuite(PatternsTestCase.class); suite.addTestSuite(CoverageTestCase.class); suite.addTestSuite(ExecutionTestCase.class);// !!! must be last because it exists //$JUnit-END$ return suite; } }
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/CoverageTestCase.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; /** * A long way to go until full coverage, but this is the place to add more. * * @author Mik Kersten */ public class CoverageTestCase extends TestCase { protected File file0 = new File("testdata/coverage/InDefaultPackage.java"); protected File file1 = new File("testdata/coverage/foo/ClassA.java"); protected File aspect1 = new File("testdata/coverage/foo/UseThisAspectForLinkCheck.aj"); protected File file2 = new File("testdata/coverage/foo/InterfaceI.java"); protected File file3 = new File("testdata/coverage/foo/PlainJava.java"); protected File file4 = new File("testdata/coverage/foo/ModelCoverage.java"); protected File file5 = new File("testdata/coverage/fluffy/Fluffy.java"); protected File file6 = new File("testdata/coverage/fluffy/bunny/Bunny.java"); protected File file7 = new File("testdata/coverage/fluffy/bunny/rocks/Rocks.java"); protected File file8 = new File("testdata/coverage/fluffy/bunny/rocks/UseThisAspectForLinkCheckToo.java"); protected File file9 = new File("testdata/coverage/foo/PkgVisibleClass.java"); protected File file10 = new File("testdata/coverage/foo/NoMembers.java"); protected File outdir = new File("testdata/coverage/doc"); public void testOptions() { outdir.delete(); String[] args = { "-private", "-encoding", "EUCJIS", "-docencoding", "EUCJIS", "-charset", "UTF-8", "-classpath", AjdocTests.ASPECTJRT_PATH.getPath(), "-d", outdir.getAbsolutePath(), file0.getAbsolutePath(), }; org.aspectj.tools.ajdoc.Main.main(args); assertTrue(true); } public void testCoveragePublicMode() { outdir.delete(); String[] args = { "-public", "-source", "1.4", "-classpath", AjdocTests.ASPECTJRT_PATH.getPath(), "-d", outdir.getAbsolutePath(), file3.getAbsolutePath(), file9.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); } public void testCoverage() { outdir.delete(); String[] args = { // "-XajdocDebug", "-source", "1.4", "-private", "-classpath", AjdocTests.ASPECTJRT_PATH.getPath(), "-d", outdir.getAbsolutePath(), aspect1.getAbsolutePath(), file0.getAbsolutePath(), file1.getAbsolutePath(), file2.getAbsolutePath(), file3.getAbsolutePath(), file4.getAbsolutePath(), file5.getAbsolutePath(), file6.getAbsolutePath(), file7.getAbsolutePath(), file8.getAbsolutePath(), file9.getAbsolutePath(), file10.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); } // public void testPlainJava() { // outdir.delete(); // String[] args = { "-d", // outdir.getAbsolutePath(), // file3.getAbsolutePath() }; // org.aspectj.tools.ajdoc.Main.main(args); // } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/DeclareFormsTest.java
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/ExecutionTestCase.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; import org.aspectj.bridge.Version; /** * @author Mik Kersten */ public class ExecutionTestCase extends TestCase { public void testVersionMatch() { String ajdocVersion = Main.getVersion(); String compilerVersion = Version.text; assertTrue("version check", ajdocVersion.endsWith(compilerVersion)); } public void testFailingBuild() { File file1 = new File("testdata/failing-build/Fail.java"); String[] args = { file1.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); assertTrue(Main.hasAborted()); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/PatternsTestCase.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; /** * A long way to go until full coverage, but this is the place to add more. * * @author Mik Kersten */ public class PatternsTestCase extends TestCase { public void testSimpleExample() { // System.err.println(new File("testdata.figures-demo").exists()); // File file1 = new File("testdata/patterns/allPatterns.lst"); File outdir = new File("testdata/patterns/doc"); File srcdir = new File("../docs/sandbox/ubc-design-patterns/src"); String[] args = { // "-XajdocDebug", "-classpath", AjdocTests.ASPECTJRT_PATH.getPath(), "-d", outdir.getAbsolutePath(), "-sourcepath", srcdir.getAbsolutePath(), "ca.ubc.cs.spl.aspectPatterns.patternLibrary", "ca.ubc.cs.spl.aspectPatterns.examples.abstractFactory.java", "ca.ubc.cs.spl.aspectPatterns.examples.abstractFactory.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.builder.java", "ca.ubc.cs.spl.aspectPatterns.examples.builder.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.factoryMethod.java", "ca.ubc.cs.spl.aspectPatterns.examples.factoryMethod.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.prototype.java", "ca.ubc.cs.spl.aspectPatterns.examples.prototype.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.singleton.java", "ca.ubc.cs.spl.aspectPatterns.examples.singleton.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.adapter.java", "ca.ubc.cs.spl.aspectPatterns.examples.adapter.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.bridge.java", "ca.ubc.cs.spl.aspectPatterns.examples.bridge.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.composite.java", "ca.ubc.cs.spl.aspectPatterns.examples.composite.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.decorator.java", "ca.ubc.cs.spl.aspectPatterns.examples.decorator.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.facade.java", "ca.ubc.cs.spl.aspectPatterns.examples.facade.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.flyweight.java", "ca.ubc.cs.spl.aspectPatterns.examples.flyweight.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.proxy.java", "ca.ubc.cs.spl.aspectPatterns.examples.proxy.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.chainOfResponsibility.java", "ca.ubc.cs.spl.aspectPatterns.examples.chainOfResponsibility.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.command.java", "ca.ubc.cs.spl.aspectPatterns.examples.command.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.interpreter.java", "ca.ubc.cs.spl.aspectPatterns.examples.interpreter.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.iterator.java", "ca.ubc.cs.spl.aspectPatterns.examples.iterator.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.mediator.java", "ca.ubc.cs.spl.aspectPatterns.examples.mediator.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.memento.java", "ca.ubc.cs.spl.aspectPatterns.examples.memento.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.observer.java", "ca.ubc.cs.spl.aspectPatterns.examples.observer.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.state.java", "ca.ubc.cs.spl.aspectPatterns.examples.state.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.strategy.java", "ca.ubc.cs.spl.aspectPatterns.examples.strategy.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.templateMethod.java", "ca.ubc.cs.spl.aspectPatterns.examples.templateMethod.aspectj", "ca.ubc.cs.spl.aspectPatterns.examples.visitor.java", "ca.ubc.cs.spl.aspectPatterns.examples.visitor.aspectj" }; org.aspectj.tools.ajdoc.Main.main(args); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/PointcutVisibilityTest.java
/* * Created on Jan 12, 2005 */ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; /** * @author Mik Kersten */ public class PointcutVisibilityTest extends TestCase { protected File file1 = new File("testdata/bug82340/Pointcuts.java"); protected File outdir = new File("testdata/bug82340/doc"); public void testCoveragePublicMode() { outdir.delete(); String[] args = { "-XajdocDebug", "-protected", "-d", outdir.getAbsolutePath(), file1.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); } }
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/SpacewarTestCase.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; /** * @author Mik Kersten */ public class SpacewarTestCase extends TestCase { protected void setUp() throws Exception { super.setUp(); new File("testdata/spacewar/docdir").delete(); } public void testSimpleExample() { File outdir = new File("testdata/spacewar/docdir"); File sourcepath = new File("testdata/spacewar"); String[] args = { "-classpath", AjdocTests.ASPECTJRT_PATH.getPath(), "-d", outdir.getAbsolutePath(), "-sourcepath", sourcepath.getAbsolutePath(), "spacewar", "coordination" }; org.aspectj.tools.ajdoc.Main.main(args); assertTrue(true); } public void testPublicModeExample() { File outdir = new File("testdata/spacewar/docdir"); File sourcepath = new File("testdata/spacewar"); String[] args = { "-public", "-classpath", AjdocTests.ASPECTJRT_PATH.getPath(), "-d", outdir.getAbsolutePath(), "-sourcepath", sourcepath.getAbsolutePath(), "spacewar", "coordination" }; org.aspectj.tools.ajdoc.Main.main(args); assertTrue(true); } protected void tearDown() throws Exception { super.tearDown(); } }
56,779
Bug 56779 [ajdoc] add ajdoc support for inter-type declarations and other declare forms
Currently ajdoc only exposes the "Advises" and "Advised by" relationships from the structure model. It needs to support inter-type field and member declarations using a UI similar to how Javadoc presents inherited members. It also needs to support the other declare forms: error, warning, soft, parents, and precedence.
resolved fixed
ab6c7a5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-05T16:15:43Z
2004-03-30T18:06:40Z
asm/src/org/aspectj/asm/IRelationship.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.asm; import java.io.*; import java.util.List; /** * @author Mik Kersten */ public interface IRelationship extends Serializable { public String getName(); public List/*String*/ getTargets(); public String getSourceHandle(); public boolean addTarget(String handle); public Kind getKind(); public boolean hasRuntimeTest(); /** * Uses "typesafe enum" pattern. */ public static class Kind implements Serializable { public static final Kind DECLARE_WARNING = new Kind("declare warning"); public static final Kind DECLARE_ERROR = new Kind("declare error"); public static final Kind ADVICE_AROUND = new Kind("around advice"); public static final Kind ADVICE_AFTERRETURNING = new Kind("after returning advice"); public static final Kind ADVICE_AFTERTHROWING = new Kind("after throwing advice"); public static final Kind ADVICE_AFTER = new Kind("after advice"); public static final Kind ADVICE_BEFORE = new Kind("before advice"); public static final Kind ADVICE = new Kind("advice"); public static final Kind DECLARE = new Kind("declare"); public static final Kind DECLARE_INTER_TYPE = new Kind("inter-type declaration"); public static final Kind USES_POINTCUT = new Kind("uses pointcut"); public static final Kind DECLARE_SOFT = new Kind("declare soft"); public static final Kind[] ALL = { DECLARE_WARNING, DECLARE_ERROR, ADVICE_AROUND,ADVICE_AFTERRETURNING,ADVICE_AFTERTHROWING,ADVICE_AFTER,ADVICE_BEFORE, ADVICE, DECLARE, DECLARE_INTER_TYPE, USES_POINTCUT, DECLARE_SOFT }; private final String name; private Kind(String name) { this.name = name; } public String toString() { return name; } // The 4 declarations below are necessary for serialization private static int nextOrdinal = 0; private final int ordinal = nextOrdinal++; private Object readResolve() throws ObjectStreamException { return ALL[ordinal]; } } }
112,243
Bug 112243 Compiler Core Dump with Apparent Fix
null
resolved fixed
04e8dca
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-13T10:44:13Z
2005-10-11T19:46:40Z
weaver/src/org/aspectj/weaver/World.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer, Andy Clement, overhaul for generics * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import org.aspectj.asm.IHierarchy; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.context.PinpointingMessageHandler; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; /** * A World is a collection of known types and crosscutting members. */ public abstract class World implements Dump.INode { /** handler for any messages produced during resolution etc. */ private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR; /** handler for cross-reference information produced during the weaving process */ private ICrossReferenceHandler xrefHandler = null; /** Currently 'active' scope in which to lookup (resolve) typevariable references */ private TypeVariableDeclaringElement typeVariableLookupScope; /** The heart of the world, a map from type signatures to resolved types */ protected TypeMap typeMap = new TypeMap(); // Signature to ResolvedType /** Calculator for working out aspect precedence */ private AspectPrecedenceCalculator precedenceCalculator; /** All of the type and shadow mungers known to us */ private CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this); /** Model holds ASM relationships */ private IHierarchy model = null; /** for processing Xlint messages */ private Lint lint = new Lint(this); /** XnoInline option setting passed down to weaver */ private boolean XnoInline; /** XlazyTjp option setting passed down to weaver */ private boolean XlazyTjp; /** XhasMember option setting passed down to weaver */ private boolean XhasMember = false; /** Xpinpoint controls whether we put out developer info showing the source of messages */ private boolean Xpinpoint = false; /** When behaving in a Java 5 way autoboxing is considered */ private boolean behaveInJava5Way = false; /** * A list of RuntimeExceptions containing full stack information for every * type we couldn't find. */ private List dumpState_cantFindTypeExceptions = null; /** * Play God. * On the first day, God created the primitive types and put them in the type * map. */ protected World() { super(); Dump.registerNode(this.getClass(),this); typeMap.put("B", ResolvedType.BYTE); typeMap.put("S", ResolvedType.SHORT); typeMap.put("I", ResolvedType.INT); typeMap.put("J", ResolvedType.LONG); typeMap.put("F", ResolvedType.FLOAT); typeMap.put("D", ResolvedType.DOUBLE); typeMap.put("C", ResolvedType.CHAR); typeMap.put("Z", ResolvedType.BOOLEAN); typeMap.put("V", ResolvedType.VOID); precedenceCalculator = new AspectPrecedenceCalculator(this); } /** * Dump processing when a fatal error occurs */ public void accept (Dump.IVisitor visitor) { visitor.visitString("Shadow mungers:"); visitor.visitList(crosscuttingMembersSet.getShadowMungers()); visitor.visitString("Type mungers:"); visitor.visitList(crosscuttingMembersSet.getTypeMungers()); visitor.visitString("Late Type mungers:"); visitor.visitList(crosscuttingMembersSet.getLateTypeMungers()); if (dumpState_cantFindTypeExceptions!=null) { visitor.visitString("Cant find type problems:"); visitor.visitList(dumpState_cantFindTypeExceptions); dumpState_cantFindTypeExceptions = null; } } // ============================================================================= // T Y P E R E S O L U T I O N // ============================================================================= /** * Resolve a type that we require to be present in the world */ public ResolvedType resolve(UnresolvedType ty) { return resolve(ty, false); } /** * Attempt to resolve a type - the source location gives you some context in which * resolution is taking place. In the case of an error where we can't find the * type - we can then at least report why (source location) we were trying to resolve it. */ public ResolvedType resolve(UnresolvedType ty,ISourceLocation isl) { ResolvedType ret = resolve(ty,true); if (ty == ResolvedType.MISSING) { IMessage msg = null; if (isl!=null) { msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl); } else { msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName())); } messageHandler.handleMessage(msg); } return ret; } /** * Convenience method for resolving an array of unresolved types * in one hit. Useful for e.g. resolving type parameters in signatures. */ public ResolvedType[] resolve(UnresolvedType[] types) { if (types == null) return new ResolvedType[0]; ResolvedType[] ret = new ResolvedType[types.length]; for (int i=0; i<types.length; i++) { ret[i] = resolve(types[i]); } return ret; } /** * Resolve a type. This the hub of type resolution. The resolved type is added * to the type map by signature. */ public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) { // special resolution processing for already resolved types. if (ty instanceof ResolvedType) { ResolvedType rty = (ResolvedType) ty; rty = resolve(rty); return rty; } // dispatch back to the type variable reference to resolve its constituent parts // don't do this for other unresolved types otherwise you'll end up in a loop if (ty.isTypeVariableReference()) { return ty.resolve(this); } // if we've already got a resolved type for the signature, just return it // after updating the world String signature = ty.getSignature(); ResolvedType ret = typeMap.get(signature); if (ret != null) { ret.world = this; // Set the world for the RTX return ret; } else if ( signature.equals("?") || signature.equals("*")) { // might be a problem here, not sure '?' should make it to here as a signature, the // proper signature for wildcard '?' is '*' // fault in generic wildcard, can't be done earlier because of init issues ResolvedType something = new BoundedReferenceType("?",this); typeMap.put("?",something); return something; } // no existing resolved type, create one if (ty.isArray()) { ret = new ResolvedType.Array(signature, this, resolve(ty.getComponentType(), allowMissing)); } else { ret = resolveToReferenceType(ty); if (!allowMissing && ret == ResolvedType.MISSING) { ret = handleRequiredMissingTypeDuringResolution(ty); } } // Pulling in the type may have already put the right entry in the map if (typeMap.get(signature)==null && ret != ResolvedType.MISSING) { typeMap.put(signature, ret); } return ret; } /** * We tried to resolve a type and couldn't find it... */ private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) { // defer the message until someone asks a question of the type that we can't answer // just from the signature. // MessageUtil.error(messageHandler, // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName())); if (dumpState_cantFindTypeExceptions==null) { dumpState_cantFindTypeExceptions = new ArrayList(); } dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type "+ty.getName())); return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),this); } /** * Some TypeFactory operations create resolved types directly, but these won't be * in the typeMap - this resolution process puts them there. Resolved types are * also told their world which is needed for the special autoboxing resolved types. */ public ResolvedType resolve(ResolvedType ty) { if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs... ResolvedType resolved = typeMap.get(ty.getSignature()); if (resolved == null) { typeMap.put(ty.getSignature(), ty); resolved = ty; } resolved.world = this; return resolved; } /** * Convenience method for finding a type by name and resolving it in one step. */ public ResolvedType resolve(String name) { return resolve(UnresolvedType.forName(name)); } public ResolvedType resolve(String name,boolean allowMissing) { return resolve(UnresolvedType.forName(name),allowMissing); } /** * Resolve to a ReferenceType - simple, raw, parameterized, or generic. * Raw, parameterized, and generic versions of a type share a delegate. */ private final ResolvedType resolveToReferenceType(UnresolvedType ty) { if (ty.isParameterizedType()) { // ======= parameterized types ================ ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false); ReferenceType parameterizedType = TypeFactory.createParameterizedType(genericType, ty.typeParameters, this); return parameterizedType; } else if (ty.isGenericType()) { // ======= generic types ====================== ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false); return genericType; } else if (ty.isGenericWildcard()) { // ======= generic wildcard types ============= return resolveGenericWildcardFor(ty); } else { // ======= simple and raw types =============== String erasedSignature = ty.getErasureSignature(); ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this); ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType); if (delegate == null) return ResolvedType.MISSING; if (delegate.isGeneric() && behaveInJava5Way) { // ======== raw type =========== simpleOrRawType.typeKind = TypeKind.RAW; ReferenceType genericType = makeGenericTypeFrom(delegate,simpleOrRawType); // name = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(ty.getName()),this); simpleOrRawType.setDelegate(delegate); genericType.setDelegate(delegate); simpleOrRawType.setGenericType(genericType); return simpleOrRawType; } else { // ======== simple type ========= simpleOrRawType.setDelegate(delegate); return simpleOrRawType; } } } /** * Attempt to resolve a type that should be a generic type. */ public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) { // Look up the raw type by signature String rawSignature = anUnresolvedType.getRawType().getSignature(); ResolvedType rawType = (ResolvedType) typeMap.get(rawSignature); if (rawType==null) { rawType = resolve(UnresolvedType.forSignature(rawSignature),false); typeMap.put(rawSignature,rawType); } // Does the raw type know its generic form? (It will if we created the // raw type from a source type, it won't if its been created just through // being referenced, e.g. java.util.List ResolvedType genericType = rawType.getGenericType(); // There is a special case to consider here (testGenericsBang_pr95993 highlights it) // You may have an unresolvedType for a parameterized type but it // is backed by a simple type rather than a generic type. This occurs for // inner types of generic types that inherit their enclosing types // type variables. if (rawType.isSimpleType() && (anUnresolvedType.typeParameters==null || anUnresolvedType.typeParameters.length==0)) { rawType.world = this; return rawType; } if (genericType != null) { genericType.world = this; return genericType; } else { // Fault in the generic that underpins the raw type ;) ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType)rawType); ReferenceType genericRefType = makeGenericTypeFrom(delegate,((ReferenceType)rawType)); ((ReferenceType)rawType).setGenericType(genericRefType); genericRefType.setDelegate(delegate); ((ReferenceType)rawType).setDelegate(delegate); return genericRefType; } } private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) { String genericSig = delegate.getDeclaredGenericSignature(); if (genericSig != null) { return new ReferenceType( UnresolvedType.forGenericTypeSignature(rawType.getSignature(),delegate.getDeclaredGenericSignature()),this); } else { return new ReferenceType( UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),this); } } /** * Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType). */ private ReferenceType resolveGenericWildcardFor(UnresolvedType aType) { BoundedReferenceType ret = null; // FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?) if (aType.isExtends()) { ReferenceType upperBound = (ReferenceType)resolve(aType.getUpperBound()); ret = new BoundedReferenceType(upperBound,true,this); } else if (aType.isSuper()) { ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound()); ret = new BoundedReferenceType(lowerBound,false,this); } else { // must be ? on its own! } return ret; } /** * Find the ReferenceTypeDelegate behind this reference type so that it can * fulfill its contract. */ protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty); /** * Special resolution for "core" types like OBJECT. These are resolved just like * any other type, but if they are not found it is more serious and we issue an * error message immediately. */ public ResolvedType getCoreType(UnresolvedType tx) { ResolvedType coreTy = resolve(tx,true); if (coreTy == ResolvedType.MISSING) { MessageUtil.error(messageHandler, WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName())); } return coreTy; } /** * Lookup a type by signature, if not found then build one and put it in the * map. */ public ReferenceType lookupOrCreateName(UnresolvedType ty) { String signature = ty.getSignature(); ReferenceType ret = lookupBySignature(signature); if (ret == null) { ret = ReferenceType.fromTypeX(ty, this); typeMap.put(signature, ret); } return ret; } /** * Lookup a reference type in the world by its signature. Returns * null if not found. */ public ReferenceType lookupBySignature(String signature) { return (ReferenceType) typeMap.get(signature); } // ============================================================================= // T Y P E R E S O L U T I O N -- E N D // ============================================================================= /** * Member resolution is achieved by resolving the declaring type and then * looking up the member in the resolved declaring type. */ public ResolvedMember resolve(Member member) { ResolvedType declaring = member.getDeclaringType().resolve(this); if (declaring.isRawType()) declaring = declaring.getGenericType(); ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = declaring.lookupField(member); } else { ret = declaring.lookupMethod(member); } if (ret != null) return ret; return declaring.lookupSyntheticMember(member); } // Methods for creating various cross-cutting members... // =========================================================== /** * Create an advice shadow munger from the given advice attribute */ public abstract Advice createAdviceMunger( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature); /** * Create an advice shadow munger for the given advice kind */ public final Advice createAdviceMunger( AdviceKind kind, Pointcut p, Member signature, int extraParameterFlags, IHasSourceLocation loc) { AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext()); return createAdviceMunger(attribute, p, signature); } public abstract ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField); public abstract ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField); /** * Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed * @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind) */ public abstract ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind); public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType); /** * Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo */ public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.compareByPrecedence(aspect1, aspect2); } /** * compares by precedence with the additional rule that a super-aspect is * sorted before its sub-aspects */ public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2); } // simple property getter and setters // =========================================================== /** * Nobody should hold onto a copy of this message handler, or setMessageHandler won't * work right. */ public IMessageHandler getMessageHandler() { return messageHandler; } public void setMessageHandler(IMessageHandler messageHandler) { if (this.isInPinpointMode()) { this.messageHandler = new PinpointingMessageHandler(messageHandler); } else { this.messageHandler = messageHandler; } } /** * convenenience method for creating and issuing messages via the message handler - * if you supply two locations you will get two messages. */ public void showMessage( Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { if (loc1 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc1)); if (loc2 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } else { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) { this.xrefHandler = xrefHandler; } /** * Get the cross-reference handler for the world, may be null. */ public ICrossReferenceHandler getCrossReferenceHandler() { return this.xrefHandler; } public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) { this.typeVariableLookupScope = scope; } public TypeVariableDeclaringElement getTypeVariableLookupScope() { return typeVariableLookupScope; } public List getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } public List getDeclareAnnotationOnTypes() { return crosscuttingMembersSet.getDeclareAnnotationOnTypes(); } public List getDeclareAnnotationOnFields() { return crosscuttingMembersSet.getDeclareAnnotationOnFields(); } public List getDeclareAnnotationOnMethods() { return crosscuttingMembersSet.getDeclareAnnotationOnMethods(); } public List getDeclareSoft() { return crosscuttingMembersSet.getDeclareSofts(); } public CrosscuttingMembersSet getCrosscuttingMembersSet() { return crosscuttingMembersSet; } public IHierarchy getModel() { return model; } public void setModel(IHierarchy model) { this.model = model; } public Lint getLint() { return lint; } public void setLint(Lint lint) { this.lint = lint; } public boolean isXnoInline() { return XnoInline; } public void setXnoInline(boolean xnoInline) { XnoInline = xnoInline; } public boolean isXlazyTjp() { return XlazyTjp; } public void setXlazyTjp(boolean b) { XlazyTjp = b; } public boolean isHasMemberSupportEnabled() { return XhasMember; } public void setXHasMemberSupportEnabled(boolean b) { XhasMember = b; } public boolean isInPinpointMode() { return Xpinpoint; } public void setPinpointMode(boolean b) { this.Xpinpoint = b; } public void setBehaveInJava5Way(boolean b) { behaveInJava5Way = b; } public boolean isInJava5Mode() { return behaveInJava5Way; } /* * Map of types in the world, with soft links to expendable ones. * An expendable type is a reference type that is not exposed to the weaver (ie * just pulled in for type resolution purposes). */ protected static class TypeMap { /** Map of types that never get thrown away */ private Map tMap = new HashMap(); /** Map of types that may be ejected from the cache if we need space */ private Map expendableMap = new WeakHashMap(); private static final boolean debug = false; /** * Add a new type into the map, the key is the type signature. * Some types do *not* go in the map, these are ones involving * *member* type variables. The reason is that when all you have is the * signature which gives you a type variable name, you cannot * guarantee you are using the type variable in the same way * as someone previously working with a similarly * named type variable. So, these do not go into the map: * - TypeVariableReferenceType. * - ParameterizedType where a member type variable is involved. * - BoundedReferenceType when one of the bounds is a type variable. * * definition: "member type variables" - a tvar declared on a generic * method/ctor as opposed to those you see declared on a generic type. */ public ResolvedType put(String key, ResolvedType type) { if (type.isParameterizedType() && type.isParameterizedWithAMemberTypeVariable()) { if (debug) System.err.println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="+key+" type="+type); return type; } if (type.isTypeVariableReference()) { if (debug) System.err.println("Not putting a type variable reference type into the typemap: key="+key+" type="+type); return type; } // this test should be improved - only avoid putting them in if one of the // bounds is a member type variable if (type instanceof BoundedReferenceType) { if (debug) System.err.println("Not putting a bounded reference type into the typemap: key="+key+" type="+type); return type; } if (isExpendable(type)) { return (ResolvedType) expendableMap.put(key,type); } else { return (ResolvedType) tMap.put(key,type); } } /** Lookup a type by its signature */ public ResolvedType get(String key) { ResolvedType ret = (ResolvedType) tMap.get(key); if (ret == null) ret = (ResolvedType) expendableMap.get(key); return ret; } /** Remove a type from the map */ public ResolvedType remove(String key) { ResolvedType ret = (ResolvedType) tMap.remove(key); if (ret == null) ret = (ResolvedType) expendableMap.remove(key); return ret; } /** Reference types we don't intend to weave may be ejected from * the cache if we need the space. */ private boolean isExpendable(ResolvedType type) { return ( (type != null) && (!type.isExposedToWeaver()) && (!type.isPrimitiveType()) ); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("types:\n"); sb.append(dumpthem(tMap)); sb.append("expendables:\n"); sb.append(dumpthem(expendableMap)); return sb.toString(); } private String dumpthem(Map m) { StringBuffer sb = new StringBuffer(); Set keys = m.keySet(); for (Iterator iter = keys.iterator(); iter.hasNext();) { String k = (String) iter.next(); sb.append(k+"="+m.get(k)).append("\n"); } return sb.toString(); } } /** * This class is used to compute and store precedence relationships between * aspects. */ private static class AspectPrecedenceCalculator { private World world; private Map cachedResults; public AspectPrecedenceCalculator(World forSomeWorld) { this.world = forSomeWorld; this.cachedResults = new HashMap(); } /** * Ask every declare precedence in the world to order the two aspects. * If more than one declare precedence gives an ordering, and the orderings * conflict, then that's an error. */ public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) { PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect,secondAspect); if (cachedResults.containsKey(key)) { return ((Integer) cachedResults.get(key)).intValue(); } else { int order = 0; DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering for (Iterator i = world.getCrosscuttingMembersSet().getDeclareDominates().iterator(); i.hasNext(); ) { DeclarePrecedence d = (DeclarePrecedence)i.next(); int thisOrder = d.compare(firstAspect, secondAspect); if (thisOrder != 0) { if (orderer==null) orderer = d; if (order != 0 && order != thisOrder) { ISourceLocation[] isls = new ISourceLocation[2]; isls[0]=orderer.getSourceLocation(); isls[1]=d.getSourceLocation(); Message m = new Message("conflicting declare precedence orderings for aspects: "+ firstAspect.getName()+" and "+secondAspect.getName(),null,true,isls); world.getMessageHandler().handleMessage(m); } else { order = thisOrder; } } } cachedResults.put(key, new Integer(order)); return order; } } public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) { if (firstAspect.equals(secondAspect)) return 0; int ret = compareByPrecedence(firstAspect, secondAspect); if (ret != 0) return ret; if (firstAspect.isAssignableFrom(secondAspect)) return -1; else if (secondAspect.isAssignableFrom(firstAspect)) return +1; return 0; } private static class PrecedenceCacheKey { public ResolvedType aspect1; public ResolvedType aspect2; public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) { this.aspect1 = a1; this.aspect2 = a2; } public boolean equals(Object obj) { if (!(obj instanceof PrecedenceCacheKey)) return false; PrecedenceCacheKey other = (PrecedenceCacheKey) obj; return (aspect1 == other.aspect1 && aspect2 == other.aspect2); } public int hashCode() { return aspect1.hashCode() + aspect2.hashCode(); } } } public void validateType(UnresolvedType type) { } }
112,243
Bug 112243 Compiler Core Dump with Apparent Fix
null
resolved fixed
04e8dca
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-13T10:44:13Z
2005-10-11T19:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelWorld.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur perClause support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.GETSTATIC; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.INVOKESTATIC; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.util.ClassLoaderRepository; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.Repository; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ICrossReferenceHandler; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.SimpleScope; public class BcelWorld extends World implements Repository { private ClassPathManager classPath; private Repository delegate; //private ClassPathManager aspectPath = null; // private List aspectPathEntries; // ---- constructors public BcelWorld() { this(""); } public BcelWorld(String cp) { this(makeDefaultClasspath(cp), IMessageHandler.THROW, null); } private static List makeDefaultClasspath(String cp) { List classPath = new ArrayList(); classPath.addAll(getPathEntries(cp)); classPath.addAll(getPathEntries(ClassPath.getClassPath())); //System.err.println("classpath: " + classPath); return classPath; } private static List getPathEntries(String s) { List ret = new ArrayList(); StringTokenizer tok = new StringTokenizer(s, File.pathSeparator); while(tok.hasMoreTokens()) ret.add(tok.nextToken()); return ret; } public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { //this.aspectPath = new ClassPathManager(aspectPath, handler); this.classPath = new ClassPathManager(classPath, handler); setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { this.classPath = cpm; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } /** * Build a World from a ClassLoader, for LTW support * * @param loader * @param handler * @param xrefHandler */ public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { this.classPath = null; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = new ClassLoaderRepository(loader); // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } public void addPath (String name) { classPath.addPath(name, this.getMessageHandler()); } /** * Parse a string into advice. * * <blockquote><pre> * Kind ( Id , ... ) : Pointcut -> MethodSignature * </pre></blockquote> */ public Advice shadowMunger(String str, int extraFlag) { str = str.trim(); int start = 0; int i = str.indexOf('('); AdviceKind kind = AdviceKind.stringToKind(str.substring(start, i)); start = ++i; i = str.indexOf(')', i); String[] ids = parseIds(str.substring(start, i).trim()); //start = ++i; i = str.indexOf(':', i); start = ++i; i = str.indexOf("->", i); Pointcut pointcut = Pointcut.fromString(str.substring(start, i).trim()); Member m = MemberImpl.methodFromString(str.substring(i+2, str.length()).trim()); // now, we resolve UnresolvedType[] types = m.getParameterTypes(); FormalBinding[] bindings = new FormalBinding[ids.length]; for (int j = 0, len = ids.length; j < len; j++) { bindings[j] = new FormalBinding(types[j], ids[j], j, 0, 0, "fromString"); } Pointcut p = pointcut.resolve(new SimpleScope(this, bindings)); return new BcelAdvice(kind, p, m, extraFlag, 0, 0, null, null); } private String[] parseIds(String str) { if (str.length() == 0) return ZERO_STRINGS; List l = new ArrayList(); int start = 0; while (true) { int i = str.indexOf(',', start); if (i == -1) { l.add(str.substring(start).trim()); break; } l.add(str.substring(start, i).trim()); start = i+1; } return (String[]) l.toArray(new String[l.size()]); } // ---- various interactions with bcel public static Type makeBcelType(UnresolvedType type) { return Type.getType(type.getErasureSignature()); } static Type[] makeBcelTypes(UnresolvedType[] types) { Type[] ret = new Type[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = makeBcelType(types[i]); } return ret; } public static UnresolvedType fromBcel(Type t) { return UnresolvedType.forSignature(t.getSignature()); } static UnresolvedType[] fromBcel(Type[] ts) { UnresolvedType[] ret = new UnresolvedType[ts.length]; for (int i = 0, len = ts.length; i < len; i++) { ret[i] = fromBcel(ts[i]); } return ret; } public ResolvedType resolve(Type t) { return resolve(fromBcel(t)); } protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) { String name = ty.getName(); JavaClass jc = null; //UnwovenClassFile classFile = (UnwovenClassFile)sourceJavaClasses.get(name); //if (classFile != null) jc = classFile.getJavaClass(); // if (jc == null) { // jc = lookupJavaClass(aspectPath, name); // } if (jc == null) { jc = lookupJavaClass(classPath, name); } if (jc == null) { return null; } else { return makeBcelObjectType(ty, jc, false); } } protected BcelObjectType makeBcelObjectType(ReferenceType resolvedTypeX, JavaClass jc, boolean exposedToWeaver) { BcelObjectType ret = new BcelObjectType(resolvedTypeX, jc, exposedToWeaver); return ret; } private JavaClass lookupJavaClass(ClassPathManager classPath, String name) { if (classPath == null) { try { return delegate.loadClass(name); } catch (ClassNotFoundException e) { return null; } } try { ClassPathManager.ClassFile file = classPath.find(UnresolvedType.forName(name)); if (file == null) return null; ClassParser parser = new ClassParser(file.getInputStream(), file.getPath()); JavaClass jc = parser.parse(); file.close(); return jc; } catch (IOException ioe) { return null; } } public BcelObjectType addSourceObjectType(JavaClass jc) { BcelObjectType ret = null; String signature = UnresolvedType.forName(jc.getClassName()).getSignature(); ReferenceType nameTypeX = (ReferenceType)typeMap.get(signature); if (nameTypeX == null) { if (jc.isGeneric()) { nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()),this); ret = makeBcelObjectType(nameTypeX, jc, true); ReferenceType genericRefType = new ReferenceType( UnresolvedType.forGenericTypeSignature(signature,ret.getDeclaredGenericSignature()),this); nameTypeX.setDelegate(ret); genericRefType.setDelegate(ret); nameTypeX.setGenericType(genericRefType); typeMap.put(signature, nameTypeX); } else { nameTypeX = new ReferenceType(signature, this); ret = makeBcelObjectType(nameTypeX, jc, true); typeMap.put(signature, nameTypeX); } } else { ret = makeBcelObjectType(nameTypeX, jc, true); } return ret; } void deleteSourceObjectType(UnresolvedType ty) { typeMap.remove(ty.getSignature()); } public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) { ConstantPoolGen cpg = cg.getConstantPoolGen(); return MemberImpl.field( fi.getClassName(cpg), (fi instanceof GETSTATIC || fi instanceof PUTSTATIC) ? Modifier.STATIC: 0, fi.getName(cpg), fi.getSignature(cpg)); } // public static Member makeFieldSetSignature(LazyClassGen cg, FieldInstruction fi) { // ConstantPoolGen cpg = cg.getConstantPoolGen(); // return // MemberImpl.field( // fi.getClassName(cpg), // (fi instanceof GETSTATIC || fi instanceof PUTSTATIC) // ? Modifier.STATIC // : 0, // fi.getName(cpg), // "(" + fi.getSignature(cpg) + ")" +fi.getSignature(cpg)); // } public Member makeJoinPointSignature(LazyMethodGen mg) { return makeJoinPointSignatureFromMethod(mg, null); } public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberImpl.Kind kind) { Member ret = mg.getMemberView(); if (ret == null) { int mods = mg.getAccessFlags(); if (mg.getEnclosingClass().isInterface()) { mods |= Modifier.INTERFACE; } if (kind == null) { if (mg.getName().equals("<init>")) { kind = Member.CONSTRUCTOR; } else if (mg.getName().equals("<clinit>")) { kind = Member.STATIC_INITIALIZATION; } else { kind = Member.METHOD; } } return new ResolvedMemberImpl(kind, UnresolvedType.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()), mg.getName(), fromBcel(mg.getArgumentTypes()) ); } else { return ret; } } public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) { ConstantPoolGen cpg = cg.getConstantPoolGen(); String name = ii.getName(cpg); String declaring = ii.getClassName(cpg); UnresolvedType declaringType = null; String signature = ii.getSignature(cpg); int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE : (ii instanceof INVOKESTATIC) ? Modifier.STATIC : (ii instanceof INVOKESPECIAL && ! name.equals("<init>")) ? Modifier.PRIVATE : 0; // in Java 1.4 and after, static method call of super class within subclass method appears // as declared by the subclass in the bytecode - but they are not // see #104212 if (ii instanceof INVOKESTATIC) { ResolvedType appearsDeclaredBy = resolve(declaring); // look for the method there for (Iterator iterator = appearsDeclaredBy.getMethods(); iterator.hasNext();) { ResolvedMember method = (ResolvedMember) iterator.next(); if (method.isStatic()) { if (name.equals(method.getName()) && signature.equals(method.getSignature())) { // we found it declaringType = method.getDeclaringType(); break; } } } } if (declaringType == null) { if (declaring.charAt(0)=='[') declaringType = UnresolvedType.forSignature(declaring); else declaringType = UnresolvedType.forName(declaring); } return MemberImpl.method(declaringType, modifier, name, signature); } public static Member makeMungerMethodSignature(JavaClass javaClass, Method method) { int mods = 0; if (method.isStatic()) mods = Modifier.STATIC; else if (javaClass.isInterface()) mods = Modifier.INTERFACE; else if (method.isPrivate()) mods = Modifier.PRIVATE; return MemberImpl.method( UnresolvedType.forName(javaClass.getClassName()), mods, method.getName(), method.getSignature()); } private static final String[] ZERO_STRINGS = new String[0]; public String toString() { StringBuffer buf = new StringBuffer(); buf.append("BcelWorld("); //buf.append(shadowMungerMap); buf.append(")"); return buf.toString(); } public Advice createAdviceMunger( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature) { //System.err.println("concrete advice: " + signature + " context " + sourceContext); return new BcelAdvice(attribute, pointcut, signature, null); } public ConcreteTypeMunger concreteTypeMunger( ResolvedTypeMunger munger, ResolvedType aspectType) { return new BcelTypeMunger(munger, aspectType); } public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) { return new BcelCflowStackFieldAdder(cflowField); } public ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField) { return new BcelCflowCounterFieldAdder(cflowField); } /** * Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed * * @param aspect * @param kind * @return */ public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind) { return new BcelPerClauseAspectAdder(aspect, kind); } /** * Retrieve a bcel delegate for an aspect - this will return NULL if the * delegate is an EclipseSourceType and not a BcelObjectType - this happens * quite often when incrementally compiling. */ public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) { ReferenceTypeDelegate rtDelegate = ((ReferenceType)concreteAspect).getDelegate(); if (rtDelegate instanceof BcelObjectType) { return (BcelObjectType)rtDelegate; } else { return null; } } public void tidyUp() { // At end of compile, close any open files so deletion of those archives is possible classPath.closeArchives(); } /// The repository interface methods public JavaClass findClass(String className) { return lookupJavaClass(classPath,className); } public JavaClass loadClass(String className) throws ClassNotFoundException { return lookupJavaClass(classPath,className); } public void storeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public void removeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public JavaClass loadClass(Class clazz) throws ClassNotFoundException { throw new RuntimeException("Not implemented"); } public void clear() { throw new RuntimeException("Not implemented"); } // @Override /** * The aim of this method is to make sure a particular type is 'ok'. Some * operations on the delegate for a type modify it and this method is * intended to undo that... see pr85132 */ public void validateType(UnresolvedType type) { ResolvedType result = typeMap.get(type.getSignature()); if (result==null) return; // We haven't heard of it yet if (!result.isExposedToWeaver()) return; // cant need resetting ReferenceType rt = (ReferenceType)result; rt.getDelegate().ensureDelegateConsistent(); // If we want to rebuild it 'from scratch' then: // ClassParser cp = new ClassParser(new ByteArrayInputStream(newbytes),new String(cs)); // try { // rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true)); // } catch (ClassFormatException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } } }
112,514
Bug 112514 ajc compile crash, not giving information which class file cause it
null
resolved fixed
999d9b0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-14T08:39:32Z
2005-10-13T16:13:20Z
bcel-builder/src/org/aspectj/apache/bcel/classfile/ClassParser.java
package org.aspectj.apache.bcel.classfile; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import org.aspectj.apache.bcel.Constants; import java.io.*; import java.util.zip.*; /** * Wrapper class that parses a given Java .class file. The method <A * href ="#parse">parse</A> returns a <A href ="JavaClass.html"> * JavaClass</A> object on success. When an I/O error or an * inconsistency occurs an appropiate exception is propagated back to * the caller. * * The structure and the names comply, except for a few conveniences, * exactly with the <A href="ftp://java.sun.com/docs/specs/vmspec.ps"> * JVM specification 1.0</a>. See this paper for * further details about the structure of a bytecode file. * * @version $Id: ClassParser.java,v 1.3 2005/09/14 11:10:57 aclement Exp $ * @author <A HREF="mailto:[email protected]">M. Dahm</A> */ public final class ClassParser { private DataInputStream file; private ZipFile zip; private String file_name; private int class_name_index, superclass_name_index; private int major, minor; // Compiler version private int access_flags; // Access rights of parsed class private int[] interfaces; // Names of implemented interfaces private ConstantPool constant_pool; // collection of constants private Field[] fields; // class fields, i.e., its variables private Method[] methods; // methods defined in the class private Attribute[] attributes; // attributes defined in the class private boolean is_zip; // Loaded from zip file private static final int BUFSIZE = 8192; /** * Parse class from the given stream. * * @param file Input stream * @param file_name File name */ public ClassParser(InputStream file, String file_name) { this.file_name = file_name; String clazz = file.getClass().getName(); // Not a very clean solution ... is_zip = clazz.startsWith("java.util.zip.") || clazz.startsWith("java.util.jar."); if(file instanceof DataInputStream) // Is already a data stream this.file = (DataInputStream)file; else this.file = new DataInputStream(new BufferedInputStream(file, BUFSIZE)); } /** Parse class from given .class file. * * @param file_name file name * @throws IOException */ public ClassParser(String file_name) throws IOException { is_zip = false; this.file_name = file_name; file = new DataInputStream(new BufferedInputStream (new FileInputStream(file_name), BUFSIZE)); } /** Parse class from given .class file in a ZIP-archive * * @param file_name file name * @throws IOException */ public ClassParser(String zip_file, String file_name) throws IOException { is_zip = true; zip = new ZipFile(zip_file); ZipEntry entry = zip.getEntry(file_name); this.file_name = file_name; file = new DataInputStream(new BufferedInputStream(zip.getInputStream(entry), BUFSIZE)); } /** * Parse the given Java class file and return an object that represents * the contained data, i.e., constants, methods, fields and commands. * A <em>ClassFormatException</em> is raised, if the file is not a valid * .class file. (This does not include verification of the byte code as it * is performed by the java interpreter). * * @return Class object representing the parsed class file * @throws IOException * @throws ClassFormatException */ public JavaClass parse() throws IOException, ClassFormatException { /****************** Read headers ********************************/ // Check magic tag of class file readID(); // Get compiler version readVersion(); /****************** Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); // Get interface information, i.e., implemented interfaces readInterfaces(); /****************** Read class fields and methods ***************/ // Read class fields, i.e., the variables of the class readFields(); // Read class methods, i.e., the functions in the class readMethods(); // Read class attributes readAttributes(); // Check for unknown variables //Unknown[] u = Unknown.getUnknownAttributes(); //for(int i=0; i < u.length; i++) // System.err.println("WARNING: " + u[i]); // Everything should have been read now // if(file.available() > 0) { // int bytes = file.available(); // byte[] buf = new byte[bytes]; // file.read(buf); // if(!(is_zip && (buf.length == 1))) { // System.err.println("WARNING: Trailing garbage at end of " + file_name); // System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf)); // } // } // Read everything of interest, so close the file file.close(); if(zip != null) zip.close(); // Return the information we have gathered in a new object return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, access_flags, constant_pool, interfaces, fields, methods, attributes, is_zip? JavaClass.ZIP : JavaClass.FILE); } /** * Read information about the attributes of the class. * @throws IOException * @throws ClassFormatException */ private final void readAttributes() throws IOException, ClassFormatException { int attributes_count; attributes_count = file.readUnsignedShort(); attributes = new Attribute[attributes_count]; for(int i=0; i < attributes_count; i++) attributes[i] = Attribute.readAttribute(file, constant_pool); } /** * Read information about the class and its super class. * @throws IOException * @throws ClassFormatException */ private final void readClassInfo() throws IOException, ClassFormatException { access_flags = file.readUnsignedShort(); /* Interfaces are implicitely abstract, the flag should be set * according to the JVM specification. */ if((access_flags & Constants.ACC_INTERFACE) != 0) access_flags |= Constants.ACC_ABSTRACT; // don't police it like this... leave higher level verification code to check it. // if(((access_flags & Constants.ACC_ABSTRACT) != 0) && // ((access_flags & Constants.ACC_FINAL) != 0 )) // throw new ClassFormatException("Class can't be both final and abstract"); class_name_index = file.readUnsignedShort(); superclass_name_index = file.readUnsignedShort(); } /** * Read constant pool entries. * @throws IOException * @throws ClassFormatException */ private final void readConstantPool() throws IOException, ClassFormatException { constant_pool = new ConstantPool(file); } /** * Read information about the fields of the class, i.e., its variables. * @throws IOException * @throws ClassFormatException */ private final void readFields() throws IOException, ClassFormatException { int fields_count; fields_count = file.readUnsignedShort(); fields = new Field[fields_count]; for(int i=0; i < fields_count; i++) fields[i] = new Field(file, constant_pool); } /******************** Private utility methods **********************/ /** * Check whether the header of the file is ok. * Of course, this has to be the first action on successive file reads. * @throws IOException * @throws ClassFormatException */ private final void readID() throws IOException, ClassFormatException { int magic = 0xCAFEBABE; if(file.readInt() != magic) throw new ClassFormatException(file_name + " is not a Java .class file"); } /** * Read information about the interfaces implemented by this class. * @throws IOException * @throws ClassFormatException */ private final void readInterfaces() throws IOException, ClassFormatException { int interfaces_count; interfaces_count = file.readUnsignedShort(); interfaces = new int[interfaces_count]; for(int i=0; i < interfaces_count; i++) interfaces[i] = file.readUnsignedShort(); } /** * Read information about the methods of the class. * @throws IOException * @throws ClassFormatException */ private final void readMethods() throws IOException, ClassFormatException { int methods_count; methods_count = file.readUnsignedShort(); methods = new Method[methods_count]; for(int i=0; i < methods_count; i++) methods[i] = new Method(file, constant_pool); } /** * Read major and minor version of compiler which created the file. * @throws IOException * @throws ClassFormatException */ private final void readVersion() throws IOException, ClassFormatException { minor = file.readUnsignedShort(); major = file.readUnsignedShort(); } }
107,299
Bug 107299 -aspectpath -inpath arguments fail without drive letter
ajc doesn't recognize Windows absolute file paths that don't start with a drive letter, e.g., run: ajc -inpath \test.jar [error] build config error: bad inpath component: \test.jar but ajc -inpath c:\test.jar works ajc -aspectpath \test.jar Test.aj [error] build config error: bad aspectpath: \test.jar ajc -aspectpath c:\test.jar Test.aj (works)
resolved fixed
332a5df
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-15T03:20:41Z
2005-08-18T04:40:00Z
util/src/org/aspectj/util/ConfigParser.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.util; import java.util.*; import java.io.*; public class ConfigParser { Location location; protected File relativeDirectory = null; protected List files = new LinkedList(); private boolean fileParsed = false; protected static String CONFIG_MSG = "build config error: "; public List getFiles() { return files; } public void parseCommandLine(String[] argsArray) throws ParseException { location = new CommandLineLocation(); LinkedList args = new LinkedList(); for (int i = 0; i < argsArray.length; i++) { args.add(new Arg(argsArray[i], location)); } parseArgs(args); } public void parseConfigFile(File configFile) throws ParseException { if (fileParsed == true) { throw new ParseException(CONFIG_MSG + "The file has already been parsed.", null); } else { parseConfigFileHelper(configFile); } } /** * @throws ParseException if the config file has already been prased. */ private void parseConfigFileHelper(File configFile) { if (!configFile.exists()) { showError("file does not exist: " + configFile.getPath()); return; } LinkedList args = new LinkedList(); int lineNum = 0; try { BufferedReader stream = new BufferedReader(new FileReader(configFile)); String line = null; while ( (line = stream.readLine()) != null) { lineNum += 1; line = stripWhitespaceAndComments(line); if (line.length() == 0) continue; args.add(new Arg(line, new SourceLocation(configFile, lineNum))); } } catch (IOException e) { location = new SourceLocation(configFile, lineNum); showError("error reading config file: " + e.toString()); } File oldRelativeDirectory = relativeDirectory; // for nested arg files; relativeDirectory = configFile.getParentFile(); parseArgs(args); relativeDirectory = oldRelativeDirectory; fileParsed = true; } File getCurrentDir() { return location.getDirectory(); } String stripSingleLineComment(String s, String commentString) { int commentStart = s.indexOf(commentString); if (commentStart == -1) return s; else return s.substring(0, commentStart); } String stripWhitespaceAndComments(String s) { s = stripSingleLineComment(s, "//"); s = stripSingleLineComment(s, "#"); s = s.trim(); if (s.startsWith("\"") && s.endsWith("\"")) { s = s.substring(1, s.length()-1); } return s; } /** ??? We would like to call a showNonFatalError method here * to show all errors in config files before aborting the compilation */ protected void addFile(File sourceFile) { if (!sourceFile.isFile()) { showError("source file does not exist: " + sourceFile.getPath()); } files.add(sourceFile); } void addFileOrPattern(File sourceFile) { if (sourceFile.getName().equals("*.java")) { addFiles(sourceFile.getParentFile(), new FileFilter() { public boolean accept(File f) { return f != null && f.getName().endsWith(".java"); }}); } else if (sourceFile.getName().equals("*.aj")) { addFiles(sourceFile.getParentFile(), new FileFilter() { public boolean accept(File f) { return f != null && f.getName().endsWith(".aj"); }}); } else { addFile(sourceFile); } } void addFiles(File dir, FileFilter filter) { if (dir == null) dir = new File(System.getProperty("user.dir")); if (!dir.isDirectory()) { showError("can't find " + dir.getPath()); } else { File[] files = dir.listFiles(filter); if (files.length == 0) { showWarning("no matching files found in: " + dir); } for (int i = 0; i < files.length; i++) { addFile(files[i]); } } } protected void parseOption(String arg, LinkedList args) { showWarning("unrecognized option: " + arg); } protected void showWarning(String message) { if (location != null) { message += " at " + location.toString(); } System.err.println(CONFIG_MSG + message); } protected void showError(String message) { throw new ParseException(CONFIG_MSG + message, location); } void parseArgs(LinkedList args) { while (args.size() > 0) parseOneArg(args); } protected Arg removeArg(LinkedList args) { if (args.size() == 0) { showError("value missing"); return null; } else { return (Arg)args.removeFirst(); } } protected String removeStringArg(LinkedList args) { Arg arg = removeArg(args); if (arg == null) return null; return arg.getValue(); } boolean isSourceFileName(String s) { if (s.endsWith(".java")) return true; if (s.endsWith(".aj")) return true; if (s.endsWith(".ajava")) { showWarning(".ajava is deprecated, replace with .aj or .java: " + s); return true; } return false; } void parseOneArg(LinkedList args) { Arg arg = removeArg(args); String v = arg.getValue(); location = arg.getLocation(); if (v.startsWith("@")) { parseImportedConfigFile(v.substring(1)); } else if (v.equals("-argfile")) { parseConfigFileHelper(makeFile(removeArg(args).getValue())); } else if (isSourceFileName(v)) { addFileOrPattern(makeFile(v)); } else { parseOption(arg.getValue(), args); } } protected void parseImportedConfigFile(String relativeFilePath) { parseConfigFileHelper(makeFile(relativeFilePath)); } public File makeFile(String name) { if (relativeDirectory != null) { return makeFile(relativeDirectory,name); } else { return makeFile(getCurrentDir(), name); } } private File makeFile(File dir, String name) { name = name.replace('/', File.separatorChar); File ret = new File(name); if (dir != null && !ret.isAbsolute()) { ret = new File(dir, name); } try { ret = ret.getCanonicalFile(); } catch (IOException ioEx) { // proceed without canonicalization // so nothing to do here } return ret; } protected static class Arg { private Location location; private String value; public Arg(String value, Location location) { this.value = value; this.location = location; } public void setValue(String value) { this.value = value; } public void setLocation(Location location) { this.location = location; } public String getValue() { return value; } public Location getLocation() { return location; } } static abstract class Location { public abstract File getFile(); public abstract File getDirectory(); public abstract int getLine(); public abstract String toString(); } static class SourceLocation extends Location { private int line; private File file; public SourceLocation(File file, int line) { this.line = line; this.file = file; } public File getFile() { return file; } public File getDirectory() { return file.getParentFile(); } public int getLine() { return line; } public String toString() { return file.getPath()+":"+line; } } static class CommandLineLocation extends Location { public File getFile() { return new File(System.getProperty("user.dir")); } public File getDirectory() { return new File(System.getProperty("user.dir")); } public int getLine() { return -1; } public String toString() { return "command-line"; } } public static class ParseException extends RuntimeException { private Location location; public ParseException(String message, Location location) { super(message); this.location = location; } public int getLine() { if (location == null) return -1; return location.getLine(); } public File getFile() { if (location == null) return null; return location.getFile(); } } }
112,027
Bug 112027 unexpected error unboundFormalInPC
In 1.5.0M4, I get error "the parameter tis is not bound in [all branches of] pointcut". Not true of 1.2.1. Untested in other development versions of 1.5.0. No branches (all &&) but duplicate specification of this(..). ------------------------------------------ package demo; /** * PerThis */ public class PerThis { public static void main(String[] args) { new This().test(); } } aspect PerThisTest perthis(pc()) { // TutIndex example-basic-perthis pointcut pc() : this(This) && !within(PerThisTest) && call(void run()); before(This tis) : pc() && this(tis){ System.out.println("bef " + this + " <-- " + tis); } } class This { int i; void test() { run(); } void run() { System.out.println("run " + this); } }
resolved fixed
ae612d9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-18T15:40:35Z
2005-10-08T05:40:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.internal.Relationship; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } /* Andys bug area - enter at your own risk... public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");} public void testMissingAccessor_pr73856() { runTest("missing accessor");} public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");} public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");} public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");} */ public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");} public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");} public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");} public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");} public void testVarargsITD_pr110906() { runTest("ITD varargs problem");} public void testBadGenericSigAttribute_pr110927() { runTest("cant create signature attribute"); Signature sig = GenericsTests.getClassSignature(ajc,"I"); if (sig==null) fail("Couldn't find signature attribute for type I"); String sigString = sig.getSignature(); if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") || sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) { fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"); } } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");} public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } // IfPointcut.findResidueInternal() was modified to make this test complete in a short amount // of time - if you see it hanging, someone has messed with the optimization. public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");} public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testAtAnnotationBadTest_pr103740() { runTest("Compiler failure on at_annotation"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } public void testNoVerifyErrorOnGenericCollectionMemberAccess() { runTest("no verify error on generic collection member access"); } public void testRawAndGenericTypeConversionITDCons() { runTest("raw and generic type conversion with itd cons"); } public void testAtAnnotationBindingWithAround() { runTest("@annotation binding with around advice"); } public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");} public void testMessageOnMissingTypeInDecP() { runTest("declare parents on a missing type"); } public void testParameterizedGenericMethods() { runTest("parameterized generic methods"); } public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");} public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");} public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");} public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");} public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");} // Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats // where we can police whether a type variable has been used without being specified appropriately. //public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");} public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");} public void testCallJoinPointsInAnonymousInnerClasses() { runTest("call join points in anonymous inner classes"); } public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() { runTest("default impl of Runnable"); } public void testArrayCloneCallJoinPoints() { runTest("array clone call join points in 1.4 vs 1.3"); } public void testDebugInfoForAroundAdvice() { runTest("debug info in around advice inlining"); } public void testCCEWithGenericWildcard_pr112602() { runTest("ClassCastException with generic wildcard"); } public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the run() method inside anonymous inner class is in // the structure model IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"run()"); assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'run()' but is " + target.toLabelString(),"run()",target.toLabelString()); } public void testAdviceInStructureModelWithNamedInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with named inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the m() method inside named inner class is in // the structure model IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"m()"); assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'm()' but is " + target.toLabelString(),"m()",target.toLabelString()); } public void testDWInStructureModelWithAnonymousInnerClass_pr77269() { // AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("declare warning in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())"); assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe); } public void testVarArgsIITDInConstructor() { runTest("ITD varargs in constructor"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
112,027
Bug 112027 unexpected error unboundFormalInPC
In 1.5.0M4, I get error "the parameter tis is not bound in [all branches of] pointcut". Not true of 1.2.1. Untested in other development versions of 1.5.0. No branches (all &&) but duplicate specification of this(..). ------------------------------------------ package demo; /** * PerThis */ public class PerThis { public static void main(String[] args) { new This().test(); } } aspect PerThisTest perthis(pc()) { // TutIndex example-basic-perthis pointcut pc() : this(This) && !within(PerThisTest) && call(void run()); before(This tis) : pc() && this(tis){ System.out.println("bef " + this + " <-- " + tis); } } class This { int i; void test() { run(); } void run() { System.out.println("run " + this); } }
resolved fixed
ae612d9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-18T15:40:35Z
2005-10-08T05:40:00Z
weaver/src/org/aspectj/weaver/patterns/BindingTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; public class BindingTypePattern extends ExactTypePattern implements BindingPattern { private int formalIndex; public BindingTypePattern(UnresolvedType type, int index,boolean isVarArgs) { super(type, false,isVarArgs); this.formalIndex = index; } public BindingTypePattern(FormalBinding binding, boolean isVarArgs) { this(binding.getType(), binding.getIndex(),isVarArgs); } public int getFormalIndex() { return formalIndex; } public boolean equals(Object other) { if (!(other instanceof BindingTypePattern)) return false; BindingTypePattern o = (BindingTypePattern)other; if (includeSubtypes != o.includeSubtypes) return false; if (isVarArgs != o.isVarArgs) return false; return o.type.equals(this.type) && o.formalIndex == this.formalIndex; } public int hashCode() { int result = 17; result = 37*result + type.hashCode(); result = 37*result + formalIndex; return result; } public void write(DataOutputStream out) throws IOException { out.writeByte(TypePattern.BINDING); type.write(out); out.writeShort((short)formalIndex); out.writeBoolean(isVarArgs); writeLocation(out); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { UnresolvedType type = UnresolvedType.read(s); int index = s.readShort(); boolean isVarargs = false; if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { isVarargs = s.readBoolean(); } TypePattern ret = new BindingTypePattern(type,index,isVarargs); ret.readLocation(context, s); return ret; } public TypePattern remapAdviceFormals(IntMap bindings) { if (!bindings.hasKey(formalIndex)) { return new ExactTypePattern(type, false, isVarArgs); } else { int newFormalIndex = bindings.get(formalIndex); return new BindingTypePattern(type, newFormalIndex, isVarArgs); } } public TypePattern parameterizeWith(Map typeVariableMap) { ExactTypePattern superParameterized = (ExactTypePattern) super.parameterizeWith(typeVariableMap); BindingTypePattern ret = new BindingTypePattern(superParameterized.getExactType(),this.formalIndex,this.isVarArgs); ret.copyLocationFrom(this); return ret; } public String toString() { //Thread.currentThread().dumpStack(); return "BindingTypePattern(" + super.toString() + ", " + formalIndex + ")"; } }
112,027
Bug 112027 unexpected error unboundFormalInPC
In 1.5.0M4, I get error "the parameter tis is not bound in [all branches of] pointcut". Not true of 1.2.1. Untested in other development versions of 1.5.0. No branches (all &&) but duplicate specification of this(..). ------------------------------------------ package demo; /** * PerThis */ public class PerThis { public static void main(String[] args) { new This().test(); } } aspect PerThisTest perthis(pc()) { // TutIndex example-basic-perthis pointcut pc() : this(This) && !within(PerThisTest) && call(void run()); before(This tis) : pc() && this(tis){ System.out.println("bef " + this + " <-- " + tis); } } class This { int i; void test() { run(); } void run() { System.out.println("run " + this); } }
resolved fixed
ae612d9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-18T15:40:35Z
2005-10-08T05:40:00Z
weaver/src/org/aspectj/weaver/patterns/ExactTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.TypeVariableReferenceType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; public class ExactTypePattern extends TypePattern { protected UnresolvedType type; public static final Map primitiveTypesMap; public static final Map boxedPrimitivesMap; private static final Map boxedTypesMap; static { primitiveTypesMap = new HashMap(); primitiveTypesMap.put("int",int.class); primitiveTypesMap.put("short",short.class); primitiveTypesMap.put("long",long.class); primitiveTypesMap.put("byte",byte.class); primitiveTypesMap.put("char",char.class); primitiveTypesMap.put("float",float.class); primitiveTypesMap.put("double",double.class); boxedPrimitivesMap = new HashMap(); boxedPrimitivesMap.put("java.lang.Integer",Integer.class); boxedPrimitivesMap.put("java.lang.Short",Short.class); boxedPrimitivesMap.put("java.lang.Long",Long.class); boxedPrimitivesMap.put("java.lang.Byte",Byte.class); boxedPrimitivesMap.put("java.lang.Character",Character.class); boxedPrimitivesMap.put("java.lang.Float",Float.class); boxedPrimitivesMap.put("java.lang.Double",Double.class); boxedTypesMap = new HashMap(); boxedTypesMap.put("int",Integer.class); boxedTypesMap.put("short",Short.class); boxedTypesMap.put("long",Long.class); boxedTypesMap.put("byte",Byte.class); boxedTypesMap.put("char",Character.class); boxedTypesMap.put("float",Float.class); boxedTypesMap.put("double",Double.class); } public ExactTypePattern(UnresolvedType type, boolean includeSubtypes,boolean isVarArgs) { super(includeSubtypes,isVarArgs); this.type = type; } public boolean isArray() { return type.isArray(); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (super.couldEverMatchSameTypesAs(other)) return true; // false is necessary but not sufficient UnresolvedType otherType = other.getExactType(); if (otherType != ResolvedType.MISSING) { return type.equals(otherType); } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String yourSimpleNamePrefix = owtp.getNamePatterns()[0].maybeGetSimpleName(); if (yourSimpleNamePrefix != null) { return (type.getName().startsWith(yourSimpleNamePrefix)); } } return true; } protected boolean matchesExactly(ResolvedType matchType) { boolean typeMatch = this.type.equals(matchType); if (!typeMatch && (matchType.isParameterizedType() || matchType.isGenericType())) { typeMatch = this.type.equals(matchType.getRawType()); } if (!typeMatch && matchType.isTypeVariableReference()) { typeMatch = matchesTypeVariable((TypeVariableReferenceType)matchType); } annotationPattern.resolve(matchType.getWorld()); boolean annMatch = this.annotationPattern.matches(matchType).alwaysTrue(); return (typeMatch && annMatch); } private boolean matchesTypeVariable(TypeVariableReferenceType matchType) { return false; } protected boolean matchesExactly(ResolvedType matchType, ResolvedType annotatedType) { boolean typeMatch = this.type.equals(matchType); if (!typeMatch && (matchType.isParameterizedType() || matchType.isGenericType())) { typeMatch = this.type.equals(matchType.getRawType()); } if (!typeMatch && matchType.isTypeVariableReference()) { typeMatch = matchesTypeVariable((TypeVariableReferenceType)matchType); } annotationPattern.resolve(matchType.getWorld()); boolean annMatch = this.annotationPattern.matches(annotatedType).alwaysTrue(); return (typeMatch && annMatch); } public UnresolvedType getType() { return type; } // true if (matchType instanceof this.type) public FuzzyBoolean matchesInstanceof(ResolvedType matchType) { // in our world, Object is assignable from anything if (type.equals(ResolvedType.OBJECT)) return FuzzyBoolean.YES.and(annotationPattern.matches(matchType)); if (type.resolve(matchType.getWorld()).isAssignableFrom(matchType)) { return FuzzyBoolean.YES.and(annotationPattern.matches(matchType)); } // fix for PR 64262 - shouldn't try to coerce primitives if (type.isPrimitiveType()) { return FuzzyBoolean.NO; } else { return matchType.isCoerceableFrom(type.resolve(matchType.getWorld())) ? FuzzyBoolean.MAYBE : FuzzyBoolean.NO; } } public boolean equals(Object other) { if (!(other instanceof ExactTypePattern)) return false; ExactTypePattern o = (ExactTypePattern)other; if (includeSubtypes != o.includeSubtypes) return false; if (isVarArgs != o.isVarArgs) return false; if (!typeParameters.equals(o.typeParameters)) return false; return (o.type.equals(this.type) && o.annotationPattern.equals(this.annotationPattern)); } public int hashCode() { int result = 17; result = 37*result + type.hashCode(); result = 37*result + annotationPattern.hashCode(); return result; } private static final byte EXACT_VERSION = 1; // rev if changed public void write(DataOutputStream out) throws IOException { out.writeByte(TypePattern.EXACT); out.writeByte(EXACT_VERSION); type.write(out); out.writeBoolean(includeSubtypes); out.writeBoolean(isVarArgs); annotationPattern.write(out); typeParameters.write(out); writeLocation(out); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { return readTypePattern150(s,context); } else { return readTypePatternOldStyle(s,context); } } public static TypePattern readTypePattern150(VersionedDataInputStream s, ISourceContext context) throws IOException { byte version = s.readByte(); if (version > EXACT_VERSION) throw new BCException("ExactTypePattern was written by a more recent version of AspectJ"); TypePattern ret = new ExactTypePattern(UnresolvedType.read(s), s.readBoolean(), s.readBoolean()); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); ret.setTypeParameters(TypePatternList.read(s,context)); ret.readLocation(context, s); return ret; } public static TypePattern readTypePatternOldStyle(DataInputStream s, ISourceContext context) throws IOException { TypePattern ret = new ExactTypePattern(UnresolvedType.read(s), s.readBoolean(),false); ret.readLocation(context, s); return ret; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } String typeString = type.toString(); if (isVarArgs) typeString = typeString.substring(0,typeString.lastIndexOf('[')); buff.append(typeString); if (includeSubtypes) buff.append('+'); if (isVarArgs) buff.append("..."); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { throw new BCException("trying to re-resolve"); } /** * return a version of this type pattern with all type variables references replaced * by the corresponding entry in the map. */ public TypePattern parameterizeWith(Map typeVariableMap) { UnresolvedType newType = type; if (type.isTypeVariableReference()) { TypeVariableReference t = (TypeVariableReference) type; String key = t.getTypeVariable().getName(); if (typeVariableMap.containsKey(key)) { newType = (UnresolvedType) typeVariableMap.get(key); } } else if (type.isParameterizedType()) { newType = type.parameterize(typeVariableMap); } ExactTypePattern ret = new ExactTypePattern(newType,includeSubtypes,isVarArgs); ret.annotationPattern = annotationPattern.parameterizeWith(typeVariableMap); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
113,073
Bug 113073 weaveinfo messages not reported if applying declare @method on an ITD'd method
Given the following class: @interface Annotation{} aspect B { declare @method : public * C.anotherMethod(..) : @Annotation; } class C { } aspect D { public void C.anotherMethod(String s) { } public void C.anotherMethod() { } } I would expect a two weaveinfo messages of the form: weaveinfo 'public void C.anotherMethod()' (pr99191_4.java) is annotated with @Annotation method annotation from 'B' (pr99191_4.java:3) weaveinfo 'public void C.anotherMethod(String)' (pr99191_4.java) is annotated with @Annotation method annotation from 'B' (pr99191_4.java:3) However, only the two "intertyped" messages are coming out.
resolved fixed
f06df41
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-20T13:54:50Z
2005-10-19T13:53:20Z
tests/bugs150/pr113073.java
113,073
Bug 113073 weaveinfo messages not reported if applying declare @method on an ITD'd method
Given the following class: @interface Annotation{} aspect B { declare @method : public * C.anotherMethod(..) : @Annotation; } class C { } aspect D { public void C.anotherMethod(String s) { } public void C.anotherMethod() { } } I would expect a two weaveinfo messages of the form: weaveinfo 'public void C.anotherMethod()' (pr99191_4.java) is annotated with @Annotation method annotation from 'B' (pr99191_4.java:3) weaveinfo 'public void C.anotherMethod(String)' (pr99191_4.java) is annotated with @Annotation method annotation from 'B' (pr99191_4.java:3) However, only the two "intertyped" messages are coming out.
resolved fixed
f06df41
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-20T13:54:50Z
2005-10-19T13:53:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.internal.Relationship; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } /* Andys bug area - enter at your own risk... public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");} public void testMissingAccessor_pr73856() { runTest("missing accessor");} public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");} public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");} public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");} */ public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");} public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");} public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");} public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");} public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");} public void testVarargsITD_pr110906() { runTest("ITD varargs problem");} public void testBadGenericSigAttribute_pr110927() { runTest("cant create signature attribute"); Signature sig = GenericsTests.getClassSignature(ajc,"I"); if (sig==null) fail("Couldn't find signature attribute for type I"); String sigString = sig.getSignature(); if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") || sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) { fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"); } } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");} public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } // IfPointcut.findResidueInternal() was modified to make this test complete in a short amount // of time - if you see it hanging, someone has messed with the optimization. public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");} public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testAtAnnotationBadTest_pr103740() { runTest("Compiler failure on at_annotation"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } public void testNoVerifyErrorOnGenericCollectionMemberAccess() { runTest("no verify error on generic collection member access"); } public void testRawAndGenericTypeConversionITDCons() { runTest("raw and generic type conversion with itd cons"); } public void testAtAnnotationBindingWithAround() { runTest("@annotation binding with around advice"); } public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");} public void testMessageOnMissingTypeInDecP() { runTest("declare parents on a missing type"); } public void testParameterizedGenericMethods() { runTest("parameterized generic methods"); } public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");} public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");} public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");} public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");} public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");} // Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats // where we can police whether a type variable has been used without being specified appropriately. //public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");} public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");} public void testCallJoinPointsInAnonymousInnerClasses() { runTest("call join points in anonymous inner classes"); } public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() { runTest("default impl of Runnable"); } public void testArrayCloneCallJoinPoints() { runTest("array clone call join points in 1.4 vs 1.3"); } public void testDebugInfoForAroundAdvice() { runTest("debug info in around advice inlining"); } public void testCCEWithGenericWildcard_pr112602() { runTest("ClassCastException with generic wildcard"); } public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the run() method inside anonymous inner class is in // the structure model IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"run()"); assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'run()' but is " + target.toLabelString(),"run()",target.toLabelString()); } public void testAdviceInStructureModelWithNamedInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with named inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the m() method inside named inner class is in // the structure model IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"m()"); assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'm()' but is " + target.toLabelString(),"m()",target.toLabelString()); } public void testDWInStructureModelWithAnonymousInnerClass_pr77269() { // AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("declare warning in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())"); assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe); } public void testVarArgsIITDInConstructor() { runTest("ITD varargs in constructor"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
113,073
Bug 113073 weaveinfo messages not reported if applying declare @method on an ITD'd method
Given the following class: @interface Annotation{} aspect B { declare @method : public * C.anotherMethod(..) : @Annotation; } class C { } aspect D { public void C.anotherMethod(String s) { } public void C.anotherMethod() { } } I would expect a two weaveinfo messages of the form: weaveinfo 'public void C.anotherMethod()' (pr99191_4.java) is annotated with @Annotation method annotation from 'B' (pr99191_4.java:3) weaveinfo 'public void C.anotherMethod(String)' (pr99191_4.java) is annotated with @Annotation method annotation from 'B' (pr99191_4.java:3) However, only the two "intertyped" messages are coming out.
resolved fixed
f06df41
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-20T13:54:50Z
2005-10-19T13:53:20Z
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.IndexedInstruction; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.NEW; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUTFIELD; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.RET; import org.aspectj.apache.bcel.generic.ReturnInstruction; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.PartialOrder; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IClassWeaver; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.DeclareAnnotation; class BcelClassWeaver implements IClassWeaver { /** * This is called from {@link BcelWeaver} to perform the per-class weaving process. */ public static boolean weave( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers).weave(); //System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState()); //clazz.print(); return b; } // -------------------------------------------- private final LazyClassGen clazz; private final List shadowMungers; private final List typeMungers; private final List lateTypeMungers; private final BcelObjectType ty; // alias of clazz.getType() private final BcelWorld world; // alias of ty.getWorld() private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen() private final InstructionFactory fact; // alias of clazz.getFactory(); private final List addedLazyMethodGens = new ArrayList(); private final Set addedDispatchTargets = new HashSet(); // Static setting across BcelClassWeavers private static boolean inReweavableMode = false; private List addedSuperInitializersAsList = null; // List<IfaceInitList> private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger> private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger> private Map mapToAnnotations = new HashMap(); private BcelShadow clinitShadow = null; /** * This holds the initialization and pre-initialization shadows for this class * that were actually matched by mungers (if no match, then we don't even create the * shadows really). */ private final List initializationShadows = new ArrayList(1); private BcelClassWeaver( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { super(); // assert world == clazz.getType().getWorld() this.world = world; this.clazz = clazz; this.shadowMungers = shadowMungers; this.typeMungers = typeMungers; this.lateTypeMungers = lateTypeMungers; this.ty = clazz.getBcelObjectType(); this.cpg = clazz.getConstantPoolGen(); this.fact = clazz.getFactory(); fastMatchShadowMungers(shadowMungers); initializeSuperInitializerMap(ty.getResolvedTypeX()); } private List[] perKindShadowMungers; private boolean canMatchBodyShadows = false; private boolean canMatchInitialization = false; private void fastMatchShadowMungers(List shadowMungers) { // beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) ! perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1]; for (int i = 0; i < perKindShadowMungers.length; i++) { perKindShadowMungers[i] = new ArrayList(0); } for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Set couldMatchKinds = munger.getPointcut().couldMatchKinds(); for (Iterator kindIterator = couldMatchKinds.iterator(); kindIterator.hasNext();) { Shadow.Kind aKind = (Shadow.Kind) kindIterator.next(); perKindShadowMungers[aKind.getKey()].add(munger); } } if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty()) canMatchInitialization = true; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (!kind.isEnclosingKind() && !perKindShadowMungers[i+1].isEmpty()) { canMatchBodyShadows = true; } if (perKindShadowMungers[i+1].isEmpty()) { perKindShadowMungers[i+1] = null; } } } private boolean canMatch(Shadow.Kind kind) { return perKindShadowMungers[kind.getKey()] != null; } // private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) { // FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind); // for (Iterator i = shadowMungers.iterator(); i.hasNext();) { // ShadowMunger munger = (ShadowMunger) i.next(); // FuzzyBoolean fb = munger.getPointcut().fastMatch(info); // WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString() // if (fb.maybeTrue()) mungers.add(munger); // } // } private void initializeSuperInitializerMap(ResolvedType child) { ResolvedType[] superInterfaces = child.getDeclaredInterfaces(); for (int i=0, len=superInterfaces.length; i < len; i++) { if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) { if (addSuperInitializer(superInterfaces[i])) { initializeSuperInitializerMap(superInterfaces[i]); } } } } private boolean addSuperInitializer(ResolvedType onType) { if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); if (l != null) return false; l = new IfaceInitList(onType); addedSuperInitializers.put(onType, l); return true; } public void addInitializer(ConcreteTypeMunger cm) { NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger(); ResolvedType onType = m.getSignature().getDeclaringType().resolve(world); if (onType.isRawType()) onType = onType.getGenericType(); if (m.getSignature().isStatic()) { addedClassInitializers.add(cm); } else { if (onType == ty.getResolvedTypeX()) { addedThisInitializers.add(cm); } else { IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); l.list.add(cm); } } } private static class IfaceInitList implements PartialOrder.PartialComparable { final ResolvedType onType; List list = new ArrayList(); IfaceInitList(ResolvedType onType) { this.onType = onType; } public int compareTo(Object other) { IfaceInitList o = (IfaceInitList)other; if (onType.isAssignableFrom(o.onType)) return +1; else if (o.onType.isAssignableFrom(onType)) return -1; else return 0; } public int fallbackCompareTo(Object other) { return 0; } } // XXX this is being called, but the result doesn't seem to be being used public boolean addDispatchTarget(ResolvedMember m) { return addedDispatchTargets.add(m); } public void addLazyMethodGen(LazyMethodGen gen) { addedLazyMethodGens.add(gen); } public void addOrReplaceLazyMethodGen(LazyMethodGen mg) { if (alreadyDefined(clazz, mg)) return; for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (existing.definingType == null) { // this means existing was introduced on the class itself return; } else if (mg.definingType.isAssignableFrom(existing.definingType)) { // existing is mg's subtype and dominates mg return; } else if (existing.definingType.isAssignableFrom(mg.definingType)) { // mg is existing's subtype and dominates existing i.remove(); addedLazyMethodGens.add(mg); return; } else { throw new BCException("conflict between: " + mg + " and " + existing); } } } addedLazyMethodGens.add(mg); } private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) { for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (!mg.isAbstract() && existing.isAbstract()) { i.remove(); return false; } return true; } } return false; } private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) { return mg.getName().equals(existing.getName()) && mg.getSignature().equals(existing.getSignature()); } // ---- public boolean weave() { if (clazz.isWoven() && !clazz.isReweavable()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()), ty.getSourceLocation(), null); return false; } Set aspectsAffectingType = null; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType = new HashSet(); boolean isChanged = false; // we want to "touch" all aspects if (clazz.getType().isAspect()) isChanged = true; // start by munging all typeMungers for (Iterator i = typeMungers.iterator(); i.hasNext(); ) { Object o = i.next(); if ( !(o instanceof BcelTypeMunger) ) { //???System.err.println("surprising: " + o); continue; } BcelTypeMunger munger = (BcelTypeMunger)o; boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } // Weave special half type/half shadow mungers... isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged; isChanged = weaveDeclareAtField(clazz) || isChanged; // XXX do major sort of stuff // sort according to: Major: type hierarchy // within each list: dominates // don't forget to sort addedThisInitialiers according to dominates addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values()); addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList); if (addedSuperInitializersAsList == null) { throw new BCException("circularity in inter-types"); } // this will create a static initializer if there isn't one // this is in just as bad taste as NOPs LazyMethodGen staticInit = clazz.getStaticInitializer(); staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true)); // now go through each method, and match against each method. This // sets up each method's {@link LazyMethodGen#matchedShadows} field, // and it also possibly adds to {@link #initializationShadows}. List methodGens = new ArrayList(clazz.getMethodGens()); for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; boolean shadowMungerMatched = match(mg); if (shadowMungerMatched) { // For matching mungers, add their declaring aspects to the list that affected this type if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.addAll(findAspectsForMungers(mg)); isChanged = true; } } // now we weave all but the initialization shadows for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; implement(mg); } // if we matched any initialization shadows, we inline and weave if (! initializationShadows.isEmpty()) { // Repeat next step until nothing left to inline...cant go on // infinetly as compiler will have detected and reported // "Recursive constructor invocation" while (inlineSelfConstructors(methodGens)); positionAndImplement(initializationShadows); } // now proceed with late type mungers if (lateTypeMungers != null) { for (Iterator i = lateTypeMungers.iterator(); i.hasNext(); ) { BcelTypeMunger munger = (BcelTypeMunger)i.next(); if (munger.matches(clazz.getType())) { boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } } } //FIXME AV - see #75442, for now this is not enough to fix the bug, comment that out until we really fix it // // flush to save some memory // PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType()); // finally, if we changed, we add in the introduced methods. if (isChanged) { clazz.getOrCreateWeaverStateInfo(inReweavableMode); weaveInAddedMethods(); // FIXME asc are these potentially affected by declare annotation? } if (inReweavableMode) { WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(true); wsi.addAspectsAffectingType(aspectsAffectingType); wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes()); wsi.setReweavable(true); } else { clazz.getOrCreateWeaverStateInfo(false).setReweavable(false); } return isChanged; } /** * Weave any declare @method/@ctor statements into the members of the supplied class */ private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) { List reportedProblems = new ArrayList(); List allDecams = world.getDeclareAnnotationOnMethods(); if (allDecams.isEmpty()) return false; // nothing to do boolean isChanged = false; // deal with ITDs List itdMethodsCtors = getITDSubset(clazz,ResolvedTypeMunger.Method); itdMethodsCtors.addAll(getITDSubset(clazz,ResolvedTypeMunger.Constructor)); if (!itdMethodsCtors.isEmpty()) { // Can't use the subset called 'decaMs' as it won't be right for ITDs... isChanged = weaveAtMethodOnITDSRepeatedly(allDecams,itdMethodsCtors,reportedProblems); } // deal with all the other methods... List members = clazz.getMethodGens(); List decaMs = getMatchingSubset(allDecams,clazz.getType()); if (decaMs.isEmpty()) return false; // nothing to do if (!members.isEmpty()) { for (int memberCounter = 0;memberCounter<members.size();memberCounter++) { LazyMethodGen mg = (LazyMethodGen)members.get(memberCounter); if (!mg.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter = decaMs.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) continue; // skip this one... Annotation a = decaM.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); Method oldMethod = mg.getMethod(); MethodGen myGen = new MethodGen(oldMethod,clazz.getClassName(),clazz.getConstantPoolGen()); myGen.addAnnotation(ag); Method newMethod = myGen.getMethod(); mg.addAnnotation(decaM.getAnnotationX()); members.set(memberCounter,new LazyMethodGen(newMethod,clazz)); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); reportMethodCtorWeavingMessage(clazz, mg, decaM); isChanged = true; modificationOccured = true; } else { if (!decaM.isStarredAnnotationPattern()) worthRetrying.add(decaM); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) continue; // skip this one... mg.addAnnotation(decaM.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); isChanged = true; modificationOccured = true; forRemoval.add(decaM); } } worthRetrying.removeAll(forRemoval); } } } } return isChanged; } // TAG: WeavingMessage private void reportMethodCtorWeavingMessage(LazyClassGen clazz, LazyMethodGen mg, DeclareAnnotation decaM) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ StringBuffer parmString = new StringBuffer("("); Type[] args = mg.getMethod().getArgumentTypes(); for (int i = 0; i < args.length; i++) { Type type2 = args[i]; String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type2.getSignature()); if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1); parmString.append(s); if ((i+1)<args.length) parmString.append(","); } parmString.append(")"); String methodName = mg.getMethod().getName(); StringBuffer sig = new StringBuffer(); sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(mg.getMethod().getAccessFlags()) ); sig.append(" "); sig.append(mg.getMethod().getReturnType().toString()); sig.append(" "); sig.append(clazz.getName()); sig.append("."); sig.append(methodName.equals("<init>")?"new":methodName); sig.append(parmString); StringBuffer loc = new StringBuffer(); if (clazz.getFileName()==null) { loc.append("no debug info available"); } else { loc.append(clazz.getFileName()); if (mg.getDeclarationLineNumber()!=-1) { loc.append(":"+mg.getDeclarationLineNumber()); } } getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ sig.toString(), loc.toString(), decaM.getAnnotationString(), methodName.startsWith("<init>")?"constructor":"method", decaM.getAspect().toString(), Utility.beautifyLocation(decaM.getSourceLocation()) })); } } /** * Looks through a list of declare annotation statements and only returns * those that could possibly match on a field/method/ctor in type. */ private List getMatchingSubset(List declareAnnotations, ResolvedType type) { List subset = new ArrayList(); for (Iterator iter = declareAnnotations.iterator(); iter.hasNext();) { DeclareAnnotation da = (DeclareAnnotation) iter.next(); if (da.couldEverMatch(type)) { subset.add(da); } } return subset; } /** * Get a subset of all the type mungers defined on this aspect */ private List getITDSubset(LazyClassGen clazz,ResolvedTypeMunger.Kind wantedKind) { List subset = new ArrayList(); Collection c = clazz.getBcelObjectType().getTypeMungers(); for (Iterator iter = c.iterator();iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger)iter.next(); if (typeMunger.getMunger().getKind()==wantedKind) subset.add(typeMunger); } return subset; } public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz,BcelTypeMunger fieldMunger) { NewFieldTypeMunger nftm = (NewFieldTypeMunger)fieldMunger.getMunger(); ResolvedMember lookingFor =AjcMemberMaker.interFieldInitializer(nftm.getSignature(),clazz.getType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName())) return element; } return null; } // FIXME asc refactor this to neaten it up public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz,BcelTypeMunger methodCtorMunger) { if (methodCtorMunger.getMunger() instanceof NewMethodTypeMunger) { NewMethodTypeMunger nftm = (NewMethodTypeMunger)methodCtorMunger.getMunger(); ResolvedMember lookingFor = AjcMemberMaker.interMethodDispatcher(nftm.getSignature(),methodCtorMunger.getAspectType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element; } return null; } else if (methodCtorMunger.getMunger() instanceof NewConstructorTypeMunger) { NewConstructorTypeMunger nftm = (NewConstructorTypeMunger)methodCtorMunger.getMunger(); ResolvedMember lookingFor =AjcMemberMaker.postIntroducedConstructor(methodCtorMunger.getAspectType(),nftm.getSignature().getDeclaringType(),nftm.getSignature().getParameterTypes()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element; } return null; } else { throw new RuntimeException("Not sure what this is: "+methodCtorMunger); } } /** * Applies some set of declare @field constructs (List<DeclareAnnotation>) to some bunch * of ITDfields (List<BcelTypeMunger>. It will iterate over the fields repeatedly until * everything has been applied. * */ private boolean weaveAtFieldRepeatedly(List decaFs, List itdFields,List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdFields.iterator(); iter.hasNext();) { BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next(); ResolvedMember itdIsActually = fieldMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaFs.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaF); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } /** * Applies some set of declare @method/@ctor constructs (List<DeclareAnnotation>) to some bunch * of ITDmembers (List<BcelTypeMunger>. It will iterate over the fields repeatedly until * everything has been applied. */ private boolean weaveAtMethodOnITDSRepeatedly(List decaMCs, List itdMethodsCtors,List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdMethodsCtors.iterator(); iter.hasNext();) { BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next(); ResolvedMember unMangledInterMethod = methodctorMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaMCs.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz,methodctorMunger); if (annotationHolder == null || doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)){ continue; // skip this one... } annotationHolder.addAnnotation(decaMC.getAnnotationX()); isChanged=true; AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation()); modificationOccured = true; } else { if (!decaMC.isStarredAnnotationPattern()) worthRetrying.add(decaMC); // an annotation is specified that might be put on by a subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,methodctorMunger); if (doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaMC.getAnnotationX()); unMangledInterMethod.addAnnotation(decaMC.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaMC); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } private boolean dontAddTwice(DeclareAnnotation decaF, Annotation [] dontAddMeTwice){ for (int i = 0; i < dontAddMeTwice.length; i++){ Annotation ann = dontAddMeTwice[i]; if (ann != null && decaF.getAnnotationX().getTypeName().equals(ann.getTypeName())){ dontAddMeTwice[i] = null; // incase it really has been added twice! return true; } } return false; } /** * Weave any declare @field statements into the fields of the supplied class * * Interesting case relating to public ITDd fields. The annotations are really stored against * the interfieldinit method in the aspect, but the public field is placed in the target * type and then is processed in the 2nd pass over fields that occurs. I think it would be * more expensive to avoid putting the annotation on that inserted public field than just to * have it put there as well as on the interfieldinit method. */ private boolean weaveDeclareAtField(LazyClassGen clazz) { // BUGWARNING not getting enough warnings out on declare @field ? // There is a potential problem here with warnings not coming out - this // will occur if they are created on the second iteration round this loop. // We currently deactivate error reporting for the second time round. // A possible solution is to record what annotations were added by what // decafs and check that to see if an error needs to be reported - this // would be expensive so lets skip it for now List reportedProblems = new ArrayList(); List allDecafs = world.getDeclareAnnotationOnFields(); if (allDecafs.isEmpty()) return false; // nothing to do boolean isChanged = false; List itdFields = getITDSubset(clazz,ResolvedTypeMunger.Field); if (itdFields!=null) { isChanged = weaveAtFieldRepeatedly(allDecafs,itdFields,reportedProblems); } List decaFs = getMatchingSubset(allDecafs,clazz.getType()); if (decaFs.isEmpty()) return false; // nothing more to do Field[] fields = clazz.getFieldGens(); if (fields!=null) { for (int fieldCounter = 0;fieldCounter<fields.length;fieldCounter++) { BcelField aBcelField = new BcelField(clazz.getBcelObjectType(),fields[fieldCounter]); if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; Annotation [] dontAddMeTwice = fields[fieldCounter].getAnnotations(); // go through all the declare @field statements for (Iterator iter = decaFs.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { if (!dontAddTwice(decaF,dontAddMeTwice)){ if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)){ continue; } if(decaF.getAnnotationX().isRuntimeVisible()){ // isAnnotationWithRuntimeRetention(clazz.getJavaClass(world))){ //if(decaF.getAnnotationTypeX().isAnnotationWithRuntimeRetention(world)){ // it should be runtime visible, so put it on the Field Annotation a = decaF.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); FieldGen myGen = new FieldGen(fields[fieldCounter],clazz.getConstantPoolGen()); myGen.addAnnotation(ag); Field newField = myGen.getField(); aBcelField.addAnnotation(decaF.getAnnotationX()); clazz.replaceField(fields[fieldCounter],newField); fields[fieldCounter]=newField; } else{ aBcelField.addAnnotation(decaF.getAnnotationX()); } } AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); reportFieldAnnotationWeavingMessage(clazz, fields, fieldCounter, decaF); isChanged = true; modificationOccured = true; } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { // below code is for recursive things if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) continue; // skip this one... aBcelField.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); isChanged = true; modificationOccured = true; forRemoval.add(decaF); } } worthRetrying.removeAll(forRemoval); } } } } return isChanged; } // TAG: WeavingMessage private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, Field[] fields, int fieldCounter, DeclareAnnotation decaF) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ Field theField = fields[fieldCounter]; world.getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ theField.toString() + "' of type '" + clazz.getName(), clazz.getFileName(), decaF.getAnnotationString(), "field", decaF.getAspect().toString(), Utility.beautifyLocation(decaF.getSourceLocation())})); } } /** * Check if a resolved member (field/method/ctor) already has an annotation, if it * does then put out a warning and return true */ private boolean doesAlreadyHaveAnnotation(ResolvedMember rm,DeclareAnnotation deca,List reportedProblems) { if (rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); world.getLint().elementAlreadyAnnotated.signal( new String[]{rm.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } } return true; } return false; } private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm,ResolvedMember itdfieldsig,DeclareAnnotation deca,List reportedProblems) { if (rm != null && rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); reportedProblems.add(new Integer(itdfieldsig.hashCode()*deca.hashCode())); world.getLint().elementAlreadyAnnotated.signal( new String[]{rm.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } } return true; } return false; } private Set findAspectsForMungers(LazyMethodGen mg) { Set aspectsAffectingType = new HashSet(); for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) { BcelShadow aShadow = (BcelShadow) iter.next(); // Mungers in effect on that shadow for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) { ShadowMunger aMunger = (ShadowMunger) iter2.next(); if (aMunger instanceof BcelAdvice) { BcelAdvice bAdvice = (BcelAdvice)aMunger; if(bAdvice.getConcreteAspect() != null){ aspectsAffectingType.add(bAdvice.getConcreteAspect().getName()); } } else { // It is a 'Checker' - we don't need to remember aspects that only contributed Checkers... } } } return aspectsAffectingType; } private boolean inlineSelfConstructors(List methodGens) { boolean inlinedSomething = false; for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); if (! mg.getName().equals("<init>")) continue; InstructionHandle ih = findSuperOrThisCall(mg); if (ih != null && isThisCall(ih)) { LazyMethodGen donor = getCalledMethod(ih); inlineMethod(donor, mg, ih); inlinedSomething = true; } } return inlinedSomething; } private void positionAndImplement(List initializationShadows) { for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) { BcelShadow s = (BcelShadow) i.next(); positionInitializationShadow(s); //s.getEnclosingMethod().print(); s.implement(); } } private void positionInitializationShadow(BcelShadow s) { LazyMethodGen mg = s.getEnclosingMethod(); InstructionHandle call = findSuperOrThisCall(mg); InstructionList body = mg.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow((BcelShadow) s); if (s.getKind() == Shadow.PreInitialization) { // XXX assert first instruction is an ALOAD_0. // a pre shadow goes from AFTER the first instruction (which we believe to // be an ALOAD_0) to just before the call to super r.associateWithTargets( Range.genStart(body, body.getStart().getNext()), Range.genEnd(body, call.getPrev())); } else { // assert s.getKind() == Shadow.Initialization r.associateWithTargets( Range.genStart(body, call.getNext()), Range.genEnd(body)); } } private boolean isThisCall(InstructionHandle ih) { INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction(); return inst.getClassName(cpg).equals(clazz.getName()); } /** inline a particular call in bytecode. * * @param donor the method we want to inline * @param recipient the method containing the call we want to inline * @param call the instructionHandle in recipient's body holding the call we want to * inline. */ public static void inlineMethod( LazyMethodGen donor, LazyMethodGen recipient, InstructionHandle call) { // assert recipient.contains(call) /* Implementation notes: * * We allocate two slots for every tempvar so we don't screw up * longs and doubles which may share space. This could be conservatively avoided * (no reference to a long/double instruction, don't do it) or packed later. * Right now we don't bother to pack. * * Allocate a new var for each formal param of the inlined. Fill with stack * contents. Then copy the inlined instructions in with the appropriate remap * table. Any framelocs used by locals in inlined are reallocated to top of * frame, */ final InstructionFactory fact = recipient.getEnclosingClass().getFactory(); IntMap frameEnv = new IntMap(); // this also sets up the initial environment InstructionList argumentStores = genArgumentStores(donor, recipient, frameEnv, fact); InstructionList inlineInstructions = genInlineInstructions(donor, recipient, frameEnv, fact, false); inlineInstructions.insert(argumentStores); recipient.getBody().append(call, inlineInstructions); Utility.deleteInstruction(call, recipient); } /** generate the instructions to be inlined. * * @param donor the method from which we will copy (and adjust frame and jumps) * instructions. * @param recipient the method the instructions will go into. Used to get the frame * size so we can allocate new frame locations for locals in donor. * @param frameEnv an environment to map from donor frame to recipient frame, * initially populated with argument locations. * @param fact an instruction factory for recipient */ static InstructionList genInlineInstructions( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact, boolean keepReturns) { InstructionList footer = new InstructionList(); InstructionHandle end = footer.append(InstructionConstants.NOP); InstructionList ret = new InstructionList(); InstructionList sourceList = donor.getBody(); Map srcToDest = new HashMap(); ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen(); ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen(); boolean isAcrossClass = donorCpg != recipientCpg; // first pass: copy the instructions directly, populate the srcToDest map, // fix frame instructions for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) { Instruction fresh = Utility.copyInstruction(src.getInstruction()); InstructionHandle dest; if (fresh instanceof CPInstruction) { // need to reset index to go to new constant pool. This is totally // a computation leak... we're testing this LOTS of times. Sigh. if (isAcrossClass) { CPInstruction cpi = (CPInstruction) fresh; cpi.setIndex( recipientCpg.addConstant( donorCpg.getConstant(cpi.getIndex()), donorCpg)); } } if (src.getInstruction() == Range.RANGEINSTRUCTION) { dest = ret.append(Range.RANGEINSTRUCTION); } else if (fresh instanceof ReturnInstruction) { if (keepReturns) { dest = ret.append(fresh); } else { dest = ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end)); } } else if (fresh instanceof BranchInstruction) { dest = ret.append((BranchInstruction) fresh); } else if ( fresh instanceof LocalVariableInstruction || fresh instanceof RET) { IndexedInstruction indexed = (IndexedInstruction) fresh; int oldIndex = indexed.getIndex(); int freshIndex; if (!frameEnv.hasKey(oldIndex)) { freshIndex = recipient.allocateLocal(2); frameEnv.put(oldIndex, freshIndex); } else { freshIndex = frameEnv.get(oldIndex); } indexed.setIndex(freshIndex); dest = ret.append(fresh); } else { dest = ret.append(fresh); } srcToDest.put(src, dest); } // second pass: retarget branch instructions, copy ranges and tags Map tagMap = new HashMap(); Map shadowMap = new HashMap(); for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src.getNext()) { Instruction inst = dest.getInstruction(); // retarget branches if (inst instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction) inst; InstructionHandle oldTarget = branch.getTarget(); InstructionHandle newTarget = (InstructionHandle) srcToDest.get(oldTarget); if (newTarget == null) { // assert this is a GOTO // this was a return instruction we previously replaced } else { branch.setTarget(newTarget); if (branch instanceof Select) { Select select = (Select) branch; InstructionHandle[] oldTargets = select.getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { select.setTarget( k, (InstructionHandle) srcToDest.get(oldTargets[k])); } } } } //copy over tags and range attributes InstructionTargeter[] srcTargeters = src.getTargeters(); if (srcTargeters != null) { for (int j = srcTargeters.length - 1; j >= 0; j--) { InstructionTargeter old = srcTargeters[j]; if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = (Tag) tagMap.get(oldTag); if (fresh == null) { fresh = oldTag.copy(); tagMap.put(oldTag, fresh); } dest.addTargeter(fresh); } else if (old instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) old; if (er.getStart() == src) { ExceptionRange freshEr = new ExceptionRange( recipient.getBody(), er.getCatchType(), er.getPriority()); freshEr.associateWithTargets( dest, (InstructionHandle)srcToDest.get(er.getEnd()), (InstructionHandle)srcToDest.get(er.getHandler())); } } else if (old instanceof ShadowRange) { ShadowRange oldRange = (ShadowRange) old; if (oldRange.getStart() == src) { BcelShadow oldShadow = oldRange.getShadow(); BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow()); BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing); ShadowRange freshRange = new ShadowRange(recipient.getBody()); freshRange.associateWithShadow(freshShadow); freshRange.associateWithTargets( dest, (InstructionHandle) srcToDest.get(oldRange.getEnd())); shadowMap.put(oldRange, freshRange); //recipient.matchedShadows.add(freshShadow); // XXX should go through the NEW copied shadow and update // the thisVar, targetVar, and argsVar // ??? Might want to also go through at this time and add // "extra" vars to the shadow. } } } } } if (!keepReturns) ret.append(footer); return ret; } /** generate the argument stores in preparation for inlining. * * @param donor the method we will inline from. Used to get the signature. * @param recipient the method we will inline into. Used to get the frame size * so we can allocate fresh locations. * @param frameEnv an empty environment we populate with a map from donor frame to * recipient frame. * @param fact an instruction factory for recipient */ private static InstructionList genArgumentStores( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact) { InstructionList ret = new InstructionList(); int donorFramePos = 0; // writing ret back to front because we're popping. if (! donor.isStatic()) { int targetSlot = recipient.allocateLocal(Type.OBJECT); ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot)); frameEnv.put(donorFramePos, targetSlot); donorFramePos += 1; } Type[] argTypes = donor.getArgumentTypes(); for (int i = 0, len = argTypes.length; i < len; i++) { Type argType = argTypes[i]; int argSlot = recipient.allocateLocal(argType); ret.insert(InstructionFactory.createStore(argType, argSlot)); frameEnv.put(donorFramePos, argSlot); donorFramePos += argType.getSize(); } return ret; } /** get a called method: Assumes the called method is in this class, * and the reference to it is exact (a la INVOKESPECIAL). * * @param ih The InvokeInstruction instructionHandle pointing to the called method. */ private LazyMethodGen getCalledMethod( InstructionHandle ih) { InvokeInstruction inst = (InvokeInstruction) ih.getInstruction(); String methodName = inst.getName(cpg); String signature = inst.getSignature(cpg); return clazz.getLazyMethodGen(methodName, signature); } private void weaveInAddedMethods() { Collections.sort(addedLazyMethodGens, new Comparator() { public int compare(Object a, Object b) { LazyMethodGen aa = (LazyMethodGen) a; LazyMethodGen bb = (LazyMethodGen) b; int i = aa.getName().compareTo(bb.getName()); if (i != 0) return i; return aa.getSignature().compareTo(bb.getSignature()); } } ); for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { clazz.addMethodGen((LazyMethodGen)i.next()); } } void addPerSingletonField(Member field) { ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType()); String aspectName = field.getReturnType().getName(); LazyMethodGen clinit = clazz.getStaticInitializer(); InstructionList setup = new InstructionList(); InstructionFactory fact = clazz.getFactory(); setup.append(fact.createNew(aspectType)); setup.append(InstructionFactory.createDup(1)); setup.append(fact.createInvoke( aspectName, "<init>", Type.VOID, new Type[0], Constants.INVOKESPECIAL)); setup.append( fact.createFieldAccess( aspectName, field.getName(), aspectType, Constants.PUTSTATIC)); clinit.getBody().insert(setup); } /** * Returns null if this is not a Java constructor, and then we won't * weave into it at all */ private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) { int depth = 1; InstructionHandle start = mg.getBody().getStart(); while (true) { if (start == null) return null; Instruction inst = start.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth--; if (depth == 0) return start; } else if (inst instanceof NEW) { depth++; } start = start.getNext(); } } // ---- private boolean match(LazyMethodGen mg) { BcelShadow enclosingShadow; List shadowAccumulator = new ArrayList(); // we want to match ajsynthetic constructors... if (mg.getName().equals("<init>")) { return matchInit(mg, shadowAccumulator); } else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) { return false; } else { if (mg.getName().equals("<clinit>")) { clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg); //System.err.println(enclosingShadow); } else if (mg.isAdviceMethod()) { enclosingShadow = BcelShadow.makeAdviceExecution(world, mg); } else { AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature(); if (effective == null) { enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows); } else if (effective.isWeaveBody()) { ResolvedMember rm = effective.getEffectiveSignature(); // Annotations for things with effective signatures are never stored in the effective // signature itself - we have to hunt for them. Storing them in the effective signature // would mean keeping two sets up to date (no way!!) fixAnnotationsForResolvedMember(rm,mg.getMemberView()); enclosingShadow = BcelShadow.makeShadowForMethod(world,mg,effective.getShadowKind(),rm); } else { return false; } } if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { match(mg, h, enclosingShadow, shadowAccumulator); } } // FIXME asc change from string match if we can, rather brittle. this check actually prevents field-exec jps if (canMatch(enclosingShadow.getKind()) && !mg.getName().startsWith("ajc$interFieldInit")) { if (match(enclosingShadow, shadowAccumulator)) { enclosingShadow.init(); } } mg.matchedShadows = shadowAccumulator; return !shadowAccumulator.isEmpty(); } } private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) { BcelShadow enclosingShadow; // XXX the enclosing join point is wrong for things before ignoreMe. InstructionHandle superOrThisCall = findSuperOrThisCall(mg); // we don't walk bodies of things where it's a wrong constructor thingie if (superOrThisCall == null) return false; enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall); if (mg.getEffectiveSignature() != null) { enclosingShadow.setMatchingSignature(mg.getEffectiveSignature().getEffectiveSignature()); } // walk the body boolean beforeSuperOrThisCall = true; if (shouldWeaveBody(mg)) { if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { if (h == superOrThisCall) { beforeSuperOrThisCall = false; continue; } match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator); } } if (canMatch(Shadow.ConstructorExecution)) match(enclosingShadow, shadowAccumulator); } // XXX we don't do pre-inits of interfaces // now add interface inits if (superOrThisCall != null && ! isThisCall(superOrThisCall)) { InstructionHandle curr = enclosingShadow.getRange().getStart(); for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) { IfaceInitList l = (IfaceInitList) i.next(); Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType); BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig); // insert code in place InstructionList inits = genInitInstructions(l.list, false); if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) { initShadow.initIfaceInitializer(curr); initShadow.getRange().insert(inits, Range.OutsideBefore); } } // now we add our initialization code InstructionList inits = genInitInstructions(addedThisInitializers, false); enclosingShadow.getRange().insert(inits, Range.OutsideBefore); } // actually, you only need to inline the self constructors that are // in a particular group (partition the constructors into groups where members // call or are called only by those in the group). Then only inline // constructors // in groups where at least one initialization jp matched. Future work. boolean addedInitialization = match( BcelShadow.makeUnfinishedInitialization(world, mg), initializationShadows); addedInitialization |= match( BcelShadow.makeUnfinishedPreinitialization(world, mg), initializationShadows); mg.matchedShadows = shadowAccumulator; return addedInitialization || !shadowAccumulator.isEmpty(); } private boolean shouldWeaveBody(LazyMethodGen mg) { if (mg.isBridgeMethod()) return false; if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>"); AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature(); if (a != null) return a.isWeaveBody(); return true; } /** * first sorts the mungers, then gens the initializers in the right order */ private InstructionList genInitInstructions(List list, boolean isStatic) { list = PartialOrder.sort(list); if (list == null) { throw new BCException("circularity in inter-types"); } InstructionList ret = new InstructionList(); for (Iterator i = list.iterator(); i.hasNext();) { ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next(); NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger(); ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType()); if (!isStatic) ret.append(InstructionConstants.ALOAD_0); ret.append(Utility.createInvoke(fact, world, initMethod)); } return ret; } private void match( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { Instruction i = ih.getInstruction(); if ((i instanceof FieldInstruction) && (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) ) { FieldInstruction fi = (FieldInstruction) i; if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) { // check for sets of constant fields. We first check the previous // instruction. If the previous instruction is a LD_WHATEVER (push // constant on the stack) then we must resolve the field to determine // if it's final. If it is final, then we don't generate a shadow. InstructionHandle prevHandle = ih.getPrev(); Instruction prevI = prevHandle.getInstruction(); if (Utility.isConstantPushInstruction(prevI)) { Member field = BcelWorld.makeFieldJoinPointSignature(clazz, (FieldInstruction) i); ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. } else if (Modifier.isFinal(resolvedField.getModifiers())) { // it's final, so it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldGet)) matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else if (i instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction) i; if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) { if (canMatch(Shadow.ConstructorCall)) match( BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow), shadowAccumulator); } else if (ii instanceof INVOKESPECIAL) { String onTypeName = ii.getClassName(cpg); if (onTypeName.equals(mg.getEnclosingClass().getName())) { // we are private matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } else { // we are a super call, and this is not a join point in AspectJ-1.{0,1} } } else { matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } } // performance optimization... we only actually care about ASTORE instructions, // since that's what every javac type thing ever uses to start a handler, but for // now we'll do this for everybody. if (!canMatch(Shadow.ExceptionHandler)) return; if (Range.isRangeHandle(ih)) return; InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int j = 0; j < targeters.length; j++) { InstructionTargeter t = targeters[j]; if (t instanceof ExceptionRange) { // assert t.getHandler() == ih ExceptionRange er = (ExceptionRange) t; if (er.getCatchType() == null) continue; if (isInitFailureHandler(ih)) return; match( BcelShadow.makeExceptionHandler( world, er, mg, ih, enclosingShadow), shadowAccumulator); } } } } private boolean isInitFailureHandler(InstructionHandle ih) { // Skip the astore_0 and aload_0 at the start of the handler and // then check if the instruction following these is // 'putstatic ajc$initFailureCause'. If it is then we are // in the handler we created in AspectClinit.generatePostSyntheticCode() InstructionHandle twoInstructionsAway = ih.getNext().getNext(); if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) { String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg); if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true; } return false; } private void matchSetInstruction( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if ( Modifier.isFinal(resolvedField.getModifiers()) && Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) { // it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { match( BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow), shadowAccumulator); } } private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { BcelShadow bs = BcelShadow.makeFieldGet(world,resolvedField,mg,ih,enclosingShadow); String cname = fi.getClassName(cpg); if (!resolvedField.getDeclaringType().getName().equals(cname)) { bs.setActualTargetType(cname); } match(bs, shadowAccumulator); } } /** * For a given resolvedmember, this will discover the real annotations for it. * <b>Should only be used when the resolvedmember is the contents of an effective signature * attribute, as thats the only time when the annotations aren't stored directly in the * resolvedMember</b> * @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing * @param declaredSig the real sig 'blah.ajc$xxx' */ private void fixAnnotationsForResolvedMember(ResolvedMember rm,ResolvedMember declaredSig) { try { UnresolvedType memberHostType = declaredSig.getDeclaringType(); ResolvedType[] annotations = (ResolvedType[])mapToAnnotations.get(rm); String methodName = declaredSig.getName(); // FIXME asc shouldnt really rely on string names ! if (annotations == null) { if (rm.getKind()==Member.FIELD) { if (methodName.startsWith("ajc$inlineAccessField")) { ResolvedMember resolvedDooberry = world.resolve(rm); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interFieldInitializer(rm,memberHostType); ResolvedMember resolvedDooberry = world.resolve(realthing); annotations = resolvedDooberry.getAnnotationTypes(); } } else if (rm.getKind()==Member.METHOD && !rm.isAbstract()) { if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) { ResolvedMember resolvedDooberry = world.resolve(declaredSig); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world),memberHostType); ResolvedMember resolvedDooberry = world.resolve(realthing); // AMC temp guard for M4 if (resolvedDooberry == null) { throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified"); } annotations = resolvedDooberry.getAnnotationTypes(); } } else if (rm.getKind()==Member.CONSTRUCTOR) { ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(),rm.getParameterTypes()); ResolvedMember resolvedDooberry = world.resolve(realThing); // AMC temp guard for M4 if (resolvedDooberry == null) { throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified"); } annotations = resolvedDooberry.getAnnotationTypes(); } if (annotations == null) annotations = new ResolvedType[0]; mapToAnnotations.put(rm,annotations); } rm.setAnnotationTypes(annotations); } catch (UnsupportedOperationException ex) { throw ex; } catch (Throwable t) { //FIXME asc remove this catch after more testing has confirmed the above stuff is OK throw new BCException("Unexpectedly went bang when searching for annotations on "+rm,t); } } private void matchInvokeInstruction(LazyMethodGen mg, InstructionHandle ih, InvokeInstruction invoke, BcelShadow enclosingShadow, List shadowAccumulator) { String methodName = invoke.getName(cpg); if (methodName.startsWith(NameMangler.PREFIX)) { Member jpSig = world.makeJoinPointSignatureForMethodInvocation(clazz, invoke); ResolvedMember declaredSig = jpSig.resolve(world); //System.err.println(method + ", declaredSig: " +declaredSig); if (declaredSig == null) return; if (declaredSig.getKind() == Member.FIELD) { Shadow.Kind kind; if (jpSig.getReturnType().equals(ResolvedType.VOID)) { kind = Shadow.FieldSet; } else { kind = Shadow.FieldGet; } if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, kind, declaredSig), shadowAccumulator); } else { AjAttribute.EffectiveSignatureAttribute effectiveSig = declaredSig.getEffectiveSignature(); if (effectiveSig == null) return; //System.err.println("call to inter-type member: " + effectiveSig); if (effectiveSig.isWeaveBody()) return; ResolvedMember rm = effectiveSig.getEffectiveSignature(); fixAnnotationsForResolvedMember(rm,declaredSig); // abracadabra if (canMatch(effectiveSig.getShadowKind())) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, effectiveSig.getShadowKind(), rm), shadowAccumulator); } } else { if (canMatch(Shadow.MethodCall)) match( BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow), shadowAccumulator); } } private boolean match(BcelShadow shadow, List shadowAccumulator) { //System.err.println("match: " + shadow); ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_SHADOW, shadow); boolean isMatched = false; for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) { ShadowMunger munger = (ShadowMunger)i.next(); ContextToken mungerMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_POINTCUT, munger.getPointcut()); if (munger.match(shadow, world)) { WeaverMetrics.recordMatchResult(true);// Could pass: munger shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation()); } } else { WeaverMetrics.recordMatchResult(false); // Could pass: munger } CompilationAndWeavingContext.leavingPhase(mungerMatchToken); } if (isMatched) shadowAccumulator.add(shadow); CompilationAndWeavingContext.leavingPhase(shadowMatchToken); return isMatched; } // ---- private void implement(LazyMethodGen mg) { List shadows = mg.matchedShadows; if (shadows == null) return; // We depend on a partial order such that inner shadows are earlier on the list // than outer shadows. That's fine. This order is preserved if: // A preceeds B iff B.getStart() is LATER THAN A.getStart(). for (Iterator i = shadows.iterator(); i.hasNext(); ) { BcelShadow shadow = (BcelShadow)i.next(); ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.IMPLEMENTING_ON_SHADOW,shadow); shadow.implement(); CompilationAndWeavingContext.leavingPhase(tok); } int ii = mg.getMaxLocals(); mg.matchedShadows = null; } // ---- public LazyClassGen getLazyClassGen() { return clazz; } public List getShadowMungers() { return shadowMungers; } public BcelWorld getWorld() { return world; } // Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info public static void setReweavableMode(boolean mode) { inReweavableMode = mode; } public static boolean getReweavableMode() { return inReweavableMode; } }
111,915
Bug 111915 illegal change to pointcut declaration
org.aspectj.weaver.BCException at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:306) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:331) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:216) at org.aspectj.weaver.Advice.concretize(Advice.java:273) at org.aspectj.weaver.bcel.BcelAdvice.concretize(BcelAdvice.java:83) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger(CrosscuttingMembers.java:84) at org.aspectj.weaver.CrosscuttingMembers.addShadowMungers(CrosscuttingMembers.java:78) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:462) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:62) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java:426) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:283) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:760) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:225) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:151) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) BCException thrown: illegal change to pointcut declaration: spike.np.CommandCase.handleCommand(BindingTypePattern(spike.np.OtherHandler$MyWorld, 0)) when batch building BuildConfig[/home/guido/workspace/.metadata/.plugins/org.eclipse.ajdt.core/np.generated.lst] #Files=11
resolved fixed
3021284
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-21T06:56:11Z
2005-10-07T15:46:40Z
tests/bugs150/pr111915.java
111,915
Bug 111915 illegal change to pointcut declaration
org.aspectj.weaver.BCException at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:306) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:331) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:216) at org.aspectj.weaver.Advice.concretize(Advice.java:273) at org.aspectj.weaver.bcel.BcelAdvice.concretize(BcelAdvice.java:83) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger(CrosscuttingMembers.java:84) at org.aspectj.weaver.CrosscuttingMembers.addShadowMungers(CrosscuttingMembers.java:78) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:462) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:62) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java:426) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:283) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:760) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:225) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:151) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) BCException thrown: illegal change to pointcut declaration: spike.np.CommandCase.handleCommand(BindingTypePattern(spike.np.OtherHandler$MyWorld, 0)) when batch building BuildConfig[/home/guido/workspace/.metadata/.plugins/org.eclipse.ajdt.core/np.generated.lst] #Files=11
resolved fixed
3021284
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-21T06:56:11Z
2005-10-07T15:46:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.internal.Relationship; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } /* Andys bug area - enter at your own risk... public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");} public void testMissingAccessor_pr73856() { runTest("missing accessor");} public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");} public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");} public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");} */ public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");} public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");} public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");} public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");} public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");} public void testVarargsITD_pr110906() { runTest("ITD varargs problem");} public void testBadGenericSigAttribute_pr110927() { runTest("cant create signature attribute"); Signature sig = GenericsTests.getClassSignature(ajc,"I"); if (sig==null) fail("Couldn't find signature attribute for type I"); String sigString = sig.getSignature(); if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") || sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) { fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"); } } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");} public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } // IfPointcut.findResidueInternal() was modified to make this test complete in a short amount // of time - if you see it hanging, someone has messed with the optimization. public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");} public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testAtAnnotationBadTest_pr103740() { runTest("Compiler failure on at_annotation"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } public void testNoVerifyErrorOnGenericCollectionMemberAccess() { runTest("no verify error on generic collection member access"); } public void testRawAndGenericTypeConversionITDCons() { runTest("raw and generic type conversion with itd cons"); } public void testAtAnnotationBindingWithAround() { runTest("@annotation binding with around advice"); } public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");} public void testMessageOnMissingTypeInDecP() { runTest("declare parents on a missing type"); } public void testParameterizedGenericMethods() { runTest("parameterized generic methods"); } public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");} public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");} public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");} public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");} public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");} // Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats // where we can police whether a type variable has been used without being specified appropriately. //public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");} public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");} public void testCallJoinPointsInAnonymousInnerClasses() { runTest("call join points in anonymous inner classes"); } public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() { runTest("default impl of Runnable"); } public void testArrayCloneCallJoinPoints() { runTest("array clone call join points in 1.4 vs 1.3"); } public void testDebugInfoForAroundAdvice() { runTest("debug info in around advice inlining"); } public void testCCEWithGenericWildcard_pr112602() { runTest("ClassCastException with generic wildcard"); } public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the run() method inside anonymous inner class is in // the structure model IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"run()"); assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'run()' but is " + target.toLabelString(),"run()",target.toLabelString()); } public void testAdviceInStructureModelWithNamedInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with named inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the m() method inside named inner class is in // the structure model IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"m()"); assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'm()' but is " + target.toLabelString(),"m()",target.toLabelString()); } public void testDWInStructureModelWithAnonymousInnerClass_pr77269() { // AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("declare warning in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())"); assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe); } public void testVarArgsIITDInConstructor() { runTest("ITD varargs in constructor"); } public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() { runTest("weaveinfo message for declare at method on an ITDd method"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
111,915
Bug 111915 illegal change to pointcut declaration
org.aspectj.weaver.BCException at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:306) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:331) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:216) at org.aspectj.weaver.Advice.concretize(Advice.java:273) at org.aspectj.weaver.bcel.BcelAdvice.concretize(BcelAdvice.java:83) at org.aspectj.weaver.CrosscuttingMembers.addShadowMunger(CrosscuttingMembers.java:84) at org.aspectj.weaver.CrosscuttingMembers.addShadowMungers(CrosscuttingMembers.java:78) at org.aspectj.weaver.ResolvedType.collectCrosscuttingMembers(ResolvedType.java:462) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:62) at org.aspectj.weaver.bcel.BcelWeaver.prepareForWeave(BcelWeaver.java:426) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:283) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:760) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:225) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:151) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) BCException thrown: illegal change to pointcut declaration: spike.np.CommandCase.handleCommand(BindingTypePattern(spike.np.OtherHandler$MyWorld, 0)) when batch building BuildConfig[/home/guido/workspace/.metadata/.plugins/org.eclipse.ajdt.core/np.generated.lst] #Files=11
resolved fixed
3021284
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-21T06:56:11Z
2005-10-07T15:46:40Z
weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Test; /** */ //XXX needs check that arguments contains no WildTypePatterns public class ReferencePointcut extends Pointcut { public UnresolvedType onType; public TypePattern onTypeSymbolic; public String name; public TypePatternList arguments; /** * if this is non-null then when the pointcut is concretized the result will be parameterized too. */ private Map typeVariableMap; //public ResolvedPointcut binding; public ReferencePointcut(TypePattern onTypeSymbolic, String name, TypePatternList arguments) { this.onTypeSymbolic = onTypeSymbolic; this.name = name; this.arguments = arguments; this.pointcutKind = REFERENCE; } public ReferencePointcut(UnresolvedType onType, String name, TypePatternList arguments) { this.onType = onType; this.name = name; this.arguments = arguments; this.pointcutKind = REFERENCE; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } //??? do either of these match methods make any sense??? public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } /** * Do I really match this shadow? */ protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public String toString() { StringBuffer buf = new StringBuffer(); if (onType != null) { buf.append(onType); buf.append("."); // for (int i=0, len=fromType.length; i < len; i++) { // buf.append(fromType[i]); // buf.append("."); // } } buf.append(name); buf.append(arguments.toString()); return buf.toString(); } public void write(DataOutputStream s) throws IOException { //XXX ignores onType s.writeByte(Pointcut.REFERENCE); if (onType != null) { s.writeBoolean(true); onType.write(s); } else { s.writeBoolean(false); } s.writeUTF(name); arguments.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { UnresolvedType onType = null; if (s.readBoolean()) { onType = UnresolvedType.read(s); } ReferencePointcut ret = new ReferencePointcut(onType, s.readUTF(), TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { if (onTypeSymbolic != null) { onType = onTypeSymbolic.resolveExactType(scope, bindings); // in this case we've already signalled an error if (onType == ResolvedType.MISSING) return; } ResolvedType searchType; if (onType != null) { searchType = scope.getWorld().resolve(onType); } else { searchType = scope.getEnclosingType(); } arguments.resolveBindings(scope, bindings, true, true); //XXX ensure that arguments has no ..'s in it // check that I refer to a real pointcut declaration and that I match ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name); // if we're not a static reference, then do a lookup of outers if (pointcutDef == null && onType == null) { while (true) { UnresolvedType declaringType = searchType.getDeclaringType(); if (declaringType == null) break; searchType = declaringType.resolve(scope.getWorld()); pointcutDef = searchType.findPointcut(name); if (pointcutDef != null) { // make this a static reference onType = searchType; break; } } } if (pointcutDef == null) { scope.message(IMessage.ERROR, this, "can't find referenced pointcut " + name); return; } // check visibility if (!pointcutDef.isVisible(scope.getEnclosingType())) { scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible"); return; } if (Modifier.isAbstract(pointcutDef.getModifiers())) { if (onType != null) { scope.message(IMessage.ERROR, this, "can't make static reference to abstract pointcut"); return; } else if (!searchType.isAbstract()) { scope.message(IMessage.ERROR, this, "can't use abstract pointcut in concrete context"); return; } } ResolvedType[] parameterTypes = scope.getWorld().resolve(pointcutDef.getParameterTypes()); if (parameterTypes.length != arguments.size()) { scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " + parameterTypes.length + " found " + arguments.size()); return; } for (int i=0,len=arguments.size(); i < len; i++) { TypePattern p = arguments.get(i); //we are allowed to bind to pointcuts which use subtypes as this is type safe if (p == TypePattern.NO) { scope.message(IMessage.ERROR, this, "bad parameter to pointcut reference"); return; } if (!p.matchesSubtypes(parameterTypes[i]) && !p.getExactType().equals(UnresolvedType.OBJECT)) { scope.message(IMessage.ERROR, p, "incompatible type, expected " + parameterTypes[i].getName() + " found " + p); return; } } if (onType != null) { if (onType.isParameterizedType()) { // build a type map mapping type variable names in the generic type to // the type parameters presented typeVariableMap = new HashMap(); ResolvedType underlyingGenericType = ((ResolvedType) onType).getGenericType(); TypeVariable[] tVars = underlyingGenericType.getTypeVariables(); ResolvedType[] typeParams = ((ResolvedType)onType).getResolvedTypeParameters(); for (int i = 0; i < tVars.length; i++) { typeVariableMap.put(tVars[i].getName(),typeParams[i]); } } else if (onType.isGenericType()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_REFERENCE_POINTCUT_IN_RAW_TYPE), getSourceLocation())); } } } public void postRead(ResolvedType enclosingType) { arguments.postRead(enclosingType); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { throw new RuntimeException("shouldn't happen"); } //??? This is not thread safe, but this class is not designed for multi-threading private boolean concretizing = false; // declaring type is the type that declared the member referencing this pointcut. // If it declares a matching private pointcut, then that pointcut should be used // and not one in a subtype that happens to have the same name. public Pointcut concretize1(ResolvedType searchStart, ResolvedType declaringType, IntMap bindings) { if (concretizing) { //Thread.currentThread().dumpStack(); searchStart.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CIRCULAR_POINTCUT,this), getSourceLocation())); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } try { concretizing = true; ResolvedPointcutDefinition pointcutDec; if (onType != null) { searchStart = onType.resolve(searchStart.getWorld()); if (searchStart == ResolvedType.MISSING) { return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } } if (declaringType == null) declaringType = searchStart; pointcutDec = declaringType.findPointcut(name); boolean foundMatchingPointcut = (pointcutDec != null && pointcutDec.isPrivate()); if (!foundMatchingPointcut) { pointcutDec = searchStart.findPointcut(name); if (pointcutDec == null) { searchStart.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_POINTCUT,name,searchStart.getName()), getSourceLocation()) ); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } } if (pointcutDec.isAbstract()) { //Thread.currentThread().dumpStack(); ShadowMunger enclosingAdvice = bindings.getEnclosingAdvice(); searchStart.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ABSTRACT_POINTCUT,pointcutDec), getSourceLocation(), (null == enclosingAdvice) ? null : enclosingAdvice.getSourceLocation()); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } //System.err.println("start: " + searchStart); ResolvedType[] parameterTypes = searchStart.getWorld().resolve(pointcutDec.getParameterTypes()); TypePatternList arguments = this.arguments.resolveReferences(bindings); IntMap newBindings = new IntMap(); for (int i=0,len=arguments.size(); i < len; i++) { TypePattern p = arguments.get(i); if (p == TypePattern.NO) continue; //we are allowed to bind to pointcuts which use subtypes as this is type safe if (!p.matchesSubtypes(parameterTypes[i]) && !p.getExactType().equals(UnresolvedType.OBJECT)) { throw new BCException("illegal change to pointcut declaration: " + this); } if (p instanceof BindingTypePattern) { newBindings.put(i, ((BindingTypePattern)p).getFormalIndex()); } } if (searchStart.isParameterizedType()) { // build a type map mapping type variable names in the generic type to // the type parameters presented typeVariableMap = new HashMap(); ResolvedType underlyingGenericType = searchStart.getGenericType(); TypeVariable[] tVars = underlyingGenericType.getTypeVariables(); ResolvedType[] typeParams = searchStart.getResolvedTypeParameters(); for (int i = 0; i < tVars.length; i++) { typeVariableMap.put(tVars[i].getName(),typeParams[i]); } } newBindings.copyContext(bindings); newBindings.pushEnclosingDefinition(pointcutDec); try { Pointcut ret = pointcutDec.getPointcut(); if (typeVariableMap != null) ret = ret.parameterizeWith(typeVariableMap); return ret.concretize(searchStart, declaringType, newBindings); } finally { newBindings.popEnclosingDefinitition(); } } finally { concretizing = false; } } /** * make a version of this pointcut with any refs to typeVariables replaced by their entry in the map. * Tricky thing is, we can't do this at the point in time this method will be called, so we make a * version that will parameterize the pointcut it ultimately resolves to. */ public Pointcut parameterizeWith(Map typeVariableMap) { ReferencePointcut ret = new ReferencePointcut(onType,name,arguments); ret.onTypeSymbolic = onTypeSymbolic; ret.typeVariableMap = typeVariableMap; return ret; } // We want to keep the original source location, not the reference location protected boolean shouldCopyLocationForConcretize() { return false; } public boolean equals(Object other) { if (!(other instanceof ReferencePointcut)) return false; if (this == other) return true; ReferencePointcut o = (ReferencePointcut)other; return o.name.equals(name) && o.arguments.equals(arguments) && ((o.onType == null) ? (onType == null) : o.onType.equals(onType)); } public int hashCode() { int result = 17; result = 37*result + ((onType == null) ? 0 : onType.hashCode()); result = 37*result + arguments.hashCode(); result = 37*result + name.hashCode(); return result; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
113,511
Bug 113511 LTW enhancements
Alex, here is the basic patch that is working well before you leave for the weekend ;-) I'll let Matthew post it officially to bugzilla since it was his idea. The earlier return from !enabled is a small addition I made that seems to help further. It would be great to have this in HEAD so I can report performance numbers based on it in part 2 of my article on developerworks ;-) Hope you are enjoying your new addition! Thanks! Index: ClassLoaderWeavingAdaptor.java =================================================================== RCS file: /home/technology/org.aspectj/modules/loadtime/src/org/aspectj/weaver/loadtim e/ClassLoaderWeavingAdaptor.java,v retrieving revision 1.18 diff -u -r1.18 ClassLoaderWeavingAdaptor.java --- ClassLoaderWeavingAdaptor.java 19 Oct 2005 13:11:36 -0000 1.18 +++ ClassLoaderWeavingAdaptor.java 21 Oct 2005 16:04:41 -0000 @@ -107,8 +107,13 @@ // register the definitions registerDefinitions(weaver, loader); + if (!enabled) { + return; + } messageHandler = bcelWorld.getMessageHandler(); + bcelWorld.setResolutionLoader((ClassLoader)null);//loader.getParent()); + // after adding aspects weaver.prepareForWeave(); } @@ -148,7 +153,11 @@ definitions.add(DocumentParser.parse(xml)); } } - + if (definitions.isEmpty()) { + enabled = false; + return; + } + // still go thru if definitions is empty since we will configure // the default message handler in there registerOptions(weaver, loader, definitions);
resolved fixed
70888dd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-24T09:48:39Z
2005-10-24T10:33:20Z
loadtime/src/org/aspectj/weaver/loadtime/Aj.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package org.aspectj.weaver.loadtime; import java.io.File; import java.io.FileOutputStream; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.WeakHashMap; import org.aspectj.weaver.tools.WeavingAdaptor; /** * Adapter between the generic class pre processor interface and the AspectJ weaver * Load time weaving consistency relies on Bcel.setRepository * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class Aj implements ClassPreProcessor { private IWeavingContext weavingContext; public Aj(){ this(null); } public Aj(IWeavingContext context){ weavingContext = context; } /** * Initialization */ public void initialize() { ; } /** * Weave * * @param className * @param bytes * @param loader * @return weaved bytes */ public byte[] preProcess(String className, byte[] bytes, ClassLoader loader) { //TODO AV needs to doc that if (loader == null || className == null) { // skip boot loader or null classes (hibernate) return bytes; } try { WeavingAdaptor weavingAdaptor = WeaverContainer.getWeaver(loader, weavingContext); byte[] weaved = weavingAdaptor.weaveClass(className, bytes); if (weavingAdaptor.shouldDump(className.replace('/', '.'))) { dump(className, weaved); } return weaved; } catch (Throwable t) { //FIXME AV wondering if we should have the option to fail (throw runtime exception) here // would make sense at least in test f.e. see TestHelper.handleMessage() t.printStackTrace(); return bytes; } } /** * Cache of weaver * There is one weaver per classloader */ static class WeaverContainer { private static Map weavingAdaptors = new WeakHashMap(); static WeavingAdaptor getWeaver(ClassLoader loader, IWeavingContext weavingContext) { ExplicitlyInitializedClassLaoderWeavingAdaptor adaptor = null; synchronized(weavingAdaptors) { adaptor = (ExplicitlyInitializedClassLaoderWeavingAdaptor) weavingAdaptors.get(loader); if (adaptor == null) { // create it and put it back in the weavingAdaptors map but avoid any kind of instantiation // within the synchronized block ClassLoaderWeavingAdaptor weavingAdaptor = new ClassLoaderWeavingAdaptor(loader, weavingContext); adaptor = new ExplicitlyInitializedClassLaoderWeavingAdaptor(weavingAdaptor); weavingAdaptors.put(loader, adaptor); } } // perform the initialization return adaptor.getWeavingAdaptor(loader, weavingContext); // old version // synchronized(loader) {//FIXME AV - temp fix for #99861 // synchronized (weavingAdaptors) { // WeavingAdaptor weavingAdaptor = (WeavingAdaptor) weavingAdaptors.get(loader); // if (weavingAdaptor == null) { // weavingAdaptor = new ClassLoaderWeavingAdaptor(loader, weavingContext); // weavingAdaptors.put(loader, weavingAdaptor); // } // return weavingAdaptor; // } // } } } static class ExplicitlyInitializedClassLaoderWeavingAdaptor { private final ClassLoaderWeavingAdaptor weavingAdaptor; private boolean isInitialized; public ExplicitlyInitializedClassLaoderWeavingAdaptor(ClassLoaderWeavingAdaptor weavingAdaptor) { this.weavingAdaptor = weavingAdaptor; this.isInitialized = false; } private void initialize(ClassLoader loader, IWeavingContext weavingContext) { if (!isInitialized) { isInitialized = true; weavingAdaptor.initialize(loader, weavingContext); } } public ClassLoaderWeavingAdaptor getWeavingAdaptor(ClassLoader loader, IWeavingContext weavingContext) { initialize(loader, weavingContext); return weavingAdaptor; } } static void defineClass(ClassLoader loader, String name, byte[] bytes) { try { //TODO av protection domain, and optimize Method defineClass = ClassLoader.class.getDeclaredMethod( "defineClass", new Class[]{ String.class, bytes.getClass(), int.class, int.class } ); defineClass.setAccessible(true); defineClass.invoke( loader, new Object[]{ name, bytes, new Integer(0), new Integer(bytes.length) } ); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof LinkageError) { ;//is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved) } else { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } /** * Dump the given bytcode in _dump/... (dev mode) * * @param name * @param b * @throws Throwable */ static void dump(String name, byte[] b) throws Throwable { String className = name.replace('.', '/'); final File dir; if (className.indexOf('/') > 0) { dir = new File("_ajdump" + File.separator + className.substring(0, className.lastIndexOf('/'))); } else { dir = new File("_ajdump"); } dir.mkdirs(); String fileName = "_ajdump" + File.separator + className + ".class"; FileOutputStream os = new FileOutputStream(fileName); os.write(b); os.close(); } /* * Shared classes methods */ /** * Returns a namespace based on the contest of the aspects available */ public String getNamespace (ClassLoader loader) { ClassLoaderWeavingAdaptor weavingAdaptor = (ClassLoaderWeavingAdaptor)WeaverContainer.getWeaver(loader, weavingContext); return weavingAdaptor.getNamespace(); } /** * Check to see if any classes have been generated for a particular classes loader. * Calls ClassLoaderWeavingAdaptor.generatedClassesExist() * @param loader the class cloder * @return true if classes have been generated. */ public boolean generatedClassesExist(ClassLoader loader){ return ((ClassLoaderWeavingAdaptor)WeaverContainer.getWeaver(loader, weavingContext)).generatedClassesExist(); } public void flushGeneratedClasses(ClassLoader loader){ ((ClassLoaderWeavingAdaptor)WeaverContainer.getWeaver(loader, weavingContext)).flushGeneratedClasses(); } }
113,511
Bug 113511 LTW enhancements
Alex, here is the basic patch that is working well before you leave for the weekend ;-) I'll let Matthew post it officially to bugzilla since it was his idea. The earlier return from !enabled is a small addition I made that seems to help further. It would be great to have this in HEAD so I can report performance numbers based on it in part 2 of my article on developerworks ;-) Hope you are enjoying your new addition! Thanks! Index: ClassLoaderWeavingAdaptor.java =================================================================== RCS file: /home/technology/org.aspectj/modules/loadtime/src/org/aspectj/weaver/loadtim e/ClassLoaderWeavingAdaptor.java,v retrieving revision 1.18 diff -u -r1.18 ClassLoaderWeavingAdaptor.java --- ClassLoaderWeavingAdaptor.java 19 Oct 2005 13:11:36 -0000 1.18 +++ ClassLoaderWeavingAdaptor.java 21 Oct 2005 16:04:41 -0000 @@ -107,8 +107,13 @@ // register the definitions registerDefinitions(weaver, loader); + if (!enabled) { + return; + } messageHandler = bcelWorld.getMessageHandler(); + bcelWorld.setResolutionLoader((ClassLoader)null);//loader.getParent()); + // after adding aspects weaver.prepareForWeave(); } @@ -148,7 +153,11 @@ definitions.add(DocumentParser.parse(xml)); } } - + if (definitions.isEmpty()) { + enabled = false; + return; + } + // still go thru if definitions is empty since we will configure // the default message handler in there registerOptions(weaver, loader, definitions);
resolved fixed
70888dd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-24T09:48:39Z
2005-10-24T10:33:20Z
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation * David Knibb weaving context enhancments *******************************************************************************/ package org.aspectj.weaver.loadtime; import org.aspectj.asm.IRelationship; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.ICrossReferenceHandler; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.loadtime.definition.DocumentParser; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.tools.GeneratedClassHandler; import org.aspectj.weaver.tools.WeavingAdaptor; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; /** * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { private final static String AOP_XML = "META-INF/aop.xml"; private List m_dumpTypePattern = new ArrayList(); private List m_includeTypePattern = new ArrayList(); private List m_excludeTypePattern = new ArrayList(); private List m_aspectExcludeTypePattern = new ArrayList(); private StringBuffer namespace; private IWeavingContext weavingContext; public ClassLoaderWeavingAdaptor(final ClassLoader loader, IWeavingContext wContext) { super(null); } void initialize(final ClassLoader loader, IWeavingContext wContext) { //super(null);// at this stage we don't have yet a generatedClassHandler to define to the VM the closures this.generatedClassHandler = new GeneratedClassHandler() { /** * Callback when we need to define a Closure in the JVM * * @param name * @param bytes */ public void acceptClass(String name, byte[] bytes) { //TODO av make dump configurable try { if (shouldDump(name.replace('/', '.'))) { Aj.dump(name, bytes); } } catch (Throwable throwable) { throwable.printStackTrace(); } Aj.defineClass(loader, name, bytes);// could be done lazily using the hook } }; if(wContext==null){ weavingContext = new DefaultWeavingContext(loader); }else{ weavingContext = wContext ; } bcelWorld = new BcelWorld( loader, messageHandler, new ICrossReferenceHandler() { public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) { ;// for tools only } } ); // //TODO this AJ code will call // //org.aspectj.apache.bcel.Repository.setRepository(this); // //ie set some static things // //==> bogus as Bcel is expected to be // org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader)); weaver = new BcelWeaver(bcelWorld); // register the definitions registerDefinitions(weaver, loader); messageHandler = bcelWorld.getMessageHandler(); // after adding aspects weaver.prepareForWeave(); } /** * Load and cache the aop.xml/properties according to the classloader visibility rules * * @param weaver * @param loader */ private void registerDefinitions(final BcelWeaver weaver, final ClassLoader loader) { try { MessageUtil.info(messageHandler, "register classloader " + ((loader!=null)?loader.getClass().getName()+"@"+loader.hashCode():"null")); //TODO av underoptimized: we will parse each XML once per CL that see it List definitions = new ArrayList(); //TODO av dev mode needed ? TBD -Daj5.def=... if (ClassLoader.getSystemClassLoader().equals(loader)) { String file = System.getProperty("aj5.def", null); if (file != null) { MessageUtil.info(messageHandler, "using (-Daj5.def) " + file); definitions.add(DocumentParser.parse((new File(file)).toURL())); } } String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration",AOP_XML); StringTokenizer st = new StringTokenizer(resourcePath,";"); while(st.hasMoreTokens()){ Enumeration xmls = weavingContext.getResources(st.nextToken()); // System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader); while (xmls.hasMoreElements()) { URL xml = (URL) xmls.nextElement(); MessageUtil.info(messageHandler, "using " + xml.getFile()); definitions.add(DocumentParser.parse(xml)); } } // still go thru if definitions is empty since we will configure // the default message handler in there registerOptions(weaver, loader, definitions); registerAspectExclude(weaver, loader, definitions); registerAspects(weaver, loader, definitions); registerIncludeExclude(weaver, loader, definitions); registerDump(weaver, loader, definitions); } catch (Exception e) { weaver.getWorld().getMessageHandler().handleMessage( new Message("Register definition failed", IMessage.WARNING, e, null) ); } } /** * Configure the weaver according to the option directives * TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW * * @param weaver * @param loader * @param definitions */ private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { StringBuffer allOptions = new StringBuffer(); for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); allOptions.append(definition.getWeaverOptions()).append(' '); } Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader); // configure the weaver and world // AV - code duplicates AspectJBuilder.initWorldAndWeaver() World world = weaver.getWorld(); world.setMessageHandler(weaverOption.messageHandler); world.setXlazyTjp(weaverOption.lazyTjp); world.setXHasMemberSupportEnabled(weaverOption.hasMember); world.setPinpointMode(weaverOption.pinpoint); weaver.setReweavableMode(weaverOption.notReWeavable); world.setXnoInline(weaverOption.noInline); world.setBehaveInJava5Way(weaverOption.java5);//TODO should be autodetected ? //-Xlintfile: first so that lint wins if (weaverOption.lintFile != null) { InputStream resource = null; try { resource = loader.getResourceAsStream(weaverOption.lintFile); Exception failure = null; if (resource != null) { try { Properties properties = new Properties(); properties.load(resource); world.getLint().setFromProperties(properties); } catch (IOException e) { failure = e; } } if (failure != null || resource == null) { world.getMessageHandler().handleMessage(new Message( "Cannot access resource for -Xlintfile:"+weaverOption.lintFile, IMessage.WARNING, failure, null)); } } finally { try { resource.close(); } catch (Throwable t) {;} } } if (weaverOption.lint != null) { if (weaverOption.lint.equals("default")) {//FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps.. bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(weaverOption.lint); } } //TODO proceedOnError option } private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) { String exclude = (String) iterator1.next(); TypePattern excludePattern = new PatternParser(exclude).parseTypePattern(); m_aspectExcludeTypePattern.add(excludePattern); } } } /** * Register the aspect, following include / exclude rules * * @param weaver * @param loader * @param definitions */ private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { //TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ?? // if not, review the getResource so that we track which resource is defined by which CL //it aspectClassNames //exclude if in any of the exclude list for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) { String aspectClassName = (String) aspects.next(); if (acceptAspect(aspectClassName)) { weaver.addLibraryAspect(aspectClassName); //generate key for SC String aspectCode = readAspect(aspectClassName, loader); if(namespace==null){ namespace=new StringBuffer(aspectCode); }else{ namespace = namespace.append(";"+aspectCode); } } } } //it concreteAspects //exclude if in any of the exclude list //TODO } /** * Register the include / exclude filters * * @param weaver * @param loader * @param definitions */ private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) { String include = (String) iterator1.next(); TypePattern includePattern = new PatternParser(include).parseTypePattern(); m_includeTypePattern.add(includePattern); } for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) { String exclude = (String) iterator1.next(); TypePattern excludePattern = new PatternParser(exclude).parseTypePattern(); m_excludeTypePattern.add(excludePattern); } } } /** * Register the dump filter * * @param weaver * @param loader * @param definitions */ private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) { for (Iterator iterator = definitions.iterator(); iterator.hasNext();) { Definition definition = (Definition) iterator.next(); for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) { String dump = (String) iterator1.next(); TypePattern pattern = new PatternParser(dump).parseTypePattern(); m_dumpTypePattern.add(pattern); } } } protected boolean accept(String className) { // avoid ResolvedType if not needed if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) { return true; } //TODO AV - optimize for className.startWith only ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true); //exclude are "AND"ed for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // exclude match - skip return false; } } //include are "OR"ed boolean accept = true;//defaults to true if no include for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); accept = typePattern.matchesStatically(classInfo); if (accept) { break; } // goes on if this include did not match ("OR"ed) } return accept; } private boolean acceptAspect(String aspectClassName) { // avoid ResolvedType if not needed if (m_aspectExcludeTypePattern.isEmpty()) { return true; } //TODO AV - optimize for className.startWith only ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true); //exclude are "AND"ed for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // exclude match - skip return false; } } return true; } public boolean shouldDump(String className) { // avoid ResolvedType if not needed if (m_dumpTypePattern.isEmpty()) { return false; } //TODO AV - optimize for className.startWith only ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true); //dump for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) { TypePattern typePattern = (TypePattern) iterator.next(); if (typePattern.matchesStatically(classInfo)) { // dump match return true; } } return false; } /* * shared classes methods */ /** * @return Returns the key. */ public String getNamespace() { if(namespace==null) return ""; else return new String(namespace); } /** * Check to see if any classes are stored in the generated classes cache. * Then flush the cache if it is not empty * @return true if a class has been generated and is stored in the cache */ public boolean generatedClassesExist(){ if(generatedClasses.size()>0) { return true; } return false; } /** * Flush the generated classes cache */ public void flushGeneratedClasses(){ generatedClasses = new HashMap(); } /** * Read in an aspect from the disk and return its bytecode as a String * @param name the name of the aspect to read in * @return the bytecode representation of the aspect */ private String readAspect(String name, ClassLoader loader){ if (true) return name+"@"+(loader==null?"0":Integer.toString(loader.hashCode())); // FIXME AV - ?? can someone tell me why we read the whole bytecode // especially one byte by one byte // also it does some NPE sometime (see AtAjLTW "LTW Decp2") InputStream is = null; try { String result = ""; is = loader.getResourceAsStream(name.replace('.','/')+".class"); int b = is.read(); while(b!=-1){ result = result + b; b=is.read(); } is.close(); return result; } catch (IOException e) { e.printStackTrace(); return ""; } catch (NullPointerException e) { //probably tried to read in a "non aspect @missing@" aspect System.err.println("ClassLoaderWeavingAdaptor.readAspect() name: "+name+" Exception: "+e); return ""; } finally { try {is.close();} catch (Throwable t) {;} } } }
112,615
Bug 112615 -XhasMember is not processed correctly when passed from AJDT
To test this in AJDT install the bean example, add a new interface called I and then add the following line to BoundPoint.aj: declare parents: hasmethod(* set*(..)) implements I; Now open the AspectJ Compiler preference page and select "Has Member" on the advanced tab. Click OK, rebuild and if the option was working the project would build correctly. As it stands there is an error: the type pattern hasmethod(* set*(..)) can only be used when the -XhasMember option is set
resolved fixed
cc6862f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-25T12:40:39Z
2005-10-14T11:40:00Z
ajde/testsrc/org/aspectj/ajde/BuildConfigurationTests.java
/********************************************************************** Copyright (c) 2003 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: Adrian Colyer - initial version ... **********************************************************************/ package org.aspectj.ajde; import java.io.File; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.TestSuite; import org.aspectj.ajde.internal.CompilerAdapter; import org.aspectj.ajde.ui.UserPreferencesAdapter; import org.aspectj.ajde.ui.internal.AjcBuildOptions; import org.aspectj.ajde.ui.internal.UserPreferencesStore; import org.aspectj.ajdt.internal.core.builder.AjBuildConfig; import org.aspectj.bridge.*; import org.aspectj.bridge.MessageHandler; import org.aspectj.util.LangUtil; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; /** * Tests that a correctly populated AjBuildConfig object is created * in reponse to the setting in BuildOptionsAdapter and * ProjectPropretiesAdapter */ public class BuildConfigurationTests extends AjdeTestCase { private CompilerAdapter compilerAdapter; private AjBuildConfig buildConfig = null; private AjcBuildOptions buildOptions = null; private UserPreferencesAdapter preferencesAdapter = null; private NullIdeProperties projectProperties = null; private MessageHandler messageHandler; private static final String configFile = AjdeTests.testDataPath("examples/figures-coverage/all.lst"); public BuildConfigurationTests( String name ) { super( name ); } public static void main(String[] args) { junit.swingui.TestRunner.run(BuildConfigurationTests.class); } public static TestSuite suite() { TestSuite result = new TestSuite(); result.addTestSuite(BuildConfigurationTests.class); return result; } // The tests... public void testCharacterEncoding() { buildOptions.setCharacterEncoding( "UTF-8" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String encoding = (String) options.get( CompilerOptions.OPTION_Encoding ); assertEquals( "character encoding", "UTF-8", encoding ); } public void testComplianceLevel() { buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_14 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); assertEquals( "compliance level", CompilerOptions.VERSION_1_4, compliance); assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel ); } public void testSourceCompatibilityLevel() { buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_13); buildOptions.setSourceCompatibilityLevel( BuildOptionsAdapter.VERSION_14); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); assertEquals( "compliance level", CompilerOptions.VERSION_1_3, compliance); assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel ); } public void testSourceIncompatibilityLevel() { // this config should "fail" and leave source level at 1.4 buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_14); buildOptions.setSourceCompatibilityLevel( BuildOptionsAdapter.VERSION_13); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); assertEquals( "compliance level", CompilerOptions.VERSION_1_4, compliance); assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel ); } public void testNullWarnings() { buildOptions.setWarnings( null ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with the default warnings assertOptionEquals( "report overriding package default", options, CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, CompilerOptions.WARNING); assertOptionEquals( "report method with cons name", options, CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.WARNING); assertOptionEquals( "report deprecation", options, CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); assertOptionEquals( "report hidden catch block", options, CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.WARNING); assertOptionEquals( "report unused local", options, CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.IGNORE); assertOptionEquals( "report unused param", options, CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.IGNORE); assertOptionEquals( "report synthectic access", options, CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.IGNORE); assertOptionEquals( "report non-externalized string literal", options, CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.IGNORE); assertOptionEquals( "report assert identifer", options, CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.WARNING); } // public void testEmptyWarnings() { // buildOptions.setWarnings( new HashSet() ); // buildConfig = compilerAdapter.genBuildConfig( configFile ); // Map options = buildConfig.getJavaOptions(); // // // this should leave us with the user specifiable warnings // // turned off // assertOptionEquals( "report overriding package default", // options, // CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, // CompilerOptions.WARNING); // assertOptionEquals( "report method with cons name", // options, // CompilerOptions.OPTION_ReportMethodWithConstructorName, // CompilerOptions.WARNING); // assertOptionEquals( "report deprecation", // options, // CompilerOptions.OPTION_ReportDeprecation, // CompilerOptions.WARNING); // assertOptionEquals( "report hidden catch block", // options, // CompilerOptions.OPTION_ReportHiddenCatchBlock, // CompilerOptions.WARNING); // assertOptionEquals( "report unused local", // options, // CompilerOptions.OPTION_ReportUnusedLocal, // CompilerOptions.WARNING); // assertOptionEquals( "report unused param", // options, // CompilerOptions.OPTION_ReportUnusedParameter, // CompilerOptions.WARNING); // assertOptionEquals( "report synthectic access", // options, // CompilerOptions.OPTION_ReportSyntheticAccessEmulation, // CompilerOptions.WARNING); // assertOptionEquals( "report non-externalized string literal", // options, // CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, // CompilerOptions.WARNING); // assertOptionEquals( "report assert identifer", // options, // CompilerOptions.OPTION_ReportAssertIdentifier, // CompilerOptions.WARNING); // } public void testSetOfWarnings() { HashSet warnings = new HashSet(); warnings.add( BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER ); warnings.add( BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME ); warnings.add( BuildOptionsAdapter.WARN_DEPRECATION ); warnings.add( BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS ); warnings.add( BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD ); warnings.add( BuildOptionsAdapter.WARN_SYNTHETIC_ACCESS ); warnings.add( BuildOptionsAdapter.WARN_UNUSED_ARGUMENTS ); warnings.add( BuildOptionsAdapter.WARN_UNUSED_IMPORTS ); warnings.add( BuildOptionsAdapter.WARN_UNUSED_LOCALS ); warnings.add( BuildOptionsAdapter.WARN_NLS ); buildOptions.setWarnings( warnings ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with all the user specifiable warnings // turned on assertOptionEquals( "report overriding package default", options, CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, CompilerOptions.WARNING); assertOptionEquals( "report method with cons name", options, CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.WARNING); assertOptionEquals( "report deprecation", options, CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); assertOptionEquals( "report hidden catch block", options, CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.WARNING); assertOptionEquals( "report unused local", options, CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.WARNING); assertOptionEquals( "report unused param", options, CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.WARNING); assertOptionEquals( "report synthectic access", options, CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.WARNING); assertOptionEquals( "report non-externalized string literal", options, CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.WARNING); assertOptionEquals( "report assert identifer", options, CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.WARNING); } public void testNoDebugOptions() { buildOptions.setDebugLevel( null ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with the default debug settings assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testEmptyDebugOptions() { buildOptions.setDebugLevel( new HashSet() ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with the default debug assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testDebugAll() { HashSet debugOpts = new HashSet(); debugOpts.add( BuildOptionsAdapter.DEBUG_ALL ); buildOptions.setDebugLevel( debugOpts ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with all debug on assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testDebugSet() { HashSet debugOpts = new HashSet(); debugOpts.add( BuildOptionsAdapter.DEBUG_SOURCE ); debugOpts.add( BuildOptionsAdapter.DEBUG_VARS ); buildOptions.setDebugLevel( debugOpts ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with all debug on assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testNoImport() { buildOptions.setNoImportError( true ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); // Map options = buildConfig.getJavaOptions(); // String noImport = (String) options.get( CompilerOptions.OPTION_ReportInvalidImport ); // assertEquals( "no import", CompilerOptions.WARNING, noImport ); // buildOptions.setNoImportError( false ); } public void testPreserveAllLocals() { buildOptions.setPreserveAllLocals( true ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String preserve = (String) options.get( CompilerOptions.OPTION_PreserveUnusedLocal ); assertEquals( "preserve unused", CompilerOptions.PRESERVE, preserve ); } public void testNonStandardOptions() { buildOptions.setNonStandardOptions( "-XnoWeave" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertTrue( "XnoWeave", buildConfig.isNoWeave() ); buildOptions.setNonStandardOptions( "-XserializableAspects" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue( "XserializableAspects", buildConfig.isXserializableAspects() ); buildOptions.setNonStandardOptions( "-XnoInline" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue( "XnoInline", buildConfig.isXnoInline()); buildOptions.setNonStandardOptions( "-Xlint" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertEquals( "Xlint", AjBuildConfig.AJLINT_DEFAULT, buildConfig.getLintMode()); buildOptions.setNonStandardOptions( "-Xlint:error" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertEquals( "Xlint", AjBuildConfig.AJLINT_ERROR, buildConfig.getLintMode()); // XXX test for lintfile // buildOptions.setNonStandardOptions( "-Xlintfile testdata/AspectJBuildManagerTest/lint.properties" ); // buildConfig = compilerAdapter.genBuildConfig( configFile ); // assertEquals( "Xlintfile", new File( "testdata/AspectJBuildManagerTest/lint.properties" ).getAbsolutePath(), // buildConfig.getLintSpecFile().toString()); // and a few options thrown in at once buildOptions.setNonStandardOptions( "-Xlint -XnoInline -XserializableAspects" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertEquals( "Xlint", AjBuildConfig.AJLINT_DEFAULT, buildConfig.getLintMode()); assertTrue( "XnoInline", buildConfig.isXnoInline()); assertTrue( "XserializableAspects", buildConfig.isXserializableAspects() ); } public void testSourceRoots() { Set roots = new HashSet(); projectProperties.setSourceRoots( roots ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List configRoots = buildConfig.getSourceRoots(); assertTrue( "no source dirs", configRoots.isEmpty() ); File f = new File( AjdeTests.testDataPath("examples/figures/figures-coverage" )); roots.add( f ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List configRoots2 = buildConfig.getSourceRoots(); assertTrue( "one source dir", configRoots2.size() == 1 ); assertTrue( "source dir", configRoots2.contains(f) ); File f2 = new File( AjdeTests.testDataPath("examples/figures/figures-demo")); roots.add( f2 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List configRoots3 = buildConfig.getSourceRoots(); assertTrue( "two source dirs", configRoots3.size() == 2 ); assertTrue( "source dir 1", configRoots3.contains(f) ); assertTrue( "source dir 2", configRoots3.contains(f2) ); } public void testInJars() { Set jars = new HashSet(); projectProperties.setInJars( jars ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List inJars = buildConfig.getInJars(); assertTrue( "no in jars", inJars.isEmpty() ); File f = new File( "jarone.jar" ); jars.add( f ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List inJars2 = buildConfig.getInJars(); assertTrue( "one in jar", inJars2.size() == 1 ); assertTrue( "in jar", inJars2.contains(f) ); File f2 = new File( "jartwo.jar" ); jars.add( f2 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); List inJars3 = buildConfig.getInJars(); assertTrue( "two in jars", inJars3.size() == 2 ); assertTrue( "in jar 1", inJars3.contains(f) ); assertTrue( "in jar 2", inJars3.contains(f2) ); } public void testAspectPath() { Set aspects = new HashSet(); projectProperties.setAspectPath( aspects ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List aPath = buildConfig.getAspectpath(); assertTrue( "no aspect path", aPath.isEmpty() ); File f = new File( "jarone.jar" ); aspects.add( f ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List aPath2 = buildConfig.getAspectpath(); assertEquals("aspectpath", 1, aPath2.size()); assertTrue( "1 aspectpath", aPath2.contains(f) ); File f2 = new File( "jartwo.jar" ); aspects.add( f2 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List aPath3 = buildConfig.getAspectpath(); assertTrue( "two jars in path", aPath3.size() == 2 ); assertTrue( "1 aspectpath", aPath3.contains(f) ); assertTrue( "2 aspectpath", aPath3.contains(f2) ); } public void testOutJar() { String outJar = "mybuild.jar"; projectProperties.setOutJar( outJar ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertNotNull("output jar", buildConfig.getOutputJar()); assertEquals( "out jar", outJar, buildConfig.getOutputJar().toString() ); } protected void setUp() throws Exception { preferencesAdapter = new UserPreferencesStore(false); buildOptions = new AjcBuildOptions(preferencesAdapter); compilerAdapter = new CompilerAdapter(); projectProperties = new NullIdeProperties( "" ); messageHandler = new MessageHandler(true); ErrorHandler handler = new ErrorHandler() { public void handleWarning(String message) { MessageUtil.warn(messageHandler, message); } public void handleError(String message) { MessageUtil.error(messageHandler, message); } public void handleError(String message, Throwable t) { IMessage m = new Message(message, IMessage.ERROR, t, null); messageHandler.handleMessage(m); } }; try { // String s = null; Ajde.init( null, null, null, projectProperties, buildOptions, null, null, handler); } catch (Throwable t) { String s = "Unable to initialize AJDE " + LangUtil.renderException(t); assertTrue(s, false); } } protected void tearDown() throws Exception { super.tearDown(); preferencesAdapter = null; buildOptions = null; compilerAdapter = null; projectProperties = null; messageHandler = null; } private void assertOptionEquals( String reason, Map options, String optionName, String value) { String mapValue = (String) options.get(optionName); assertEquals( reason, value, mapValue ); } }
112,615
Bug 112615 -XhasMember is not processed correctly when passed from AJDT
To test this in AJDT install the bean example, add a new interface called I and then add the following line to BoundPoint.aj: declare parents: hasmethod(* set*(..)) implements I; Now open the AspectJ Compiler preference page and select "Has Member" on the advanced tab. Click OK, rebuild and if the option was working the project would build correctly. As it stands there is an error: the type pattern hasmethod(* set*(..)) can only be used when the -XhasMember option is set
resolved fixed
cc6862f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-25T12:40:39Z
2005-10-14T11:40:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer added constructor to populate javaOptions with * default settings - 01.20.2003 * Bugzilla #29768, 29769 * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.util.FileUtil; /** * All configuration information needed to run the AspectJ compiler. * Compiler options (as opposed to path information) are held in an AjCompilerOptions instance */ public class AjBuildConfig { private boolean shouldProceed = true; public static final String AJLINT_IGNORE = "ignore"; public static final String AJLINT_WARN = "warn"; public static final String AJLINT_ERROR = "error"; public static final String AJLINT_DEFAULT = "default"; private File outputDir; private File outputJar; private List/*File*/ sourceRoots = new ArrayList(); private List/*File*/ files = new ArrayList(); private List /*File*/ binaryFiles = new ArrayList(); // .class files in indirs... private List/*File*/ inJars = new ArrayList(); private List/*File*/ inPath = new ArrayList(); private Map/*String->File*/ sourcePathResources = new HashMap(); private List/*File*/ aspectpath = new ArrayList(); private List/*String*/ classpath = new ArrayList(); private List/*String*/ bootclasspath = new ArrayList(); private File configFile; private String lintMode = AJLINT_DEFAULT; private File lintSpecFile = null; private AjCompilerOptions options; /** if true, then global values override local when joining */ private boolean override = true; // incremental variants handled by the compiler client, but parsed here private boolean incrementalMode; private File incrementalFile; public String toString() { StringBuffer sb = new StringBuffer(); sb.append("BuildConfig["+(configFile==null?"null":configFile.getAbsoluteFile().toString())+"] #Files="+files.size()); return sb.toString(); } public static class BinarySourceFile { public BinarySourceFile(File dir, File src) { this.fromInPathDirectory = dir; this.binSrc = src; } public File fromInPathDirectory; public File binSrc; public boolean equals(Object obj) { if ((obj instanceof BinarySourceFile) && (obj != null)) { BinarySourceFile other = (BinarySourceFile)obj; return(binSrc.equals(other.binSrc)); } return false; } public int hashCode() { return binSrc != null ? binSrc.hashCode() : 0; } } /** * Intialises the javaOptions Map to hold the default * JDT Compiler settings. Added by AMC 01.20.2003 in reponse * to bug #29768 and enh. 29769. * The settings here are duplicated from those set in * org.eclipse.jdt.internal.compiler.batch.Main, but I've elected to * copy them rather than refactor the JDT class since this keeps * integration with future JDT releases easier (?). */ public AjBuildConfig( ) { options = new AjCompilerOptions(); } /** * returned files includes <ul> * <li>files explicitly listed on command-line</li> * <li>files listed by reference in argument list files</li> * <li>files contained in sourceRootDir if that exists</li> * </ul> * * @return all source files that should be compiled. */ public List/*File*/ getFiles() { return files; } /** * returned files includes all .class files found in * a directory on the inpath, but does not include * .class files contained within jars. */ public List/*BinarySourceFile*/ getBinaryFiles() { return binaryFiles; } public File getOutputDir() { return outputDir; } public void setFiles(List files) { this.files = files; } public void setOutputDir(File outputDir) { this.outputDir = outputDir; } public AjCompilerOptions getOptions() { return options; } /** * This does not include -bootclasspath but includes -extdirs and -classpath */ public List getClasspath() { // XXX setters don't respect javadoc contract... return classpath; } public void setClasspath(List classpath) { this.classpath = classpath; } public List getBootclasspath() { return bootclasspath; } public void setBootclasspath(List bootclasspath) { this.bootclasspath = bootclasspath; } public File getOutputJar() { return outputJar; } public List/*File*/ getInpath() { // Elements of the list are either archives (jars/zips) or directories return inPath; } public List/*File*/ getInJars() { return inJars; } public Map getSourcePathResources() { return sourcePathResources; } public void setOutputJar(File outputJar) { this.outputJar = outputJar; } public void setInJars(List sourceJars) { this.inJars = sourceJars; } public void setInPath(List dirsOrJars) { inPath = dirsOrJars; // remember all the class files in directories on the inpath binaryFiles = new ArrayList(); FileFilter filter = new FileFilter() { public boolean accept(File pathname) { return pathname.getPath().endsWith(".class"); }}; for (Iterator iter = dirsOrJars.iterator(); iter.hasNext();) { File inpathElement = (File) iter.next(); if (inpathElement.isDirectory()) { File[] files = FileUtil.listFiles(inpathElement, filter); for (int i = 0; i < files.length; i++) { binaryFiles.add(new BinarySourceFile(inpathElement,files[i])); } } } } public List getSourceRoots() { return sourceRoots; } public void setSourceRoots(List sourceRootDir) { this.sourceRoots = sourceRootDir; } public File getConfigFile() { return configFile; } public void setConfigFile(File configFile) { this.configFile = configFile; } public void setIncrementalMode(boolean incrementalMode) { this.incrementalMode = incrementalMode; } public boolean isIncrementalMode() { return incrementalMode; } public void setIncrementalFile(File incrementalFile) { this.incrementalFile = incrementalFile; } public boolean isIncrementalFileMode() { return (null != incrementalFile); } /** * @return List (String) classpath of bootclasspath, injars, inpath, aspectpath * entries, specified classpath (extdirs, and classpath), and output dir or jar */ public List getFullClasspath() { List full = new ArrayList(); full.addAll(getBootclasspath()); // XXX Is it OK that boot classpath overrides inpath/injars/aspectpath? for (Iterator i = inJars.iterator(); i.hasNext(); ) { full.add(((File)i.next()).getAbsolutePath()); } for (Iterator i = inPath.iterator();i.hasNext();) { full.add(((File)i.next()).getAbsolutePath()); } for (Iterator i = aspectpath.iterator(); i.hasNext(); ) { full.add(((File)i.next()).getAbsolutePath()); } full.addAll(getClasspath()); // if (null != outputDir) { // full.add(outputDir.getAbsolutePath()); // } else if (null != outputJar) { // full.add(outputJar.getAbsolutePath()); // } return full; } public File getLintSpecFile() { return lintSpecFile; } public void setLintSpecFile(File lintSpecFile) { this.lintSpecFile = lintSpecFile; } public List getAspectpath() { return aspectpath; } public void setAspectpath(List aspectpath) { this.aspectpath = aspectpath; } /** @return true if any config file, sourceroots, sourcefiles, injars or inpath */ public boolean hasSources() { return ((null != configFile) || (0 < sourceRoots.size()) || (0 < files.size()) || (0 < inJars.size()) || (0 < inPath.size()) ); } // /** @return null if no errors, String errors otherwise */ // public String configErrors() { // StringBuffer result = new StringBuffer(); // // ok, permit both. sigh. //// if ((null != outputDir) && (null != outputJar)) { //// result.append("specified both outputDir and outputJar"); //// } // // incremental => only sourceroots // // // return (0 == result.length() ? null : result.toString()); // } /** * Install global values into local config * unless values conflict: * <ul> * <li>Collections are unioned</li> * <li>values takes local value unless default and global set</li> * <li>this only sets one of outputDir and outputJar as needed</li> * <ul> * This also configures super if javaOptions change. * @param global the AjBuildConfig to read globals from */ public void installGlobals(AjBuildConfig global) { // XXX relies on default values // don't join the options - they already have defaults taken care of. // Map optionsMap = options.getMap(); // join(optionsMap,global.getOptions().getMap()); // options.set(optionsMap); join(aspectpath, global.aspectpath); join(classpath, global.classpath); if (null == configFile) { configFile = global.configFile; // XXX correct? } if (!isEmacsSymMode() && global.isEmacsSymMode()) { setEmacsSymMode(true); } join(files, global.files); if (!isGenerateModelMode() && global.isGenerateModelMode()) { setGenerateModelMode(true); } if (null == incrementalFile) { incrementalFile = global.incrementalFile; } if (!incrementalMode && global.incrementalMode) { incrementalMode = true; } join(inJars, global.inJars); join(inPath, global.inPath); if ((null == lintMode) || (AJLINT_DEFAULT.equals(lintMode))) { setLintMode(global.lintMode); } if (null == lintSpecFile) { lintSpecFile = global.lintSpecFile; } if (!isNoWeave() && global.isNoWeave()) { setNoWeave(true); } if ((null == outputDir) && (null == outputJar)) { if (null != global.outputDir) { outputDir = global.outputDir; } if (null != global.outputJar) { outputJar = global.outputJar; } } join(sourceRoots, global.sourceRoots); if (!isXnoInline() && global.isXnoInline()) { setXnoInline(true); } if (!isXserializableAspects() && global.isXserializableAspects()) { setXserializableAspects(true); } if (!isXlazyTjp() && global.isXlazyTjp()) { setXlazyTjp(true); } if (!isXNotReweavable() && global.isXNotReweavable()) { setXnotReweavable(true); } } void join(Collection local, Collection global) { for (Iterator iter = global.iterator(); iter.hasNext();) { Object next = iter.next(); if (!local.contains(next)) { local.add(next); } } } void join(Map local, Map global) { for (Iterator iter = global.keySet().iterator(); iter.hasNext();) { Object key = iter.next(); if (override || (null == local.get(key))) { // Object value = global.get(key); if (null != value) { local.put(key, value); } } } } public void setSourcePathResources(Map map) { sourcePathResources = map; } /** * used to indicate whether to proceed after parsing config */ public boolean shouldProceed() { return shouldProceed; } public void doNotProceed() { shouldProceed = false; } public String getLintMode() { return lintMode; } // options... public void setLintMode(String lintMode) { this.lintMode = lintMode; String lintValue = null; if (AJLINT_IGNORE.equals(lintMode)) { lintValue = AjCompilerOptions.IGNORE; } else if (AJLINT_WARN.equals(lintMode)) { lintValue = AjCompilerOptions.WARNING; } else if (AJLINT_ERROR.equals(lintMode)) { lintValue = AjCompilerOptions.ERROR; } if (lintValue != null) { Map lintOptions = new HashMap(); lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportUnresolvableMember,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion,lintValue); options.set(lintOptions); } } public boolean isNoWeave() { return options.noWeave; } public void setNoWeave(boolean noWeave) { options.noWeave = noWeave; } public boolean isXserializableAspects() { return options.xSerializableAspects; } public void setXserializableAspects(boolean xserializableAspects) { options.xSerializableAspects = xserializableAspects; } public boolean isXnoInline() { return options.xNoInline; } public void setXnoInline(boolean xnoInline) { options.xNoInline = xnoInline; } public boolean isXlazyTjp() { return options.xLazyThisJoinPoint; } public void setXlazyTjp(boolean b) { options.xLazyThisJoinPoint = b; } public void setXnotReweavable(boolean b) { options.xNotReweavable = b; } public void setXHasMemberSupport(boolean enabled) { options.xHasMember = enabled; } public boolean isXHasMemberEnabled() { return options.xHasMember; } public void setXdevPinpointMode(boolean enabled) { options.xdevPinpoint = enabled; } public boolean isXdevPinpoint() { return options.xdevPinpoint; } public boolean isXNotReweavable() { return options.xNotReweavable; } public boolean isGenerateJavadocsInModelMode() { return options.generateJavaDocsInModel; } public void setGenerateJavadocsInModelMode( boolean generateJavadocsInModelMode) { options.generateJavaDocsInModel = generateJavadocsInModelMode; } public boolean isEmacsSymMode() { return options.generateEmacsSymFiles; } public void setEmacsSymMode(boolean emacsSymMode) { options.generateEmacsSymFiles = emacsSymMode; } public boolean isGenerateModelMode() { return options.generateModel; } public void setGenerateModelMode(boolean structureModelMode) { options.generateModel = structureModelMode; } public boolean isNoAtAspectJAnnotationProcessing() { return options.noAtAspectJProcessing; } public void setNoAtAspectJAnnotationProcessing(boolean noProcess) { options.noAtAspectJProcessing = noProcess; } public void setShowWeavingInformation(boolean b) { options.showWeavingInformation = true; } public boolean getShowWeavingInformation() { return options.showWeavingInformation; } public void setProceedOnError(boolean b) { options.proceedOnError = b; } public boolean getProceedOnError() { return options.proceedOnError; } public void setBehaveInJava5Way(boolean b) { options.behaveInJava5Way = b; } public boolean getBehaveInJava5Way() { return options.behaveInJava5Way; } }
99,191
Bug 99191 declare @field allowed for non existent fields
///// in this code @interface anInterface{} aspect B { declare @field : int B.noSuchField : @anInterface; // should be an error } ////////////////// I don't get an error, even though B.noSuchField doesn't exist. If I try declare @field on NoSuchCLass.noSuchField I do get an error though.
resolved fixed
2da9b31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T15:49:49Z
2005-06-09T15:13:20Z
tests/bugs150/pr99191/pr99191_1.java
99,191
Bug 99191 declare @field allowed for non existent fields
///// in this code @interface anInterface{} aspect B { declare @field : int B.noSuchField : @anInterface; // should be an error } ////////////////// I don't get an error, even though B.noSuchField doesn't exist. If I try declare @field on NoSuchCLass.noSuchField I do get an error though.
resolved fixed
2da9b31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T15:49:49Z
2005-06-09T15:13:20Z
tests/bugs150/pr99191/pr99191_2.java
99,191
Bug 99191 declare @field allowed for non existent fields
///// in this code @interface anInterface{} aspect B { declare @field : int B.noSuchField : @anInterface; // should be an error } ////////////////// I don't get an error, even though B.noSuchField doesn't exist. If I try declare @field on NoSuchCLass.noSuchField I do get an error though.
resolved fixed
2da9b31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T15:49:49Z
2005-06-09T15:13:20Z
tests/bugs150/pr99191/pr99191_3.java
99,191
Bug 99191 declare @field allowed for non existent fields
///// in this code @interface anInterface{} aspect B { declare @field : int B.noSuchField : @anInterface; // should be an error } ////////////////// I don't get an error, even though B.noSuchField doesn't exist. If I try declare @field on NoSuchCLass.noSuchField I do get an error though.
resolved fixed
2da9b31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T15:49:49Z
2005-06-09T15:13:20Z
tests/bugs150/pr99191/pr99191_4.java
99,191
Bug 99191 declare @field allowed for non existent fields
///// in this code @interface anInterface{} aspect B { declare @field : int B.noSuchField : @anInterface; // should be an error } ////////////////// I don't get an error, even though B.noSuchField doesn't exist. If I try declare @field on NoSuchCLass.noSuchField I do get an error though.
resolved fixed
2da9b31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T15:49:49Z
2005-06-09T15:13:20Z
tests/bugs150/pr99191/pr99191_5.java
99,191
Bug 99191 declare @field allowed for non existent fields
///// in this code @interface anInterface{} aspect B { declare @field : int B.noSuchField : @anInterface; // should be an error } ////////////////// I don't get an error, even though B.noSuchField doesn't exist. If I try declare @field on NoSuchCLass.noSuchField I do get an error though.
resolved fixed
2da9b31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T15:49:49Z
2005-06-09T15:13:20Z
tests/bugs150/pr99191/pr99191_6.java
99,191
Bug 99191 declare @field allowed for non existent fields
///// in this code @interface anInterface{} aspect B { declare @field : int B.noSuchField : @anInterface; // should be an error } ////////////////// I don't get an error, even though B.noSuchField doesn't exist. If I try declare @field on NoSuchCLass.noSuchField I do get an error though.
resolved fixed
2da9b31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T15:49:49Z
2005-06-09T15:13:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.internal.Relationship; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } /* public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");} public void testMissingAccessor_pr73856() { runTest("missing accessor");} public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");} public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");} public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");} public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");} */ public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");} public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");} public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");} public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");} public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");} public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");} public void testVarargsITD_pr110906() { runTest("ITD varargs problem");} public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");} public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");} public void testBadGenericSigAttribute_pr110927() { runTest("cant create signature attribute"); Signature sig = GenericsTests.getClassSignature(ajc,"I"); if (sig==null) fail("Couldn't find signature attribute for type I"); String sigString = sig.getSignature(); if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") || sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) { fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"); } } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");} public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } // IfPointcut.findResidueInternal() was modified to make this test complete in a short amount // of time - if you see it hanging, someone has messed with the optimization. public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");} public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testAtAnnotationBadTest_pr103740() { runTest("Compiler failure on at_annotation"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } public void testNoVerifyErrorOnGenericCollectionMemberAccess() { runTest("no verify error on generic collection member access"); } public void testRawAndGenericTypeConversionITDCons() { runTest("raw and generic type conversion with itd cons"); } public void testAtAnnotationBindingWithAround() { runTest("@annotation binding with around advice"); } public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");} public void testMessageOnMissingTypeInDecP() { runTest("declare parents on a missing type"); } public void testParameterizedGenericMethods() { runTest("parameterized generic methods"); } public void testIllegalChangeToPointcutDeclaration_pr111915() { runTest("test illegal change to pointcut declaration"); } public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");} public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");} public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");} public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");} public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");} // Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats // where we can police whether a type variable has been used without being specified appropriately. //public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");} public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");} public void testCallJoinPointsInAnonymousInnerClasses() { runTest("call join points in anonymous inner classes"); } public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() { runTest("default impl of Runnable"); } public void testArrayCloneCallJoinPoints() { runTest("array clone call join points in 1.4 vs 1.3"); } public void testDebugInfoForAroundAdvice() { runTest("debug info in around advice inlining"); } public void testCCEWithGenericWildcard_pr112602() { runTest("ClassCastException with generic wildcard"); } public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the run() method inside anonymous inner class is in // the structure model IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"run()"); assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'run()' but is " + target.toLabelString(),"run()",target.toLabelString()); } public void testAdviceInStructureModelWithNamedInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with named inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the m() method inside named inner class is in // the structure model IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"m()"); assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'm()' but is " + target.toLabelString(),"m()",target.toLabelString()); } public void testDWInStructureModelWithAnonymousInnerClass_pr77269() { // AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("declare warning in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())"); assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe); } public void testVarArgsIITDInConstructor() { runTest("ITD varargs in constructor"); } public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() { runTest("weaveinfo message for declare at method on an ITDd method"); } public void testNoVerifyErrorWithTwoThisPCDs_pr113447() { runTest("no verify error with two this pcds"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
99,191
Bug 99191 declare @field allowed for non existent fields
///// in this code @interface anInterface{} aspect B { declare @field : int B.noSuchField : @anInterface; // should be an error } ////////////////// I don't get an error, even though B.noSuchField doesn't exist. If I try declare @field on NoSuchCLass.noSuchField I do get an error though.
resolved fixed
2da9b31
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T15:49:49Z
2005-06-09T15:13:20Z
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.IndexedInstruction; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.NEW; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUTFIELD; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.RET; import org.aspectj.apache.bcel.generic.ReturnInstruction; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.PartialOrder; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IClassWeaver; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.DeclareAnnotation; class BcelClassWeaver implements IClassWeaver { /** * This is called from {@link BcelWeaver} to perform the per-class weaving process. */ public static boolean weave( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers).weave(); //System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState()); //clazz.print(); return b; } // -------------------------------------------- private final LazyClassGen clazz; private final List shadowMungers; private final List typeMungers; private final List lateTypeMungers; private final BcelObjectType ty; // alias of clazz.getType() private final BcelWorld world; // alias of ty.getWorld() private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen() private final InstructionFactory fact; // alias of clazz.getFactory(); private final List addedLazyMethodGens = new ArrayList(); private final Set addedDispatchTargets = new HashSet(); // Static setting across BcelClassWeavers private static boolean inReweavableMode = false; private List addedSuperInitializersAsList = null; // List<IfaceInitList> private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger> private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger> private Map mapToAnnotations = new HashMap(); private BcelShadow clinitShadow = null; /** * This holds the initialization and pre-initialization shadows for this class * that were actually matched by mungers (if no match, then we don't even create the * shadows really). */ private final List initializationShadows = new ArrayList(1); private BcelClassWeaver( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers, List lateTypeMungers) { super(); // assert world == clazz.getType().getWorld() this.world = world; this.clazz = clazz; this.shadowMungers = shadowMungers; this.typeMungers = typeMungers; this.lateTypeMungers = lateTypeMungers; this.ty = clazz.getBcelObjectType(); this.cpg = clazz.getConstantPoolGen(); this.fact = clazz.getFactory(); fastMatchShadowMungers(shadowMungers); initializeSuperInitializerMap(ty.getResolvedTypeX()); } private List[] perKindShadowMungers; private boolean canMatchBodyShadows = false; private boolean canMatchInitialization = false; private void fastMatchShadowMungers(List shadowMungers) { // beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) ! perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1]; for (int i = 0; i < perKindShadowMungers.length; i++) { perKindShadowMungers[i] = new ArrayList(0); } for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Set couldMatchKinds = munger.getPointcut().couldMatchKinds(); for (Iterator kindIterator = couldMatchKinds.iterator(); kindIterator.hasNext();) { Shadow.Kind aKind = (Shadow.Kind) kindIterator.next(); perKindShadowMungers[aKind.getKey()].add(munger); } } if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty()) canMatchInitialization = true; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (!kind.isEnclosingKind() && !perKindShadowMungers[i+1].isEmpty()) { canMatchBodyShadows = true; } if (perKindShadowMungers[i+1].isEmpty()) { perKindShadowMungers[i+1] = null; } } } private boolean canMatch(Shadow.Kind kind) { return perKindShadowMungers[kind.getKey()] != null; } // private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) { // FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind); // for (Iterator i = shadowMungers.iterator(); i.hasNext();) { // ShadowMunger munger = (ShadowMunger) i.next(); // FuzzyBoolean fb = munger.getPointcut().fastMatch(info); // WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString() // if (fb.maybeTrue()) mungers.add(munger); // } // } private void initializeSuperInitializerMap(ResolvedType child) { ResolvedType[] superInterfaces = child.getDeclaredInterfaces(); for (int i=0, len=superInterfaces.length; i < len; i++) { if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) { if (addSuperInitializer(superInterfaces[i])) { initializeSuperInitializerMap(superInterfaces[i]); } } } } private boolean addSuperInitializer(ResolvedType onType) { if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); if (l != null) return false; l = new IfaceInitList(onType); addedSuperInitializers.put(onType, l); return true; } public void addInitializer(ConcreteTypeMunger cm) { NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger(); ResolvedType onType = m.getSignature().getDeclaringType().resolve(world); if (onType.isRawType()) onType = onType.getGenericType(); if (m.getSignature().isStatic()) { addedClassInitializers.add(cm); } else { if (onType == ty.getResolvedTypeX()) { addedThisInitializers.add(cm); } else { IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); l.list.add(cm); } } } private static class IfaceInitList implements PartialOrder.PartialComparable { final ResolvedType onType; List list = new ArrayList(); IfaceInitList(ResolvedType onType) { this.onType = onType; } public int compareTo(Object other) { IfaceInitList o = (IfaceInitList)other; if (onType.isAssignableFrom(o.onType)) return +1; else if (o.onType.isAssignableFrom(onType)) return -1; else return 0; } public int fallbackCompareTo(Object other) { return 0; } } // XXX this is being called, but the result doesn't seem to be being used public boolean addDispatchTarget(ResolvedMember m) { return addedDispatchTargets.add(m); } public void addLazyMethodGen(LazyMethodGen gen) { addedLazyMethodGens.add(gen); } public void addOrReplaceLazyMethodGen(LazyMethodGen mg) { if (alreadyDefined(clazz, mg)) return; for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (existing.definingType == null) { // this means existing was introduced on the class itself return; } else if (mg.definingType.isAssignableFrom(existing.definingType)) { // existing is mg's subtype and dominates mg return; } else if (existing.definingType.isAssignableFrom(mg.definingType)) { // mg is existing's subtype and dominates existing i.remove(); addedLazyMethodGens.add(mg); return; } else { throw new BCException("conflict between: " + mg + " and " + existing); } } } addedLazyMethodGens.add(mg); } private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) { for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (!mg.isAbstract() && existing.isAbstract()) { i.remove(); return false; } return true; } } return false; } private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) { return mg.getName().equals(existing.getName()) && mg.getSignature().equals(existing.getSignature()); } // ---- public boolean weave() { if (clazz.isWoven() && !clazz.isReweavable()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()), ty.getSourceLocation(), null); return false; } Set aspectsAffectingType = null; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType = new HashSet(); boolean isChanged = false; // we want to "touch" all aspects if (clazz.getType().isAspect()) isChanged = true; // start by munging all typeMungers for (Iterator i = typeMungers.iterator(); i.hasNext(); ) { Object o = i.next(); if ( !(o instanceof BcelTypeMunger) ) { //???System.err.println("surprising: " + o); continue; } BcelTypeMunger munger = (BcelTypeMunger)o; boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } // Weave special half type/half shadow mungers... isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged; isChanged = weaveDeclareAtField(clazz) || isChanged; // XXX do major sort of stuff // sort according to: Major: type hierarchy // within each list: dominates // don't forget to sort addedThisInitialiers according to dominates addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values()); addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList); if (addedSuperInitializersAsList == null) { throw new BCException("circularity in inter-types"); } // this will create a static initializer if there isn't one // this is in just as bad taste as NOPs LazyMethodGen staticInit = clazz.getStaticInitializer(); staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true)); // now go through each method, and match against each method. This // sets up each method's {@link LazyMethodGen#matchedShadows} field, // and it also possibly adds to {@link #initializationShadows}. List methodGens = new ArrayList(clazz.getMethodGens()); for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; boolean shadowMungerMatched = match(mg); if (shadowMungerMatched) { // For matching mungers, add their declaring aspects to the list that affected this type if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.addAll(findAspectsForMungers(mg)); isChanged = true; } } // now we weave all but the initialization shadows for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; implement(mg); } // if we matched any initialization shadows, we inline and weave if (! initializationShadows.isEmpty()) { // Repeat next step until nothing left to inline...cant go on // infinetly as compiler will have detected and reported // "Recursive constructor invocation" while (inlineSelfConstructors(methodGens)); positionAndImplement(initializationShadows); } // now proceed with late type mungers if (lateTypeMungers != null) { for (Iterator i = lateTypeMungers.iterator(); i.hasNext(); ) { BcelTypeMunger munger = (BcelTypeMunger)i.next(); if (munger.matches(clazz.getType())) { boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName()); } } } } //FIXME AV - see #75442, for now this is not enough to fix the bug, comment that out until we really fix it // // flush to save some memory // PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType()); // finally, if we changed, we add in the introduced methods. if (isChanged) { clazz.getOrCreateWeaverStateInfo(inReweavableMode); weaveInAddedMethods(); // FIXME asc are these potentially affected by declare annotation? } if (inReweavableMode) { WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(true); wsi.addAspectsAffectingType(aspectsAffectingType); wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes()); wsi.setReweavable(true); } else { clazz.getOrCreateWeaverStateInfo(false).setReweavable(false); } return isChanged; } /** * Weave any declare @method/@ctor statements into the members of the supplied class */ private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) { List reportedProblems = new ArrayList(); List allDecams = world.getDeclareAnnotationOnMethods(); if (allDecams.isEmpty()) return false; // nothing to do boolean isChanged = false; // deal with ITDs List itdMethodsCtors = getITDSubset(clazz,ResolvedTypeMunger.Method); itdMethodsCtors.addAll(getITDSubset(clazz,ResolvedTypeMunger.Constructor)); if (!itdMethodsCtors.isEmpty()) { // Can't use the subset called 'decaMs' as it won't be right for ITDs... isChanged = weaveAtMethodOnITDSRepeatedly(allDecams,itdMethodsCtors,reportedProblems); } // deal with all the other methods... List members = clazz.getMethodGens(); List decaMs = getMatchingSubset(allDecams,clazz.getType()); if (decaMs.isEmpty()) return false; // nothing to do if (!members.isEmpty()) { for (int memberCounter = 0;memberCounter<members.size();memberCounter++) { LazyMethodGen mg = (LazyMethodGen)members.get(memberCounter); if (!mg.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter = decaMs.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) continue; // skip this one... Annotation a = decaM.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); Method oldMethod = mg.getMethod(); MethodGen myGen = new MethodGen(oldMethod,clazz.getClassName(),clazz.getConstantPoolGen()); myGen.addAnnotation(ag); Method newMethod = myGen.getMethod(); mg.addAnnotation(decaM.getAnnotationX()); members.set(memberCounter,new LazyMethodGen(newMethod,clazz)); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); reportMethodCtorWeavingMessage(clazz, mg.getMemberView(), decaM,mg.getDeclarationLineNumber()); isChanged = true; modificationOccured = true; } else { if (!decaM.isStarredAnnotationPattern()) worthRetrying.add(decaM); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) continue; // skip this one... mg.addAnnotation(decaM.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); isChanged = true; modificationOccured = true; forRemoval.add(decaM); } } worthRetrying.removeAll(forRemoval); } } } } return isChanged; } // TAG: WeavingMessage private void reportMethodCtorWeavingMessage(LazyClassGen clazz, ResolvedMember member, DeclareAnnotation decaM,int memberLineNumber) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ StringBuffer parmString = new StringBuffer("("); UnresolvedType[] paramTypes = member.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { UnresolvedType type = paramTypes[i]; String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type.getSignature()); if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1); parmString.append(s); if ((i+1)<paramTypes.length) parmString.append(","); } parmString.append(")"); String methodName = member.getName(); StringBuffer sig = new StringBuffer(); sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(member.getModifiers())); sig.append(" "); sig.append(member.getReturnType().toString()); sig.append(" "); sig.append(member.getDeclaringType().toString()); sig.append("."); sig.append(methodName.equals("<init>")?"new":methodName); sig.append(parmString); StringBuffer loc = new StringBuffer(); if (clazz.getFileName()==null) { loc.append("no debug info available"); } else { loc.append(clazz.getFileName()); if (memberLineNumber!=-1) { loc.append(":"+memberLineNumber); } } getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ sig.toString(), loc.toString(), decaM.getAnnotationString(), methodName.startsWith("<init>")?"constructor":"method", decaM.getAspect().toString(), Utility.beautifyLocation(decaM.getSourceLocation()) })); } } /** * Looks through a list of declare annotation statements and only returns * those that could possibly match on a field/method/ctor in type. */ private List getMatchingSubset(List declareAnnotations, ResolvedType type) { List subset = new ArrayList(); for (Iterator iter = declareAnnotations.iterator(); iter.hasNext();) { DeclareAnnotation da = (DeclareAnnotation) iter.next(); if (da.couldEverMatch(type)) { subset.add(da); } } return subset; } /** * Get a subset of all the type mungers defined on this aspect */ private List getITDSubset(LazyClassGen clazz,ResolvedTypeMunger.Kind wantedKind) { List subset = new ArrayList(); Collection c = clazz.getBcelObjectType().getTypeMungers(); for (Iterator iter = c.iterator();iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger)iter.next(); if (typeMunger.getMunger().getKind()==wantedKind) subset.add(typeMunger); } return subset; } public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz,BcelTypeMunger fieldMunger) { NewFieldTypeMunger nftm = (NewFieldTypeMunger)fieldMunger.getMunger(); ResolvedMember lookingFor =AjcMemberMaker.interFieldInitializer(nftm.getSignature(),clazz.getType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName())) return element; } return null; } // FIXME asc refactor this to neaten it up public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz,BcelTypeMunger methodCtorMunger) { if (methodCtorMunger.getMunger() instanceof NewMethodTypeMunger) { NewMethodTypeMunger nftm = (NewMethodTypeMunger)methodCtorMunger.getMunger(); ResolvedMember lookingFor = AjcMemberMaker.interMethodDispatcher(nftm.getSignature(),methodCtorMunger.getAspectType()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element; } return null; } else if (methodCtorMunger.getMunger() instanceof NewConstructorTypeMunger) { NewConstructorTypeMunger nftm = (NewConstructorTypeMunger)methodCtorMunger.getMunger(); ResolvedMember lookingFor =AjcMemberMaker.postIntroducedConstructor(methodCtorMunger.getAspectType(),nftm.getSignature().getDeclaringType(),nftm.getSignature().getParameterTypes()); List meths = clazz.getMethodGens(); for (Iterator iter = meths.iterator(); iter.hasNext();) { LazyMethodGen element = (LazyMethodGen) iter.next(); if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element; } return null; } else { throw new RuntimeException("Not sure what this is: "+methodCtorMunger); } } /** * Applies some set of declare @field constructs (List<DeclareAnnotation>) to some bunch * of ITDfields (List<BcelTypeMunger>. It will iterate over the fields repeatedly until * everything has been applied. * */ private boolean weaveAtFieldRepeatedly(List decaFs, List itdFields,List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdFields.iterator(); iter.hasNext();) { BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next(); ResolvedMember itdIsActually = fieldMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaFs.iterator(); iter2.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter2.next(); if (decaF.matches(itdIsActually,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger); if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaF); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } /** * Applies some set of declare @method/@ctor constructs (List<DeclareAnnotation>) to some bunch * of ITDmembers (List<BcelTypeMunger>. It will iterate over the fields repeatedly until * everything has been applied. */ private boolean weaveAtMethodOnITDSRepeatedly(List decaMCs, List itdMethodsCtors,List reportedErrors) { boolean isChanged = false; for (Iterator iter = itdMethodsCtors.iterator(); iter.hasNext();) { BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next(); ResolvedMember unMangledInterMethod = methodctorMunger.getSignature(); List worthRetrying = new ArrayList(); boolean modificationOccured = false; for (Iterator iter2 = decaMCs.iterator(); iter2.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz,methodctorMunger); if (annotationHolder == null || doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)){ continue; // skip this one... } annotationHolder.addAnnotation(decaMC.getAnnotationX()); isChanged=true; AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation()); reportMethodCtorWeavingMessage(clazz, unMangledInterMethod, decaMC,-1); modificationOccured = true; } else { if (!decaMC.isStarredAnnotationPattern()) worthRetrying.add(decaMC); // an annotation is specified that might be put on by a subsequent decaf } } while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List forRemoval = new ArrayList(); for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next(); if (decaMC.matches(unMangledInterMethod,world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,methodctorMunger); if (doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)) continue; // skip this one... annotationHolder.addAnnotation(decaMC.getAnnotationX()); unMangledInterMethod.addAnnotation(decaMC.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation()); isChanged = true; modificationOccured = true; forRemoval.add(decaMC); } worthRetrying.removeAll(forRemoval); } } } return isChanged; } private boolean dontAddTwice(DeclareAnnotation decaF, Annotation [] dontAddMeTwice){ for (int i = 0; i < dontAddMeTwice.length; i++){ Annotation ann = dontAddMeTwice[i]; if (ann != null && decaF.getAnnotationX().getTypeName().equals(ann.getTypeName())){ dontAddMeTwice[i] = null; // incase it really has been added twice! return true; } } return false; } /** * Weave any declare @field statements into the fields of the supplied class * * Interesting case relating to public ITDd fields. The annotations are really stored against * the interfieldinit method in the aspect, but the public field is placed in the target * type and then is processed in the 2nd pass over fields that occurs. I think it would be * more expensive to avoid putting the annotation on that inserted public field than just to * have it put there as well as on the interfieldinit method. */ private boolean weaveDeclareAtField(LazyClassGen clazz) { // BUGWARNING not getting enough warnings out on declare @field ? // There is a potential problem here with warnings not coming out - this // will occur if they are created on the second iteration round this loop. // We currently deactivate error reporting for the second time round. // A possible solution is to record what annotations were added by what // decafs and check that to see if an error needs to be reported - this // would be expensive so lets skip it for now List reportedProblems = new ArrayList(); List allDecafs = world.getDeclareAnnotationOnFields(); if (allDecafs.isEmpty()) return false; // nothing to do boolean isChanged = false; List itdFields = getITDSubset(clazz,ResolvedTypeMunger.Field); if (itdFields!=null) { isChanged = weaveAtFieldRepeatedly(allDecafs,itdFields,reportedProblems); } List decaFs = getMatchingSubset(allDecafs,clazz.getType()); if (decaFs.isEmpty()) return false; // nothing more to do Field[] fields = clazz.getFieldGens(); if (fields!=null) { for (int fieldCounter = 0;fieldCounter<fields.length;fieldCounter++) { BcelField aBcelField = new BcelField(clazz.getBcelObjectType(),fields[fieldCounter]); if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; Annotation [] dontAddMeTwice = fields[fieldCounter].getAnnotations(); // go through all the declare @field statements for (Iterator iter = decaFs.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { if (!dontAddTwice(decaF,dontAddMeTwice)){ if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)){ continue; } if(decaF.getAnnotationX().isRuntimeVisible()){ // isAnnotationWithRuntimeRetention(clazz.getJavaClass(world))){ //if(decaF.getAnnotationTypeX().isAnnotationWithRuntimeRetention(world)){ // it should be runtime visible, so put it on the Field Annotation a = decaF.getAnnotationX().getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true); FieldGen myGen = new FieldGen(fields[fieldCounter],clazz.getConstantPoolGen()); myGen.addAnnotation(ag); Field newField = myGen.getField(); aBcelField.addAnnotation(decaF.getAnnotationX()); clazz.replaceField(fields[fieldCounter],newField); fields[fieldCounter]=newField; } else{ aBcelField.addAnnotation(decaF.getAnnotationX()); } } AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); reportFieldAnnotationWeavingMessage(clazz, fields, fieldCounter, decaF); isChanged = true; modificationOccured = true; } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { // below code is for recursive things if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) continue; // skip this one... aBcelField.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); isChanged = true; modificationOccured = true; forRemoval.add(decaF); } } worthRetrying.removeAll(forRemoval); } } } } return isChanged; } // TAG: WeavingMessage private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, Field[] fields, int fieldCounter, DeclareAnnotation decaF) { if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ Field theField = fields[fieldCounter]; world.getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ theField.toString() + "' of type '" + clazz.getName(), clazz.getFileName(), decaF.getAnnotationString(), "field", decaF.getAspect().toString(), Utility.beautifyLocation(decaF.getSourceLocation())})); } } /** * Check if a resolved member (field/method/ctor) already has an annotation, if it * does then put out a warning and return true */ private boolean doesAlreadyHaveAnnotation(ResolvedMember rm,DeclareAnnotation deca,List reportedProblems) { if (rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); world.getLint().elementAlreadyAnnotated.signal( new String[]{rm.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } } return true; } return false; } private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm,ResolvedMember itdfieldsig,DeclareAnnotation deca,List reportedProblems) { if (rm != null && rm.hasAnnotation(deca.getAnnotationTypeX())) { if (world.getLint().elementAlreadyAnnotated.isEnabled()) { Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode()); if (!reportedProblems.contains(uniqueID)) { reportedProblems.add(uniqueID); reportedProblems.add(new Integer(itdfieldsig.hashCode()*deca.hashCode())); world.getLint().elementAlreadyAnnotated.signal( new String[]{rm.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } } return true; } return false; } private Set findAspectsForMungers(LazyMethodGen mg) { Set aspectsAffectingType = new HashSet(); for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) { BcelShadow aShadow = (BcelShadow) iter.next(); // Mungers in effect on that shadow for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) { ShadowMunger aMunger = (ShadowMunger) iter2.next(); if (aMunger instanceof BcelAdvice) { BcelAdvice bAdvice = (BcelAdvice)aMunger; if(bAdvice.getConcreteAspect() != null){ aspectsAffectingType.add(bAdvice.getConcreteAspect().getName()); } } else { // It is a 'Checker' - we don't need to remember aspects that only contributed Checkers... } } } return aspectsAffectingType; } private boolean inlineSelfConstructors(List methodGens) { boolean inlinedSomething = false; for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); if (! mg.getName().equals("<init>")) continue; InstructionHandle ih = findSuperOrThisCall(mg); if (ih != null && isThisCall(ih)) { LazyMethodGen donor = getCalledMethod(ih); inlineMethod(donor, mg, ih); inlinedSomething = true; } } return inlinedSomething; } private void positionAndImplement(List initializationShadows) { for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) { BcelShadow s = (BcelShadow) i.next(); positionInitializationShadow(s); //s.getEnclosingMethod().print(); s.implement(); } } private void positionInitializationShadow(BcelShadow s) { LazyMethodGen mg = s.getEnclosingMethod(); InstructionHandle call = findSuperOrThisCall(mg); InstructionList body = mg.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow((BcelShadow) s); if (s.getKind() == Shadow.PreInitialization) { // XXX assert first instruction is an ALOAD_0. // a pre shadow goes from AFTER the first instruction (which we believe to // be an ALOAD_0) to just before the call to super r.associateWithTargets( Range.genStart(body, body.getStart().getNext()), Range.genEnd(body, call.getPrev())); } else { // assert s.getKind() == Shadow.Initialization r.associateWithTargets( Range.genStart(body, call.getNext()), Range.genEnd(body)); } } private boolean isThisCall(InstructionHandle ih) { INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction(); return inst.getClassName(cpg).equals(clazz.getName()); } /** inline a particular call in bytecode. * * @param donor the method we want to inline * @param recipient the method containing the call we want to inline * @param call the instructionHandle in recipient's body holding the call we want to * inline. */ public static void inlineMethod( LazyMethodGen donor, LazyMethodGen recipient, InstructionHandle call) { // assert recipient.contains(call) /* Implementation notes: * * We allocate two slots for every tempvar so we don't screw up * longs and doubles which may share space. This could be conservatively avoided * (no reference to a long/double instruction, don't do it) or packed later. * Right now we don't bother to pack. * * Allocate a new var for each formal param of the inlined. Fill with stack * contents. Then copy the inlined instructions in with the appropriate remap * table. Any framelocs used by locals in inlined are reallocated to top of * frame, */ final InstructionFactory fact = recipient.getEnclosingClass().getFactory(); IntMap frameEnv = new IntMap(); // this also sets up the initial environment InstructionList argumentStores = genArgumentStores(donor, recipient, frameEnv, fact); InstructionList inlineInstructions = genInlineInstructions(donor, recipient, frameEnv, fact, false); inlineInstructions.insert(argumentStores); recipient.getBody().append(call, inlineInstructions); Utility.deleteInstruction(call, recipient); } /** generate the instructions to be inlined. * * @param donor the method from which we will copy (and adjust frame and jumps) * instructions. * @param recipient the method the instructions will go into. Used to get the frame * size so we can allocate new frame locations for locals in donor. * @param frameEnv an environment to map from donor frame to recipient frame, * initially populated with argument locations. * @param fact an instruction factory for recipient */ static InstructionList genInlineInstructions( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact, boolean keepReturns) { InstructionList footer = new InstructionList(); InstructionHandle end = footer.append(InstructionConstants.NOP); InstructionList ret = new InstructionList(); InstructionList sourceList = donor.getBody(); Map srcToDest = new HashMap(); ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen(); ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen(); boolean isAcrossClass = donorCpg != recipientCpg; // first pass: copy the instructions directly, populate the srcToDest map, // fix frame instructions for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) { Instruction fresh = Utility.copyInstruction(src.getInstruction()); InstructionHandle dest; if (fresh instanceof CPInstruction) { // need to reset index to go to new constant pool. This is totally // a computation leak... we're testing this LOTS of times. Sigh. if (isAcrossClass) { CPInstruction cpi = (CPInstruction) fresh; cpi.setIndex( recipientCpg.addConstant( donorCpg.getConstant(cpi.getIndex()), donorCpg)); } } if (src.getInstruction() == Range.RANGEINSTRUCTION) { dest = ret.append(Range.RANGEINSTRUCTION); } else if (fresh instanceof ReturnInstruction) { if (keepReturns) { dest = ret.append(fresh); } else { dest = ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end)); } } else if (fresh instanceof BranchInstruction) { dest = ret.append((BranchInstruction) fresh); } else if ( fresh instanceof LocalVariableInstruction || fresh instanceof RET) { IndexedInstruction indexed = (IndexedInstruction) fresh; int oldIndex = indexed.getIndex(); int freshIndex; if (!frameEnv.hasKey(oldIndex)) { freshIndex = recipient.allocateLocal(2); frameEnv.put(oldIndex, freshIndex); } else { freshIndex = frameEnv.get(oldIndex); } indexed.setIndex(freshIndex); dest = ret.append(fresh); } else { dest = ret.append(fresh); } srcToDest.put(src, dest); } // second pass: retarget branch instructions, copy ranges and tags Map tagMap = new HashMap(); Map shadowMap = new HashMap(); for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src.getNext()) { Instruction inst = dest.getInstruction(); // retarget branches if (inst instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction) inst; InstructionHandle oldTarget = branch.getTarget(); InstructionHandle newTarget = (InstructionHandle) srcToDest.get(oldTarget); if (newTarget == null) { // assert this is a GOTO // this was a return instruction we previously replaced } else { branch.setTarget(newTarget); if (branch instanceof Select) { Select select = (Select) branch; InstructionHandle[] oldTargets = select.getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { select.setTarget( k, (InstructionHandle) srcToDest.get(oldTargets[k])); } } } } //copy over tags and range attributes InstructionTargeter[] srcTargeters = src.getTargeters(); if (srcTargeters != null) { for (int j = srcTargeters.length - 1; j >= 0; j--) { InstructionTargeter old = srcTargeters[j]; if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = (Tag) tagMap.get(oldTag); if (fresh == null) { fresh = oldTag.copy(); tagMap.put(oldTag, fresh); } dest.addTargeter(fresh); } else if (old instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) old; if (er.getStart() == src) { ExceptionRange freshEr = new ExceptionRange( recipient.getBody(), er.getCatchType(), er.getPriority()); freshEr.associateWithTargets( dest, (InstructionHandle)srcToDest.get(er.getEnd()), (InstructionHandle)srcToDest.get(er.getHandler())); } } else if (old instanceof ShadowRange) { ShadowRange oldRange = (ShadowRange) old; if (oldRange.getStart() == src) { BcelShadow oldShadow = oldRange.getShadow(); BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow()); BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing); ShadowRange freshRange = new ShadowRange(recipient.getBody()); freshRange.associateWithShadow(freshShadow); freshRange.associateWithTargets( dest, (InstructionHandle) srcToDest.get(oldRange.getEnd())); shadowMap.put(oldRange, freshRange); //recipient.matchedShadows.add(freshShadow); // XXX should go through the NEW copied shadow and update // the thisVar, targetVar, and argsVar // ??? Might want to also go through at this time and add // "extra" vars to the shadow. } } } } } if (!keepReturns) ret.append(footer); return ret; } /** generate the argument stores in preparation for inlining. * * @param donor the method we will inline from. Used to get the signature. * @param recipient the method we will inline into. Used to get the frame size * so we can allocate fresh locations. * @param frameEnv an empty environment we populate with a map from donor frame to * recipient frame. * @param fact an instruction factory for recipient */ private static InstructionList genArgumentStores( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact) { InstructionList ret = new InstructionList(); int donorFramePos = 0; // writing ret back to front because we're popping. if (! donor.isStatic()) { int targetSlot = recipient.allocateLocal(Type.OBJECT); ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot)); frameEnv.put(donorFramePos, targetSlot); donorFramePos += 1; } Type[] argTypes = donor.getArgumentTypes(); for (int i = 0, len = argTypes.length; i < len; i++) { Type argType = argTypes[i]; int argSlot = recipient.allocateLocal(argType); ret.insert(InstructionFactory.createStore(argType, argSlot)); frameEnv.put(donorFramePos, argSlot); donorFramePos += argType.getSize(); } return ret; } /** get a called method: Assumes the called method is in this class, * and the reference to it is exact (a la INVOKESPECIAL). * * @param ih The InvokeInstruction instructionHandle pointing to the called method. */ private LazyMethodGen getCalledMethod( InstructionHandle ih) { InvokeInstruction inst = (InvokeInstruction) ih.getInstruction(); String methodName = inst.getName(cpg); String signature = inst.getSignature(cpg); return clazz.getLazyMethodGen(methodName, signature); } private void weaveInAddedMethods() { Collections.sort(addedLazyMethodGens, new Comparator() { public int compare(Object a, Object b) { LazyMethodGen aa = (LazyMethodGen) a; LazyMethodGen bb = (LazyMethodGen) b; int i = aa.getName().compareTo(bb.getName()); if (i != 0) return i; return aa.getSignature().compareTo(bb.getSignature()); } } ); for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { clazz.addMethodGen((LazyMethodGen)i.next()); } } void addPerSingletonField(Member field) { ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType()); String aspectName = field.getReturnType().getName(); LazyMethodGen clinit = clazz.getStaticInitializer(); InstructionList setup = new InstructionList(); InstructionFactory fact = clazz.getFactory(); setup.append(fact.createNew(aspectType)); setup.append(InstructionFactory.createDup(1)); setup.append(fact.createInvoke( aspectName, "<init>", Type.VOID, new Type[0], Constants.INVOKESPECIAL)); setup.append( fact.createFieldAccess( aspectName, field.getName(), aspectType, Constants.PUTSTATIC)); clinit.getBody().insert(setup); } /** * Returns null if this is not a Java constructor, and then we won't * weave into it at all */ private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) { int depth = 1; InstructionHandle start = mg.getBody().getStart(); while (true) { if (start == null) return null; Instruction inst = start.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth--; if (depth == 0) return start; } else if (inst instanceof NEW) { depth++; } start = start.getNext(); } } // ---- private boolean match(LazyMethodGen mg) { BcelShadow enclosingShadow; List shadowAccumulator = new ArrayList(); // we want to match ajsynthetic constructors... if (mg.getName().equals("<init>")) { return matchInit(mg, shadowAccumulator); } else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) { return false; } else { if (mg.getName().equals("<clinit>")) { clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg); //System.err.println(enclosingShadow); } else if (mg.isAdviceMethod()) { enclosingShadow = BcelShadow.makeAdviceExecution(world, mg); } else { AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature(); if (effective == null) { enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows); } else if (effective.isWeaveBody()) { ResolvedMember rm = effective.getEffectiveSignature(); // Annotations for things with effective signatures are never stored in the effective // signature itself - we have to hunt for them. Storing them in the effective signature // would mean keeping two sets up to date (no way!!) fixAnnotationsForResolvedMember(rm,mg.getMemberView()); enclosingShadow = BcelShadow.makeShadowForMethod(world,mg,effective.getShadowKind(),rm); } else { return false; } } if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { match(mg, h, enclosingShadow, shadowAccumulator); } } // FIXME asc change from string match if we can, rather brittle. this check actually prevents field-exec jps if (canMatch(enclosingShadow.getKind()) && !mg.getName().startsWith("ajc$interFieldInit")) { if (match(enclosingShadow, shadowAccumulator)) { enclosingShadow.init(); } } mg.matchedShadows = shadowAccumulator; return !shadowAccumulator.isEmpty(); } } private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) { BcelShadow enclosingShadow; // XXX the enclosing join point is wrong for things before ignoreMe. InstructionHandle superOrThisCall = findSuperOrThisCall(mg); // we don't walk bodies of things where it's a wrong constructor thingie if (superOrThisCall == null) return false; enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall); if (mg.getEffectiveSignature() != null) { enclosingShadow.setMatchingSignature(mg.getEffectiveSignature().getEffectiveSignature()); } // walk the body boolean beforeSuperOrThisCall = true; if (shouldWeaveBody(mg)) { if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { if (h == superOrThisCall) { beforeSuperOrThisCall = false; continue; } match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator); } } if (canMatch(Shadow.ConstructorExecution)) match(enclosingShadow, shadowAccumulator); } // XXX we don't do pre-inits of interfaces // now add interface inits if (superOrThisCall != null && ! isThisCall(superOrThisCall)) { InstructionHandle curr = enclosingShadow.getRange().getStart(); for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) { IfaceInitList l = (IfaceInitList) i.next(); Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType); BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig); // insert code in place InstructionList inits = genInitInstructions(l.list, false); if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) { initShadow.initIfaceInitializer(curr); initShadow.getRange().insert(inits, Range.OutsideBefore); } } // now we add our initialization code InstructionList inits = genInitInstructions(addedThisInitializers, false); enclosingShadow.getRange().insert(inits, Range.OutsideBefore); } // actually, you only need to inline the self constructors that are // in a particular group (partition the constructors into groups where members // call or are called only by those in the group). Then only inline // constructors // in groups where at least one initialization jp matched. Future work. boolean addedInitialization = match( BcelShadow.makeUnfinishedInitialization(world, mg), initializationShadows); addedInitialization |= match( BcelShadow.makeUnfinishedPreinitialization(world, mg), initializationShadows); mg.matchedShadows = shadowAccumulator; return addedInitialization || !shadowAccumulator.isEmpty(); } private boolean shouldWeaveBody(LazyMethodGen mg) { if (mg.isBridgeMethod()) return false; if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>"); AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature(); if (a != null) return a.isWeaveBody(); return true; } /** * first sorts the mungers, then gens the initializers in the right order */ private InstructionList genInitInstructions(List list, boolean isStatic) { list = PartialOrder.sort(list); if (list == null) { throw new BCException("circularity in inter-types"); } InstructionList ret = new InstructionList(); for (Iterator i = list.iterator(); i.hasNext();) { ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next(); NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger(); ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType()); if (!isStatic) ret.append(InstructionConstants.ALOAD_0); ret.append(Utility.createInvoke(fact, world, initMethod)); } return ret; } private void match( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { Instruction i = ih.getInstruction(); if ((i instanceof FieldInstruction) && (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) ) { FieldInstruction fi = (FieldInstruction) i; if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) { // check for sets of constant fields. We first check the previous // instruction. If the previous instruction is a LD_WHATEVER (push // constant on the stack) then we must resolve the field to determine // if it's final. If it is final, then we don't generate a shadow. InstructionHandle prevHandle = ih.getPrev(); Instruction prevI = prevHandle.getInstruction(); if (Utility.isConstantPushInstruction(prevI)) { Member field = BcelWorld.makeFieldJoinPointSignature(clazz, (FieldInstruction) i); ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. } else if (Modifier.isFinal(resolvedField.getModifiers())) { // it's final, so it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldGet)) matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else if (i instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction) i; if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) { if (canMatch(Shadow.ConstructorCall)) match( BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow), shadowAccumulator); } else if (ii instanceof INVOKESPECIAL) { String onTypeName = ii.getClassName(cpg); if (onTypeName.equals(mg.getEnclosingClass().getName())) { // we are private matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } else { // we are a super call, and this is not a join point in AspectJ-1.{0,1} } } else { matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } } // performance optimization... we only actually care about ASTORE instructions, // since that's what every javac type thing ever uses to start a handler, but for // now we'll do this for everybody. if (!canMatch(Shadow.ExceptionHandler)) return; if (Range.isRangeHandle(ih)) return; InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int j = 0; j < targeters.length; j++) { InstructionTargeter t = targeters[j]; if (t instanceof ExceptionRange) { // assert t.getHandler() == ih ExceptionRange er = (ExceptionRange) t; if (er.getCatchType() == null) continue; if (isInitFailureHandler(ih)) return; match( BcelShadow.makeExceptionHandler( world, er, mg, ih, enclosingShadow), shadowAccumulator); } } } } private boolean isInitFailureHandler(InstructionHandle ih) { // Skip the astore_0 and aload_0 at the start of the handler and // then check if the instruction following these is // 'putstatic ajc$initFailureCause'. If it is then we are // in the handler we created in AspectClinit.generatePostSyntheticCode() InstructionHandle twoInstructionsAway = ih.getNext().getNext(); if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) { String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg); if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true; } return false; } private void matchSetInstruction( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if ( Modifier.isFinal(resolvedField.getModifiers()) && Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) { // it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { match( BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow), shadowAccumulator); } } private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { BcelShadow bs = BcelShadow.makeFieldGet(world,resolvedField,mg,ih,enclosingShadow); String cname = fi.getClassName(cpg); if (!resolvedField.getDeclaringType().getName().equals(cname)) { bs.setActualTargetType(cname); } match(bs, shadowAccumulator); } } /** * For some named resolved type, this method looks for a member with a particular name - * it should only be used when you truly believe there is only one member with that * name in the type as it returns the first one it finds. */ private ResolvedMember findResolvedMemberNamed(ResolvedType type,String methodName) { ResolvedMember[] allMethods = type.getDeclaredMethods(); for (int i = 0; i < allMethods.length; i++) { ResolvedMember member = allMethods[i]; if (member.getName().equals(methodName)) return member; } return null; } /** * For a given resolvedmember, this will discover the real annotations for it. * <b>Should only be used when the resolvedmember is the contents of an effective signature * attribute, as thats the only time when the annotations aren't stored directly in the * resolvedMember</b> * @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing * @param declaredSig the real sig 'blah.ajc$xxx' */ private void fixAnnotationsForResolvedMember(ResolvedMember rm,ResolvedMember declaredSig) { try { UnresolvedType memberHostType = declaredSig.getDeclaringType(); ResolvedType[] annotations = (ResolvedType[])mapToAnnotations.get(rm); String methodName = declaredSig.getName(); // FIXME asc shouldnt really rely on string names ! if (annotations == null) { if (rm.getKind()==Member.FIELD) { if (methodName.startsWith("ajc$inlineAccessField")) { ResolvedMember resolvedDooberry = world.resolve(rm); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interFieldInitializer(rm,memberHostType); ResolvedMember resolvedDooberry = world.resolve(realthing); annotations = resolvedDooberry.getAnnotationTypes(); } } else if (rm.getKind()==Member.METHOD && !rm.isAbstract()) { if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) { ResolvedMember resolvedDooberry = world.resolve(declaredSig); annotations = resolvedDooberry.getAnnotationTypes(); } else { ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world),memberHostType).resolve(world); // ResolvedMember resolvedDooberry = world.resolve(realthing); ResolvedMember theRealMember = findResolvedMemberNamed(memberHostType.resolve(world),realthing.getName()); // AMC temp guard for M4 if (theRealMember == null) { throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified"); } annotations = theRealMember.getAnnotationTypes(); } } else if (rm.getKind()==Member.CONSTRUCTOR) { ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(),rm.getParameterTypes()); ResolvedMember resolvedDooberry = world.resolve(realThing); // AMC temp guard for M4 if (resolvedDooberry == null) { throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified"); } annotations = resolvedDooberry.getAnnotationTypes(); } if (annotations == null) annotations = new ResolvedType[0]; mapToAnnotations.put(rm,annotations); } rm.setAnnotationTypes(annotations); } catch (UnsupportedOperationException ex) { throw ex; } catch (Throwable t) { //FIXME asc remove this catch after more testing has confirmed the above stuff is OK throw new BCException("Unexpectedly went bang when searching for annotations on "+rm,t); } } private void matchInvokeInstruction(LazyMethodGen mg, InstructionHandle ih, InvokeInstruction invoke, BcelShadow enclosingShadow, List shadowAccumulator) { String methodName = invoke.getName(cpg); if (methodName.startsWith(NameMangler.PREFIX)) { Member jpSig = world.makeJoinPointSignatureForMethodInvocation(clazz, invoke); ResolvedMember declaredSig = jpSig.resolve(world); //System.err.println(method + ", declaredSig: " +declaredSig); if (declaredSig == null) return; if (declaredSig.getKind() == Member.FIELD) { Shadow.Kind kind; if (jpSig.getReturnType().equals(ResolvedType.VOID)) { kind = Shadow.FieldSet; } else { kind = Shadow.FieldGet; } if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, kind, declaredSig), shadowAccumulator); } else { AjAttribute.EffectiveSignatureAttribute effectiveSig = declaredSig.getEffectiveSignature(); if (effectiveSig == null) return; //System.err.println("call to inter-type member: " + effectiveSig); if (effectiveSig.isWeaveBody()) return; ResolvedMember rm = effectiveSig.getEffectiveSignature(); fixAnnotationsForResolvedMember(rm,declaredSig); // abracadabra if (canMatch(effectiveSig.getShadowKind())) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, effectiveSig.getShadowKind(), rm), shadowAccumulator); } } else { if (canMatch(Shadow.MethodCall)) match( BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow), shadowAccumulator); } } private boolean match(BcelShadow shadow, List shadowAccumulator) { //System.err.println("match: " + shadow); ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_SHADOW, shadow); boolean isMatched = false; for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) { ShadowMunger munger = (ShadowMunger)i.next(); ContextToken mungerMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_POINTCUT, munger.getPointcut()); if (munger.match(shadow, world)) { WeaverMetrics.recordMatchResult(true);// Could pass: munger shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation()); } } else { WeaverMetrics.recordMatchResult(false); // Could pass: munger } CompilationAndWeavingContext.leavingPhase(mungerMatchToken); } if (isMatched) shadowAccumulator.add(shadow); CompilationAndWeavingContext.leavingPhase(shadowMatchToken); return isMatched; } // ---- private void implement(LazyMethodGen mg) { List shadows = mg.matchedShadows; if (shadows == null) return; // We depend on a partial order such that inner shadows are earlier on the list // than outer shadows. That's fine. This order is preserved if: // A preceeds B iff B.getStart() is LATER THAN A.getStart(). for (Iterator i = shadows.iterator(); i.hasNext(); ) { BcelShadow shadow = (BcelShadow)i.next(); ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.IMPLEMENTING_ON_SHADOW,shadow); shadow.implement(); CompilationAndWeavingContext.leavingPhase(tok); } int ii = mg.getMaxLocals(); mg.matchedShadows = null; } // ---- public LazyClassGen getLazyClassGen() { return clazz; } public List getShadowMungers() { return shadowMungers; } public BcelWorld getWorld() { return world; } // Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info public static void setReweavableMode(boolean mode) { inReweavableMode = mode; } public static boolean getReweavableMode() { return inReweavableMode; } }
113,861
Bug 113861 [generics] field-get problems when generic field is used.
Hi, When i'm compiling the following example, i'm getting this errors: TestAspect.aj:21 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Test.java:18 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Here is the example ------------------- Java Code: package com; public class Test { Set<Integer> intsSet; public Set<Integer> foo() { 18: return intsSet; } } Aspect: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set<Integer> com.*.*) && !within(TestAspect); 21: Set<Integer> around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } I've tried many kinds of workarounds, and the only thing which worked, is defining the member field without using generics (regular Set) ... One more disturbing is, that this fiture worked(!) in M2 release. This is an example of the functionality that worked in my project (with M2), but now, also reports the same error: Java code is the same, Aspect is: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set com.*.*) && !within(TestAspect); Set around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } Is it a bug? Or am i doing something wrong? Thanks! Misha.
resolved fixed
8cea30f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T18:01:54Z
2005-10-26T18:06:40Z
tests/bugs150/pr113861/Test.java
113,861
Bug 113861 [generics] field-get problems when generic field is used.
Hi, When i'm compiling the following example, i'm getting this errors: TestAspect.aj:21 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Test.java:18 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Here is the example ------------------- Java Code: package com; public class Test { Set<Integer> intsSet; public Set<Integer> foo() { 18: return intsSet; } } Aspect: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set<Integer> com.*.*) && !within(TestAspect); 21: Set<Integer> around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } I've tried many kinds of workarounds, and the only thing which worked, is defining the member field without using generics (regular Set) ... One more disturbing is, that this fiture worked(!) in M2 release. This is an example of the functionality that worked in my project (with M2), but now, also reports the same error: Java code is the same, Aspect is: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set com.*.*) && !within(TestAspect); Set around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } Is it a bug? Or am i doing something wrong? Thanks! Misha.
resolved fixed
8cea30f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T18:01:54Z
2005-10-26T18:06:40Z
tests/bugs150/pr113861/TestAspect.java
113,861
Bug 113861 [generics] field-get problems when generic field is used.
Hi, When i'm compiling the following example, i'm getting this errors: TestAspect.aj:21 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Test.java:18 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Here is the example ------------------- Java Code: package com; public class Test { Set<Integer> intsSet; public Set<Integer> foo() { 18: return intsSet; } } Aspect: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set<Integer> com.*.*) && !within(TestAspect); 21: Set<Integer> around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } I've tried many kinds of workarounds, and the only thing which worked, is defining the member field without using generics (regular Set) ... One more disturbing is, that this fiture worked(!) in M2 release. This is an example of the functionality that worked in my project (with M2), but now, also reports the same error: Java code is the same, Aspect is: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set com.*.*) && !within(TestAspect); Set around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } Is it a bug? Or am i doing something wrong? Thanks! Misha.
resolved fixed
8cea30f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T18:01:54Z
2005-10-26T18:06:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.internal.Relationship; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } /* public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");} public void testMissingAccessor_pr73856() { runTest("missing accessor");} public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");} public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");} public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");} public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");} */ public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");} public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");} public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");} public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");} public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");} public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");} public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");} public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");} public void testVarargsITD_pr110906() { runTest("ITD varargs problem");} public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");} public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");} public void testDeclareAnnotationOnNonExistentType_pr99191_1() { runTest("declare annotation on non existent type - 1");} public void testDeclareAnnotationOnNonExistentType_pr99191_2() { runTest("declare annotation on non existent type - 2");} public void testDeclareAnnotationOnNonExistentType_pr99191_3() { runTest("declare annotation on non existent type - 3");} public void testDeclareAnnotationOnNonExistentType_pr99191_4() { runTest("declare annotation on non existent type - 4");} public void testDeclareAnnotationOnNonExistentType_pr99191_5() { runTest("declare annotation on non existent type - 5");} public void testBadGenericSigAttribute_pr110927() { runTest("cant create signature attribute"); Signature sig = GenericsTests.getClassSignature(ajc,"I"); if (sig==null) fail("Couldn't find signature attribute for type I"); String sigString = sig.getSignature(); if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") || sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) { fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"); } } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");} public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } // IfPointcut.findResidueInternal() was modified to make this test complete in a short amount // of time - if you see it hanging, someone has messed with the optimization. public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");} public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testAtAnnotationBadTest_pr103740() { runTest("Compiler failure on at_annotation"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } public void testNoVerifyErrorOnGenericCollectionMemberAccess() { runTest("no verify error on generic collection member access"); } public void testRawAndGenericTypeConversionITDCons() { runTest("raw and generic type conversion with itd cons"); } public void testAtAnnotationBindingWithAround() { runTest("@annotation binding with around advice"); } public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");} public void testMessageOnMissingTypeInDecP() { runTest("declare parents on a missing type"); } public void testParameterizedGenericMethods() { runTest("parameterized generic methods"); } public void testIllegalChangeToPointcutDeclaration_pr111915() { runTest("test illegal change to pointcut declaration"); } public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");} public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");} public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");} public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");} public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");} // Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats // where we can police whether a type variable has been used without being specified appropriately. //public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");} public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");} public void testCallJoinPointsInAnonymousInnerClasses() { runTest("call join points in anonymous inner classes"); } public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() { runTest("default impl of Runnable"); } public void testArrayCloneCallJoinPoints() { runTest("array clone call join points in 1.4 vs 1.3"); } public void testDebugInfoForAroundAdvice() { runTest("debug info in around advice inlining"); } public void testCCEWithGenericWildcard_pr112602() { runTest("ClassCastException with generic wildcard"); } public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the run() method inside anonymous inner class is in // the structure model IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"run()"); assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'run()' but is " + target.toLabelString(),"run()",target.toLabelString()); } public void testAdviceInStructureModelWithNamedInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with named inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the m() method inside named inner class is in // the structure model IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"m()"); assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'm()' but is " + target.toLabelString(),"m()",target.toLabelString()); } public void testDWInStructureModelWithAnonymousInnerClass_pr77269() { // AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("declare warning in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())"); assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe); } public void testVarArgsIITDInConstructor() { runTest("ITD varargs in constructor"); } public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() { runTest("weaveinfo message for declare at method on an ITDd method"); } public void testNoVerifyErrorWithTwoThisPCDs_pr113447() { runTest("no verify error with two this pcds"); } // helper methods..... public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
113,861
Bug 113861 [generics] field-get problems when generic field is used.
Hi, When i'm compiling the following example, i'm getting this errors: TestAspect.aj:21 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Test.java:18 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Here is the example ------------------- Java Code: package com; public class Test { Set<Integer> intsSet; public Set<Integer> foo() { 18: return intsSet; } } Aspect: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set<Integer> com.*.*) && !within(TestAspect); 21: Set<Integer> around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } I've tried many kinds of workarounds, and the only thing which worked, is defining the member field without using generics (regular Set) ... One more disturbing is, that this fiture worked(!) in M2 release. This is an example of the functionality that worked in my project (with M2), but now, also reports the same error: Java code is the same, Aspect is: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set com.*.*) && !within(TestAspect); Set around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } Is it a bug? Or am i doing something wrong? Thanks! Misha.
resolved fixed
8cea30f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T18:01:54Z
2005-10-26T18:06:40Z
weaver/src/org/aspectj/weaver/Advice.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.Collections; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.bcel.Utility; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.TypePattern; public abstract class Advice extends ShadowMunger { protected AjAttribute.AdviceAttribute attribute; // the pointcut field is ignored protected AdviceKind kind; // alias of attribute.getKind() protected Member signature; // not necessarily declaring aspect, this is a semantics change from 1.0 protected ResolvedType concreteAspect; // null until after concretize protected List innerCflowEntries = Collections.EMPTY_LIST; // just for cflow*Entry kinds protected int nFreeVars; // just for cflow*Entry kinds protected TypePattern exceptionType; // just for Softener kind // if we are parameterized, these type may be different to the advice signature types protected UnresolvedType[] bindingParameterTypes; protected List/*Lint.Kind*/ suppressedLintKinds = null; // based on annotations on this advice public static Advice makeCflowEntry(World world, Pointcut entry, boolean isBelow, Member stackField, int nFreeVars, List innerCflowEntries, ResolvedType inAspect){ Advice ret = world.createAdviceMunger(isBelow ? AdviceKind.CflowBelowEntry : AdviceKind.CflowEntry, entry, stackField, 0, entry); //0); ret.innerCflowEntries = innerCflowEntries; ret.nFreeVars = nFreeVars; ret.concreteAspect = inAspect; return ret; } public static Advice makePerCflowEntry(World world, Pointcut entry, boolean isBelow, Member stackField, ResolvedType inAspect, List innerCflowEntries) { Advice ret = world.createAdviceMunger(isBelow ? AdviceKind.PerCflowBelowEntry : AdviceKind.PerCflowEntry, entry, stackField, 0, entry); ret.innerCflowEntries = innerCflowEntries; ret.concreteAspect = inAspect; return ret; } public static Advice makePerObjectEntry(World world, Pointcut entry, boolean isThis, ResolvedType inAspect) { Advice ret = world.createAdviceMunger(isThis ? AdviceKind.PerThisEntry : AdviceKind.PerTargetEntry, entry, null, 0, entry); ret.concreteAspect = inAspect; return ret; } // PTWIMPL per type within entry advice is what initializes the aspect instance in the matched type public static Advice makePerTypeWithinEntry(World world, Pointcut p, ResolvedType inAspect) { Advice ret = world.createAdviceMunger(AdviceKind.PerTypeWithinEntry,p,null,0,p); ret.concreteAspect = inAspect; return ret; } public static Advice makeSoftener(World world, Pointcut entry, TypePattern exceptionType,ResolvedType inAspect,IHasSourceLocation loc) { Advice ret = world.createAdviceMunger(AdviceKind.Softener, entry, null, 0, loc); ret.exceptionType = exceptionType; ret.concreteAspect = inAspect; // System.out.println("made ret: " + ret + " with " + exceptionType); return ret; } public Advice(AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature) { super(pointcut, attribute.getStart(), attribute.getEnd(), attribute.getSourceContext()); this.attribute = attribute; this.kind = attribute.getKind(); // alias this.signature = signature; if (signature != null) { this.bindingParameterTypes = signature.getParameterTypes(); } else { this.bindingParameterTypes = new UnresolvedType[0]; } } public boolean match(Shadow shadow, World world) { if (super.match(shadow, world)) { if (shadow.getKind() == Shadow.ExceptionHandler) { if (kind.isAfter() || kind == AdviceKind.Around) { world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.ONLY_BEFORE_ON_HANDLER), getSourceLocation(), shadow.getSourceLocation()); return false; } } if (hasExtraParameter() && kind == AdviceKind.AfterReturning) { ResolvedType resolvedExtraParameterType = getExtraParameterType().resolve(world); ResolvedType shadowReturnType = shadow.getReturnType().resolve(world); boolean matches = resolvedExtraParameterType.isConvertableFrom(shadowReturnType); if (matches && resolvedExtraParameterType.isParameterizedType()) { maybeIssueUncheckedMatchWarning(resolvedExtraParameterType,shadowReturnType,shadow,world); } return matches; } else if (kind == AdviceKind.PerTargetEntry) { return shadow.hasTarget(); } else if (kind == AdviceKind.PerThisEntry) { return shadow.hasThis(); } else if (kind == AdviceKind.Around) { if (shadow.getKind() == Shadow.PreInitialization) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AROUND_ON_PREINIT), getSourceLocation(), shadow.getSourceLocation()); return false; } else if (shadow.getKind() == Shadow.Initialization) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AROUND_ON_INIT), getSourceLocation(), shadow.getSourceLocation()); return false; } else if (shadow.getKind() == Shadow.StaticInitialization && shadow.getEnclosingType().resolve(world).isInterface()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AROUND_ON_INTERFACE_STATICINIT,shadow.getEnclosingType().getName()), getSourceLocation(), shadow.getSourceLocation()); return false; } else { //System.err.println(getSignature().getReturnType() + " from " + shadow.getReturnType()); if (getSignature().getReturnType() == ResolvedType.VOID) { if (shadow.getReturnType() != ResolvedType.VOID) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NON_VOID_RETURN,shadow), getSourceLocation(), shadow.getSourceLocation()); return false; } } else if (getSignature().getReturnType().equals(UnresolvedType.OBJECT)) { return true; } else if(!shadow.getReturnType().resolve(world).isAssignableFrom(getSignature().getReturnType().resolve(world))) { //System.err.println(this + ", " + sourceContext + ", " + start); world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.INCOMPATIBLE_RETURN_TYPE,shadow), getSourceLocation(), shadow.getSourceLocation()); return false; } } } return true; } else { return false; } } /** * In after returning advice if we are binding the extra parameter to a parameterized * type we may not be able to do a type-safe conversion. * @param resolvedExtraParameterType the type in the after returning declaration * @param shadowReturnType the type at the shadow * @param world */ private void maybeIssueUncheckedMatchWarning(ResolvedType afterReturningType, ResolvedType shadowReturnType, Shadow shadow, World world) { boolean inDoubt = !afterReturningType.isAssignableFrom(shadowReturnType); if (inDoubt && world.getLint().uncheckedArgument.isEnabled()) { String uncheckedMatchWith = afterReturningType.getSimpleBaseName(); if (shadowReturnType.isParameterizedType() && (shadowReturnType.getRawType() == afterReturningType.getRawType())) { uncheckedMatchWith = shadowReturnType.getSimpleName(); } if (!Utility.isSuppressing(getSignature().getAnnotations(), "uncheckedArgument")) { world.getLint().uncheckedArgument.signal( new String[] { afterReturningType.getSimpleName(), uncheckedMatchWith, afterReturningType.getSimpleBaseName(), shadow.toResolvedString(world)}, getSourceLocation(), new ISourceLocation[] {shadow.getSourceLocation()}); } } } // ---- public AdviceKind getKind() { return kind; } public Member getSignature() { return signature; } // only called as part of parameterization.... public void setSignature(Member signature) { this.signature = signature; } public boolean hasExtraParameter() { return (getExtraParameterFlags() & ExtraArgument) != 0; } protected int getExtraParameterFlags() { return attribute.getExtraParameterFlags(); } protected int getExtraParameterCount() { return countOnes(getExtraParameterFlags() & ParameterMask); } public UnresolvedType[] getBindingParameterTypes() { return this.bindingParameterTypes; } public void setBindingParameterTypes(UnresolvedType[] types) { this.bindingParameterTypes = types; } public static int countOnes(int bits) { int ret = 0; while (bits != 0) { if ((bits & 1) != 0) ret += 1; bits = bits >> 1; } return ret; } public int getBaseParameterCount() { return getSignature().getParameterTypes().length - getExtraParameterCount(); } public String[] getBaseParameterNames(World world) { String[] allNames = getSignature().getParameterNames(world); int extras = getExtraParameterCount(); if (extras == 0) return allNames; String[] result = new String[getBaseParameterCount()]; for (int i = 0; i < result.length; i++) { result[i] = allNames[i]; } return result; } public UnresolvedType getExtraParameterType() { if (!hasExtraParameter()) return ResolvedType.MISSING; if (signature instanceof ResolvedMember) { return ((ResolvedMember)signature).getGenericParameterTypes()[getBaseParameterCount()]; } else { return signature.getParameterTypes()[getBaseParameterCount()]; } } public UnresolvedType getDeclaringAspect() { return signature.getDeclaringType(); } protected String extraParametersToString() { if (getExtraParameterFlags() == 0) { return ""; } else { return "(extraFlags: " + getExtraParameterFlags() + ")"; } } public Pointcut getPointcut() { return pointcut; } // ---- /** @param fromType is guaranteed to be a non-abstract aspect * @param clause has been concretized at a higher level */ public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) { // assert !fromType.isAbstract(); Pointcut p = pointcut.concretize(fromType, getDeclaringType(), signature.getArity(), this); if (clause != null) { Pointcut oldP = p; p = new AndPointcut(clause, p); p.copyLocationFrom(oldP); p.state = Pointcut.CONCRETE; //FIXME ? ATAJ copy unbound bindings to ignore p.m_ignoreUnboundBindingForNames =oldP.m_ignoreUnboundBindingForNames; } Advice munger = world.createAdviceMunger(attribute, p, signature); munger.concreteAspect = fromType; munger.bindingParameterTypes = this.bindingParameterTypes; //System.err.println("concretizing here " + p + " with clause " + clause); return munger; } // ---- from object public String toString() { StringBuffer sb = new StringBuffer(); sb.append("(").append(getKind()).append(extraParametersToString()); sb.append(": ").append(pointcut).append("->").append(signature).append(")"); return sb.toString(); // return "(" // + getKind() // + extraParametersToString() // + ": " // + pointcut // + "->" // + signature // + ")"; } public boolean equals(Object other) { if (! (other instanceof Advice)) return false; Advice o = (Advice) other; return o.attribute.equals(attribute) && o.pointcut.equals(pointcut) && o.signature.equals(signature); } private volatile int hashCode = 0; public int hashCode() { if (hashCode == 0) { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + pointcut.hashCode(); if (signature != null) result = 37*result + signature.hashCode(); hashCode = result; } return hashCode; } // ---- fields public static final int ExtraArgument = 1; public static final int ThisJoinPoint = 2; public static final int ThisJoinPointStaticPart = 4; public static final int ThisEnclosingJoinPointStaticPart = 8; public static final int ParameterMask = 0xf; public static final int CanInline = 0x40; // for testing only public void setLexicalPosition(int lexicalPosition) { start = lexicalPosition; } public ResolvedType getConcreteAspect() { return concreteAspect; } }
113,861
Bug 113861 [generics] field-get problems when generic field is used.
Hi, When i'm compiling the following example, i'm getting this errors: TestAspect.aj:21 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Test.java:18 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Here is the example ------------------- Java Code: package com; public class Test { Set<Integer> intsSet; public Set<Integer> foo() { 18: return intsSet; } } Aspect: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set<Integer> com.*.*) && !within(TestAspect); 21: Set<Integer> around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } I've tried many kinds of workarounds, and the only thing which worked, is defining the member field without using generics (regular Set) ... One more disturbing is, that this fiture worked(!) in M2 release. This is an example of the functionality that worked in my project (with M2), but now, also reports the same error: Java code is the same, Aspect is: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set com.*.*) && !within(TestAspect); Set around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } Is it a bug? Or am i doing something wrong? Thanks! Misha.
resolved fixed
8cea30f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T18:01:54Z
2005-10-26T18:06:40Z
weaver/src/org/aspectj/weaver/Member.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * AMC extracted as interface * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import org.aspectj.util.TypeSafeEnum; public interface Member { public static class Kind extends TypeSafeEnum { public Kind(String name, int key) { super(name, key); } public static Kind read(DataInputStream s) throws IOException { int key = s.readByte(); switch(key) { case 1: return METHOD; case 2: return FIELD; case 3: return CONSTRUCTOR; case 4: return STATIC_INITIALIZATION; case 5: return POINTCUT; case 6: return ADVICE; case 7: return HANDLER; } throw new BCException("weird kind " + key); } } public static final Member[] NONE = new Member[0]; public static final Kind METHOD = new Kind("METHOD", 1); public static final Kind FIELD = new Kind("FIELD", 2); public static final Kind CONSTRUCTOR = new Kind("CONSTRUCTOR", 3); public static final Kind STATIC_INITIALIZATION = new Kind("STATIC_INITIALIZATION", 4); public static final Kind POINTCUT = new Kind("POINTCUT", 5); public static final Kind ADVICE = new Kind("ADVICE", 6); public static final Kind HANDLER = new Kind("HANDLER", 7); public ResolvedMember resolve(World world); public int compareTo(Object other); public String toLongString(); public Kind getKind(); public UnresolvedType getDeclaringType(); public UnresolvedType getReturnType(); public UnresolvedType getType(); public String getName(); public UnresolvedType[] getParameterTypes(); /** * Return full signature, including return type, e.g. "()LFastCar;" for a signature without the return type, * use getParameterSignature() - it is importnant to choose the right one in the face of covariance. */ public String getSignature(); /** * All the signatures that a join point with this member as its signature has. */ public Iterator getJoinPointSignatures(World world); /** TODO ASC Should return the non-erased version of the signature... untested */ public String getDeclaredSignature(); public int getArity(); /** * Return signature without return type, e.g. "()" for a signature *with* the return type, * use getSignature() - it is important to choose the right one in the face of covariance. */ public String getParameterSignature(); public boolean isCompatibleWith(Member am); public int getModifiers(World world); public int getModifiers(); public UnresolvedType[] getExceptions(World world); public boolean isProtected(World world); public boolean isStatic(World world); public boolean isStrict(World world); public boolean isStatic(); public boolean isInterface(); public boolean isPrivate(); /** * Returns true iff the member is generic (NOT parameterized) * For example, a method declared in a generic type */ public boolean canBeParameterized(); public int getCallsiteModifiers(); public String getExtractableName(); /** * If you want a sensible answer, resolve the member and call * hasAnnotation() on the ResolvedMember. */ public boolean hasAnnotation(UnresolvedType ofType); /* (non-Javadoc) * @see org.aspectj.weaver.AnnotatedElement#getAnnotationTypes() */ public ResolvedType[] getAnnotationTypes(); public AnnotationX[] getAnnotations(); public Collection/*ResolvedType*/getDeclaringTypes(World world); // ---- reflective thisJoinPoint stuff public String getSignatureMakerName(); public String getSignatureType(); public String getSignatureString(World world); public String[] getParameterNames(World world); }
113,861
Bug 113861 [generics] field-get problems when generic field is used.
Hi, When i'm compiling the following example, i'm getting this errors: TestAspect.aj:21 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Test.java:18 [error] incompatible return type applying to field-get (java.util.Set com.mprv.secsph.Test.intsSet) Here is the example ------------------- Java Code: package com; public class Test { Set<Integer> intsSet; public Set<Integer> foo() { 18: return intsSet; } } Aspect: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set<Integer> com.*.*) && !within(TestAspect); 21: Set<Integer> around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } I've tried many kinds of workarounds, and the only thing which worked, is defining the member field without using generics (regular Set) ... One more disturbing is, that this fiture worked(!) in M2 release. This is an example of the functionality that worked in my project (with M2), but now, also reports the same error: Java code is the same, Aspect is: public privileged aspect TestAspect { pointcut gettingMember(Test t) : target(t) && get(!public Set com.*.*) && !within(TestAspect); Set around(Test t) : gettingMemberCollection(t) { Set s = proceed(t); return s; } } Is it a bug? Or am i doing something wrong? Thanks! Misha.
resolved fixed
8cea30f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-27T18:01:54Z
2005-10-26T18:06:40Z
weaver/src/org/aspectj/weaver/MemberImpl.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; public class MemberImpl implements Comparable, AnnotatedElement,Member { protected Kind kind; protected UnresolvedType declaringType; protected int modifiers; protected UnresolvedType returnType; protected String name; protected UnresolvedType[] parameterTypes; private final String signature; private final String declaredSignature; // TODO asc Is this redundant? Is it needed for generics? private String paramSignature; /** * All the signatures that a join point with this member as its signature has. * The fact that this has to go on MemberImpl and not ResolvedMemberImpl says a lot about * how broken the Member/ResolvedMember distinction currently is. */ private JoinPointSignatureIterator joinPointSignatures = null; public MemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, String name, String signature) { this.kind = kind; this.declaringType = declaringType; this.modifiers = modifiers; this.name = name; this.signature = signature; this.declaredSignature = signature; if (kind == FIELD) { this.returnType = UnresolvedType.forSignature(signature); this.parameterTypes = UnresolvedType.NONE; } else { Object[] returnAndParams = signatureToTypes(signature,false); this.returnType = (UnresolvedType) returnAndParams[0]; this.parameterTypes = (UnresolvedType[]) returnAndParams[1]; signature = typesToSignature(returnType,parameterTypes,true); } } public MemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes) { super(); this.kind = kind; this.declaringType = declaringType; this.modifiers = modifiers; this.returnType = returnType; this.name = name; this.parameterTypes = parameterTypes; if (kind == FIELD) { this.signature = returnType.getErasureSignature(); this.declaredSignature = returnType.getSignature(); } else { this.signature = typesToSignature(returnType, parameterTypes,true); this.declaredSignature = typesToSignature(returnType,parameterTypes,false); } } /* (non-Javadoc) * @see org.aspectj.weaver.Member#resolve(org.aspectj.weaver.World) */ public ResolvedMember resolve(World world) { return world.resolve(this); } // ---- utility methods /** returns an Object[] pair of UnresolvedType, UnresolvedType[] representing return type, * argument types parsed from the JVM bytecode signature of a method. Yes, * this should actually return a nice statically-typed pair object, but we * don't have one of those. * * <blockquote><pre> * UnresolvedType.signatureToTypes("()[Z")[0].equals(Type.forSignature("[Z")) * UnresolvedType.signatureToTypes("(JJ)I")[1] * .equals(UnresolvedType.forSignatures(new String[] {"J", "J"})) * </pre></blockquote> * * @param signature the JVM bytecode method signature string we want to break apart * @return a pair of UnresolvedType, UnresolvedType[] representing the return types and parameter types. */ public static String typesToSignature(UnresolvedType returnType, UnresolvedType[] paramTypes, boolean useRawTypes) { StringBuffer buf = new StringBuffer(); buf.append("("); for (int i = 0, len = paramTypes.length; i < len; i++) { if (paramTypes[i].isParameterizedType() && useRawTypes) buf.append(paramTypes[i].getErasureSignature()); else if (paramTypes[i].isTypeVariableReference() && useRawTypes) buf.append(paramTypes[i].getErasureSignature()); else buf.append(paramTypes[i].getSignature()); } buf.append(")"); if (returnType.isParameterizedType() && useRawTypes) buf.append(returnType.getErasureSignature()); else if (returnType.isTypeVariableReference() && useRawTypes) buf.append(returnType.getErasureSignature()); else buf.append(returnType.getSignature()); return buf.toString(); } /** * Returns "(<signaturesOfParamTypes>,...)" - unlike the other typesToSignature * that also includes the return type, this one just deals with the parameter types. */ public static String typesToSignature(UnresolvedType[] paramTypes) { StringBuffer buf = new StringBuffer(); buf.append("("); for(int i=0;i<paramTypes.length;i++) { buf.append(paramTypes[i].getSignature()); } buf.append(")"); return buf.toString(); } /** * returns an Object[] pair of UnresolvedType, UnresolvedType[] representing return type, * argument types parsed from the JVM bytecode signature of a method. Yes, * this should actually return a nice statically-typed pair object, but we * don't have one of those. * * <blockquote><pre> * UnresolvedType.signatureToTypes("()[Z")[0].equals(Type.forSignature("[Z")) * UnresolvedType.signatureToTypes("(JJ)I")[1] * .equals(UnresolvedType.forSignatures(new String[] {"J", "J"})) * </pre></blockquote> * * @param signature the JVM bytecode method signature string we want to break apart * @return a pair of UnresolvedType, UnresolvedType[] representing the return types and parameter types. */ private static Object[] signatureToTypes(String sig,boolean keepParameterizationInfo) { List l = new ArrayList(); int i = 1; while (true) { char c = sig.charAt(i); if (c == ')') break; // break out when the hit the ')' int start = i; while (c == '[') c = sig.charAt(++i); if (c == 'L' || c == 'P') { int nextSemicolon = sig.indexOf(';',start); int firstAngly = sig.indexOf('<',start); if (firstAngly == -1 || firstAngly>nextSemicolon) { i = nextSemicolon + 1; l.add(UnresolvedType.forSignature(sig.substring(start, i))); } else { // generics generics generics // Have to skip to the *correct* ';' boolean endOfSigReached = false; int posn = firstAngly; int genericDepth=0; while (!endOfSigReached) { switch (sig.charAt(posn)) { case '<': genericDepth++;break; case '>': genericDepth--;break; case ';': if (genericDepth==0) endOfSigReached=true;break; default: } posn++; } // posn now points to the correct nextSemicolon :) i=posn; String toProcess = null; toProcess = sig.substring(start,i); UnresolvedType tx = UnresolvedType.forSignature(toProcess); l.add(tx); } } else if (c=='T') { // assumed 'reference' to a type variable, so just "Tname;" int nextSemicolon = sig.indexOf(';',start); String nextbit = sig.substring(start,nextSemicolon); l.add(UnresolvedType.forSignature(nextbit)); i=nextSemicolon+1; } else { i++; l.add(UnresolvedType.forSignature(sig.substring(start, i))); } } UnresolvedType[] paramTypes = (UnresolvedType[]) l.toArray(new UnresolvedType[l.size()]); UnresolvedType returnType = UnresolvedType.forSignature(sig.substring(i+1, sig.length())); return new Object[] { returnType, paramTypes }; } // ---- factory methods public static MemberImpl field(String declaring, int mods, String name, String signature) { return field(declaring, mods, UnresolvedType.forSignature(signature), name); } public static Member field(UnresolvedType declaring, int mods, String name, UnresolvedType type) { return new MemberImpl(FIELD, declaring, mods, type, name, UnresolvedType.NONE); } public static MemberImpl method(UnresolvedType declaring, int mods, String name, String signature) { Object[] pair = signatureToTypes(signature,false); return method(declaring, mods, (UnresolvedType) pair[0], name, (UnresolvedType[]) pair[1]); } public static Member pointcut(UnresolvedType declaring, String name, String signature) { Object[] pair = signatureToTypes(signature,false); return pointcut(declaring, 0, (UnresolvedType) pair[0], name, (UnresolvedType[]) pair[1]); } private static MemberImpl field(String declaring, int mods, UnresolvedType ty, String name) { return new MemberImpl( FIELD, UnresolvedType.forName(declaring), mods, ty, name, UnresolvedType.NONE); } public static MemberImpl method(UnresolvedType declTy, int mods, UnresolvedType rTy, String name, UnresolvedType[] paramTys) { return new MemberImpl( //??? this calls <clinit> a method name.equals("<init>") ? CONSTRUCTOR : METHOD, declTy, mods, rTy, name, paramTys); } private static Member pointcut(UnresolvedType declTy, int mods, UnresolvedType rTy, String name, UnresolvedType[] paramTys) { return new MemberImpl( POINTCUT, declTy, mods, rTy, name, paramTys); } public static ResolvedMemberImpl makeExceptionHandlerSignature(UnresolvedType inType, UnresolvedType catchType) { return new ResolvedMemberImpl( HANDLER, inType, Modifier.STATIC, "<catch>", "(" + catchType.getSignature() + ")V"); } // ---- parsing methods /** Takes a string in this form: * * <blockquote><pre> * static? TypeName TypeName.Id * </pre></blockquote> * Pretty much just for testing, and as such should perhaps be moved. */ public static MemberImpl fieldFromString(String str) { str = str.trim(); final int len = str.length(); int i = 0; int mods = 0; if (str.startsWith("static", i)) { mods = Modifier.STATIC; i += 6; while (Character.isWhitespace(str.charAt(i))) i++; } int start = i; while (! Character.isWhitespace(str.charAt(i))) i++; UnresolvedType retTy = UnresolvedType.forName(str.substring(start, i)); start = i; i = str.lastIndexOf('.'); UnresolvedType declaringTy = UnresolvedType.forName(str.substring(start, i).trim()); start = ++i; String name = str.substring(start, len).trim(); return new MemberImpl( FIELD, declaringTy, mods, retTy, name, UnresolvedType.NONE); } /** Takes a string in this form: * * <blockquote><pre> * (static|interface|private)? TypeName TypeName . Id ( TypeName , ...) * </pre></blockquote> * Pretty much just for testing, and as such should perhaps be moved. */ public static Member methodFromString(String str) { str = str.trim(); // final int len = str.length(); int i = 0; int mods = 0; if (str.startsWith("static", i)) { mods = Modifier.STATIC; i += 6; } else if (str.startsWith("interface", i)) { mods = Modifier.INTERFACE; i += 9; } else if (str.startsWith("private", i)) { mods = Modifier.PRIVATE; i += 7; } while (Character.isWhitespace(str.charAt(i))) i++; int start = i; while (! Character.isWhitespace(str.charAt(i))) i++; UnresolvedType returnTy = UnresolvedType.forName(str.substring(start, i)); start = i; i = str.indexOf('(', i); i = str.lastIndexOf('.', i); UnresolvedType declaringTy = UnresolvedType.forName(str.substring(start, i).trim()); start = ++i; i = str.indexOf('(', i); String name = str.substring(start, i).trim(); start = ++i; i = str.indexOf(')', i); String[] paramTypeNames = parseIds(str.substring(start, i).trim()); return method(declaringTy, mods, returnTy, name, UnresolvedType.forNames(paramTypeNames)); } private static String[] parseIds(String str) { if (str.length() == 0) return ZERO_STRINGS; List l = new ArrayList(); int start = 0; while (true) { int i = str.indexOf(',', start); if (i == -1) { l.add(str.substring(start).trim()); break; } l.add(str.substring(start, i).trim()); start = i+1; } return (String[]) l.toArray(new String[l.size()]); } private static final String[] ZERO_STRINGS = new String[0]; // ---- things we know without resolution public boolean equals(Object other) { if (! (other instanceof Member)) return false; Member o = (Member) other; return (kind == o.getKind() && name.equals(o.getName()) && signature.equals(o.getSignature()) && declaringType.equals(o.getDeclaringType())); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#compareTo(java.lang.Object) */ public int compareTo(Object other) { Member o = (Member) other; int i = getName().compareTo(o.getName()); if (i != 0) return i; return getSignature().compareTo(o.getSignature()); } /** * Equality is checked based on the underlying signature, so the hash code * of a member is based on its kind, name, signature, and declaring type. The * algorithm for this was taken from page 38 of effective java. */ private volatile int hashCode = 0; public int hashCode() { if (hashCode == 0) { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + name.hashCode(); result = 37*result + signature.hashCode(); result = 37*result + declaringType.hashCode(); hashCode = result; } return hashCode; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(returnType.getName()); buf.append(' '); buf.append(declaringType.getName()); buf.append('.'); buf.append(name); if (kind != FIELD) { buf.append("("); if (parameterTypes.length != 0) { buf.append(parameterTypes[0]); for (int i=1, len = parameterTypes.length; i < len; i++) { buf.append(", "); buf.append(parameterTypes[i].getName()); } } buf.append(")"); } return buf.toString(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#toLongString() */ public String toLongString() { StringBuffer buf = new StringBuffer(); buf.append(kind); buf.append(' '); if (modifiers != 0) { buf.append(Modifier.toString(modifiers)); buf.append(' '); } buf.append(toString()); buf.append(" <"); buf.append(signature); buf.append(" >"); return buf.toString(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getKind() */ public Kind getKind() { return kind; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getDeclaringType() */ public UnresolvedType getDeclaringType() { return declaringType; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getReturnType() */ public UnresolvedType getReturnType() { return returnType; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getType() */ public UnresolvedType getType() { return returnType; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getName() */ public String getName() { return name; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getParameterTypes() */ public UnresolvedType[] getParameterTypes() { return parameterTypes; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignature() */ public String getSignature() { return signature; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getDeclaredSignature() */ public String getDeclaredSignature() { return declaredSignature;} /* (non-Javadoc) * @see org.aspectj.weaver.Member#getArity() */ public int getArity() { return parameterTypes.length; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getParameterSignature() */ public String getParameterSignature() { if (paramSignature != null) return paramSignature; StringBuffer sb = new StringBuffer(); sb.append("("); for (int i = 0; i < parameterTypes.length; i++) { UnresolvedType tx = parameterTypes[i]; sb.append(tx.getSignature()); } sb.append(")"); paramSignature = sb.toString(); return paramSignature; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isCompatibleWith(org.aspectj.weaver.Member) */ public boolean isCompatibleWith(Member am) { if (kind != METHOD || am.getKind() != METHOD) return true; if (! name.equals(am.getName())) return true; if (! equalTypes(getParameterTypes(), am.getParameterTypes())) return true; return getReturnType().equals(am.getReturnType()); } private static boolean equalTypes(UnresolvedType[] a, UnresolvedType[] b) { int len = a.length; if (len != b.length) return false; for (int i = 0; i < len; i++) { if (!a[i].equals(b[i])) return false; } return true; } // ---- things we know only with resolution /* (non-Javadoc) * @see org.aspectj.weaver.Member#getModifiers(org.aspectj.weaver.World) */ public int getModifiers(World world) { return resolve(world).getModifiers(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getExceptions(org.aspectj.weaver.World) */ public UnresolvedType[] getExceptions(World world) { return resolve(world).getExceptions(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isProtected(org.aspectj.weaver.World) */ public final boolean isProtected(World world) { return Modifier.isProtected(resolve(world).getModifiers()); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isStatic(org.aspectj.weaver.World) */ public final boolean isStatic(World world) { return Modifier.isStatic(resolve(world).getModifiers()); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isStrict(org.aspectj.weaver.World) */ public final boolean isStrict(World world) { return Modifier.isStrict(resolve(world).getModifiers()); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isStatic() */ public final boolean isStatic() { return Modifier.isStatic(modifiers); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isInterface() */ public final boolean isInterface() { return Modifier.isInterface(modifiers); // this is kinda weird } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isPrivate() */ public final boolean isPrivate() { return Modifier.isPrivate(modifiers); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#canBeParameterized() */ public boolean canBeParameterized() { return false; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getCallsiteModifiers() */ public final int getCallsiteModifiers() { return modifiers & ~ Modifier.INTERFACE; } public int getModifiers() { return modifiers; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getExtractableName() */ public final String getExtractableName() { if (name.equals("<init>")) return "init$"; else if (name.equals("<clinit>")) return "clinit$"; else return name; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#hasAnnotation(org.aspectj.weaver.UnresolvedType) */ public boolean hasAnnotation(UnresolvedType ofType) { throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result..."); } /* (non-Javadoc) * @see org.aspectj.weaver.AnnotatedElement#getAnnotationTypes() */ /* (non-Javadoc) * @see org.aspectj.weaver.Member#getAnnotationTypes() */ public ResolvedType[] getAnnotationTypes() { throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result..."); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getAnnotations() */ public AnnotationX[] getAnnotations() { throw new UnsupportedOperationException("You should resolve this member and call getAnnotations() on the result..."); } // ---- fields 'n' stuff /* (non-Javadoc) * @see org.aspectj.weaver.Member#getDeclaringTypes(org.aspectj.weaver.World) */ public Collection/*ResolvedType*/ getDeclaringTypes(World world) { ResolvedType myType = getDeclaringType().resolve(world); Collection ret = new HashSet(); if (kind == CONSTRUCTOR) { // this is wrong if the member doesn't exist, but that doesn't matter ret.add(myType); } else if (isStatic() || kind == FIELD) { walkUpStatic(ret, myType); } else { walkUp(ret, myType); } return ret; } private boolean walkUp(Collection acc, ResolvedType curr) { if (acc.contains(curr)) return true; boolean b = false; for (Iterator i = curr.getDirectSupertypes(); i.hasNext(); ) { b |= walkUp(acc, (ResolvedType)i.next()); } if (!b && curr.isParameterizedType()) { b = walkUp(acc,curr.getGenericType()); } if (!b) { b = curr.lookupMemberNoSupers(this) != null; } if (b) acc.add(curr); return b; } private boolean walkUpStatic(Collection acc, ResolvedType curr) { if (curr.lookupMemberNoSupers(this) != null) { acc.add(curr); return true; } else { boolean b = false; for (Iterator i = curr.getDirectSupertypes(); i.hasNext(); ) { b |= walkUpStatic(acc, (ResolvedType)i.next()); } if (!b && curr.isParameterizedType()) { b = walkUpStatic(acc,curr.getGenericType()); } if (b) acc.add(curr); return b; } } // ---- reflective thisJoinPoint stuff /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignatureMakerName() */ public String getSignatureMakerName() { if (getName().equals("<clinit>")) return "makeInitializerSig"; Kind kind = getKind(); if (kind == METHOD) { return "makeMethodSig"; } else if (kind == CONSTRUCTOR) { return "makeConstructorSig"; } else if (kind == FIELD) { return "makeFieldSig"; } else if (kind == HANDLER) { return "makeCatchClauseSig"; } else if (kind == STATIC_INITIALIZATION) { return "makeInitializerSig"; } else if (kind == ADVICE) { return "makeAdviceSig"; } else { throw new RuntimeException("unimplemented"); } } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignatureType() */ public String getSignatureType() { Kind kind = getKind(); if (getName().equals("<clinit>")) return "org.aspectj.lang.reflect.InitializerSignature"; if (kind == METHOD) { return "org.aspectj.lang.reflect.MethodSignature"; } else if (kind == CONSTRUCTOR) { return "org.aspectj.lang.reflect.ConstructorSignature"; } else if (kind == FIELD) { return "org.aspectj.lang.reflect.FieldSignature"; } else if (kind == HANDLER) { return "org.aspectj.lang.reflect.CatchClauseSignature"; } else if (kind == STATIC_INITIALIZATION) { return "org.aspectj.lang.reflect.InitializerSignature"; } else if (kind == ADVICE) { return "org.aspectj.lang.reflect.AdviceSignature"; } else { throw new RuntimeException("unimplemented"); } } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignatureString(org.aspectj.weaver.World) */ public String getSignatureString(World world) { if (getName().equals("<clinit>")) return getStaticInitializationSignatureString(world); Kind kind = getKind(); if (kind == METHOD) { return getMethodSignatureString(world); } else if (kind == CONSTRUCTOR) { return getConstructorSignatureString(world); } else if (kind == FIELD) { return getFieldSignatureString(world); } else if (kind == HANDLER) { return getHandlerSignatureString(world); } else if (kind == STATIC_INITIALIZATION) { return getStaticInitializationSignatureString(world); } else if (kind == ADVICE) { return getAdviceSignatureString(world); } else { throw new RuntimeException("unimplemented"); } } private String getHandlerSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(0)); buf.append('-'); //buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes()[0])); buf.append('-'); String pName = "<missing>"; String[] names = getParameterNames(world); if (names != null) pName = names[0]; buf.append(pName); buf.append('-'); return buf.toString(); } private String getStaticInitializationSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); //buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); return buf.toString(); } protected String getAdviceSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes())); buf.append('-'); buf.append(makeString(getParameterNames(world))); buf.append('-'); buf.append(makeString(getExceptions(world))); buf.append('-'); buf.append(makeString(getReturnType())); buf.append('-'); return buf.toString(); } protected String getMethodSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes())); buf.append('-'); buf.append(makeString(getParameterNames(world))); buf.append('-'); buf.append(makeString(getExceptions(world))); buf.append('-'); buf.append(makeString(getReturnType())); buf.append('-'); return buf.toString(); } protected String getConstructorSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes())); buf.append('-'); buf.append(makeString(getParameterNames(world))); buf.append('-'); buf.append(makeString(getExceptions(world))); buf.append('-'); return buf.toString(); } protected String getFieldSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getReturnType())); buf.append('-'); return buf.toString(); } protected String makeString(int i) { return Integer.toString(i, 16); //??? expensive } protected String makeString(UnresolvedType t) { // this is the inverse of the odd behavior for Class.forName w/ arrays if (t.isArray()) { // this behavior matches the string used by the eclipse compiler for Foo.class literals return t.getSignature().replace('/', '.'); } else { return t.getName(); } } protected String makeString(UnresolvedType[] types) { if (types == null) return ""; StringBuffer buf = new StringBuffer(); for (int i = 0, len=types.length; i < len; i++) { buf.append(makeString(types[i])); buf.append(':'); } return buf.toString(); } protected String makeString(String[] names) { if (names == null) return ""; StringBuffer buf = new StringBuffer(); for (int i = 0, len=names.length; i < len; i++) { buf.append(names[i]); buf.append(':'); } return buf.toString(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getParameterNames(org.aspectj.weaver.World) */ public String[] getParameterNames(World world) { return resolve(world).getParameterNames(); } /** * All the signatures that a join point with this member as its signature has. */ public Iterator getJoinPointSignatures(World inAWorld) { if (joinPointSignatures == null) { joinPointSignatures = new JoinPointSignatureIterator(this,inAWorld); } joinPointSignatures.reset(); return joinPointSignatures; } }
108,892
Bug 108892 Load Time Weaving problem with Aspect Definition at 2 Levels of Hierarchy
I am trying to weave into Tomcat with a system-level aspect (META-INF/aop.xml is found in a jar on the system classpath), and also have a Web application with an aop.xml properly deployed. When I try to run them both together, only the system-level aspects work. If I remove the system-level aspect jar from the classpath, the application-level aspects work. What would be a reasonable way to isolate this into a test case? If I could package up a simple system.jar and app.war file for Tomcat 5.5.9, would that be useful for you to use in debugging it? I tried making a simple standalone version with 2 aop.xml files in the same app classloader but that works just fine.
resolved fixed
794f9b5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-28T12:07:14Z
2005-09-07T02:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java
/* ******************************************************************* * Copyright (c) 2005 IBM Corporation Ltd * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import java.util.Stack; import java.util.ArrayList; import java.util.List; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope; import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.patterns.AbstractPatternNodeVisitor; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.Pointcut; public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { private static final char[] beforeAdviceSig = "Lorg/aspectj/lang/annotation/Before;".toCharArray(); private static final char[] afterAdviceSig = "Lorg/aspectj/lang/annotation/After;".toCharArray(); private static final char[] afterReturningAdviceSig = "Lorg/aspectj/lang/annotation/AfterReturning;".toCharArray(); private static final char[] afterThrowingAdviceSig = "Lorg/aspectj/lang/annotation/AfterThrowing;".toCharArray(); private static final char[] aroundAdviceSig = "Lorg/aspectj/lang/annotation/Around;".toCharArray(); 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[] adviceNameSig = "Lorg/aspectj/lang/annotation/AdviceName;".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 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) { typeStack.pop(); } 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) { 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) { typeStack.pop(); } private void checkTypeDeclaration(TypeDeclaration typeDecl) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, typeDecl.name); if (!(typeDecl instanceof AspectDeclaration)) { if (ajAnnotations.hasAspectAnnotation) { validateAspectDeclaration(typeDecl); } else { // check that class doesn't extend aspect TypeReference parentRef = typeDecl.superclass; if (parentRef != null) { TypeBinding parentBinding = parentRef.resolvedType; if (parentBinding instanceof SourceTypeBinding) { SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding; 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"); } } } } } } 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" ); } } CompilationAndWeavingContext.leavingPhase(tok); } public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { 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"); } } 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"); } } else { if (ajAnnotations.hasAspectJAnnotations()) { 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); } 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 insideAspect() { if (typeStack.empty()) return false; TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek(); return isAspect(typeDecl); } private boolean isAspect(TypeDeclaration typeDecl) { if (typeDecl instanceof AspectDeclaration) return true; return new AspectJAnnotations(typeDecl.annotations).hasAspectAnnotation; } /** * 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"); 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"); } } TypeReference parentRef = typeDecl.superclass; if (parentRef != null) { TypeBinding parentBinding = parentRef.resolvedType; if (parentBinding instanceof SourceTypeBinding) { SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding; 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"); } } } Annotation aspectAnnotation = ajAnnotations.aspectAnnotation; int[] pcLoc = new int[2]; String perClause = getStringLiteralFor("value", aspectAnnotation, pcLoc); AspectDeclaration aspectDecl = new AspectDeclaration(typeDecl.compilationResult); 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)); } } 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 */ private void validateAdvice(MethodDeclaration methodDeclaration) { if (!insideAspect()) { 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"); } if (ajAnnotations.hasMultipleAdviceAnnotations) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.duplicateAdviceAnnotation); } if (ajAnnotations.hasPointcutAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.pointcutAnnotation); } if (ajAnnotations.hasAspectAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation); } if (ajAnnotations.hasAdviceNameAnnotation) { 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); 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"); } } } if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) { int[] throwingLocation = new int[2]; 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"); } } } 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; } } 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); try { 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)); 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 ); 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()}); } } private void ensureVoidReturnType(MethodDeclaration methodDeclaration) { boolean returnsVoid = true; if ((methodDeclaration.returnType instanceof SingleTypeReference)) { SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType; if (!CharOperation.equals(voidType,retType.token)) { returnsVoid = false; } } else { returnsVoid = false; } if (!returnsVoid) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "This advice must return void"); } } private FormalBinding[] buildFormalAdviceBindingsFrom(MethodDeclaration mDecl) { if (mDecl.arguments == null) return new FormalBinding[0]; EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(mDecl.scope); String extraArgName = maybeGetExtraArgName(); 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); } else { 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]); } else if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) { argName = getStringLiteralFor("throwing",ajAnnotations.adviceAnnotation,new int[2]); } return argName; } private String getStringLiteralFor(String memberName, Annotation inAnnotation, int[] location) { if (inAnnotation instanceof SingleMemberAnnotation && memberName.equals("value")) { SingleMemberAnnotation sma = (SingleMemberAnnotation) inAnnotation; if (sma.memberValue instanceof StringLiteral) { StringLiteral sv = (StringLiteral) sma.memberValue; location[0] = sv.sourceStart; location[1] = sv.sourceEnd; return new String(sv.source()); } } if (! (inAnnotation instanceof NormalAnnotation)) return null; NormalAnnotation ann = (NormalAnnotation) inAnnotation; MemberValuePair[] mvps = ann.memberValuePairs; if (mvps == null) return null; for (int i = 0; i < mvps.length; i++) { if (CharOperation.equals(memberName.toCharArray(),mvps[i].name)) { if (mvps[i].value instanceof StringLiteral) { StringLiteral sv = (StringLiteral) mvps[i].value; location[0] = sv.sourceStart; location[1] = sv.sourceEnd; return new String(sv.source()); } } } 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"); } } if (methodDeclaration.thrownExceptions != null && methodDeclaration.thrownExceptions.length > 0) { methodDeclaration.scope.problemReporter() .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"pointcuts cannot throw exceptions!"); } PointcutDeclaration pcDecl = new PointcutDeclaration(unit.compilationResult); copyAllFields(methodDeclaration,pcDecl); if (ajAnnotations.hasAdviceAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceAnnotation); } if (ajAnnotations.hasAspectAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation); } if (ajAnnotations.hasAdviceNameAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation); } boolean containsIfPcd = false; int[] pcLocation = new int[2]; 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) { ;//will have to ensure abstract ()V method } else { 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; 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); 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()}); } 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 (!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"); } 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"); } 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) //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"); } } private void copyAllFields(MethodDeclaration from, MethodDeclaration to) { to.annotations = from.annotations; to.arguments = from.arguments; to.binding = from.binding; to.bits = from.bits; to.bodyEnd = from.bodyEnd; to.bodyStart = from.bodyStart; to.declarationSourceEnd = from.declarationSourceEnd; to.declarationSourceStart = from.declarationSourceStart; to.errorInSignature = from.errorInSignature; to.explicitDeclarations = from.explicitDeclarations; to.ignoreFurtherInvestigation = from.ignoreFurtherInvestigation; to.javadoc = from.javadoc; to.modifiers = from.modifiers; to.modifiersSourceStart = from.modifiersSourceStart; to.needFreeReturn = from.needFreeReturn; to.returnType = from.returnType; to.scope = from.scope; to.selector = from.selector; to.sourceEnd = from.sourceEnd; to.sourceStart = from.sourceStart; to.statements = from.statements; 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) { inType.methods[i] = forThatDeclaration; break; } } } private static class AspectJAnnotations { boolean hasAdviceAnnotation = false; boolean hasPointcutAnnotation = false; boolean hasAspectAnnotation = false; boolean hasAdviceNameAnnotation = false; boolean hasMultipleAdviceAnnotations = false; boolean hasMultiplePointcutAnnotations = false; boolean hasMultipleAspectAnnotations = false; AdviceKind adviceKind = null; Annotation adviceAnnotation = null; Annotation pointcutAnnotation = null; Annotation aspectAnnotation = null; Annotation adviceNameAnnotation = null; Annotation duplicateAdviceAnnotation = null; Annotation duplicatePointcutAnnotation = null; Annotation duplicateAspectAnnotation = null; public AspectJAnnotations(Annotation[] annotations) { if (annotations == null) return; for (int i = 0; i < annotations.length; i++) { if (annotations[i].resolvedType == null) continue; // user messed up annotation declaration char[] sig = annotations[i].resolvedType.signature(); if (CharOperation.equals(afterAdviceSig,sig)) { adviceKind = AdviceKind.After; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(afterReturningAdviceSig,sig)) { adviceKind = AdviceKind.AfterReturning; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(afterThrowingAdviceSig,sig)) { adviceKind = AdviceKind.AfterThrowing; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(beforeAdviceSig,sig)) { adviceKind = AdviceKind.Before; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(aroundAdviceSig,sig)) { adviceKind = AdviceKind.Around; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(adviceNameSig,sig)) { hasAdviceNameAnnotation = true; adviceNameAnnotation = annotations[i]; } else if (CharOperation.equals(aspectSig,sig)) { if (hasAspectAnnotation) { hasMultipleAspectAnnotations = true; duplicateAspectAnnotation = annotations[i]; } else { hasAspectAnnotation = true; aspectAnnotation = annotations[i]; } } else if (CharOperation.equals(pointcutSig,sig)) { if (hasPointcutAnnotation) { hasMultiplePointcutAnnotations = true; duplicatePointcutAnnotation = annotations[i]; } else { hasPointcutAnnotation = true; pointcutAnnotation = annotations[i]; } } } } public boolean hasAspectJAnnotations() { return hasAdviceAnnotation || hasPointcutAnnotation || hasAdviceNameAnnotation || hasAspectAnnotation; } private void addAdviceAnnotation(Annotation annotation) { if (!hasAdviceAnnotation) { hasAdviceAnnotation = true; adviceAnnotation = annotation; } else { hasMultipleAdviceAnnotations = true; duplicateAdviceAnnotation = annotation; } } } private static class HasIfPCDVisitor extends AbstractPatternNodeVisitor { public boolean containsIfPcd = false; public Object visit(IfPointcut node, Object data) { containsIfPcd = true; return data; } } }
108,892
Bug 108892 Load Time Weaving problem with Aspect Definition at 2 Levels of Hierarchy
I am trying to weave into Tomcat with a system-level aspect (META-INF/aop.xml is found in a jar on the system classpath), and also have a Web application with an aop.xml properly deployed. When I try to run them both together, only the system-level aspects work. If I remove the system-level aspect jar from the classpath, the application-level aspects work. What would be a reasonable way to isolate this into a test case? If I could package up a simple system.jar and app.war file for Tomcat 5.5.9, would that be useful for you to use in debugging it? I tried making a simple standalone version with 2 aop.xml files in the same app classloader but that works just fine.
resolved fixed
794f9b5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-28T12:07:14Z
2005-09-07T02:26:40Z
tests/java5/ataspectj/ataspectj/hierarchy/AppContainerTest.java
108,892
Bug 108892 Load Time Weaving problem with Aspect Definition at 2 Levels of Hierarchy
I am trying to weave into Tomcat with a system-level aspect (META-INF/aop.xml is found in a jar on the system classpath), and also have a Web application with an aop.xml properly deployed. When I try to run them both together, only the system-level aspects work. If I remove the system-level aspect jar from the classpath, the application-level aspects work. What would be a reasonable way to isolate this into a test case? If I could package up a simple system.jar and app.war file for Tomcat 5.5.9, would that be useful for you to use in debugging it? I tried making a simple standalone version with 2 aop.xml files in the same app classloader but that works just fine.
resolved fixed
794f9b5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-28T12:07:14Z
2005-09-07T02:26:40Z
tests/java5/ataspectj/ataspectj/hierarchy/app/SubApp.java
108,892
Bug 108892 Load Time Weaving problem with Aspect Definition at 2 Levels of Hierarchy
I am trying to weave into Tomcat with a system-level aspect (META-INF/aop.xml is found in a jar on the system classpath), and also have a Web application with an aop.xml properly deployed. When I try to run them both together, only the system-level aspects work. If I remove the system-level aspect jar from the classpath, the application-level aspects work. What would be a reasonable way to isolate this into a test case? If I could package up a simple system.jar and app.war file for Tomcat 5.5.9, would that be useful for you to use in debugging it? I tried making a simple standalone version with 2 aop.xml files in the same app classloader but that works just fine.
resolved fixed
794f9b5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-10-28T12:07:14Z
2005-09-07T02:26:40Z
tests/src/org/aspectj/systemtest/ajc150/ataspectj/AtAjLTWTests.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150.ataspectj; import org.aspectj.testing.XMLBasedAjcTestCase; import junit.framework.Test; import java.io.File; /** * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class AtAjLTWTests extends XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(org.aspectj.systemtest.ajc150.ataspectj.AtAjLTWTests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ataspectj/ltw.xml"); } public void testRunThemAllWithJavacCompiledAndLTW() { runTest("RunThemAllWithJavacCompiledAndLTW"); } public void testAjcLTWPerClauseTest_XnoWeave() { runTest("AjcLTW PerClauseTest -XnoWeave"); } public void testAjcLTWPerClauseTest_Xreweavable() { runTest("AjcLTW PerClauseTest -Xreweavable"); } public void testJavaCAjcLTWPerClauseTest() { runTest("JavaCAjcLTW PerClauseTest"); } public void testAjcLTWAroundInlineMungerTest_XnoWeave() { runTest("AjcLTW AroundInlineMungerTest -XnoWeave"); } public void testAjcLTWAroundInlineMungerTest_Xreweavable() { runTest("AjcLTW AroundInlineMungerTest"); } public void testAjcLTWAroundInlineMungerTest() { runTest("AjcLTW AroundInlineMungerTest"); } public void testAjcLTWAroundInlineMungerTest_XnoInline_Xreweavable() { runTest("AjcLTW AroundInlineMungerTest -XnoInline -Xreweavable"); } public void testAjcLTWAroundInlineMungerTest2() { runTest("AjcLTW AroundInlineMungerTest2"); } public void testLTWDump() { runTest("LTW DumpTest"); } public void testAjcAspect1LTWAspect2_Xreweavable() { runTest("Ajc Aspect1 LTW Aspect2 -Xreweavable"); } public void testLTWLog() { runTest("LTW Log"); } public void testLTWUnweavable() { // actually test that we do LTW proxy and jit classes runTest("LTW Unweavable"); } public void testLTWDecp() { runTest("LTW Decp"); } public void testLTWDecp2() { runTest("LTW Decp2"); } public void testCompileTimeAspectsDeclaredToLTWWeaver() { runTest("Compile time aspects declared to ltw weaver"); } public void testConcreteAtAspect() { runTest("Concrete@Aspect"); } public void testConcreteAspect() { runTest("ConcreteAspect"); } public void testConcretePrecedenceAspect() { runTest("ConcretePrecedenceAspect"); } public void testAspectOfWhenAspectNotInInclude() { runTest("AspectOfWhenAspectNotInInclude"); } }