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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; 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.lang.JoinPoint; import org.aspectj.lang.reflect.CodeSignature; 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; import org.aspectj.weaver.internal.tools.PointcutExpressionImpl; /** * 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; } public FuzzyBoolean fastMatch(Class targetType) { 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; } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart jpsp) { FuzzyBoolean ret = arguments.matches(jp.getArgs(),TypePattern.DYNAMIC); // this may have given a false match (e.g. args(int) may have matched a call to doIt(Integer x)) due to boxing // check for this... if (ret == FuzzyBoolean.YES) { // are the sigs compatible too... CodeSignature sig = (CodeSignature)jp.getSignature(); Class[] pTypes = sig.getParameterTypes(); ret = checkSignatureMatch(pTypes); } return ret; } /** * @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; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return (arguments.matches(args,TypePattern.DYNAMIC) == FuzzyBoolean.YES); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically(String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { Class[] paramTypes = new Class[0]; if (member instanceof Method) { paramTypes = ((Method)member).getParameterTypes(); } else if (member instanceof Constructor) { paramTypes = ((Constructor)member).getParameterTypes(); } else if (member instanceof PointcutExpressionImpl.Handler){ paramTypes = new Class[] {((PointcutExpressionImpl.Handler)member).getHandledExceptionType()}; } else if (member instanceof Field) { if (joinpointKind.equals(Shadow.FieldGet.getName())) return FuzzyBoolean.NO; // no args here paramTypes = new Class[] {((Field)member).getType()}; } else { return FuzzyBoolean.NO; } return arguments.matchesArgsPatternSubset(paramTypes); } 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 resolveBindingsFromRTTI() { arguments.resolveBindingsFromRTTI(true, true); if (arguments.ellipsisCount > 1) { throw new UnsupportedOperationException("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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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; } public FuzzyBoolean fastMatch(Class targetType) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { throw new UnsupportedOperationException("cflow pointcut matching not supported by this operation"); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, java.lang.reflect.Member member, Class thisClass, Class targetClass, java.lang.reflect.Member withinCode) { throw new UnsupportedOperationException("cflow pointcut matching not supported by this operation"); } 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 void resolveBindingsFromRTTI() { if (entry.state != RESOLVED) { entry.resolveBindingsFromRTTI(); } } 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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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; } public FuzzyBoolean fastMatch(Class targetType) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { throw new UnsupportedOperationException("cflow pointcut matching not supported by this operation"); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, java.lang.reflect.Member member, Class thisClass, Class targetClass, java.lang.reflect.Member withinCode) { throw new UnsupportedOperationException("cflow pointcut matching not supported by this operation"); } // 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 void resolveBindingsFromRTTI() { 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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
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 matchesExactly(Class matchType) { try { Class toMatchAgainst = getClassFor(type.getName()); return matchType == toMatchAgainst; } catch (ClassNotFoundException cnfEx) { return false; } } public FuzzyBoolean matchesInstanceof(Class matchType) { if (matchType.equals(Object.class)) return FuzzyBoolean.YES; try { String typeName = type.getName(); Class toMatchAgainst = getClassFor(typeName); FuzzyBoolean ret = FuzzyBoolean.fromBoolean(toMatchAgainst.isAssignableFrom(matchType)); if (ret == FuzzyBoolean.NO) { if (boxedTypesMap.containsKey(typeName)) { // try again with 'boxed' alternative toMatchAgainst = (Class) boxedTypesMap.get(typeName); ret = FuzzyBoolean.fromBoolean(toMatchAgainst.isAssignableFrom(matchType)); } } return ret; } catch (ClassNotFoundException cnfEx) { return FuzzyBoolean.NO; } } /** * Return YES if any subtype of the static type would match, * MAYBE if some subtypes could match * NO if there could never be a match * @param staticType * @return */ public FuzzyBoolean willMatchDynamically(Class staticType) { if (matchesExactly(staticType)) return FuzzyBoolean.YES; if (matchesInstanceof(staticType) == FuzzyBoolean.YES) return FuzzyBoolean.YES; try { String typeName = type.getName(); Class toMatchAgainst = getClassFor(typeName); if (toMatchAgainst.isInterface()) return FuzzyBoolean.MAYBE; if (staticType.isAssignableFrom(toMatchAgainst)) return FuzzyBoolean.MAYBE; return FuzzyBoolean.NO; } catch (ClassNotFoundException cnfEx) { return FuzzyBoolean.NO; } } private Class getClassFor(String typeName) throws ClassNotFoundException { Class ret = null; ret = (Class) primitiveTypesMap.get(typeName); if (ret == null) ret = Class.forName(typeName); return ret; } 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"); } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { throw new IllegalStateException("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); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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.lang.reflect.Member; import java.util.HashSet; import java.util.Set; import org.aspectj.bridge.MessageUtil; import org.aspectj.lang.JoinPoint; 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.internal.tools.PointcutExpressionImpl; /** * 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; } public FuzzyBoolean fastMatch(Class targetType) { 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 FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart jpsp) { if (!jp.getKind().equals(JoinPoint.EXCEPTION_HANDLER)) return FuzzyBoolean.NO; if (jp.getArgs().length > 0) { Object caughtException = jp.getArgs()[0]; return exceptionType.matches(caughtException,TypePattern.STATIC); } else { return FuzzyBoolean.NO; } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { if (args.length > 0) { return (exceptionType.matches(args[0],TypePattern.STATIC) == FuzzyBoolean.YES); } else return false; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically(String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { if (!(member instanceof PointcutExpressionImpl.Handler)) { return FuzzyBoolean.NO; } else { Class exceptionClass = ((PointcutExpressionImpl.Handler)member).getHandledExceptionType(); return exceptionType.matches(exceptionClass,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 } public void resolveBindingsFromRTTI() { exceptionType = exceptionType.resolveBindingsFromRTTI(false,false); } 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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/HasMemberTypePattern.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: * Adrian Colyer 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.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * @author colyer * Matches types that have a certain method / constructor / field * Currently only allowed within declare parents and declare @type */ public class HasMemberTypePattern extends TypePattern { private SignaturePattern signaturePattern; public HasMemberTypePattern(SignaturePattern aSignaturePattern) { super(false,false); this.signaturePattern = aSignaturePattern; } protected boolean matchesExactly(ResolvedType type) { if (signaturePattern.getKind() == Member.FIELD) { return hasField(type); } else { return hasMethod(type); } } private boolean hasField(ResolvedType type) { // TODO what about ITDs World world = type.getWorld(); for (Iterator iter = type.getFields(); iter.hasNext();) { Member field = (Member) iter.next(); if (signaturePattern.matches(field, type.getWorld(), false)) { if (field.getDeclaringType().resolve(world) != type) { if (Modifier.isPrivate(field.getModifiers())) continue; } return true; } } return false; } private boolean hasMethod(ResolvedType type) { // TODO what about ITDs World world = type.getWorld(); for (Iterator iter = type.getMethods(); iter.hasNext();) { Member method = (Member) iter.next(); if (signaturePattern.matches(method, type.getWorld(), false)) { if (method.getDeclaringType().resolve(world) != type) { if (Modifier.isPrivate(method.getModifiers())) continue; } return true; } } // try itds before we give up List mungers = type.getInterTypeMungersIncludingSupers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); Member member = munger.getSignature(); if (signaturePattern.matches(member, type.getWorld(), false)) { if (!Modifier.isPublic(member.getModifiers())) continue; return true; } } return false; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return matchesExactly(type); } public FuzzyBoolean matchesInstanceof(ResolvedType type) { throw new UnsupportedOperationException("hasmethod/field do not support instanceof matching"); } public FuzzyBoolean matchesInstanceof(Class toMatch) { return FuzzyBoolean.NO; } protected boolean matchesExactly(Class toMatch) { return false; } public TypePattern parameterizeWith(Map typeVariableMap) { HasMemberTypePattern ret = new HasMemberTypePattern(signaturePattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { // check that hasmember type patterns are allowed! if (!scope.getWorld().isHasMemberSupportEnabled()) { String msg = WeaverMessages.format(WeaverMessages.HAS_MEMBER_NOT_ENABLED,this.toString()); scope.message(IMessage.ERROR, this, msg); } return this; } public boolean equals(Object obj) { if (!(obj instanceof HasMemberTypePattern)) return false; if (this == obj) return true; return signaturePattern.equals(((HasMemberTypePattern)obj).signaturePattern); } public int hashCode() { return signaturePattern.hashCode(); } public String toString() { StringBuffer buff = new StringBuffer(); if (signaturePattern.getKind() == Member.FIELD) { buff.append("hasfield("); } else { buff.append("hasmethod("); } buff.append(signaturePattern.toString()); buff.append(")"); return buff.toString(); } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.HAS_MEMBER); signaturePattern.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { SignaturePattern sp = SignaturePattern.read(s, context); HasMemberTypePattern ret = new HasMemberTypePattern(sp); ret.readLocation(context,s); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/IfPointcut.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 if() implementation for @AJ style * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Member; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ast.Expr; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; public class IfPointcut extends Pointcut { public ResolvedMember testMethod; public int extraParameterFlags; /** * A token source dump that looks like a pointcut (but is NOT parseable at all - just here to help debugging etc) */ private String enclosingPointcutHint; public Pointcut residueSource; int baseArgsCount; //XXX some way to compute args public IfPointcut(ResolvedMember testMethod, int extraParameterFlags) { this.testMethod = testMethod; this.extraParameterFlags = extraParameterFlags; this.pointcutKind = IF; this.enclosingPointcutHint = null; } /** * No-arg constructor for @AJ style, where the if() body is actually the @Pointcut annotated method */ public IfPointcut(String enclosingPointcutHint) { this.pointcutKind = IF; this.enclosingPointcutHint = enclosingPointcutHint; this.testMethod = null;// resolved during concretize this.extraParameterFlags = -1;//allows to keep track of the @Aj style } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } public FuzzyBoolean fastMatch(Class targetType) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } public boolean alwaysFalse() { return false; } public boolean alwaysTrue() { return false; } // enh 76055 public Pointcut getResidueSource() { return residueSource; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { throw new UnsupportedOperationException("If pointcut matching not supported by this operation"); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { throw new UnsupportedOperationException("If pointcut matching not supported by this operation"); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.IF); s.writeBoolean(testMethod != null); // do we have a test method? if (testMethod != null) testMethod.write(s); s.writeByte(extraParameterFlags); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { boolean hasTestMethod = s.readBoolean(); ResolvedMember resolvedTestMethod = null; if (hasTestMethod) { // should always have a test method unless @AJ style resolvedTestMethod = ResolvedMemberImpl.readResolvedMember(s, context); } IfPointcut ret = new IfPointcut(resolvedTestMethod, s.readByte()); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { //??? all we need is good error messages in here in cflow contexts } public void resolveBindingsFromRTTI() {} public boolean equals(Object other) { if (!(other instanceof IfPointcut)) return false; IfPointcut o = (IfPointcut)other; return o.testMethod.equals(this.testMethod); } public int hashCode() { int result = 17; result = 37*result + testMethod.hashCode(); return result; } public String toString() { if (extraParameterFlags < 0) { //@AJ style return "if()"; } else { return "if(" + testMethod + ")";//FIXME AV - bad, this makes it unparsable. Perhaps we can use if() for code style behind the scene! } } //??? The implementation of name binding and type checking in if PCDs is very convoluted // There has to be a better way... private boolean findingResidue = false; // Similar to lastMatchedShadowId - but only for if PCDs. private int ifLastMatchedShadowId; private Test ifLastMatchedShadowResidue; /** * At each shadow that matched, the residue can be different. */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (findingResidue) return Literal.TRUE; findingResidue = true; try { // Have we already been asked this question? if (shadow.shadowId == ifLastMatchedShadowId) return ifLastMatchedShadowResidue; Test ret = Literal.TRUE; List args = new ArrayList(); // code style if (extraParameterFlags >= 0) { // If there are no args to sort out, don't bother with the recursive call if (baseArgsCount > 0) { ExposedState myState = new ExposedState(baseArgsCount); //??? we throw out the test that comes from this walk. All we want here // is bindings for the arguments residueSource.findResidue(shadow, myState); for (int i=0; i < baseArgsCount; i++) { Var v = myState.get(i); args.add(v); ret = Test.makeAnd(ret, Test.makeInstanceof(v, testMethod.getParameterTypes()[i].resolve(shadow.getIWorld()))); } } // handle thisJoinPoint parameters if ((extraParameterFlags & Advice.ThisJoinPoint) != 0) { args.add(shadow.getThisJoinPointVar()); } if ((extraParameterFlags & Advice.ThisJoinPointStaticPart) != 0) { args.add(shadow.getThisJoinPointStaticPartVar()); } if ((extraParameterFlags & Advice.ThisEnclosingJoinPointStaticPart) != 0) { args.add(shadow.getThisEnclosingJoinPointStaticPartVar()); } } else { // @style is slightly different int currentStateIndex = 0; //FIXME AV - "args(jp)" test(jp, thejp) will fail here for (int i = 0; i < testMethod.getParameterTypes().length; i++) { String argSignature = testMethod.getParameterTypes()[i].getSignature(); if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisJoinPointVar()); } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisJoinPointVar()); } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisJoinPointStaticPartVar()); } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argSignature)) { args.add(shadow.getThisEnclosingJoinPointStaticPartVar()); } else { // we don't use i as JoinPoint.* can be anywhere in the signature in @style Var v = state.get(currentStateIndex++); args.add(v); ret = Test.makeAnd(ret, Test.makeInstanceof(v, testMethod.getParameterTypes()[i].resolve(shadow.getIWorld()))); } } } ret = Test.makeAnd(ret, Test.makeCall(testMethod, (Expr[])args.toArray(new Expr[args.size()]))); // Remember... ifLastMatchedShadowId = shadow.shadowId; ifLastMatchedShadowResidue = ret; return ret; } finally { findingResidue = false; } } // amc - the only reason this override seems to be here is to stop the copy, but // that can be prevented by overriding shouldCopyLocationForConcretization, // allowing me to make the method final in Pointcut. // public Pointcut concretize(ResolvedType inAspect, IntMap bindings) { // return this.concretize1(inAspect, bindings); // } protected boolean shouldCopyLocationForConcretize() { return false; } private IfPointcut partiallyConcretized = null; public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { //System.err.println("concretize: " + this + " already: " + partiallyConcretized); if (isDeclare(bindings.getEnclosingAdvice())) { // Enforce rule about which designators are supported in declare inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (partiallyConcretized != null) { return partiallyConcretized; } final IfPointcut ret; if (extraParameterFlags < 0 && testMethod == null) { // @AJ style, we need to find the testMethod in the aspect defining the "if()" enclosing pointcut ResolvedPointcutDefinition def = bindings.peekEnclosingDefinitition(); if (def != null) { ResolvedType aspect = inAspect.getWorld().resolve(def.getDeclaringType()); for (Iterator memberIter = aspect.getMethods(); memberIter.hasNext();) { ResolvedMember method = (ResolvedMember) memberIter.next(); if (def.getName().equals(method.getName()) && def.getParameterTypes().length == method.getParameterTypes().length) { boolean sameSig = true; for (int j = 0; j < method.getParameterTypes().length; j++) { UnresolvedType argJ = method.getParameterTypes()[j]; if (!argJ.equals(def.getParameterTypes()[j])) { sameSig = false; break; } } if (sameSig) { testMethod = method; break; } } } if (testMethod == null) { inAspect.getWorld().showMessage( IMessage.ERROR, "Cannot find if() body from '" + def.toString() + "' for '" + enclosingPointcutHint + "'", this.getSourceLocation(), null ); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } } else { testMethod = inAspect.getWorld().resolve(bindings.getAdviceSignature()); } ret = new IfPointcut(enclosingPointcutHint); ret.testMethod = testMethod; } else { ret = new IfPointcut(testMethod, extraParameterFlags); } ret.copyLocationFrom(this); partiallyConcretized = ret; // It is possible to directly code your pointcut expression in a per clause // rather than defining a pointcut declaration and referencing it in your // per clause. If you do this, we have problems (bug #62458). For now, // let's police that you are trying to code a pointcut in a per clause and // put out a compiler error. if (bindings.directlyInAdvice() && bindings.getEnclosingAdvice()==null) { // Assumption: if() is in a per clause if we say we are directly in advice // but we have no enclosing advice. inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_IN_PERCLAUSE), this.getSourceLocation(),null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } if (bindings.directlyInAdvice()) { ShadowMunger advice = bindings.getEnclosingAdvice(); if (advice instanceof Advice) { ret.baseArgsCount = ((Advice)advice).getBaseParameterCount(); } else { ret.baseArgsCount = 0; } ret.residueSource = advice.getPointcut().concretize(inAspect, inAspect, ret.baseArgsCount, advice); } else { ResolvedPointcutDefinition def = bindings.peekEnclosingDefinitition(); if (def == CflowPointcut.CFLOW_MARKER) { inAspect.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.IF_LEXICALLY_IN_CFLOW), getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } ret.baseArgsCount = def.getParameterTypes().length; // for @style, we have implicit binding for JoinPoint.* things //FIXME AV - will lead to failure for "args(jp)" test(jp, thejp) / see args() implementation if (ret.extraParameterFlags < 0) { ret.baseArgsCount = 0; for (int i = 0; i < testMethod.getParameterTypes().length; i++) { String argSignature = testMethod.getParameterTypes()[i].getSignature(); if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argSignature) || AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argSignature) || AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argSignature) || AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argSignature)) { ; } else { ret.baseArgsCount++; } } } IntMap newBindings = IntMap.idMap(ret.baseArgsCount); newBindings.copyContext(bindings); ret.residueSource = def.getPointcut().concretize(inAspect, declaringType, newBindings); } return ret; } // we can't touch "if" methods 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 IfPointcut makeIfFalsePointcut(State state) { IfPointcut ret = new IfFalsePointcut(); ret.state = state; return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public static class IfFalsePointcut extends IfPointcut { public IfFalsePointcut() { super(null,0); this.pointcutKind = Pointcut.IF_FALSE; } public Set couldMatchKinds() { return Collections.EMPTY_SET; } public boolean alwaysFalse() { return true; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Literal.FALSE; // can only get here if an earlier error occurred } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.NO; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return FuzzyBoolean.NO; } public void resolveBindings(IScope scope, Bindings bindings) { } public void resolveBindingsFromRTTI() { } public void postRead(ResolvedType 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.IF_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } return makeIfFalsePointcut(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.IF_FALSE); } public int hashCode() { int result = 17; return result; } public String toString() { return "if(false)"; } } public static IfPointcut makeIfTruePointcut(State state) { IfPointcut ret = new IfTruePointcut(); ret.state = state; return ret; } public static class IfTruePointcut extends IfPointcut { public IfTruePointcut() { super(null,0); this.pointcutKind = Pointcut.IF_TRUE; } public boolean alwaysTrue() { return true; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Literal.TRUE; // can only get here if an earlier error occurred } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.YES; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.YES; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return FuzzyBoolean.YES; } public void resolveBindings(IScope scope, Bindings bindings) { } public void resolveBindingsFromRTTI() { } public void postRead(ResolvedType 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.IF_IN_DECLARE), bindings.getEnclosingAdvice().getSourceLocation(), null); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } return makeIfTruePointcut(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(IF_TRUE); } public int hashCode() { int result = 37; return result; } public String toString() { return "if(true)"; } } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/KindedPointcut.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.Map; import java.util.Set; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.MessageUtil; import org.aspectj.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Checker; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; 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.World; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class KindedPointcut extends Pointcut { Shadow.Kind kind; private SignaturePattern signature; private Set matchKinds; private ShadowMunger munger = null; // only set after concretization public KindedPointcut( Shadow.Kind kind, SignaturePattern signature) { this.kind = kind; this.signature = signature; this.pointcutKind = KINDED; this.matchKinds = new HashSet(); matchKinds.add(kind); } public KindedPointcut( Shadow.Kind kind, SignaturePattern signature, ShadowMunger munger) { this(kind, signature); this.munger = munger; } public SignaturePattern getSignature() { return signature; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#couldMatchKinds() */ public Set couldMatchKinds() { return matchKinds; } public boolean couldEverMatchSameJoinPointsAs(KindedPointcut other) { if (this.kind != other.kind) return false; String myName = signature.getName().maybeGetSimpleName(); String yourName = other.signature.getName().maybeGetSimpleName(); if (myName != null && yourName != null) { if ( !myName.equals(yourName)) { return false; } } if (signature.getParameterTypes().ellipsisCount == 0) { if (other.signature.getParameterTypes().ellipsisCount == 0) { if (signature.getParameterTypes().getTypePatterns().length != other.signature.getParameterTypes().getTypePatterns().length) { return false; } } } return true; } public FuzzyBoolean fastMatch(FastMatchInfo info) { if (info.getKind() != null) { if (info.getKind() != kind) return FuzzyBoolean.NO; } return FuzzyBoolean.MAYBE; } public FuzzyBoolean fastMatch(Class targetType) { return FuzzyBoolean.fromBoolean(signature.couldMatch(targetType)); } protected FuzzyBoolean matchInternal(Shadow shadow) { if (shadow.getKind() != kind) return FuzzyBoolean.NO; if (!signature.matches(shadow.getMatchingSignature(), shadow.getIWorld(),this.kind == Shadow.MethodCall)){ if(kind == Shadow.MethodCall) { warnOnConfusingSig(shadow); //warnOnBridgeMethod(shadow); } return FuzzyBoolean.NO; } return FuzzyBoolean.YES; } // private void warnOnBridgeMethod(Shadow shadow) { // if (shadow.getIWorld().getLint().noJoinpointsForBridgeMethods.isEnabled()) { // ResolvedMember rm = shadow.getSignature().resolve(shadow.getIWorld()); // if (rm!=null) { // int shadowModifiers = rm.getModifiers(); //shadow.getSignature().getModifiers(shadow.getIWorld()); // if (ResolvedType.hasBridgeModifier(shadowModifiers)) { // shadow.getIWorld().getLint().noJoinpointsForBridgeMethods.signal(new String[]{},getSourceLocation(), // new ISourceLocation[]{shadow.getSourceLocation()}); // } // } // } // } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { if (jpsp.getKind().equals(kind.getName())) { if (signature.matches(jpsp)) { return FuzzyBoolean.YES; } } return FuzzyBoolean.NO; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return true; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically(String joinpointKind, java.lang.reflect.Member member, Class thisClass, Class targetClass, java.lang.reflect.Member withinCode) { if (joinpointKind.equals(kind.getName())) { return FuzzyBoolean.fromBoolean(signature.matches(targetClass,member)); } return FuzzyBoolean.NO; } private void warnOnConfusingSig(Shadow shadow) { // Don't do all this processing if we don't need to ! if (!shadow.getIWorld().getLint().unmatchedSuperTypeInCall.isEnabled()) return; // no warnings for declare error/warning if (munger instanceof Checker) return; World world = shadow.getIWorld(); // warning never needed if the declaring type is any UnresolvedType exactDeclaringType = signature.getDeclaringType().getExactType(); ResolvedType shadowDeclaringType = shadow.getSignature().getDeclaringType().resolve(world); if (signature.getDeclaringType().isStar() || exactDeclaringType== ResolvedType.MISSING) return; // warning not needed if match type couldn't ever be the declaring type if (!shadowDeclaringType.isAssignableFrom(exactDeclaringType.resolve(world))) { return; } // if the method in the declaring type is *not* visible to the // exact declaring type then warning not needed. int shadowModifiers = shadow.getSignature().resolve(world).getModifiers(); if (!ResolvedType .isVisible( shadowModifiers, shadowDeclaringType, exactDeclaringType.resolve(world))) { return; } if (!signature.getReturnType().matchesStatically(shadow.getSignature().getReturnType().resolve(world))) { // Covariance issue... // The reason we didn't match is that the type pattern for the pointcut (Car) doesn't match the // return type for the specific declaration at the shadow. (FastCar Sub.getCar()) // XXX Put out another XLINT in this case? return; } // PR60015 - Don't report the warning if the declaring type is object and 'this' is an interface if (exactDeclaringType.resolve(world).isInterface() && shadowDeclaringType.equals(world.resolve("java.lang.Object"))) { return; } SignaturePattern nonConfusingPattern = new SignaturePattern( signature.getKind(), signature.getModifiers(), signature.getReturnType(), TypePattern.ANY, signature.getName(), signature.getParameterTypes(), signature.getThrowsPattern(), signature.getAnnotationPattern()); if (nonConfusingPattern .matches(shadow.getSignature(), shadow.getIWorld(),true)) { shadow.getIWorld().getLint().unmatchedSuperTypeInCall.signal( new String[] { shadow.getSignature().getDeclaringType().toString(), signature.getDeclaringType().toString() }, this.getSourceLocation(), new ISourceLocation[] {shadow.getSourceLocation()} ); } } public boolean equals(Object other) { if (!(other instanceof KindedPointcut)) return false; KindedPointcut o = (KindedPointcut)other; return o.kind == this.kind && o.signature.equals(this.signature); } public int hashCode() { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + signature.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(kind.getSimpleName()); buf.append("("); buf.append(signature.toString()); buf.append(")"); return buf.toString(); } public void postRead(ResolvedType enclosingType) { signature.postRead(enclosingType); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.KINDED); kind.write(s); signature.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { Shadow.Kind kind = Shadow.Kind.read(s); SignaturePattern sig = SignaturePattern.read(s, context); KindedPointcut ret = new KindedPointcut(kind, sig); 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) { if (kind == Shadow.Initialization) { // scope.getMessageHandler().handleMessage( // MessageUtil.error( // "initialization unimplemented in 1.1beta1", // this.getSourceLocation())); } signature = signature.resolveBindings(scope, bindings); if (kind == Shadow.ConstructorExecution) { // Bug fix 60936 if (signature.getDeclaringType() != null) { World world = scope.getWorld(); UnresolvedType exactType = signature.getDeclaringType().getExactType(); if (signature.getKind() == Member.CONSTRUCTOR && !exactType.equals(ResolvedType.MISSING) && exactType.resolve(world).isInterface() && !signature.getDeclaringType().isIncludeSubtypes()) { world.getLint().noInterfaceCtorJoinpoint.signal(exactType.toString(), getSourceLocation()); } } } // no parameterized types if (kind == Shadow.StaticInitialization) { HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_STATIC_INIT_JPS_FOR_PARAMETERIZED_TYPES), getSourceLocation())); } } // no parameterized types in declaring type position if ((kind == Shadow.FieldGet) || (kind == Shadow.FieldSet)) { HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.GET_AND_SET_DONT_SUPPORT_DEC_TYPE_PARAMETERS), getSourceLocation())); } // fields can't have a void type! UnresolvedType returnType = signature.getReturnType().getExactType(); if (returnType == ResolvedType.VOID) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.FIELDS_CANT_HAVE_VOID_TYPE), getSourceLocation())); } } // no join points for initialization and preinitialization of parameterized types // no throwable parameterized types if ((kind == Shadow.Initialization) || (kind == Shadow.PreInitialization)) { HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_INIT_JPS_FOR_PARAMETERIZED_TYPES), getSourceLocation())); } visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getThrowsPattern().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES), getSourceLocation())); } } // no parameterized types in declaring type position // no throwable parameterized types if ((kind == Shadow.MethodExecution) || (kind == Shadow.ConstructorExecution)) { HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.EXECUTION_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())); } } // no parameterized types in declaring type position // no throwable parameterized types if ((kind == Shadow.MethodCall) || (kind == Shadow.ConstructorCall)) { HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor(); signature.getDeclaringType().traverse(visitor, null); if (visitor.wellHasItThen/*?*/()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CALL_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 resolveBindingsFromRTTI() { signature = signature.resolveBindingsFromRTTI(); } 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 KindedPointcut(kind, signature, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } public Pointcut parameterizeWith(Map typeVariableMap) { Pointcut ret = new KindedPointcut(kind, signature.parameterizeWith(typeVariableMap), munger ); ret.copyLocationFrom(this); return ret; } public Shadow.Kind getKind() { return kind; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/NotPointcut.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.Member; import java.util.Map; import java.util.Set; import org.aspectj.lang.JoinPoint; 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.ast.Test; public class NotPointcut extends Pointcut { private Pointcut body; public NotPointcut(Pointcut negated) { super(); this.body = negated; this.pointcutKind = NOT; } public NotPointcut(Pointcut pointcut, int startPos) { this(pointcut); setLocation(pointcut.getSourceContext(), startPos, pointcut.getEnd()); } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public Pointcut getNegatedPointcut() { return body; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return body.fastMatch(type).not(); } public FuzzyBoolean fastMatch(Class targetType) { return body.fastMatch(targetType).not(); } protected FuzzyBoolean matchInternal(Shadow shadow) { return body.match(shadow).not(); } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart encJP) { return body.match(jp,encJP).not(); } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return body.match(jpsp).not(); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return !body.matchesDynamically(thisObject,targetObject,args); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { return body.matchesStatically(joinpointKind,member,thisClass,targetClass,withinCode).not(); } public String toString() { return "!" + body.toString(); } public boolean equals(Object other) { if (!(other instanceof NotPointcut)) return false; NotPointcut o = (NotPointcut)other; return o.body.equals(body); } public int hashCode() { return 37*23 + body.hashCode(); } public void resolveBindings(IScope scope, Bindings bindings) { //Bindings old = bindings.copy(); //Bindings newBindings = new Bindings(bindings.size()); body.resolveBindings(scope, null); //newBindings.checkEmpty(scope, "negation does not allow binding"); //bindings.checkEquals(old, scope); } public void resolveBindingsFromRTTI() { body.resolveBindingsFromRTTI(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.NOT); body.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { NotPointcut ret = new NotPointcut(Pointcut.read(s, context)); ret.readLocation(context, s); return ret; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Test.makeNot(body.findResidue(shadow, state)); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new NotPointcut(body.concretize(inAspect, declaringType, bindings)); ret.copyLocationFrom(this); return ret; } public Pointcut parameterizeWith(Map typeVariableMap) { Pointcut ret = new NotPointcut(body.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); this.body.traverse(visitor,ret); return ret; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/NotTypePattern.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.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; /** * !TypePattern * * <p>any binding to formals is explicitly forbidden for any composite, ! is * just the most obviously wrong case. * * @author Erik Hilsdale * @author Jim Hugunin */ public class NotTypePattern extends TypePattern { private TypePattern negatedPattern; public NotTypePattern(TypePattern pattern) { super(false,false); //??? we override all methods that care about includeSubtypes this.negatedPattern = pattern; setLocation(pattern.getSourceContext(), pattern.getStart(), pattern.getEnd()); } public TypePattern getNegatedPattern() { return negatedPattern; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } public FuzzyBoolean matchesInstanceof(ResolvedType type) { return negatedPattern.matchesInstanceof(type).not(); } protected boolean matchesExactly(ResolvedType type) { return (!negatedPattern.matchesExactly(type) && annotationPattern.matches(type).alwaysTrue()); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return (!negatedPattern.matchesExactly(type,annotatedType) && annotationPattern.matches(annotatedType).alwaysTrue()); } public boolean matchesStatically(Class type) { return !negatedPattern.matchesStatically(type); } public FuzzyBoolean matchesInstanceof(Class type) { return negatedPattern.matchesInstanceof(type).not(); } protected boolean matchesExactly(Class type) { return !negatedPattern.matchesExactly(type); } public boolean matchesStatically(ResolvedType type) { return !negatedPattern.matchesStatically(type); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { super.setAnnotationTypePattern(annPatt); } public void setIsVarArgs(boolean isVarArgs) { negatedPattern.setIsVarArgs(isVarArgs); } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.NOT); negatedPattern.write(s); annotationPattern.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { TypePattern ret = new NotTypePattern(TypePattern.read(s, context)); if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { ret.annotationPattern = AnnotationTypePattern.read(s,context); } ret.readLocation(context, s); return ret; } public TypePattern resolveBindings( IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) return notExactType(scope); negatedPattern = negatedPattern.resolveBindings(scope, bindings, false, false); return this; } public TypePattern parameterizeWith(Map typeVariableMap) { TypePattern newNegatedPattern = negatedPattern.parameterizeWith(typeVariableMap); NotTypePattern ret = new NotTypePattern(newNegatedPattern); ret.copyLocationFrom(this); return ret; } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { if (requireExactType) return TypePattern.NO; negatedPattern = negatedPattern.resolveBindingsFromRTTI(allowBinding,requireExactType); return this; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } buff.append('!'); buff.append(negatedPattern); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (! (obj instanceof NotTypePattern)) return false; return (negatedPattern.equals(((NotTypePattern)obj).negatedPattern)); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37 * negatedPattern.hashCode(); } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); negatedPattern.traverse(visitor, ret); return ret; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/OrPointcut.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.Member; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.aspectj.lang.JoinPoint; 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.ast.Test; public class OrPointcut extends Pointcut { Pointcut left, right; private Set couldMatchKinds; public OrPointcut(Pointcut left, Pointcut right) { super(); this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); this.pointcutKind = OR; this.couldMatchKinds = new HashSet(left.couldMatchKinds()); this.couldMatchKinds.addAll(right.couldMatchKinds()); } public Set couldMatchKinds() { return couldMatchKinds; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return left.fastMatch(type).or(right.fastMatch(type)); } public FuzzyBoolean fastMatch(Class targetType) { return left.fastMatch(targetType).or(right.fastMatch(targetType)); } protected FuzzyBoolean matchInternal(Shadow shadow) { FuzzyBoolean leftMatch = left.match(shadow); if (leftMatch.alwaysTrue()) return leftMatch; return leftMatch.or(right.match(shadow)); } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart encJP) { return left.match(jp,encJP).or(right.match(jp,encJP)); } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return left.match(jpsp).or(right.match(jpsp)); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return left.matchesDynamically(thisObject,targetObject,args) || right.matchesDynamically(thisObject,targetObject,args); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { return left.matchesStatically(joinpointKind,member,thisClass,targetClass,withinCode) .or( right.matchesStatically(joinpointKind,member,thisClass,targetClass,withinCode)); } public String toString() { return "(" + left.toString() + " || " + right.toString() + ")"; } public boolean equals(Object other) { if (!(other instanceof OrPointcut)) return false; OrPointcut o = (OrPointcut)other; return o.left.equals(left) && o.right.equals(right); } public int hashCode() { int result = 31; result = 37*result + left.hashCode(); result = 37*result + right.hashCode(); return result; } /** * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(IScope, Bindings) */ public void resolveBindings(IScope scope, Bindings bindings) { Bindings old = bindings == null ? null : bindings.copy(); left.resolveBindings(scope, bindings); right.resolveBindings(scope, old); if (bindings != null) bindings.checkEquals(old, scope); } public void resolveBindingsFromRTTI() { left.resolveBindingsFromRTTI(); right.resolveBindingsFromRTTI(); } public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.OR); left.write(s); right.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { OrPointcut ret = new OrPointcut(Pointcut.read(s, context), Pointcut.read(s, context)); ret.readLocation(context, s); return ret; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Test.makeOr(left.findResidue(shadow, state), right.findResidue(shadow, state)); } public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { Pointcut ret = new OrPointcut(left.concretize(inAspect, declaringType, bindings), right.concretize(inAspect, declaringType, bindings)); ret.copyLocationFrom(this); return ret; } public Pointcut parameterizeWith(Map typeVariableMap) { Pointcut ret = new OrPointcut(left.parameterizeWith(typeVariableMap), right.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public Pointcut getLeft() { return left; } public Pointcut getRight() { return right; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); left.traverse(visitor, ret); right.traverse(visitor,ret); return ret; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/OrTypePattern.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.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.VersionedDataInputStream; /** * left || right * * <p>any binding to formals is explicitly forbidden for any composite by the language * * @author Erik Hilsdale * @author Jim Hugunin */ public class OrTypePattern extends TypePattern { private TypePattern left, right; public OrTypePattern(TypePattern left, TypePattern right) { super(false,false); //??? we override all methods that care about includeSubtypes this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } public TypePattern getRight() { return right; } public TypePattern getLeft() { return left; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; // don't dive at the moment... } public FuzzyBoolean matchesInstanceof(ResolvedType type) { return left.matchesInstanceof(type).or(right.matchesInstanceof(type)); } protected boolean matchesExactly(ResolvedType type) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type) || right.matchesExactly(type); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type,annotatedType) || right.matchesExactly(type,annotatedType); } public boolean matchesStatically(ResolvedType type) { return left.matchesStatically(type) || right.matchesStatically(type); } public FuzzyBoolean matchesInstanceof(Class type) { return left.matchesInstanceof(type).or(right.matchesInstanceof(type)); } protected boolean matchesExactly(Class type) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type) || right.matchesExactly(type); } public boolean matchesStatically(Class type) { return left.matchesStatically(type) || right.matchesStatically(type); } public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; left.setIsVarArgs(isVarArgs); right.setIsVarArgs(isVarArgs); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { if (annPatt == AnnotationTypePattern.ANY) return; if (left.annotationPattern == AnnotationTypePattern.ANY) { left.setAnnotationTypePattern(annPatt); } else { left.setAnnotationTypePattern( new AndAnnotationTypePattern(left.annotationPattern,annPatt)); } if (right.annotationPattern == AnnotationTypePattern.ANY) { right.setAnnotationTypePattern(annPatt); } else { right.setAnnotationTypePattern( new AndAnnotationTypePattern(right.annotationPattern,annPatt)); } } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.OR); left.write(s); right.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { OrTypePattern ret = new OrTypePattern(TypePattern.read(s, context), TypePattern.read(s, context)); ret.readLocation(context, s); if (ret.left.isVarArgs && ret.right.isVarArgs) ret.isVarArgs = true; return ret; } public TypePattern resolveBindings( IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) return notExactType(scope); left = left.resolveBindings(scope, bindings, false, false); right = right.resolveBindings(scope, bindings, false, false); return this; } public TypePattern parameterizeWith(Map typeVariableMap) { TypePattern newLeft = left.parameterizeWith(typeVariableMap); TypePattern newRight = right.parameterizeWith(typeVariableMap); OrTypePattern ret = new OrTypePattern(newLeft,newRight); ret.copyLocationFrom(this); return ret; } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { if (requireExactType) return TypePattern.NO; left = left.resolveBindingsFromRTTI(allowBinding,requireExactType); right = right.resolveBindingsFromRTTI(allowBinding,requireExactType); return this; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } buff.append('('); buff.append(left.toString()); buff.append(" || "); buff.append(right.toString()); buff.append(')'); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (! (obj instanceof OrTypePattern)) return false; OrTypePattern other = (OrTypePattern) obj; return left.equals(other.left) && right.equals(other.right); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { int ret = 17; ret = ret + 37 * left.hashCode(); ret = ret + 37 * right.hashCode(); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor,data); left.traverse(visitor, ret); right.traverse(visitor, ret); return ret; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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; } public FuzzyBoolean fastMatch(Class targetType) { 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 String toString() { return "percflow(" + inAspect + " on " + entry + ")"; } public String toDeclarationString() { if (isBelow) return "percflowbelow(" + entry + ")"; return "percflow(" + entry + ")"; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/PerClause.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.IOException; import org.aspectj.util.TypeSafeEnum; import org.aspectj.weaver.*; // PTWIMPL New kind added to this class, can be (de)serialized public abstract class PerClause extends Pointcut { protected ResolvedType inAspect; public static PerClause readPerClause(VersionedDataInputStream s, ISourceContext context) throws IOException { Kind kind = Kind.read(s); if (kind == SINGLETON) return PerSingleton.readPerClause(s, context); else if (kind == PERCFLOW) return PerCflow.readPerClause(s, context); else if (kind == PEROBJECT) return PerObject.readPerClause(s, context); else if (kind == FROMSUPER) return PerFromSuper.readPerClause(s, context); else if (kind == PERTYPEWITHIN) return PerTypeWithin.readPerClause(s,context); throw new BCException("unknown kind: " + kind); } public final Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { throw new RuntimeException("unimplemented: wrong concretize"); } public abstract PerClause concretize(ResolvedType inAspect); public abstract PerClause.Kind getKind(); public abstract String toDeclarationString(); public static class Kind extends TypeSafeEnum { public Kind(String name, int key) { super(name, key); } public static Kind read(VersionedDataInputStream s) throws IOException { int key = s.readByte(); switch(key) { case 1: return SINGLETON; case 2: return PERCFLOW; case 3: return PEROBJECT; case 4: return FROMSUPER; case 5: return PERTYPEWITHIN; } throw new BCException("weird kind " + key); } } public void resolveBindingsFromRTTI() { throw new UnsupportedOperationException("Can't resolve per-clauses at runtime"); } public static final Kind SINGLETON = new Kind("issingleton", 1); public static final Kind PERCFLOW = new Kind("percflow", 2); public static final Kind PEROBJECT = new Kind("perobject", 3); public static final Kind FROMSUPER = new Kind("fromsuper", 4); public static final Kind PERTYPEWITHIN = new Kind("pertypewithin",5); public static class KindAnnotationPrefix extends TypeSafeEnum { private KindAnnotationPrefix(String name, int key) { super(name, key); } public String extractPointcut(String perClause) { int from = getName().length(); int to = perClause.length()-1; if (!perClause.startsWith(getName()) || !perClause.endsWith(")") || from > perClause.length()) { throw new RuntimeException("cannot read perclause " + perClause); } return perClause.substring(from, to); } public static final KindAnnotationPrefix PERCFLOW = new KindAnnotationPrefix("percflow(", 1); public static final KindAnnotationPrefix PERCFLOWBELOW = new KindAnnotationPrefix("percflowbelow(", 2); public static final KindAnnotationPrefix PERTHIS = new KindAnnotationPrefix("perthis(", 3); public static final KindAnnotationPrefix PERTARGET = new KindAnnotationPrefix("pertarget(", 4); public static final KindAnnotationPrefix PERTYPEWITHIN = new KindAnnotationPrefix("pertypewithin(", 5); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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"); } public FuzzyBoolean fastMatch(Class targetType) { 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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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; } public FuzzyBoolean fastMatch(Class targetType) { 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(); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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; } public FuzzyBoolean fastMatch(Class targetType) { 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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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; } public FuzzyBoolean fastMatch(Class targetType) { 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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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.lang.reflect.Member; import java.util.Collections; import java.util.Map; import java.util.Set; import org.aspectj.lang.JoinPoint; 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 implements PointcutExpressionMatching { 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 Test lastMatchedShadowResidue; 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); /** * Could I match any shadows defined in this type? */ public abstract FuzzyBoolean fastMatch(Class targetType); /** * 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); /* * for runtime / dynamic pointcuts. * Default implementation delegates to StaticPart matcher */ public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart enclosingJoinPoint) { return match(jp.getStaticPart()); } /* * for runtime / dynamic pointcuts. * Not all pointcuts can be matched at runtime, those that can should overide either * match(JoinPoint), or this method, or both. */ public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { throw new UnsupportedOperationException("Pointcut expression " + this.toString() + "cannot be matched at runtime"); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesDynamically(java.lang.String, java.lang.reflect.Member, java.lang.Object, java.lang.Object, java.lang.reflect.Member) */ public boolean matchesDynamically( Object thisObject, Object targetObject, Object[] args) { throw new UnsupportedOperationException("Pointcut expression " + this.toString() + "cannot be matched by this operation"); } /* (non-Javadoc) * @see org.aspectj.weaver.tools.PointcutExpression#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { throw new UnsupportedOperationException("Pointcut expression " + this.toString() + "cannot be matched by this operation"); } 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); // internal, only called from resolve protected abstract void resolveBindingsFromRTTI(); /** * 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 this pointcut with type patterns etc resolved based on available RTTI */ public Pointcut resolve() { assertState(SYMBOLIC); this.resolveBindingsFromRTTI(); 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; } public FuzzyBoolean fastMatch(Class targetType) { return FuzzyBoolean.NO; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public FuzzyBoolean match(JoinPoint.StaticPart jpsp) { return FuzzyBoolean.NO; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return false; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { return FuzzyBoolean.NO; } public void resolveBindings(IScope scope, Bindings bindings) { } public void resolveBindingsFromRTTI() { } 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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/PointcutExpressionMatching.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.lang.reflect.Member; import org.aspectj.util.FuzzyBoolean; /** * Interface used by PointcutExpressionImpl to determine matches. */ public interface PointcutExpressionMatching { FuzzyBoolean matchesStatically( String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode); /** * Only considers this, target, and args primitives, returns * true for all others. * @param thisObject * @param targetObject * @param args * @return */ boolean matchesDynamically( Object thisObject, Object targetObject, Object[] args); }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26: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; } public FuzzyBoolean fastMatch(Class targetType) { 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 resolveBindingsFromRTTI() { throw new UnsupportedOperationException("Referenced pointcuts are not supported in runtime evaluation"); } 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); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/SignaturePattern.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.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.reflect.AdviceSignature; import org.aspectj.lang.reflect.ConstructorSignature; import org.aspectj.lang.reflect.FieldSignature; import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.Constants; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.JoinPointSignature; 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.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelTypeMunger; public class SignaturePattern extends PatternNode { private Member.Kind kind; private ModifiersPattern modifiers; private TypePattern returnType; private TypePattern declaringType; private NamePattern name; private TypePatternList parameterTypes; private ThrowsPattern throwsPattern; private AnnotationTypePattern annotationPattern; public SignaturePattern(Member.Kind kind, ModifiersPattern modifiers, TypePattern returnType, TypePattern declaringType, NamePattern name, TypePatternList parameterTypes, ThrowsPattern throwsPattern, AnnotationTypePattern annotationPattern) { this.kind = kind; this.modifiers = modifiers; this.returnType = returnType; this.name = name; this.declaringType = declaringType; this.parameterTypes = parameterTypes; this.throwsPattern = throwsPattern; this.annotationPattern = annotationPattern; } public SignaturePattern resolveBindings(IScope scope, Bindings bindings) { if (returnType != null) { returnType = returnType.resolveBindings(scope, bindings, false, false); } if (declaringType != null) { declaringType = declaringType.resolveBindings(scope, bindings, false, false); } if (parameterTypes != null) { parameterTypes = parameterTypes.resolveBindings(scope, bindings, false, false); } if (throwsPattern != null) { throwsPattern = throwsPattern.resolveBindings(scope, bindings); } if (annotationPattern != null) { annotationPattern = annotationPattern.resolveBindings(scope,bindings,false); } return this; } public SignaturePattern resolveBindingsFromRTTI() { if (returnType != null) { returnType = returnType.resolveBindingsFromRTTI(false, false); } if (declaringType != null) { declaringType = declaringType.resolveBindingsFromRTTI(false, false); } if (parameterTypes != null) { parameterTypes = parameterTypes.resolveBindingsFromRTTI(false, false); } if (throwsPattern != null) { throwsPattern = throwsPattern.resolveBindingsFromRTTI(); } return this; } public void postRead(ResolvedType enclosingType) { if (returnType != null) { returnType.postRead(enclosingType); } if (declaringType != null) { declaringType.postRead(enclosingType); } if (parameterTypes != null) { parameterTypes.postRead(enclosingType); } } /** * return a copy of this signature pattern in which every type variable reference * is replaced by the corresponding entry in the map. */ public SignaturePattern parameterizeWith(Map typeVariableMap) { SignaturePattern ret = new SignaturePattern( kind, modifiers, returnType.parameterizeWith(typeVariableMap), declaringType.parameterizeWith(typeVariableMap), name, parameterTypes.parameterizeWith(typeVariableMap), throwsPattern.parameterizeWith(typeVariableMap), annotationPattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public boolean matches(Member joinPointSignature, World world, boolean allowBridgeMethods) { // fail (or succeed!) fast tests... if (joinPointSignature == null) return false; if (kind != joinPointSignature.getKind()) return false; if (kind == Member.ADVICE) return true; // do the hard work then... JoinPointSignature[] candidateMatches = joinPointSignature.getJoinPointSignatures(world); for (int i = 0; i < candidateMatches.length; i++) { if (matchesExactly(candidateMatches[i],world,allowBridgeMethods)) return true; } return false; } // Does this pattern match this exact signature (no declaring type mucking about // or chasing up the hierarchy) private boolean matchesExactly(JoinPointSignature aMember, World inAWorld, boolean allowBridgeMethods) { // Java5 introduces bridge methods, we match a call to them but nothing else... if (aMember.isBridgeMethod() && !allowBridgeMethods) { return false; } if (!modifiers.matches(aMember.getModifiers())) return false; boolean matchesIgnoringAnnotations = true; if (kind == Member.STATIC_INITIALIZATION) { matchesIgnoringAnnotations = matchesExactlyStaticInitialization(aMember, inAWorld); } else if (kind == Member.FIELD) { matchesIgnoringAnnotations = matchesExactlyField(aMember,inAWorld); } else if (kind == Member.METHOD) { matchesIgnoringAnnotations = matchesExactlyMethod(aMember,inAWorld); } else if (kind == Member.CONSTRUCTOR) { matchesIgnoringAnnotations = matchesExactlyConstructor(aMember, inAWorld); } if (!matchesIgnoringAnnotations) return false; return matchesAnnotations(aMember, inAWorld); } /** * Matches on declaring type */ private boolean matchesExactlyStaticInitialization(JoinPointSignature aMember,World world) { return declaringType.matchesStatically(aMember.getDeclaringType().resolve(world)); } /** * Matches on name, declaring type, field type */ private boolean matchesExactlyField(JoinPointSignature aField, World world) { if (!name.matches(aField.getName())) return false; if (!declaringType.matchesStatically(aField.getDeclaringType().resolve(world))) return false; if (!returnType.matchesStatically(aField.getReturnType().resolve(world))) { // looking bad, but there might be parameterization to consider... if (!returnType.matchesStatically(aField.getGenericReturnType().resolve(world))) { // ok, it's bad. return false; } } // passed all the guards... return true; } /** * Matches on name, declaring type, return type, parameter types, throws types */ private boolean matchesExactlyMethod(JoinPointSignature aMethod, World world) { if (!name.matches(aMethod.getName())) return false; if (!declaringType.matchesStatically(aMethod.getDeclaringType().resolve(world))) return false; if (!returnType.matchesStatically(aMethod.getReturnType().resolve(world))) { // looking bad, but there might be parameterization to consider... if (!returnType.matchesStatically(aMethod.getGenericReturnType().resolve(world))) { // ok, it's bad. return false; } } ResolvedType[] resolvedParameters = world.resolve(aMethod.getParameterTypes()); if (!parameterTypes.matches(resolvedParameters, TypePattern.STATIC).alwaysTrue()) { // It could still be a match based on the generic sig parameter types of a parameterized type if (!parameterTypes.matches(world.resolve(aMethod.getGenericParameterTypes()),TypePattern.STATIC).alwaysTrue()) { return false; // It could STILL be a match based on the erasure of the parameter types?? // to be determined via test cases... } } // check that varargs specifications match if (!matchesVarArgs(aMethod,world)) return false; // Check the throws pattern if (!throwsPattern.matches(aMethod.getExceptions(), world)) return false; // passed all the guards.. return true; } /** * match on declaring type, parameter types, throws types */ private boolean matchesExactlyConstructor(JoinPointSignature aConstructor, World world) { if (!declaringType.matchesStatically(aConstructor.getDeclaringType().resolve(world))) return false; ResolvedType[] resolvedParameters = world.resolve(aConstructor.getParameterTypes()); if (!parameterTypes.matches(resolvedParameters, TypePattern.STATIC).alwaysTrue()) { // It could still be a match based on the generic sig parameter types of a parameterized type if (!parameterTypes.matches(world.resolve(aConstructor.getGenericParameterTypes()),TypePattern.STATIC).alwaysTrue()) { return false; // It could STILL be a match based on the erasure of the parameter types?? // to be determined via test cases... } } // check that varargs specifications match if (!matchesVarArgs(aConstructor,world)) return false; // Check the throws pattern if (!throwsPattern.matches(aConstructor.getExceptions(), world)) return false; // passed all the guards.. return true; } /** * We've matched against this method or constructor so far, but without considering * varargs (which has been matched as a simple array thus far). Now we do the additional * checks to see if the parties agree on whether the last parameter is varargs or a * straight array. */ private boolean matchesVarArgs(JoinPointSignature aMethodOrConstructor, World inAWorld) { if (parameterTypes.size() == 0) return true; TypePattern lastPattern = parameterTypes.get(parameterTypes.size()-1); boolean canMatchVarArgsSignature = lastPattern.isStar() || lastPattern.isVarArgs() || (lastPattern == TypePattern.ELLIPSIS); if (aMethodOrConstructor.isVarargsMethod()) { // we have at least one parameter in the pattern list, and the method has a varargs signature if (!canMatchVarArgsSignature) { // XXX - Ideally the shadow would be included in the msg but we don't know it... inAWorld.getLint().cantMatchArrayTypeOnVarargs.signal(aMethodOrConstructor.toString(),getSourceLocation()); return false; } } else { // the method ends with an array type, check that we don't *require* a varargs if (lastPattern.isVarArgs()) return false; } return true; } private boolean matchesAnnotations(ResolvedMember member,World world) { if (member == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return false; } world.getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return false; } annotationPattern.resolve(world); // optimization before we go digging around for annotations on ITDs if (annotationPattern instanceof AnyAnnotationTypePattern) return true; // fake members represent ITD'd fields - for their annotations we should go and look up the // relevant member in the original aspect if (member.isAnnotatedElsewhere() && member.getKind()==Member.FIELD) { // FIXME asc duplicate of code in AnnotationPattern.matchInternal()? same fixmes apply here. ResolvedMember [] mems = member.getDeclaringType().resolve(world).getDeclaredFields(); // FIXME asc should include supers with getInterTypeMungersIncludingSupers? List mungers = member.getDeclaringType().resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); if (fakerm.equals(member)) { member = rmm; } } } } return annotationPattern.matches(member).alwaysTrue(); } 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; } public boolean declaringTypeMatchAllowingForCovariance(Member member, UnresolvedType shadowDeclaringType, World world,TypePattern returnTypePattern,ResolvedType sigReturn) { ResolvedType onType = shadowDeclaringType.resolve(world); // fastmatch if (declaringType.matchesStatically(onType) && returnTypePattern.matchesStatically(sigReturn)) return true; Collection declaringTypes = member.getDeclaringTypes(world); boolean checkReturnType = true; // XXX Possible enhancement? Doesn't seem to speed things up // if (returnTypePattern.isStar()) { // if (returnTypePattern instanceof WildTypePattern) { // if (((WildTypePattern)returnTypePattern).getDimensions()==0) checkReturnType = false; // } // } // Sometimes that list includes types that don't explicitly declare the member we are after - // they are on the list because their supertype is on the list, that's why we use // lookupMethod rather than lookupMemberNoSupers() for (Iterator i = declaringTypes.iterator(); i.hasNext(); ) { ResolvedType type = (ResolvedType)i.next(); if (declaringType.matchesStatically(type)) { if (!checkReturnType) return true; ResolvedMember rm = type.lookupMethod(member); if (rm==null) rm = type.lookupMethodInITDs(member); // It must be in here, or we have *real* problems if (rm==null) continue; // might be currently looking at the generic type and we need to continue searching in case we hit a parameterized version of this same type... UnresolvedType returnTypeX = rm.getReturnType(); ResolvedType returnType = returnTypeX.resolve(world); if (returnTypePattern.matchesStatically(returnType)) return true; } } return false; } // for dynamic join point matching public boolean matches(JoinPoint.StaticPart jpsp) { Signature sig = jpsp.getSignature(); if (kind == Member.ADVICE && !(sig instanceof AdviceSignature)) return false; if (kind == Member.CONSTRUCTOR && !(sig instanceof ConstructorSignature)) return false; if (kind == Member.FIELD && !(sig instanceof FieldSignature)) return false; if (kind == Member.METHOD && !(sig instanceof MethodSignature)) return false; if (kind == Member.STATIC_INITIALIZATION && !(jpsp.getKind().equals(JoinPoint.STATICINITIALIZATION))) return false; if (kind == Member.POINTCUT) return false; if (kind == Member.ADVICE) return true; if (!modifiers.matches(sig.getModifiers())) return false; if (kind == Member.STATIC_INITIALIZATION) { //System.err.println("match static init: " + sig.getDeclaringType() + " with " + this); return declaringType.matchesStatically(sig.getDeclaringType()); } else if (kind == Member.FIELD) { Class returnTypeClass = ((FieldSignature)sig).getFieldType(); if (!returnType.matchesStatically(returnTypeClass)) return false; if (!name.matches(sig.getName())) return false; boolean ret = declaringTypeMatch(sig); //System.out.println(" ret: " + ret); return ret; } else if (kind == Member.METHOD) { MethodSignature msig = ((MethodSignature)sig); Class returnTypeClass = msig.getReturnType(); Class[] params = msig.getParameterTypes(); Class[] exceptionTypes = msig.getExceptionTypes(); if (!returnType.matchesStatically(returnTypeClass)) return false; if (!name.matches(sig.getName())) return false; if (!parameterTypes.matches(params, TypePattern.STATIC).alwaysTrue()) { return false; } if (matchedArrayAgainstVarArgs(parameterTypes,msig.getModifiers())) { return false; } if (!throwsPattern.matches(exceptionTypes)) return false; return declaringTypeMatch(sig); // XXXAJ5 - Need to make this a covariant aware version for dynamic JP matching to work } else if (kind == Member.CONSTRUCTOR) { ConstructorSignature csig = (ConstructorSignature)sig; Class[] params = csig.getParameterTypes(); Class[] exceptionTypes = csig.getExceptionTypes(); if (!parameterTypes.matches(params, TypePattern.STATIC).alwaysTrue()) { return false; } if (matchedArrayAgainstVarArgs(parameterTypes,csig.getModifiers())) { return false; } if (!throwsPattern.matches(exceptionTypes)) return false; return declaringType.matchesStatically(sig.getDeclaringType()); //return declaringTypeMatch(member.getDeclaringType(), member, world); } return false; } public boolean couldMatch(Class declaringClass) { return declaringTypeMatch(declaringClass); } public boolean matches(Class declaringClass, java.lang.reflect.Member member) { if (kind == Member.ADVICE) return true; if (kind == Member.POINTCUT) return false; if ((member != null) && !(modifiers.matches(member.getModifiers()))) return false; if (kind == Member.STATIC_INITIALIZATION) { return declaringType.matchesStatically(declaringClass); } if (kind == Member.FIELD) { if (!(member instanceof Field)) return false; Class fieldTypeClass = ((Field)member).getType(); if (!returnType.matchesStatically(fieldTypeClass)) return false; if (!name.matches(member.getName())) return false; return declaringTypeMatch(member.getDeclaringClass()); } if (kind == Member.METHOD) { if (! (member instanceof Method)) return false; Class returnTypeClass = ((Method)member).getReturnType(); Class[] params = ((Method)member).getParameterTypes(); Class[] exceptionTypes = ((Method)member).getExceptionTypes(); if (!returnType.matchesStatically(returnTypeClass)) return false; if (!name.matches(member.getName())) return false; if (!parameterTypes.matches(params, TypePattern.STATIC).alwaysTrue()) { return false; } if (matchedArrayAgainstVarArgs(parameterTypes,member.getModifiers())) { return false; } if (!throwsPattern.matches(exceptionTypes)) return false; return declaringTypeMatch(member.getDeclaringClass()); // XXXAJ5 - Need to make this a covariant aware version for dynamic JP matching to work } if (kind == Member.CONSTRUCTOR) { if (! (member instanceof Constructor)) return false; Class[] params = ((Constructor)member).getParameterTypes(); Class[] exceptionTypes = ((Constructor)member).getExceptionTypes(); if (!parameterTypes.matches(params, TypePattern.STATIC).alwaysTrue()) { return false; } if (matchedArrayAgainstVarArgs(parameterTypes,member.getModifiers())) { return false; } if (!throwsPattern.matches(exceptionTypes)) return false; return declaringType.matchesStatically(declaringClass); } return false; } private boolean declaringTypeMatch(Signature sig) { Class onType = sig.getDeclaringType(); if (declaringType.matchesStatically(onType)) return true; Collection declaringTypes = getDeclaringTypes(sig); for (Iterator it = declaringTypes.iterator(); it.hasNext(); ) { Class pClass = (Class) it.next(); if (declaringType.matchesStatically(pClass)) return true; } return false; } private boolean declaringTypeMatch(Class clazz) { if (clazz == null) return false; if (declaringType.matchesStatically(clazz)) return true; Class[] ifs = clazz.getInterfaces(); for (int i = 0; i<ifs.length; i++) { if (declaringType.matchesStatically(ifs[i])) return true; } return declaringTypeMatch(clazz.getSuperclass()); } private Collection getDeclaringTypes(Signature sig) { List l = new ArrayList(); Class onType = sig.getDeclaringType(); String memberName = sig.getName(); if (sig instanceof FieldSignature) { Class fieldType = ((FieldSignature)sig).getFieldType(); Class superType = onType; while(superType != null) { try { Field f = (superType.getDeclaredField(memberName)); if (f.getType() == fieldType) { l.add(superType); } } catch (NoSuchFieldException nsf) {} superType = superType.getSuperclass(); } } else if (sig instanceof MethodSignature) { Class[] paramTypes = ((MethodSignature)sig).getParameterTypes(); Class superType = onType; while(superType != null) { try { superType.getDeclaredMethod(memberName,paramTypes); l.add(superType); } catch (NoSuchMethodException nsm) {} superType = superType.getSuperclass(); } } return l; } public NamePattern getName() { return name; } public TypePattern getDeclaringType() { return declaringType; } public Member.Kind getKind() { return kind; } public String toString() { StringBuffer buf = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append(annotationPattern.toString()); buf.append(' '); } if (modifiers != ModifiersPattern.ANY) { buf.append(modifiers.toString()); buf.append(' '); } if (kind == Member.STATIC_INITIALIZATION) { buf.append(declaringType.toString()); buf.append(".<clinit>()");//FIXME AV - bad, cannot be parsed again } else if (kind == Member.HANDLER) { buf.append("handler("); buf.append(parameterTypes.get(0)); buf.append(")"); } else { if (!(kind == Member.CONSTRUCTOR)) { buf.append(returnType.toString()); buf.append(' '); } if (declaringType != TypePattern.ANY) { buf.append(declaringType.toString()); buf.append('.'); } if (kind == Member.CONSTRUCTOR) { buf.append("new"); } else { buf.append(name.toString()); } if (kind == Member.METHOD || kind == Member.CONSTRUCTOR) { buf.append(parameterTypes.toString()); } //FIXME AV - throws is not printed here, weird } return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof SignaturePattern)) return false; SignaturePattern o = (SignaturePattern)other; return o.kind.equals(this.kind) && o.modifiers.equals(this.modifiers) && o.returnType.equals(this.returnType) && o.declaringType.equals(this.declaringType) && o.name.equals(this.name) && o.parameterTypes.equals(this.parameterTypes) && o.throwsPattern.equals(this.throwsPattern) && o.annotationPattern.equals(this.annotationPattern); } public int hashCode() { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + modifiers.hashCode(); result = 37*result + returnType.hashCode(); result = 37*result + declaringType.hashCode(); result = 37*result + name.hashCode(); result = 37*result + parameterTypes.hashCode(); result = 37*result + throwsPattern.hashCode(); result = 37*result + annotationPattern.hashCode(); return result; } public void write(DataOutputStream s) throws IOException { kind.write(s); modifiers.write(s); returnType.write(s); declaringType.write(s); name.write(s); parameterTypes.write(s); throwsPattern.write(s); annotationPattern.write(s); writeLocation(s); } public static SignaturePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { Member.Kind kind = Member.Kind.read(s); ModifiersPattern modifiers = ModifiersPattern.read(s); TypePattern returnType = TypePattern.read(s, context); TypePattern declaringType = TypePattern.read(s, context); NamePattern name = NamePattern.read(s); TypePatternList parameterTypes = TypePatternList.read(s, context); ThrowsPattern throwsPattern = ThrowsPattern.read(s, context); AnnotationTypePattern annotationPattern = AnnotationTypePattern.ANY; if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { annotationPattern = AnnotationTypePattern.read(s,context); } SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType, name, parameterTypes, throwsPattern,annotationPattern); ret.readLocation(context, s); return ret; } /** * @return */ public ModifiersPattern getModifiers() { return modifiers; } /** * @return */ public TypePatternList getParameterTypes() { return parameterTypes; } /** * @return */ public TypePattern getReturnType() { return returnType; } /** * @return */ public ThrowsPattern getThrowsPattern() { return throwsPattern; } /** * return true if last argument in params is an Object[] but the modifiers say this method * was declared with varargs (Object...). We shouldn't be matching if this is the case. */ private boolean matchedArrayAgainstVarArgs(TypePatternList params,int modifiers) { if (params.size()>0 && (modifiers & Constants.ACC_VARARGS)!=0) { // we have at least one parameter in the pattern list, and the method has a varargs signature TypePattern lastPattern = params.get(params.size()-1); if (lastPattern.isArray() && !lastPattern.isVarArgs) return true; } return false; } public AnnotationTypePattern getAnnotationPattern() { return annotationPattern; } public boolean isStarAnnotation() { return annotationPattern == AnnotationTypePattern.ANY; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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; } 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; } public FuzzyBoolean fastMatch(Class targetType) { 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#resolveBindingsFromRTTI() */ protected void resolveBindingsFromRTTI() { // TODO Auto-generated method stub } /* (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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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.lang.reflect.Member; 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.lang.JoinPoint; 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; } public FuzzyBoolean fastMatch(Class targetType) { 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); } public FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart encJP) { Object toMatch = isThis ? jp.getThis() : jp.getTarget(); if (toMatch == null) return FuzzyBoolean.NO; return type.matches(toMatch.getClass(), TypePattern.DYNAMIC); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { Object toMatch = isThis ? thisObject : targetObject; if (toMatch == null) return false; return type.matchesSubtypes(toMatch.getClass()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically(String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { Class staticType = isThis ? thisClass : targetClass; if (joinpointKind.equals(Shadow.StaticInitialization.getName())) { return FuzzyBoolean.NO; // no this or target at these jps } return(((ExactTypePattern)type).willMatchDynamically(staticType)); } 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 resolveBindingsFromRTTI() { type = type.resolveBindingsFromRTTI(true,true); } 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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/ThrowsPattern.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.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; public class ThrowsPattern extends PatternNode { private TypePatternList required; private TypePatternList forbidden; public static final ThrowsPattern ANY = new ThrowsPattern(TypePatternList.EMPTY, TypePatternList.EMPTY); public ThrowsPattern(TypePatternList required, TypePatternList forbidden) { this.required = required; this.forbidden = forbidden; } public TypePatternList getRequired() { return required; } public TypePatternList getForbidden() { return forbidden; } public String toString() { if (this == ANY) return ""; String ret = "throws " + required.toString(); if (forbidden.size() > 0) { ret = ret + " !(" + forbidden.toString() + ")"; } return ret; } public boolean equals(Object other) { if (!(other instanceof ThrowsPattern)) return false; ThrowsPattern o = (ThrowsPattern)other; boolean ret = o.required.equals(this.required) && o.forbidden.equals(this.forbidden); return ret; } public int hashCode() { int result = 17; result = 37*result + required.hashCode(); result = 37*result + forbidden.hashCode(); return result; } public ThrowsPattern resolveBindings(IScope scope, Bindings bindings) { if (this == ANY) return this; required = required.resolveBindings(scope, bindings, false, false); forbidden = forbidden.resolveBindings(scope, bindings, false, false); return this; } public ThrowsPattern resolveBindingsFromRTTI() { required = required.resolveBindingsFromRTTI(false,false); forbidden = forbidden.resolveBindingsFromRTTI(false,false); return this; } public ThrowsPattern parameterizeWith(Map/*name -> resolved type*/ typeVariableMap) { ThrowsPattern ret = new ThrowsPattern( required.parameterizeWith(typeVariableMap), forbidden.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public boolean matches(UnresolvedType[] tys, World world) { if (this == ANY) return true; //System.out.println("matching: " + this + " with " + Arrays.asList(tys)); ResolvedType[] types = world.resolve(tys); // int len = types.length; for (int j=0, lenj = required.size(); j < lenj; j++) { if (! matchesAny(required.get(j), types)) { return false; } } for (int j=0, lenj = forbidden.size(); j < lenj; j++) { if (matchesAny(forbidden.get(j), types)) { return false; } } return true; } public boolean matches(Class[] onTypes) { if (this == ANY) return true; //System.out.println("matching: " + this + " with " + Arrays.asList(tys)); for (int j=0, lenj = required.size(); j < lenj; j++) { if (! matchesAny(required.get(j), onTypes)) { return false; } } for (int j=0, lenj = forbidden.size(); j < lenj; j++) { if (matchesAny(forbidden.get(j), onTypes)) { return false; } } return true; } private boolean matchesAny( TypePattern typePattern, ResolvedType[] types) { for (int i = types.length - 1; i >= 0; i--) { if (typePattern.matchesStatically(types[i])) return true; } return false; } private boolean matchesAny(TypePattern typePattern, Class[] types) { for (int i = types.length - 1; i >= 0; i--) { if (typePattern.matchesStatically(types[i])) return true; } return false; } public static ThrowsPattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { TypePatternList required = TypePatternList.read(s, context); TypePatternList forbidden = TypePatternList.read(s, context); if (required.size() == 0 && forbidden.size() == 0) return ANY; ThrowsPattern ret = new ThrowsPattern(required, forbidden); //XXXret.readLocation(context, s); return ret; } public void write(DataOutputStream s) throws IOException { required.write(s); forbidden.write(s); //XXXwriteLocation(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); forbidden.traverse(visitor, data); required.traverse(visitor, data); return ret; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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"); } } // methods for dynamic pc matching... public final FuzzyBoolean matches(Class toMatch, MatchKind kind) { if (kind == STATIC) { return FuzzyBoolean.fromBoolean(matchesStatically(toMatch)); } else if (kind == DYNAMIC) { //System.err.println("matching: " + this + " with " + type); FuzzyBoolean ret = matchesInstanceof(toMatch); //System.err.println(" got: " + ret); return ret; } else { throw new IllegalArgumentException("kind must be DYNAMIC or STATIC"); } } /** * This variant is only called by the args and handler pcds when doing runtime * matching. We need to handle primitive types correctly in this case (an Integer * should match an int,...). */ public final FuzzyBoolean matches(Object o, MatchKind kind) { if (kind == STATIC) { // handler pcd return FuzzyBoolean.fromBoolean(matchesStatically(o.getClass())); } else if (kind == DYNAMIC) { // args pcd // Class clazz = o.getClass(); // FuzzyBoolean ret = FuzzyBoolean.fromBoolean(matchesSubtypes(clazz)); // if (ret == FuzzyBoolean.NO) { // // try primitive type instead // if (clazz == Integer.class) ret = FuzzyBoolean.fromBoolean(matchesExactly(int.class)); // } // return ret; return matchesInstanceof(o.getClass()); } else { throw new IllegalArgumentException("kind must be DYNAMIC or STATIC"); } } public boolean matchesStatically(Class toMatch) { if (includeSubtypes) { return matchesSubtypes(toMatch); } else { return matchesExactly(toMatch); } } public abstract FuzzyBoolean matchesInstanceof(Class toMatch); protected abstract boolean matchesExactly(Class toMatch); protected boolean matchesSubtypes(Class toMatch) { if (matchesExactly(toMatch)) { return true; } Class superClass = toMatch.getSuperclass(); if (superClass != null) { return matchesSubtypes(superClass); } return false; } 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 TypePattern resolveBindingsFromRTTI(boolean allowBindng, boolean requireExactType) { 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.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(Class type) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(Class 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.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(Class type) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(Class 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; } protected boolean matchesExactly(Class type) { return true; } public FuzzyBoolean matchesInstanceof(Class type) { return FuzzyBoolean.YES; } 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.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(Class type) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(Class 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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/TypePatternList.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.List; import java.util.Map; import org.aspectj.util.FuzzyBoolean; 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; public class TypePatternList extends PatternNode { private TypePattern[] typePatterns; int ellipsisCount = 0; public static final TypePatternList EMPTY = new TypePatternList(new TypePattern[] {}); public static final TypePatternList ANY = new TypePatternList(new TypePattern[] {new EllipsisTypePattern()}); //can't use TypePattern.ELLIPSIS because of circular static dependency that introduces public TypePatternList() { typePatterns = new TypePattern[0]; ellipsisCount = 0; } public TypePatternList(TypePattern[] arguments) { this.typePatterns = arguments; for (int i=0; i<arguments.length; i++) { if (arguments[i] == TypePattern.ELLIPSIS) ellipsisCount++; } } public TypePatternList(List l) { this((TypePattern[]) l.toArray(new TypePattern[l.size()])); } public int size() { return typePatterns.length; } public TypePattern get(int index) { return typePatterns[index]; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("("); for (int i=0, len=typePatterns.length; i < len; i++) { TypePattern type = typePatterns[i]; if (i > 0) buf.append(", "); if (type == TypePattern.ELLIPSIS) { buf.append(".."); } else { buf.append(type.toString()); } } buf.append(")"); return buf.toString(); } /** * Used by reflection-based matching for args pcds. * Returns YES if types will always be matched by the pattern, * NO if types do not match the pattern, * MAYBE if types may match the pattern dependent on a runtime test */ public FuzzyBoolean matchesArgsPatternSubset(Class[] types) { int argsLength = types.length; int patternLength = typePatterns.length; int argsIndex = 0; if ((argsLength < patternLength) && (ellipsisCount == 0)) return FuzzyBoolean.NO; if (argsLength < (patternLength -1)) return FuzzyBoolean.NO; int ellipsisMatchCount = argsLength - (patternLength - ellipsisCount); FuzzyBoolean ret = FuzzyBoolean.YES; for (int i = 0; i < typePatterns.length; i++) { if (typePatterns[i] == TypePattern.ELLIPSIS) { // match ellipsisMatchCount args argsIndex += ellipsisMatchCount; } else if (typePatterns[i] == TypePattern.ANY) { argsIndex++; } else { // be defensive, might see a type-pattern NO if (! (typePatterns[i] instanceof ExactTypePattern)) { return FuzzyBoolean.NO; } // match the argument type at argsIndex with the ExactTypePattern // we it is exact because nothing else is allowed in args ExactTypePattern tp = (ExactTypePattern)typePatterns[i]; FuzzyBoolean matches = tp.willMatchDynamically(types[argsIndex]); if (matches == FuzzyBoolean.NO) { return FuzzyBoolean.NO; } else { argsIndex++; ret = ret.and(matches); } } } return ret; } //XXX shares much code with WildTypePattern and with NamePattern /** * When called with TypePattern.STATIC this will always return either * FuzzyBoolean.YES or FuzzyBoolean.NO. * * When called with TypePattern.DYNAMIC this could return MAYBE if * at runtime it would be possible for arguments of the given static * types to dynamically match this, but it is not known for certain. * * This method will never return FuzzyBoolean.NEVER */ public FuzzyBoolean matches(ResolvedType[] types, TypePattern.MatchKind kind) { int nameLength = types.length; int patternLength = typePatterns.length; int nameIndex = 0; int patternIndex = 0; if (ellipsisCount == 0) { if (nameLength != patternLength) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (patternIndex < patternLength) { FuzzyBoolean ret = typePatterns[patternIndex++].matches(types[nameIndex++], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; } return finalReturn; } else if (ellipsisCount == 1) { if (nameLength < patternLength-1) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (patternIndex < patternLength) { TypePattern p = typePatterns[patternIndex++]; if (p == TypePattern.ELLIPSIS) { nameIndex = nameLength - (patternLength-patternIndex); } else { FuzzyBoolean ret = p.matches(types[nameIndex++], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; } } return finalReturn; } else { // System.err.print("match(" + arguments + ", " + types + ") -> "); FuzzyBoolean b = outOfStar(typePatterns, types, 0, 0, patternLength - ellipsisCount, nameLength, ellipsisCount, kind); // System.err.println(b); return b; } } // TODO Add TypePatternList.matches(Object[] objs) public FuzzyBoolean matches(Object[] objs, TypePattern.MatchKind kind) { int nameLength = objs.length; int patternLength = typePatterns.length; int nameIndex = 0; int patternIndex = 0; if (ellipsisCount == 0) { if (nameLength != patternLength) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (patternIndex < patternLength) { FuzzyBoolean ret = typePatterns[patternIndex++].matches(objs[nameIndex++],kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; } return finalReturn; } else if (ellipsisCount == 1) { if (nameLength < patternLength-1) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (patternIndex < patternLength) { TypePattern p = typePatterns[patternIndex++]; if (p == TypePattern.ELLIPSIS) { nameIndex = nameLength - (patternLength-patternIndex); } else { FuzzyBoolean ret = p.matches(objs[nameIndex++],kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; } } return finalReturn; } else { // System.err.print("match(" + arguments + ", " + types + ") -> "); FuzzyBoolean b = outOfStar(typePatterns, objs, 0, 0, patternLength - ellipsisCount, nameLength, ellipsisCount, kind); // System.err.println(b); return b; } } // XXX run-time signature matching, too much duplicated code public FuzzyBoolean matches(Class[] types, TypePattern.MatchKind kind) { int nameLength = types.length; int patternLength = typePatterns.length; int nameIndex = 0; int patternIndex = 0; if (ellipsisCount == 0) { if (nameLength != patternLength) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (patternIndex < patternLength) { FuzzyBoolean ret = typePatterns[patternIndex++].matches(types[nameIndex++], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; } return finalReturn; } else if (ellipsisCount == 1) { if (nameLength < patternLength-1) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (patternIndex < patternLength) { TypePattern p = typePatterns[patternIndex++]; if (p == TypePattern.ELLIPSIS) { nameIndex = nameLength - (patternLength-patternIndex); } else { FuzzyBoolean ret = p.matches(types[nameIndex++], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; } } return finalReturn; } else { // System.err.print("match(" + arguments + ", " + types + ") -> "); FuzzyBoolean b = outOfStar(typePatterns, types, 0, 0, patternLength - ellipsisCount, nameLength, ellipsisCount, kind); // System.err.println(b); return b; } } private static FuzzyBoolean outOfStar(final TypePattern[] pattern, final ResolvedType[] target, int pi, int ti, int pLeft, int tLeft, final int starsLeft, TypePattern.MatchKind kind) { if (pLeft > tLeft) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (true) { // invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length) if (tLeft == 0) return finalReturn; if (pLeft == 0) { if (starsLeft > 0) { return finalReturn; } else { return FuzzyBoolean.NO; } } if (pattern[pi] == TypePattern.ELLIPSIS) { return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1, kind); } FuzzyBoolean ret = pattern[pi].matches(target[ti], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; pi++; ti++; pLeft--; tLeft--; } } private static FuzzyBoolean inStar(final TypePattern[] pattern, final ResolvedType[] target, int pi, int ti, final int pLeft, int tLeft, int starsLeft, TypePattern.MatchKind kind) { // invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern TypePattern patternChar = pattern[pi]; while (patternChar == TypePattern.ELLIPSIS) { starsLeft--; patternChar = pattern[++pi]; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length) if (pLeft > tLeft) return FuzzyBoolean.NO; FuzzyBoolean ff = patternChar.matches(target[ti], kind); if (ff.maybeTrue()) { FuzzyBoolean xx = outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft, kind); if (xx.maybeTrue()) return ff.and(xx); } ti++; tLeft--; } } private static FuzzyBoolean outOfStar(final TypePattern[] pattern, final Class[] target, int pi, int ti, int pLeft, int tLeft, final int starsLeft, TypePattern.MatchKind kind) { if (pLeft > tLeft) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (true) { // invariant: if (tLeft > 0) then (ti < target.length && pi < // pattern.length) if (tLeft == 0) return finalReturn; if (pLeft == 0) { if (starsLeft > 0) { return finalReturn; } else { return FuzzyBoolean.NO; } } if (pattern[pi] == TypePattern.ELLIPSIS) { return inStar(pattern, target, pi + 1, ti, pLeft, tLeft, starsLeft - 1, kind); } FuzzyBoolean ret = pattern[pi].matches(target[ti], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; pi++; ti++; pLeft--; tLeft--; } } private static FuzzyBoolean inStar(final TypePattern[] pattern, final Class[] target, int pi, int ti, final int pLeft, int tLeft, int starsLeft, TypePattern.MatchKind kind) { // invariant: pLeft > 0, so we know we'll run out of stars and find a // real char in pattern TypePattern patternChar = pattern[pi]; while (patternChar == TypePattern.ELLIPSIS) { starsLeft--; patternChar = pattern[++pi]; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length) if (pLeft > tLeft) return FuzzyBoolean.NO; FuzzyBoolean ff = patternChar.matches(target[ti], kind); if (ff.maybeTrue()) { FuzzyBoolean xx = outOfStar(pattern, target, pi + 1, ti + 1, pLeft - 1, tLeft - 1, starsLeft, kind); if (xx.maybeTrue()) return ff.and(xx); } ti++; tLeft--; } } private static FuzzyBoolean outOfStar(final TypePattern[] pattern, final Object[] target, int pi, int ti, int pLeft, int tLeft, final int starsLeft, TypePattern.MatchKind kind) { if (pLeft > tLeft) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (true) { // invariant: if (tLeft > 0) then (ti < target.length && pi < // pattern.length) if (tLeft == 0) return finalReturn; if (pLeft == 0) { if (starsLeft > 0) { return finalReturn; } else { return FuzzyBoolean.NO; } } if (pattern[pi] == TypePattern.ELLIPSIS) { return inStar(pattern, target, pi + 1, ti, pLeft, tLeft, starsLeft - 1,kind); } FuzzyBoolean ret = pattern[pi].matches(target[ti],kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; pi++; ti++; pLeft--; tLeft--; } } private static FuzzyBoolean inStar(final TypePattern[] pattern, final Object[] target, int pi, int ti, final int pLeft, int tLeft, int starsLeft, TypePattern.MatchKind kind) { // invariant: pLeft > 0, so we know we'll run out of stars and find a // real char in pattern TypePattern patternChar = pattern[pi]; while (patternChar == TypePattern.ELLIPSIS) { starsLeft--; patternChar = pattern[++pi]; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length) if (pLeft > tLeft) return FuzzyBoolean.NO; FuzzyBoolean ff = patternChar.matches(target[ti],kind); if (ff.maybeTrue()) { FuzzyBoolean xx = outOfStar(pattern, target, pi + 1, ti + 1, pLeft - 1, tLeft - 1, starsLeft,kind); if (xx.maybeTrue()) return ff.and(xx); } ti++; tLeft--; } } /** * Return a version of this type pattern list in which all type variable references * are replaced by their corresponding entry in the map * @param typeVariableMap * @return */ public TypePatternList parameterizeWith(Map typeVariableMap) { TypePattern[] parameterizedPatterns = new TypePattern[typePatterns.length]; for (int i = 0; i < parameterizedPatterns.length; i++) { parameterizedPatterns[i] = typePatterns[i].parameterizeWith(typeVariableMap); } return new TypePatternList(parameterizedPatterns); } public TypePatternList resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { for (int i=0; i<typePatterns.length; i++) { TypePattern p = typePatterns[i]; if (p != null) { typePatterns[i] = typePatterns[i].resolveBindings(scope, bindings, allowBinding, requireExactType); } } return this; } public TypePatternList resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { for (int i=0; i<typePatterns.length; i++) { TypePattern p = typePatterns[i]; if (p != null) { typePatterns[i] = typePatterns[i].resolveBindingsFromRTTI(allowBinding, requireExactType); } } return this; } public TypePatternList resolveReferences(IntMap bindings) { int len = typePatterns.length; TypePattern[] ret = new TypePattern[len]; for (int i=0; i < len; i++) { ret[i] = typePatterns[i].remapAdviceFormals(bindings); } return new TypePatternList(ret); } public void postRead(ResolvedType enclosingType) { for (int i=0; i<typePatterns.length; i++) { TypePattern p = typePatterns[i]; p.postRead(enclosingType); } } public boolean equals(Object other) { if (!(other instanceof TypePatternList)) return false; TypePatternList o = (TypePatternList)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 TypePatternList read(VersionedDataInputStream s, ISourceContext context) throws IOException { short len = s.readShort(); TypePattern[] arguments = new TypePattern[len]; for (int i=0; i<len; i++) { arguments[i] = TypePattern.read(s, context); } TypePatternList ret = new TypePatternList(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 TypePattern[] getTypePatterns() { return typePatterns; } public Collection getExactTypes() { ArrayList ret = new ArrayList(); for (int i=0; i<typePatterns.length; i++) { UnresolvedType t = typePatterns[i].getExactType(); if (t != ResolvedType.MISSING) ret.add(t); } return ret; } 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; } public boolean areAllExactWithNoSubtypesAllowed() { for (int i = 0; i < typePatterns.length; i++) { TypePattern array_element = typePatterns[i]; if (!(array_element instanceof ExactTypePattern)) { return false; } else { ExactTypePattern etp = (ExactTypePattern) array_element; if (etp.isIncludeSubtypes()) return false; } } return true; } public String[] maybeGetCleanNames() { String[] theParamNames = new String[typePatterns.length]; for (int i = 0; i < typePatterns.length; i++) { TypePattern string = typePatterns[i]; if (!(string instanceof ExactTypePattern)) return null; theParamNames[i] = ((ExactTypePattern)string).getExactType().getName(); } return theParamNames; } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/patterns/WildTypePattern.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.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.UnresolvedTypeVariableReferenceType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * The PatternParser always creates WildTypePatterns for type patterns in pointcut * expressions (apart from *, which is sometimes directly turned into TypePattern.ANY). * resolveBindings() tries to work out what we've really got and turn it into a type * pattern that we can use for matching. This will normally be either an ExactTypePattern * or a WildTypePattern. * * Here's how the process pans out for various generic and parameterized patterns: * (see GenericsWildTypePatternResolvingTestCase) * * Foo where Foo exists and is generic * Parser creates WildTypePattern namePatterns={Foo} * resolveBindings resolves Foo to RT(Foo - raw) * return ExactTypePattern(LFoo;) * * Foo<String> where Foo exists and String meets the bounds * Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{String} * resolveBindings resolves typeParameters to ExactTypePattern(String) * resolves Foo to RT(Foo) * returns ExactTypePattern(PFoo<String>; - parameterized) * * Foo<Str*> where Foo exists and takes one bound * Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{Str*} * resolveBindings resolves typeParameters to WTP{Str*} * resolves Foo to RT(Foo) * returns WildTypePattern(name = Foo, typeParameters = WTP{Str*} isGeneric=false) * * Fo*<String> * Parser creates WildTypePattern namePatterns = {Fo*}, typeParameters=WTP{String} * resolveBindings resolves typeParameters to ETP{String} * returns WildTypePattern(name = Fo*, typeParameters = ETP{String} isGeneric=false) * * * Foo<?> * * Foo<? extends Number> * * Foo<? extends Number+> * * Foo<? super Number> * */ public class WildTypePattern extends TypePattern { private static final String GENERIC_WILDCARD_CHARACTER = "?"; private NamePattern[] namePatterns; int ellipsisCount; String[] importedPrefixes; String[] knownMatches; int dim; // these next three are set if the type pattern is constrained by extends or super clauses, in which case the // namePatterns must have length 1 // TODO AMC: read/write/resolve of these fields TypePattern upperBound; // extends Foo TypePattern[] additionalInterfaceBounds; // extends Foo & A,B,C TypePattern lowerBound; // super Foo // if we have type parameters, these fields indicate whether we should be a generic type pattern or a parameterized // type pattern. We can only tell during resolve bindings. private boolean isGeneric = true; WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim, boolean isVarArgs, TypePatternList typeParams) { super(includeSubtypes,isVarArgs,typeParams); this.namePatterns = namePatterns; this.dim = dim; ellipsisCount = 0; for (int i=0; i<namePatterns.length; i++) { if (namePatterns[i] == NamePattern.ELLIPSIS) ellipsisCount++; } setLocation(namePatterns[0].getSourceContext(), namePatterns[0].getStart(), namePatterns[namePatterns.length-1].getEnd()); } public WildTypePattern(List names, boolean includeSubtypes, int dim) { this((NamePattern[])names.toArray(new NamePattern[names.size()]), includeSubtypes, dim,false,TypePatternList.EMPTY); } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) { this(names, includeSubtypes, dim); this.end = endPos; } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg) { this(names, includeSubtypes, dim); this.end = endPos; this.isVarArgs = isVarArg; } public WildTypePattern( List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg, TypePatternList typeParams, TypePattern upperBound, TypePattern[] additionalInterfaceBounds, TypePattern lowerBound) { this((NamePattern[])names.toArray(new NamePattern[names.size()]),includeSubtypes,dim,isVarArg,typeParams); this.end = endPos; this.upperBound = upperBound; this.lowerBound = lowerBound; this.additionalInterfaceBounds = additionalInterfaceBounds; } public WildTypePattern( List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg, TypePatternList typeParams) { this((NamePattern[])names.toArray(new NamePattern[names.size()]),includeSubtypes,dim,isVarArg,typeParams); this.end = endPos; } public NamePattern[] getNamePatterns() { return namePatterns; } public TypePattern getUpperBound() { return upperBound; } public TypePattern getLowerBound() { return lowerBound; } public TypePattern[] getAdditionalIntefaceBounds() { return additionalInterfaceBounds; } // called by parser after parsing a type pattern, must bump dim as well as setting flag public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; if (isVarArgs) this.dim += 1; } /* (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) { if (namePatterns.length > 0) { if (!namePatterns[0].matches(otherType.getName())) return false; } } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String mySimpleName = namePatterns[0].maybeGetSimpleName(); String yourSimpleName = owtp.namePatterns[0].maybeGetSimpleName(); if (mySimpleName != null && yourSimpleName != null) { return (mySimpleName.startsWith(yourSimpleName) || yourSimpleName.startsWith(mySimpleName)); } } return true; } //XXX inefficient implementation public static char[][] splitNames(String s) { List ret = new ArrayList(); int startIndex = 0; while (true) { int breakIndex = s.indexOf('.', startIndex); // what about / if (breakIndex == -1) breakIndex = s.indexOf('$', startIndex); // we treat $ like . here if (breakIndex == -1) break; char[] name = s.substring(startIndex, breakIndex).toCharArray(); ret.add(name); startIndex = breakIndex+1; } ret.add(s.substring(startIndex).toCharArray()); return (char[][])ret.toArray(new char[ret.size()][]); } /** * @see org.aspectj.weaver.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return matchesExactly(type,type); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { String targetTypeName = type.getName(); //System.err.println("match: " + targetTypeName + ", " + knownMatches); //Arrays.asList(importedPrefixes)); // Ensure the annotation pattern is resolved annotationPattern.resolve(type.getWorld()); return matchesExactlyByName(targetTypeName) && matchesParameters(type,STATIC) && matchesBounds(type,STATIC) && annotationPattern.matches(annotatedType).alwaysTrue(); } // we've matched against the base (or raw) type, but if this type pattern specifies parameters or // type variables we need to make sure we match against them too private boolean matchesParameters(ResolvedType aType, MatchKind staticOrDynamic) { if (!isGeneric && typeParameters.size() > 0) { if(!aType.isParameterizedType()) return false; // we have to match type parameters return typeParameters.matches(aType.getResolvedTypeParameters(), staticOrDynamic).alwaysTrue(); } return true; } // we've matched against the base (or raw) type, but if this type pattern specifies bounds because // it is a ? extends or ? super deal then we have to match them too. private boolean matchesBounds(ResolvedType aType, MatchKind staticOrDynamic) { if (upperBound == null && aType.getUpperBound() != null) { // for upper bound, null can also match against Object - but anything else and we're out. if (!aType.getUpperBound().getName().equals(UnresolvedType.OBJECT.getName())) { return false; } } if (lowerBound == null && aType.getLowerBound() != null) return false; if (upperBound != null) { // match ? extends if (aType.isGenericWildcard() && aType.isSuper()) return false; if (aType.getUpperBound() == null) return false; return upperBound.matches((ResolvedType)aType.getUpperBound(),staticOrDynamic).alwaysTrue(); } if (lowerBound != null) { // match ? super if (!(aType.isGenericWildcard() && aType.isSuper())) return false; return lowerBound.matches((ResolvedType)aType.getLowerBound(),staticOrDynamic).alwaysTrue(); } return true; } /** * Used in conjunction with checks on 'isStar()' to tell you if this pattern represents '*' or '*[]' which are * different ! */ public int getDimensions() { return dim; } public boolean isArray() { return dim > 1; } /** * @param targetTypeName * @return */ private boolean matchesExactlyByName(String targetTypeName) { // we deal with parameter matching separately... if (targetTypeName.indexOf('<') != -1) { targetTypeName = targetTypeName.substring(0,targetTypeName.indexOf('<')); } // we deal with bounds matching separately too... if (targetTypeName.startsWith(GENERIC_WILDCARD_CHARACTER)) { targetTypeName = GENERIC_WILDCARD_CHARACTER; } //XXX hack if (knownMatches == null && importedPrefixes == null) { return innerMatchesExactly(targetTypeName); } if (isNamePatternStar()) { // we match if the dimensions match int numDimensionsInTargetType = 0; if (dim > 0) { int index; while((index = targetTypeName.indexOf('[')) != -1) { numDimensionsInTargetType++; targetTypeName = targetTypeName.substring(index+1); } if (numDimensionsInTargetType == dim) { return true; } else { return false; } } } // if our pattern is length 1, then known matches are exact matches // if it's longer than that, then known matches are prefixes of a sort if (namePatterns.length == 1) { for (int i=0, len=knownMatches.length; i < len; i++) { if (knownMatches[i].equals(targetTypeName)) return true; } } else { for (int i=0, len=knownMatches.length; i < len; i++) { String knownPrefix = knownMatches[i] + "$"; if (targetTypeName.startsWith(knownPrefix)) { int pos = lastIndexOfDotOrDollar(knownMatches[i]); if (innerMatchesExactly(targetTypeName.substring(pos+1))) { return true; } } } } // if any prefixes match, strip the prefix and check that the rest matches // assumes that prefixes have a dot at the end for (int i=0, len=importedPrefixes.length; i < len; i++) { String prefix = importedPrefixes[i]; //System.err.println("prefix match? " + prefix + " to " + targetTypeName); if (targetTypeName.startsWith(prefix)) { if (innerMatchesExactly(targetTypeName.substring(prefix.length()))) { return true; } } } return innerMatchesExactly(targetTypeName); } private int lastIndexOfDotOrDollar(String string) { int dot = string.lastIndexOf('.'); int dollar = string.lastIndexOf('$'); return Math.max(dot, dollar); } private boolean innerMatchesExactly(String targetTypeName) { //??? doing this everytime is not very efficient char[][] names = splitNames(targetTypeName); return innerMatchesExactly(names); } private boolean innerMatchesExactly(char[][] names) { int namesLength = names.length; int patternsLength = namePatterns.length; int namesIndex = 0; int patternsIndex = 0; if (ellipsisCount == 0) { if (namesLength != patternsLength) return false; while (patternsIndex < patternsLength) { if (!namePatterns[patternsIndex++].matches(names[namesIndex++])) { return false; } } return true; } else if (ellipsisCount == 1) { if (namesLength < patternsLength-1) return false; while (patternsIndex < patternsLength) { NamePattern p = namePatterns[patternsIndex++]; if (p == NamePattern.ELLIPSIS) { namesIndex = namesLength - (patternsLength-patternsIndex); } else { if (!p.matches(names[namesIndex++])) { return false; } } } return true; } else { // System.err.print("match(\"" + Arrays.asList(namePatterns) + "\", \"" + Arrays.asList(names) + "\") -> "); boolean b = outOfStar(namePatterns, names, 0, 0, patternsLength - ellipsisCount, namesLength, ellipsisCount); // System.err.println(b); return b; } } private static boolean outOfStar(final NamePattern[] pattern, final char[][] target, int pi, int ti, int pLeft, int tLeft, final int starsLeft) { if (pLeft > tLeft) return false; while (true) { // invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length) if (tLeft == 0) return true; if (pLeft == 0) { return (starsLeft > 0); } if (pattern[pi] == NamePattern.ELLIPSIS) { return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1); } if (! pattern[pi].matches(target[ti])) { return false; } pi++; ti++; pLeft--; tLeft--; } } private static boolean inStar(final NamePattern[] pattern, final char[][] target, int pi, int ti, final int pLeft, int tLeft, int starsLeft) { // invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern // of course, we probably can't parse multiple ..'s in a row, but this keeps the algorithm // exactly parallel with that in NamePattern NamePattern patternChar = pattern[pi]; while (patternChar == NamePattern.ELLIPSIS) { starsLeft--; patternChar = pattern[++pi]; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length) if (pLeft > tLeft) return false; if (patternChar.matches(target[ti])) { if (outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft)) return true; } ti++; tLeft--; } } /** * @see org.aspectj.weaver.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { //XXX hack to let unmatched types just silently remain so if (maybeGetSimpleName() != null) return FuzzyBoolean.NO; type.getWorld().getMessageHandler().handleMessage( new Message("can't do instanceof matching on patterns with wildcards", IMessage.ERROR, null, getSourceLocation())); return FuzzyBoolean.NO; } public NamePattern extractName() { if (isIncludeSubtypes() || isVarArgs() || isArray() || (typeParameters.size() > 0)) { // we can't extract a name, the pattern is something like Foo+ and therefore // it is not ok to treat Foo as a method name! return null; } //System.err.println("extract from : " + Arrays.asList(namePatterns)); int len = namePatterns.length; if (len ==1 && !annotationPattern.isAny()) return null; // can't extract NamePattern ret = namePatterns[len-1]; NamePattern[] newNames = new NamePattern[len-1]; System.arraycopy(namePatterns, 0, newNames, 0, len-1); namePatterns = newNames; //System.err.println(" left : " + Arrays.asList(namePatterns)); return ret; } /** * Method maybeExtractName. * @param string * @return boolean */ public boolean maybeExtractName(String string) { int len = namePatterns.length; NamePattern ret = namePatterns[len-1]; String simple = ret.maybeGetSimpleName(); if (simple != null && simple.equals(string)) { extractName(); return true; } return false; } /** * If this type pattern has no '.' or '*' in it, then * return a simple string * * otherwise, this will return null; */ public String maybeGetSimpleName() { if (namePatterns.length == 1) { return namePatterns[0].maybeGetSimpleName(); } return null; } /** * If this type pattern has no '*' or '..' in it */ public String maybeGetCleanName() { if (namePatterns.length == 0) { throw new RuntimeException("bad name: " + namePatterns); } //System.out.println("get clean: " + this); StringBuffer buf = new StringBuffer(); for (int i=0, len=namePatterns.length; i < len; i++) { NamePattern p = namePatterns[i]; String simpleName = p.maybeGetSimpleName(); if (simpleName == null) return null; if (i > 0) buf.append("."); buf.append(simpleName); } //System.out.println(buf); return buf.toString(); } public TypePattern parameterizeWith(Map typeVariableMap) { WildTypePattern ret = new WildTypePattern( namePatterns, includeSubtypes, dim, isVarArgs, typeParameters.parameterizeWith(typeVariableMap) ); ret.annotationPattern = this.annotationPattern.parameterizeWith(typeVariableMap); ret.additionalInterfaceBounds = new TypePattern[additionalInterfaceBounds.length]; for (int i = 0; i < additionalInterfaceBounds.length; i++) { ret.additionalInterfaceBounds[i] = additionalInterfaceBounds[i].parameterizeWith(typeVariableMap); } ret.upperBound = upperBound.parameterizeWith(typeVariableMap); ret.lowerBound = lowerBound.parameterizeWith(typeVariableMap); ret.isGeneric = isGeneric; ret.knownMatches = knownMatches; ret.importedPrefixes = importedPrefixes; ret.copyLocationFrom(this); return ret; } /** * Need to determine if I'm really a pattern or a reference to a formal * * We may wish to further optimize the case of pattern vs. non-pattern * * We will be replaced by what we return */ public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (isNamePatternStar()) { TypePattern anyPattern = maybeResolveToAnyPattern(scope, bindings, allowBinding, requireExactType); if (anyPattern != null) { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } else { return anyPattern; } } } TypePattern bindingTypePattern = maybeResolveToBindingTypePattern(scope, bindings, allowBinding, requireExactType); if (bindingTypePattern != null) return bindingTypePattern; annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); // resolve any type parameters if (typeParameters!=null && typeParameters.size()>0) { typeParameters.resolveBindings(scope,bindings,allowBinding,requireExactType); isGeneric = false; } // resolve any bounds if (upperBound != null) upperBound = upperBound.resolveBindings(scope, bindings, allowBinding, requireExactType); if (lowerBound != null) lowerBound = lowerBound.resolveBindings(scope, bindings, allowBinding, requireExactType); // amc - additional interface bounds only needed if we support type vars again. String fullyQualifiedName = maybeGetCleanName(); if (fullyQualifiedName != null) { return resolveBindingsFromFullyQualifiedTypeName(fullyQualifiedName, scope, bindings, allowBinding, requireExactType); } else { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; // pattern contains wildcards so can't be resolved to an ExactTypePattern... //XXX need to implement behavior for Lint.invalidWildcardTypeName } } private TypePattern maybeResolveToAnyPattern(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { // If there is an annotation specified we have to // use a special variant of Any TypePattern called // AnyWithAnnotation if (annotationPattern == AnnotationTypePattern.ANY) { if (dim == 0 && !isVarArgs && upperBound == null && lowerBound == null && (additionalInterfaceBounds == null || additionalInterfaceBounds.length==0)) { // pr72531 return TypePattern.ANY; //??? loses source location } } else { annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annotationPattern); ret.setLocation(sourceContext,start,end); return ret; } return null; // can't resolve to a simple "any" pattern } private TypePattern maybeResolveToBindingTypePattern(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { String simpleName = maybeGetSimpleName(); if (simpleName != null) { FormalBinding formalBinding = scope.lookupFormal(simpleName); if (formalBinding != null) { if (bindings == null) { scope.message(IMessage.ERROR, this, "negation doesn't allow binding"); return this; } if (!allowBinding) { scope.message(IMessage.ERROR, this, "name binding only allowed in target, this, and args pcds"); return this; } BindingTypePattern binding = new BindingTypePattern(formalBinding,isVarArgs); binding.copyLocationFrom(this); bindings.register(binding, scope); return binding; } } return null; // not possible to resolve to a binding type pattern } private TypePattern resolveBindingsFromFullyQualifiedTypeName(String fullyQualifiedName, IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { String originalName = fullyQualifiedName; ResolvedType resolvedTypeInTheWorld = null; UnresolvedType type; //System.out.println("resolve: " + cleanName); //??? this loop has too many inefficiencies to count resolvedTypeInTheWorld = lookupTypeInWorld(scope.getWorld(), fullyQualifiedName); if (resolvedTypeInTheWorld.isGenericWildcard()) { type = resolvedTypeInTheWorld; } else { type = lookupTypeInScope(scope, fullyQualifiedName, this); } if (type == ResolvedType.MISSING) { return resolveBindingsForMissingType(resolvedTypeInTheWorld, originalName, scope, bindings, allowBinding, requireExactType); } else { return resolveBindingsForExactType(scope,type,fullyQualifiedName,requireExactType); } } private UnresolvedType lookupTypeInScope(IScope scope, String typeName, IHasPosition location) { UnresolvedType type = null; while ((type = scope.lookupType(typeName, location)) == ResolvedType.MISSING) { int lastDot = typeName.lastIndexOf('.'); if (lastDot == -1) break; typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot+1); } return type; } private ResolvedType lookupTypeInWorld(World world, String typeName) { ResolvedType ret = world.resolve(UnresolvedType.forName(typeName),true); while (ret == ResolvedType.MISSING) { int lastDot = typeName.lastIndexOf('.'); if (lastDot == -1) break; typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot+1); ret = world.resolve(UnresolvedType.forName(typeName),true); } return ret; } private TypePattern resolveBindingsForExactType(IScope scope, UnresolvedType aType, String fullyQualifiedName,boolean requireExactType) { TypePattern ret = null; if (aType.isTypeVariableReference()) { // we have to set the bounds on it based on the bounds of this pattern ret = resolveBindingsForTypeVariable(scope, (UnresolvedTypeVariableReferenceType) aType); } else if (typeParameters.size()>0) { ret = resolveParameterizedType(scope, aType, requireExactType); } else if (upperBound != null || lowerBound != null) { // this must be a generic wildcard with bounds ret = resolveGenericWildcard(scope, aType); } else { if (dim != 0) aType = UnresolvedType.makeArray(aType, dim); ret = new ExactTypePattern(aType,includeSubtypes,isVarArgs); } ret.setAnnotationTypePattern(annotationPattern); ret.copyLocationFrom(this); return ret; } private TypePattern resolveGenericWildcard(IScope scope, UnresolvedType aType) { if (!aType.getSignature().equals(GENERIC_WILDCARD_CHARACTER)) throw new IllegalStateException("Can only have bounds for a generic wildcard"); boolean canBeExact = true; if ((upperBound != null) && (upperBound.getExactType() == ResolvedType.MISSING)) canBeExact = false; if ((lowerBound != null) && (lowerBound.getExactType() == ResolvedType.MISSING)) canBeExact = false; if (canBeExact) { ResolvedType type = null; if (upperBound != null) { if (upperBound.isIncludeSubtypes()) { canBeExact = false; } else { ReferenceType upper = (ReferenceType) upperBound.getExactType().resolve(scope.getWorld()); type = new BoundedReferenceType(upper,true,scope.getWorld()); } } else { if (lowerBound.isIncludeSubtypes()) { canBeExact = false; } else { ReferenceType lower = (ReferenceType) lowerBound.getExactType().resolve(scope.getWorld()); type = new BoundedReferenceType(lower,false,scope.getWorld()); } } if (canBeExact) { // might have changed if we find out include subtypes is set on one of the bounds... return new ExactTypePattern(type,includeSubtypes,isVarArgs); } } // we weren't able to resolve to an exact type pattern... // leave as wild type pattern importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } private TypePattern resolveParameterizedType(IScope scope, UnresolvedType aType, boolean requireExactType) { if (!verifyTypeParameters(aType.resolve(scope.getWorld()),scope,requireExactType)) return TypePattern.NO; // messages already isued // Only if the type is exact *and* the type parameters are exact should we create an // ExactTypePattern for this WildTypePattern if (typeParameters.areAllExactWithNoSubtypesAllowed()) { TypePattern[] typePats = typeParameters.getTypePatterns(); UnresolvedType[] typeParameterTypes = new UnresolvedType[typePats.length]; for (int i = 0; i < typeParameterTypes.length; i++) { typeParameterTypes[i] = ((ExactTypePattern)typePats[i]).getExactType(); } ResolvedType type = TypeFactory.createParameterizedType(aType.resolve(scope.getWorld()), typeParameterTypes, scope.getWorld()); if (isGeneric) type = type.getGenericType(); // UnresolvedType tx = UnresolvedType.forParameterizedTypes(aType,typeParameterTypes); // UnresolvedType type = scope.getWorld().resolve(tx,true); if (dim != 0) type = ResolvedType.makeArray(type, dim); return new ExactTypePattern(type,includeSubtypes,isVarArgs); } else { // AMC... just leave it as a wild type pattern then? importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } } private TypePattern resolveBindingsForMissingType(ResolvedType typeFoundInWholeWorldSearch, String nameWeLookedFor, IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) { if (!allowBinding) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE,nameWeLookedFor), getSourceLocation())); } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation()); } return NO; } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { // Only put the lint warning out if we can't find it in the world if (typeFoundInWholeWorldSearch == ResolvedType.MISSING) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation()); } } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } /** * We resolved the type to a type variable declared in the pointcut designator. * Now we have to create either an exact type pattern or a wild type pattern for it, * with upper and lower bounds set accordingly. * XXX none of this stuff gets serialized yet * @param scope * @param tvrType * @return */ private TypePattern resolveBindingsForTypeVariable(IScope scope, UnresolvedTypeVariableReferenceType tvrType) { Bindings emptyBindings = new Bindings(0); if (upperBound != null) { upperBound = upperBound.resolveBindings(scope, emptyBindings, false, false); } if (lowerBound != null) { lowerBound = lowerBound.resolveBindings(scope, emptyBindings, false, false); } if (additionalInterfaceBounds != null) { TypePattern[] resolvedIfBounds = new TypePattern[additionalInterfaceBounds.length]; for (int i = 0; i < resolvedIfBounds.length; i++) { resolvedIfBounds[i] = additionalInterfaceBounds[i].resolveBindings(scope, emptyBindings, false, false); } additionalInterfaceBounds = resolvedIfBounds; } if ( upperBound == null && lowerBound == null && additionalInterfaceBounds == null) { // no bounds to worry about... ResolvedType rType = tvrType.resolve(scope.getWorld()); if (dim != 0) rType = ResolvedType.makeArray(rType, dim); return new ExactTypePattern(rType,includeSubtypes,isVarArgs); } else { // we have to set bounds on the TypeVariable held by tvrType before resolving it boolean canCreateExactTypePattern = true; if (upperBound != null && upperBound.getExactType() == ResolvedType.MISSING) canCreateExactTypePattern = false; if (lowerBound != null && lowerBound.getExactType() == ResolvedType.MISSING) canCreateExactTypePattern = false; if (additionalInterfaceBounds != null) { for (int i = 0; i < additionalInterfaceBounds.length; i++) { if (additionalInterfaceBounds[i].getExactType() == ResolvedType.MISSING) canCreateExactTypePattern = false; } } if (canCreateExactTypePattern) { TypeVariable tv = tvrType.getTypeVariable(); if (upperBound != null) tv.setUpperBound(upperBound.getExactType()); if (lowerBound != null) tv.setLowerBound(lowerBound.getExactType()); if (additionalInterfaceBounds != null) { UnresolvedType[] ifBounds = new UnresolvedType[additionalInterfaceBounds.length]; for (int i = 0; i < ifBounds.length; i++) { ifBounds[i] = additionalInterfaceBounds[i].getExactType(); } tv.setAdditionalInterfaceBounds(ifBounds); } ResolvedType rType = tvrType.resolve(scope.getWorld()); if (dim != 0) rType = ResolvedType.makeArray(rType, dim); return new ExactTypePattern(rType,includeSubtypes,isVarArgs); } return this; // leave as wild type pattern then } } /** * When this method is called, we have resolved the base type to an exact type. * We also have a set of type patterns for the parameters. * Time to perform some basic checks: * - can the base type be parameterized? (is it generic) * - can the type parameter pattern list match the number of parameters on the base type * - do all parameter patterns meet the bounds of the respective type variables * If any of these checks fail, a warning message is issued and we return false. * @return */ private boolean verifyTypeParameters(ResolvedType baseType,IScope scope, boolean requireExactType) { ResolvedType genericType = baseType.getGenericType(); if (genericType == null) { // issue message "does not match because baseType.getName() is not generic" scope.message(MessageUtil.warn( WeaverMessages.format(WeaverMessages.NOT_A_GENERIC_TYPE,baseType.getName()), getSourceLocation())); return false; } int minRequiredTypeParameters = typeParameters.size(); boolean foundEllipsis = false; TypePattern[] typeParamPatterns = typeParameters.getTypePatterns(); for (int i = 0; i < typeParamPatterns.length; i++) { if (typeParamPatterns[i] instanceof WildTypePattern) { WildTypePattern wtp = (WildTypePattern) typeParamPatterns[i]; if (wtp.ellipsisCount > 0) { foundEllipsis = true; minRequiredTypeParameters--; } } } TypeVariable[] tvs = genericType.getTypeVariables(); if ((tvs.length < minRequiredTypeParameters) || (!foundEllipsis && minRequiredTypeParameters != tvs.length)) { // issue message "does not match because wrong no of type params" String msg = WeaverMessages.format(WeaverMessages.INCORRECT_NUMBER_OF_TYPE_ARGUMENTS, genericType.getName(),new Integer(tvs.length)); if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation())); else scope.message(MessageUtil.warn(msg,getSourceLocation())); return false; } // now check that each typeParameter pattern, if exact, matches the bounds // of the type variable. if (typeParameters.areAllExactWithNoSubtypesAllowed()) { for (int i = 0; i < tvs.length; i++) { UnresolvedType ut = typeParamPatterns[i].getExactType(); if (!tvs[i].canBeBoundTo(ut.resolve(scope.getWorld()))) { // issue message that type parameter does not meet specification String parameterName = ut.getName(); if (ut.isTypeVariableReference()) parameterName = ((TypeVariableReference)ut).getTypeVariable().getDisplayName(); String msg = WeaverMessages.format( WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS, parameterName, new Integer(i+1), tvs[i].getDisplayName(), genericType.getName()); if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation())); else scope.message(MessageUtil.warn(msg,getSourceLocation())); return false; } } } return true; } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { if (isStar()) { return TypePattern.ANY; //??? loses source location } String cleanName = maybeGetCleanName(); if (cleanName != null) { Class clazz = null; clazz = maybeGetPrimitiveClass(cleanName); while (clazz == null) { try { clazz = Class.forName(cleanName); } catch (ClassNotFoundException cnf) { int lastDotIndex = cleanName.lastIndexOf('.'); if (lastDotIndex == -1) break; cleanName = cleanName.substring(0, lastDotIndex) + '$' + cleanName.substring(lastDotIndex+1); } } if (clazz == null) { try { clazz = Class.forName("java.lang." + cleanName); } catch (ClassNotFoundException cnf) { } } if (clazz == null) { if (requireExactType) { return NO; } } else { UnresolvedType type = UnresolvedType.forName(clazz.getName()); if (dim != 0) type = UnresolvedType.makeArray(type,dim); TypePattern ret = new ExactTypePattern(type, includeSubtypes,isVarArgs); ret.copyLocationFrom(this); return ret; } } else if (requireExactType) { return NO; } importedPrefixes = SimpleScope.javaLangPrefixArray; knownMatches = new String[0]; return this; } private Class maybeGetPrimitiveClass(String typeName) { return (Class) ExactTypePattern.primitiveTypesMap.get(typeName); } public boolean isStar() { boolean annPatternStar = annotationPattern == AnnotationTypePattern.ANY; return (isNamePatternStar() && annPatternStar); } private boolean isNamePatternStar() { return namePatterns.length == 1 && namePatterns[0].isAny(); } /** * returns those possible matches which I match exactly the last element of */ private String[] preMatch(String[] possibleMatches) { //if (namePatterns.length != 1) return CollectionUtil.NO_STRINGS; List ret = new ArrayList(); for (int i=0, len=possibleMatches.length; i < len; i++) { char[][] names = splitNames(possibleMatches[i]); //??? not most efficient if (namePatterns[0].matches(names[names.length-1])) { ret.add(possibleMatches[i]); } } return (String[])ret.toArray(new String[ret.size()]); } // public void postRead(ResolvedType enclosingType) { // this.importedPrefixes = enclosingType.getImportedPrefixes(); // this.knownNames = prematch(enclosingType.getImportedNames()); // } public String toString() { StringBuffer buf = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append('('); buf.append(annotationPattern.toString()); buf.append(' '); } for (int i=0, len=namePatterns.length; i < len; i++) { NamePattern name = namePatterns[i]; if (name == null) { buf.append("."); } else { if (i > 0) buf.append("."); buf.append(name.toString()); } } if (upperBound != null) { buf.append(" extends "); buf.append(upperBound.toString()); } if (lowerBound != null) { buf.append(" super "); buf.append(lowerBound.toString()); } if (typeParameters!=null && typeParameters.size()!=0) { buf.append("<"); buf.append(typeParameters.toString()); buf.append(">"); } if (includeSubtypes) buf.append('+'); if (isVarArgs) buf.append("..."); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append(')'); } return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof WildTypePattern)) return false; WildTypePattern o = (WildTypePattern)other; int len = o.namePatterns.length; if (len != this.namePatterns.length) return false; if (this.includeSubtypes != o.includeSubtypes) return false; if (this.dim != o.dim) return false; if (this.isVarArgs != o.isVarArgs) return false; if (this.upperBound != null) { if (o.upperBound == null) return false; if (!this.upperBound.equals(o.upperBound)) return false; } else { if (o.upperBound != null) return false; } if (this.lowerBound != null) { if (o.lowerBound == null) return false; if (!this.lowerBound.equals(o.lowerBound)) return false; } else { if (o.lowerBound != null) return false; } if (!typeParameters.equals(o.typeParameters)) return false; for (int i=0; i < len; i++) { if (!o.namePatterns[i].equals(this.namePatterns[i])) return false; } return (o.annotationPattern.equals(this.annotationPattern)); } public int hashCode() { int result = 17; for (int i = 0, len = namePatterns.length; i < len; i++) { result = 37*result + namePatterns[i].hashCode(); } result = 37*result + annotationPattern.hashCode(); if (upperBound != null) result = 37*result + upperBound.hashCode(); if (lowerBound != null) result = 37*result + lowerBound.hashCode(); return result; } public FuzzyBoolean matchesInstanceof(Class type) { return FuzzyBoolean.NO; } public boolean matchesExactly(Class type) { return matchesExactlyByName(type.getName()); } private static final byte VERSION = 1; // rev on change /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.WILD); s.writeByte(VERSION); s.writeShort(namePatterns.length); for (int i = 0; i < namePatterns.length; i++) { namePatterns[i].write(s); } s.writeBoolean(includeSubtypes); s.writeInt(dim); s.writeBoolean(isVarArgs); typeParameters.write(s); // ! change from M2 //??? storing this information with every type pattern is wasteful of .class // file size. Storing it on enclosing types would be more efficient FileUtil.writeStringArray(knownMatches, s); FileUtil.writeStringArray(importedPrefixes, s); writeLocation(s); annotationPattern.write(s); // generics info, new in M3 s.writeBoolean(isGeneric); s.writeBoolean(upperBound != null); if (upperBound != null) upperBound.write(s); s.writeBoolean(lowerBound != null); if (lowerBound != null) lowerBound.write(s); s.writeInt(additionalInterfaceBounds == null ? 0 : additionalInterfaceBounds.length); if (additionalInterfaceBounds != null) { for (int i = 0; i < additionalInterfaceBounds.length; i++) { additionalInterfaceBounds[i].write(s); } } } 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 > VERSION) { throw new BCException("WildTypePattern was written by a more recent version of AspectJ, cannot read"); } int len = s.readShort(); NamePattern[] namePatterns = new NamePattern[len]; for (int i=0; i < len; i++) { namePatterns[i] = NamePattern.read(s); } boolean includeSubtypes = s.readBoolean(); int dim = s.readInt(); boolean varArg = s.readBoolean(); TypePatternList typeParams = TypePatternList.read(s, context); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, varArg,typeParams); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); // generics info, new in M3 ret.isGeneric = s.readBoolean(); if (s.readBoolean()) { ret.upperBound = TypePattern.read(s,context); } if (s.readBoolean()) { ret.lowerBound = TypePattern.read(s,context); } int numIfBounds = s.readInt(); if (numIfBounds > 0) { ret.additionalInterfaceBounds = new TypePattern[numIfBounds]; for (int i = 0; i < numIfBounds; i++) { ret.additionalInterfaceBounds[i] = TypePattern.read(s,context); } } return ret; } public static TypePattern readTypePatternOldStyle(VersionedDataInputStream s, ISourceContext context) throws IOException { int len = s.readShort(); NamePattern[] namePatterns = new NamePattern[len]; for (int i=0; i < len; i++) { namePatterns[i] = NamePattern.read(s); } boolean includeSubtypes = s.readBoolean(); int dim = s.readInt(); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, false,null); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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; } public WithinAnnotationPointcut(AnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; } 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()); } public FuzzyBoolean fastMatch(Class targetType) { // TODO AMC return FuzzyBoolean.MAYBE; } /* (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#resolveBindingsFromRTTI() */ protected void resolveBindingsFromRTTI() { // TODO Auto-generated method stub } /* (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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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.ANNOTATION; } public WithinCodeAnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; } 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; } public FuzzyBoolean fastMatch(Class targetType) { 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#resolveBindingsFromRTTI() */ protected void resolveBindingsFromRTTI() { // TODO Auto-generated method stub } /* (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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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.lang.reflect.Member; 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.lang.JoinPoint; 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; } public FuzzyBoolean fastMatch(Class targetType) { 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 FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart encJp) { return isWithinType(encJp.getSignature().getDeclaringType()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return true; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically( String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { if ((member != null) && !(joinpointKind.equals(Shadow.ConstructorCall.getName()) || joinpointKind.equals(Shadow.MethodCall.getName()) || joinpointKind.equals(Shadow.FieldGet.getName()) || joinpointKind.equals(Shadow.FieldSet.getName())) ) { return isWithinType(member.getDeclaringClass()); } else { return isWithinType(thisClass); } } private FuzzyBoolean isWithinType(Class type) { while (type != null) { if (typePattern.matchesStatically(type)) { return FuzzyBoolean.YES; } type = type.getDeclaringClass(); } return FuzzyBoolean.NO; } 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 resolveBindingsFromRTTI() { typePattern = typePattern.resolveBindingsFromRTTI(false,false); } 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,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
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.lang.reflect.Member; import java.util.HashSet; import java.util.Set; import org.aspectj.bridge.MessageUtil; import org.aspectj.lang.JoinPoint; import org.aspectj.runtime.reflect.Factory; 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; } public FuzzyBoolean fastMatch(Class targetType) { 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 FuzzyBoolean match(JoinPoint jp, JoinPoint.StaticPart encJP) { return FuzzyBoolean.fromBoolean(signature.matches(encJP)); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[]) */ public boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args) { return true; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member) */ public FuzzyBoolean matchesStatically(String joinpointKind, Member member, Class thisClass, Class targetClass, Member withinCode) { if (withinCode == null) return FuzzyBoolean.NO; return FuzzyBoolean.fromBoolean(signature.matches(Factory.makeEncSJP(withinCode))); } 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 resolveBindingsFromRTTI() { signature = signature.resolveBindingsFromRTTI(); } 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); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/reflect/AnnotationFinder.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/reflect/JoinPointMatchImpl.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/reflect/PointcutParameterImpl.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegate.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateFactory.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/reflect/ReflectionBasedResolvedMemberImpl.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/reflect/ReflectionShadow.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/reflect/ReflectionVar.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/reflect/ReflectionWorld.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/reflect/ShadowMatchImpl.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/tools/JoinPointMatch.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/tools/PointcutExpression.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.tools; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; /** * Represents an AspectJ pointcut expression and provides convenience methods to determine * whether or not the pointcut matches join points specified in terms of the * java.lang.reflect interfaces. */ public interface PointcutExpression { /** * Determine whether or not this pointcut could ever match a join point in the given class. * @param aClass the candidate class * @return true iff this pointcut <i>may</i> match a join point within(aClass), and false otherwise */ boolean couldMatchJoinPointsInType(Class aClass); /** * Returns true iff this pointcut contains any expression that might necessitate a dynamic test * at some join point (e.g. args) */ boolean mayNeedDynamicTest(); /** * Determine whether or not this pointcut matches a method call to the given method. * @param aMethod the method being called * @param thisClass the type making the method call * @param targetClass the static type of the target of the call * (may be a subtype of aMethod.getDeclaringClass() ) * @param withinCode the Method or Constructor from within which the call is made * @return a FuzzyBoolean indicating whether the pointcut always matches such a join point (YES), * never matches such a join point (NO), or may match such a join point (MAYBE) depending on the runtime * types of the arguments, caller, and called object. */ FuzzyBoolean matchesMethodCall(Method aMethod, Class thisClass, Class targetClass, Member withinCode); /** * Determine whether or not this pointcut matches the execution of a given method. * @param aMethod the method being executed * @param thisClass the static type of the object in which the method is executing * (may be a subtype of aMethod.getDeclaringClass()) * @return a FuzzyBoolean indicating whether the pointcut always matches such a join point (YES), * never matches such a join point (NO), or may match such a join point (MAYBE) depending on the * runtime types of the arguments and executing object. */ FuzzyBoolean matchesMethodExecution(Method aMethod, Class thisClass); /** * Determine whether or not this pointcut matches a call to the given constructor. * @param aConstructor the constructor being called * @param thisClass the type making the constructor call * @param withinCode the Method or Constructor from within which the call is made * @return a FuzzyBoolean indicating whether the pointcut always matches such a join point (YES), * never matches such a join point (NO), or may match such a join point (MAYBE) depending on the runtime * types of the arguments and caller. */ FuzzyBoolean matchesConstructorCall(Constructor aConstructor, Class thisClass, Member withinCode); /** * Determine whether or not this pointcut matches the execution of a given constructor. * @param aConstructor the constructor being executed * @param thisClass the static type of the object in which the constructor is executing * (may be a subtype of aConstructor.getDeclaringClass()) * @return a FuzzyBoolean indicating whether the pointcut always matches such a join point (YES), * never matches such a join point (NO), or may match such a join point (MAYBE) depending on the * runtime types of the arguments and executing object. */ FuzzyBoolean matchesConstructorExecution(Constructor aConstructor, Class thisClass); /** * Determine whether or not this pointcut matches the execution of a given piece of advice. * @param anAdviceMethod a method representing the advice being executed * @param thisClass the static type of the aspect in which the advice is executing * (may be a subtype of anAdviceMethod.getDeclaringClass()) * @return a FuzzyBoolean indicating whether the pointcut always matches such a join point (YES), * never matches such a join point (NO), or may match such a join point (MAYBE) depending on the * runtime type of the executing aspect. */ FuzzyBoolean matchesAdviceExecution(Method anAdviceMethod, Class thisClass); /** * Determine whether or not this pointcut matches the execution of a given exception * handler * @param exceptionType the static type of the exception being handled * @param inClass the class in which the catch block is declared * @param withinCode the method or constructor in which the catch block is declared * @return a FuzzyBoolean indicating whether the pointcut always matches such a join point (YES), * never matches such a join point (NO), or may match such a join point (MAYBE) depending on the * runtime types of the exception and exception-handling object. */ FuzzyBoolean matchesHandler(Class exceptionType, Class inClass, Member withinCode); /** * Determine whether or not this pointcut matches the initialization of an * object initiated by a call to the given constructor. * @param aConstructor the constructor initiating the initialization * @return a FuzzyBoolean indicating whether the pointcut always matches such a join point (YES), * never matches such a join point (NO), or may match such a join point (MAYBE) depending on the * runtime types of the arguments. */ FuzzyBoolean matchesInitialization(Constructor aConstructor); /** * Determine whether or not this pointcut matches the preinitialization of an * object initiated by a call to the given constructor. * @param aConstructor the constructor initiating the initialization * @return a FuzzyBoolean indicating whether the pointcut always matches such a join point (YES), * never matches such a join point (NO), or may match such a join point (MAYBE) depending on the * runtime types of the arguments. */ FuzzyBoolean matchesPreInitialization(Constructor aConstructor); /** * Determine whether or not this pointcut matches the static initialization * of the given class. * @param aClass the class being statically initialized * @return FuzzyBoolean.YES is the pointcut always matches, FuzzyBoolean.NO if the * pointcut never matches. */ FuzzyBoolean matchesStaticInitialization(Class aClass); /** * Determine whether or not this pointcut matches a set of the given field. * @param aField the field being updated * @param thisClass the type sending the update message * @param targetClass the static type of the target of the field update message * (may be a subtype of aField.getDeclaringClass() ) * @param withinCode the Method or Constructor from within which the update message is sent * @return a FuzzyBoolean indicating whether the pointcut always matches such a join point (YES), * never matches such a join point (NO), or may match such a join point (MAYBE) depending on the runtime * types of the caller and called object. */ FuzzyBoolean matchesFieldSet(Field aField, Class thisClass, Class targetClass, Member withinCode); /** * Determine whether or not this pointcut matches a get of the given field. * @param aField the field being accessed * @param thisClass the type accessing the field * @param targetClass the static type of the target of the field access message * (may be a subtype of aField.getDeclaringClass() ) * @param withinCode the Method or Constructor from within which the field is accessed * @return a FuzzyBoolean indicating whether the pointcut always matches such a join point (YES), * never matches such a join point (NO), or may match such a join point (MAYBE) depending on the runtime * types of the caller and called object. */ FuzzyBoolean matchesFieldGet(Field aField, Class thisClass, Class targetClass, Member withinCode); /** * Returns true iff the dynamic portions of the pointcut expression (this, target, and * args) match the given this, target, and args objects. This method only needs to be * called if a previous call to a FuzzyBoolean-returning matching method returned * FuzzyBoolean.MAYBE. Even if this method returns true, the pointcut can only be * considered to match the join point if the appropriate matches method for the join * point kind has also returned FuzzyBoolean.YES or FuzzyBoolean.MAYBE. * @param thisObject * @param targetObject * @param args * @return */ boolean matchesDynamically(Object thisObject, Object targetObject, Object[] args); /** * Return a string representation of this pointcut expression. */ String getPointcutExpression(); }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/tools/PointcutParameter.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/tools/PointcutParser.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.weaver.tools; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.internal.tools.PointcutExpressionImpl; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.ThisOrTargetPointcut; /** * A PointcutParser can be used to build PointcutExpressions for a * user-defined subset of AspectJ's pointcut language */ public class PointcutParser { private Set supportedPrimitives; /** * @return a Set containing every PointcutPrimitive except * if, cflow, and cflowbelow (useful for passing to * PointcutParser constructor). */ public static Set getAllSupportedPointcutPrimitives() { Set primitives = new HashSet(); primitives.add(PointcutPrimitive.ADVICE_EXECUTION); primitives.add(PointcutPrimitive.ARGS); primitives.add(PointcutPrimitive.CALL); primitives.add(PointcutPrimitive.EXECUTION); primitives.add(PointcutPrimitive.GET); primitives.add(PointcutPrimitive.HANDLER); primitives.add(PointcutPrimitive.INITIALIZATION); primitives.add(PointcutPrimitive.PRE_INITIALIZATION); primitives.add(PointcutPrimitive.SET); primitives.add(PointcutPrimitive.STATIC_INITIALIZATION); primitives.add(PointcutPrimitive.TARGET); primitives.add(PointcutPrimitive.THIS); primitives.add(PointcutPrimitive.WITHIN); primitives.add(PointcutPrimitive.WITHIN_CODE); return primitives; } /** * Create a pointcut parser that can parse the full AspectJ pointcut * language with the following exceptions: * <ul> * <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported * <li>Pointcut expressions must be self-contained :- they cannot contain references * to other named pointcuts * <li>The pointcut expression must be anonymous with no formals allowed. * </ul> */ public PointcutParser() { supportedPrimitives = getAllSupportedPointcutPrimitives(); } /** * Create a pointcut parser that can parse pointcut expressions built * from a user-defined subset of AspectJ's supported pointcut primitives. * The following restrictions apply: * <ul> * <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported * <li>Pointcut expressions must be self-contained :- they cannot contain references * to other named pointcuts * <li>The pointcut expression must be anonymous with no formals allowed. * </ul> * @param supportedPointcutKinds a set of PointcutPrimitives this parser * should support * @throws UnsupportedOperationException if the set contains if, cflow, or * cflow below */ public PointcutParser(Set/*<PointcutPrimitives>*/ supportedPointcutKinds) { supportedPrimitives = supportedPointcutKinds; for (Iterator iter = supportedPointcutKinds.iterator(); iter.hasNext();) { PointcutPrimitive element = (PointcutPrimitive) iter.next(); if ((element == PointcutPrimitive.IF) || (element == PointcutPrimitive.CFLOW) || (element == PointcutPrimitive.CFLOW_BELOW)) { throw new UnsupportedOperationException("Cannot handle if, cflow, and cflowbelow primitives"); } } } /** * Parse the given pointcut expression. * @throws UnsupportedPointcutPrimitiveException if the parser encounters a * primitive pointcut expression of a kind not supported by this PointcutParser. * @throws IllegalArgumentException if the expression is not a well-formed * pointcut expression */ public PointcutExpression parsePointcutExpression(String expression) throws UnsupportedPointcutPrimitiveException, IllegalArgumentException { PointcutExpressionImpl pcExpr = null; try { Pointcut pc = new PatternParser(expression).parsePointcut(); validateAgainstSupportedPrimitives(pc,expression); pc.resolve(); pcExpr = new PointcutExpressionImpl(pc,expression); } catch (ParserException pEx) { throw new IllegalArgumentException(buildUserMessageFromParserException(expression,pEx)); } return pcExpr; } /* for testing */ Set getSupportedPrimitives() { return supportedPrimitives; } private void validateAgainstSupportedPrimitives(Pointcut pc, String expression) { switch(pc.getPointcutKind()) { case Pointcut.AND: validateAgainstSupportedPrimitives(((AndPointcut)pc).getLeft(),expression); validateAgainstSupportedPrimitives(((AndPointcut)pc).getRight(),expression); break; case Pointcut.ARGS: if (!supportedPrimitives.contains(PointcutPrimitive.ARGS)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.ARGS); break; case Pointcut.CFLOW: CflowPointcut cfp = (CflowPointcut) pc; if (cfp.isCflowBelow()) { throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CFLOW_BELOW); } else { throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CFLOW); } case Pointcut.HANDLER: if (!supportedPrimitives.contains(PointcutPrimitive.HANDLER)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.HANDLER); break; case Pointcut.IF: case Pointcut.IF_FALSE: case Pointcut.IF_TRUE: throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.IF); case Pointcut.KINDED: validateKindedPointcut(((KindedPointcut)pc),expression); break; case Pointcut.NOT: validateAgainstSupportedPrimitives(((NotPointcut)pc).getNegatedPointcut(),expression); break; case Pointcut.OR: validateAgainstSupportedPrimitives(((OrPointcut)pc).getLeft(),expression); validateAgainstSupportedPrimitives(((OrPointcut)pc).getRight(),expression); break; case Pointcut.REFERENCE: throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.REFERENCE); case Pointcut.THIS_OR_TARGET: boolean isThis = ((ThisOrTargetPointcut)pc).isThis(); if (isThis && !supportedPrimitives.contains(PointcutPrimitive.THIS)) { throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.THIS); } else if (!supportedPrimitives.contains(PointcutPrimitive.TARGET)) { throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.TARGET); } break; case Pointcut.WITHIN: if (!supportedPrimitives.contains(PointcutPrimitive.WITHIN)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.WITHIN); break; case Pointcut.WITHINCODE: if (!supportedPrimitives.contains(PointcutPrimitive.WITHIN_CODE)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.WITHIN_CODE); break; case Pointcut.NONE: // deliberate fall-through default: throw new IllegalArgumentException("Unknown pointcut kind: " + pc.getPointcutKind()); } } private void validateKindedPointcut(KindedPointcut pc, String expression) { Shadow.Kind kind = pc.getKind(); if ((kind == Shadow.MethodCall) || (kind == Shadow.ConstructorCall)) { if (!supportedPrimitives.contains(PointcutPrimitive.CALL)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CALL); } else if ((kind == Shadow.MethodExecution) || (kind == Shadow.ConstructorExecution)) { if (!supportedPrimitives.contains(PointcutPrimitive.EXECUTION)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.EXECUTION); } else if (kind == Shadow.AdviceExecution) { if (!supportedPrimitives.contains(PointcutPrimitive.ADVICE_EXECUTION)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.ADVICE_EXECUTION); } else if (kind == Shadow.FieldGet) { if (!supportedPrimitives.contains(PointcutPrimitive.GET)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.GET); } else if (kind == Shadow.FieldSet) { if (!supportedPrimitives.contains(PointcutPrimitive.SET)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.SET); } else if (kind == Shadow.Initialization) { if (!supportedPrimitives.contains(PointcutPrimitive.INITIALIZATION)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.INITIALIZATION); } else if (kind == Shadow.PreInitialization) { if (!supportedPrimitives.contains(PointcutPrimitive.PRE_INITIALIZATION)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.PRE_INITIALIZATION); } else if (kind == Shadow.StaticInitialization) { if (!supportedPrimitives.contains(PointcutPrimitive.STATIC_INITIALIZATION)) throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.STATIC_INITIALIZATION); } } private String buildUserMessageFromParserException(String pc, ParserException ex) { StringBuffer msg = new StringBuffer(); msg.append("Pointcut is not well-formed: expecting '"); msg.append(ex.getMessage()); msg.append("'"); IHasPosition location = ex.getLocation(); msg.append(" at character position "); msg.append(location.getStart()); msg.append("\n"); msg.append(pc); msg.append("\n"); for (int i = 0; i < location.getStart(); i++) { msg.append(" "); } for (int j=location.getStart(); j <= location.getEnd(); j++) { msg.append("^"); } msg.append("\n"); return msg.toString(); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/tools/PointcutPrimitive.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.tools; import org.aspectj.util.TypeSafeEnum; /** * An enumeration of the different kinds of pointcut primitives * supported by AspectJ. */ public class PointcutPrimitive extends TypeSafeEnum { public static final PointcutPrimitive CALL = new PointcutPrimitive("call",1); public static final PointcutPrimitive EXECUTION = new PointcutPrimitive("execution",2); public static final PointcutPrimitive GET = new PointcutPrimitive("get",3); public static final PointcutPrimitive SET = new PointcutPrimitive("set",4); public static final PointcutPrimitive INITIALIZATION = new PointcutPrimitive("initialization",5); public static final PointcutPrimitive PRE_INITIALIZATION = new PointcutPrimitive("preinitialization",6); public static final PointcutPrimitive STATIC_INITIALIZATION = new PointcutPrimitive("staticinitialization",7); public static final PointcutPrimitive HANDLER = new PointcutPrimitive("handler",8); public static final PointcutPrimitive ADVICE_EXECUTION = new PointcutPrimitive("adviceexecution",9); public static final PointcutPrimitive WITHIN = new PointcutPrimitive("within",10); public static final PointcutPrimitive WITHIN_CODE = new PointcutPrimitive("withincode",11); public static final PointcutPrimitive CFLOW = new PointcutPrimitive("cflow",12); public static final PointcutPrimitive CFLOW_BELOW = new PointcutPrimitive("cflowbelow",13); public static final PointcutPrimitive IF = new PointcutPrimitive("if",14); public static final PointcutPrimitive THIS = new PointcutPrimitive("this",15); public static final PointcutPrimitive TARGET = new PointcutPrimitive("target",16); public static final PointcutPrimitive ARGS = new PointcutPrimitive("args",17); public static final PointcutPrimitive REFERENCE = new PointcutPrimitive("reference pointcut",18); private PointcutPrimitive(String name, int key) { super(name, key); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/src/org/aspectj/weaver/tools/ShadowMatch.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/BcweaverModuleTests15.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: * Adrian Colyer Initial implementation * ******************************************************************/ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.aspectj.weaver.BoundedReferenceTypeTestCase; import org.aspectj.weaver.MemberTestCase15; import org.aspectj.weaver.ReferenceTypeTestCase; import org.aspectj.weaver.TypeVariableReferenceTypeTestCase; import org.aspectj.weaver.TypeVariableTestCase; import org.aspectj.weaver.bcel.BcelGenericSignatureToTypeXTestCase; import org.aspectj.weaver.patterns.WildTypePatternResolutionTestCase; public class BcweaverModuleTests15 extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(BcweaverModuleTests15.class.getName()); suite.addTestSuite(TypeVariableTestCase.class); suite.addTestSuite(ReferenceTypeTestCase.class); suite.addTestSuite(BoundedReferenceTypeTestCase.class); suite.addTestSuite(TypeVariableReferenceTypeTestCase.class); suite.addTestSuite(MemberTestCase15.class); suite.addTestSuite(BcelGenericSignatureToTypeXTestCase.class); suite.addTestSuite(WildTypePatternResolutionTestCase.class); return suite; } public BcweaverModuleTests15(String name) { super(name); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/patterns/AndOrNotTestCase.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.*; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.runtime.reflect.Factory; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.bcel.*; import junit.framework.TestCase; import org.aspectj.weaver.*; /** * @author hugunin * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class AndOrNotTestCase extends TestCase { /** * Constructor for PatternTestCase. * @param name */ public AndOrNotTestCase(String name) { super(name); } World world; public void testMatch() throws IOException { world = new BcelWorld(); Pointcut foo = makePointcut("this(Foo)"); Pointcut bar = makePointcut("this(Bar)"); Pointcut c = makePointcut("this(C)"); checkEquals("this(Foo) && this(Bar)", new AndPointcut(foo, bar)); checkEquals("this(Foo) && this(Bar) && this(C)", new AndPointcut(foo, new AndPointcut(bar, c))); checkEquals("this(Foo) || this(Bar)", new OrPointcut(foo, bar)); checkEquals("this(Foo) || this(Bar) || this(C)", new OrPointcut(foo, new OrPointcut(bar, c))); checkEquals("this(Foo) && this(Bar) || this(C)", new OrPointcut(new AndPointcut(foo, bar), c)); checkEquals("this(Foo) || this(Bar) && this(C)", new OrPointcut(foo, new AndPointcut(bar, c))); checkEquals("(this(Foo) || this(Bar)) && this(C)", new AndPointcut(new OrPointcut(foo, bar), c)); checkEquals("this(Foo) || (this(Bar) && this(C))", new OrPointcut(foo, new AndPointcut(bar, c))); checkEquals("!this(Foo)", new NotPointcut(foo)); checkEquals("!this(Foo) && this(Bar)", new AndPointcut(new NotPointcut(foo), bar)); checkEquals("!(this(Foo) && this(Bar)) || this(C)", new OrPointcut(new NotPointcut(new AndPointcut(foo, bar)), c)); checkEquals("!!this(Foo)", new NotPointcut(new NotPointcut(foo))); } public void testJoinPointMatch() { Pointcut foo = makePointcut("this(org.aspectj.weaver.patterns.AndOrNotTestCase.Foo)").resolve(); Pointcut bar = makePointcut("this(org.aspectj.weaver.patterns.AndOrNotTestCase.Bar)").resolve(); Pointcut c = makePointcut("this(org.aspectj.weaver.patterns.AndOrNotTestCase.C)").resolve(); Factory f = new Factory("AndOrNotTestCase.java",AndOrNotTestCase.class); Signature methodSig = f.makeMethodSig("void aMethod()"); JoinPoint.StaticPart jpsp = f.makeSJP(JoinPoint.METHOD_EXECUTION,methodSig,1); JoinPoint jp = Factory.makeJP(jpsp,new Foo(),new Foo()); checkMatches(new AndPointcut(foo,bar),jp,null,FuzzyBoolean.NO); checkMatches(new AndPointcut(foo,foo),jp,null,FuzzyBoolean.YES); checkMatches(new AndPointcut(bar,foo),jp,null,FuzzyBoolean.NO); checkMatches(new AndPointcut(bar,c),jp,null,FuzzyBoolean.NO); checkMatches(new OrPointcut(foo,bar),jp,null,FuzzyBoolean.YES); checkMatches(new OrPointcut(foo,foo),jp,null,FuzzyBoolean.YES); checkMatches(new OrPointcut(bar,foo),jp,null,FuzzyBoolean.YES); checkMatches(new OrPointcut(bar,c),jp,null,FuzzyBoolean.NO); checkMatches(new NotPointcut(foo),jp,null,FuzzyBoolean.NO); checkMatches(new NotPointcut(bar),jp,null,FuzzyBoolean.YES); } private Pointcut makePointcut(String pattern) { return new PatternParser(pattern).parsePointcut(); } private void checkEquals(String pattern, Pointcut p) throws IOException { assertEquals(pattern, p, makePointcut(pattern)); checkSerialization(pattern); } private void checkMatches(Pointcut p, JoinPoint jp, JoinPoint.StaticPart jpsp, FuzzyBoolean expected) { assertEquals(expected,p.match(jp,jpsp)); } // private void checkMatch(Pointcut p, Signature[] matches, boolean shouldMatch) { // for (int i=0; i<matches.length; i++) { // boolean result = p.matches(matches[i]); // String msg = "matches " + p + " to " + matches[i] + " expected "; // if (shouldMatch) { // assertTrue(msg + shouldMatch, result); // } else { // assertTrue(msg + shouldMatch, !result); // } // } // } // // public void testSerialization() throws IOException { // String[] patterns = new String[] { // "public * *(..)", "void *.foo(A, B)", "A b()" // }; // // for (int i=0, len=patterns.length; i < len; i++) { // checkSerialization(patterns[i]); // } // } /** * Method checkSerialization. * @param string */ private void checkSerialization(String string) throws IOException { Pointcut p = makePointcut(string); ByteArrayOutputStream bo = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bo); p.write(out); out.close(); ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); VersionedDataInputStream in = new VersionedDataInputStream(bi); Pointcut newP = Pointcut.read(in, null); assertEquals("write/read", p, newP); } private static class Foo{}; private static class Bar{}; private static class C{}; }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/patterns/ArgsTestCase.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.weaver.patterns; import junit.framework.TestCase; import org.aspectj.lang.JoinPoint; import org.aspectj.runtime.reflect.Factory; import org.aspectj.util.FuzzyBoolean; /** * @author colyer * */ public class ArgsTestCase extends TestCase { Pointcut wildcardArgs; Pointcut oneA; Pointcut oneAandaC; Pointcut BthenAnything; Pointcut singleArg; public void testMatchJP() { Factory f = new Factory("ArgsTestCase.java",ArgsTestCase.A.class); JoinPoint.StaticPart jpsp1 = f.makeSJP(JoinPoint.METHOD_EXECUTION,f.makeMethodSig(0,"aMethod",A.class,new Class[] {A.class},new String[] {"a"},new Class[] {},null) ,1); JoinPoint.StaticPart jpsp2 = f.makeSJP(JoinPoint.METHOD_EXECUTION,f.makeMethodSig(0,"aMethod",A.class,new Class[] {B.class},new String[] {"b"},new Class[] {},null),1); JoinPoint.StaticPart jpsp3 = f.makeSJP(JoinPoint.METHOD_EXECUTION,f.makeMethodSig(0,"aMethod",A.class,new Class[] {A.class,C.class},new String[] {"a","c"},new Class[] {},null),1); JoinPoint.StaticPart jpsp4 = f.makeSJP(JoinPoint.METHOD_EXECUTION,f.makeMethodSig(0,"aMethod",A.class,new Class[] {A.class,A.class},new String[] {"a","a2"},new Class[] {},null),1); JoinPoint oneAArg = Factory.makeJP(jpsp1,new A(),new A(),new A()); JoinPoint oneBArg = Factory.makeJP(jpsp2,new A(), new A(), new B()); JoinPoint acArgs = Factory.makeJP(jpsp3,new A(), new A(), new A(), new C()); JoinPoint baArgs = Factory.makeJP(jpsp4,new A(), new A(), new B(), new A()); checkMatches(wildcardArgs,oneAArg,null,FuzzyBoolean.YES); checkMatches(wildcardArgs,oneBArg,null,FuzzyBoolean.YES); checkMatches(wildcardArgs,acArgs,null,FuzzyBoolean.YES); checkMatches(wildcardArgs,baArgs,null,FuzzyBoolean.YES); checkMatches(oneA,oneAArg,null,FuzzyBoolean.YES); checkMatches(oneA,oneBArg,null,FuzzyBoolean.YES); checkMatches(oneA,acArgs,null,FuzzyBoolean.NO); checkMatches(oneA,baArgs,null,FuzzyBoolean.NO); checkMatches(oneAandaC,oneAArg,null,FuzzyBoolean.NO); checkMatches(oneAandaC,oneBArg,null,FuzzyBoolean.NO); checkMatches(oneAandaC,acArgs,null,FuzzyBoolean.YES); checkMatches(oneAandaC,baArgs,null,FuzzyBoolean.NO); checkMatches(BthenAnything,oneAArg,null,FuzzyBoolean.NO); checkMatches(BthenAnything,oneBArg,null,FuzzyBoolean.YES); checkMatches(BthenAnything,acArgs,null,FuzzyBoolean.NO); checkMatches(BthenAnything,baArgs,null,FuzzyBoolean.YES); checkMatches(singleArg,oneAArg,null,FuzzyBoolean.YES); checkMatches(singleArg,oneBArg,null,FuzzyBoolean.YES); checkMatches(singleArg,acArgs,null,FuzzyBoolean.NO); checkMatches(singleArg,baArgs,null,FuzzyBoolean.NO); } public void testMatchJPWithPrimitiveTypes() { try { Factory f = new Factory("ArgsTestCase.java",ArgsTestCase.A.class); Pointcut oneInt = new PatternParser("args(int)").parsePointcut().resolve(); Pointcut oneInteger = new PatternParser("args(Integer)").parsePointcut().resolve(); JoinPoint.StaticPart oneIntjp = f.makeSJP(JoinPoint.METHOD_EXECUTION,f.makeMethodSig(0,"aMethod",A.class,new Class[] {int.class},new String[] {"i"},new Class[] {},null) ,1); JoinPoint.StaticPart oneIntegerjp = f.makeSJP(JoinPoint.METHOD_EXECUTION,f.makeMethodSig(0,"aMethod",A.class,new Class[] {Integer.class},new String[] {"i"},new Class[] {},null),1); JoinPoint oneIntArg = Factory.makeJP(oneIntjp,new A(),new A(),new Integer(3)); JoinPoint oneIntegerArg = Factory.makeJP(oneIntegerjp,new A(), new A(), new Integer(7)); checkMatches(oneInt,oneIntArg,null,FuzzyBoolean.YES); checkMatches(oneInt,oneIntegerArg,null,FuzzyBoolean.NO); checkMatches(oneInteger,oneIntArg,null,FuzzyBoolean.NO); checkMatches(oneInteger,oneIntegerArg,null,FuzzyBoolean.YES); } catch( Exception ex) { fail("Unexpected exception " + ex); } } private void checkMatches(Pointcut p, JoinPoint jp, JoinPoint.StaticPart jpsp, FuzzyBoolean expected) { assertEquals(expected,p.match(jp,jpsp)); } private static class A {}; private static class B extends A {}; private static class C {}; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); wildcardArgs = new PatternParser("args(..)").parsePointcut().resolve(); oneA = new PatternParser("args(org.aspectj.weaver.patterns.ArgsTestCase.A)").parsePointcut().resolve(); oneAandaC = new PatternParser("args(org.aspectj.weaver.patterns.ArgsTestCase.A,org.aspectj.weaver.patterns.ArgsTestCase.C)").parsePointcut().resolve(); BthenAnything = new PatternParser("args(org.aspectj.weaver.patterns.ArgsTestCase.B,..)").parsePointcut().resolve(); singleArg = new PatternParser("args(*)").parsePointcut().resolve(); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/patterns/HandlerTestCase.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.weaver.patterns; import java.io.IOException; import org.aspectj.lang.JoinPoint; import org.aspectj.runtime.reflect.Factory; import org.aspectj.util.FuzzyBoolean; import junit.framework.TestCase; public class HandlerTestCase extends TestCase { private Pointcut hEx; private Pointcut hExPlus; private Pointcut hIOEx; public void testHandlerMatch() { Factory f = new Factory("HandlerTestCase.java",HandlerTestCase.class); JoinPoint.StaticPart jpsp1 = f.makeSJP(JoinPoint.EXCEPTION_HANDLER,f.makeCatchClauseSig(HandlerTestCase.class,Exception.class,"ex"),1); JoinPoint ex = Factory.makeJP(jpsp1,this,this,new Exception()); JoinPoint ioex = Factory.makeJP(jpsp1,this,this,new IOException()); JoinPoint myex = Factory.makeJP(jpsp1,this,this,new MyException()); checkMatches(hEx,ex,null,FuzzyBoolean.YES); checkMatches(hEx,ioex,null,FuzzyBoolean.NO); checkMatches(hEx,myex,null,FuzzyBoolean.NO); checkMatches(hExPlus,ex,null,FuzzyBoolean.YES); checkMatches(hExPlus,ioex,null,FuzzyBoolean.YES); checkMatches(hExPlus,myex,null,FuzzyBoolean.YES); checkMatches(hIOEx,ex,null,FuzzyBoolean.NO); checkMatches(hIOEx,ioex,null,FuzzyBoolean.YES); checkMatches(hIOEx,myex,null,FuzzyBoolean.NO); } private void checkMatches(Pointcut p, JoinPoint jp, JoinPoint.StaticPart jpsp, FuzzyBoolean expected) { assertEquals(expected,p.match(jp,jpsp)); } private static class MyException extends Exception {} /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); hEx = new PatternParser("handler(Exception)").parsePointcut().resolve(); hExPlus = new PatternParser("handler(Exception+)").parsePointcut().resolve(); hIOEx = new PatternParser("handler(java.io.IOException)").parsePointcut().resolve(); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/patterns/KindedTestCase.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.weaver.patterns; import java.lang.reflect.Modifier; import org.aspectj.lang.JoinPoint; import org.aspectj.runtime.reflect.Factory; import org.aspectj.util.FuzzyBoolean; import junit.framework.TestCase; /** * @author colyer * */ public class KindedTestCase extends TestCase { Pointcut callpc; Pointcut exepc; Pointcut exepcplus; Pointcut exepcCons; Pointcut adviceexepc; Pointcut initpc; Pointcut preinitpc; Pointcut staticinitpc; Pointcut getpc; Pointcut setpc; public void testKindedMatch() { Factory f = new Factory("KindedTestCase.java",KindedTestCase.class); // JoinPoints to match against... JoinPoint.StaticPart calljp1 = f.makeSJP(JoinPoint.METHOD_CALL,f.makeMethodSig(0,"main",Hello.class,new Class[] {String.class},new String[] {"s"},new Class[0],String.class),1); JoinPoint.StaticPart calljp2 = f.makeSJP(JoinPoint.METHOD_CALL,f.makeMethodSig(0,"sayHi",Hello.class,new Class[] {String.class},new String[] {"s"},new Class[0],String.class),1); JoinPoint.StaticPart exejp1 = f.makeSJP(JoinPoint.METHOD_EXECUTION,f.makeMethodSig(0,"main",Hello.class,new Class[] {String.class},new String[] {"s"},new Class[0],String.class),1); JoinPoint.StaticPart exejp2 = f.makeSJP(JoinPoint.METHOD_EXECUTION,f.makeMethodSig(0,"sayHi",Hello.class,new Class[] {String.class},new String[] {"s"},new Class[0],void.class),1); JoinPoint.StaticPart execonsjp1 = f.makeSJP(JoinPoint.CONSTRUCTOR_EXECUTION,f.makeConstructorSig(0,Hello.class,new Class[0],new String[0],new Class[0]),1); JoinPoint.StaticPart execonsjp2 = f.makeSJP(JoinPoint.CONSTRUCTOR_EXECUTION,f.makeConstructorSig(0,String.class,new Class[] {String.class},new String[]{"s"},new Class[0]),1); JoinPoint.StaticPart initjp1 = f.makeSJP(JoinPoint.INITIALIZATION,f.makeConstructorSig(0,Hello.class,new Class[0],new String[0],new Class[0]),1); JoinPoint.StaticPart initjp2 = f.makeSJP(JoinPoint.PREINTIALIZATION,f.makeConstructorSig(0,Hello.class,new Class[]{int.class, int.class},new String[]{"a","b"},new Class[0]),1); JoinPoint.StaticPart initjp3 = f.makeSJP(JoinPoint.PREINTIALIZATION,f.makeConstructorSig(0,Hello.class,new Class[]{Integer.class, Integer.class},new String[]{"a","b"},new Class[0]),1); JoinPoint.StaticPart sinitjp1 = f.makeSJP(JoinPoint.STATICINITIALIZATION,f.makeInitializerSig(Modifier.STATIC,Hello.class),1); JoinPoint.StaticPart sinitjp2 = f.makeSJP(JoinPoint.STATICINITIALIZATION,f.makeInitializerSig(Modifier.STATIC,String.class),1); JoinPoint.StaticPart getjp1 = f.makeSJP(JoinPoint.FIELD_GET,f.makeFieldSig(0,"x",Hello.class,int.class),1); JoinPoint.StaticPart getjp2 = f.makeSJP(JoinPoint.FIELD_GET,f.makeFieldSig(0,"y",String.class,String.class),1); JoinPoint.StaticPart setjp1 = f.makeSJP(JoinPoint.FIELD_SET,f.makeFieldSig(0,"x",Hello.class,int.class),1); JoinPoint.StaticPart setjp2 = f.makeSJP(JoinPoint.FIELD_SET,f.makeFieldSig(0,"y",String.class,String.class),1); JoinPoint.StaticPart advjp = f.makeSJP(JoinPoint.ADVICE_EXECUTION,f.makeAdviceSig(0,"foo",Hello.class,new Class[0],new String[0],new Class[0],void.class),1); checkMatches(callpc,calljp1,FuzzyBoolean.YES); checkMatches(callpc,calljp2,FuzzyBoolean.NO); checkMatches(callpc,exejp1,FuzzyBoolean.NO); checkMatches(exepc,exejp1,FuzzyBoolean.NO); checkMatches(exepc,exejp2,FuzzyBoolean.YES); checkMatches(exepcplus,exejp1,FuzzyBoolean.NO); checkMatches(exepcplus,exejp2,FuzzyBoolean.YES); checkMatches(exepcCons,execonsjp1,FuzzyBoolean.YES); checkMatches(exepcCons,execonsjp2,FuzzyBoolean.NO); checkMatches(exepcCons,exejp1,FuzzyBoolean.NO); checkMatches(initpc,initjp1,FuzzyBoolean.YES); checkMatches(initpc,initjp2,FuzzyBoolean.NO); checkMatches(preinitpc,initjp1,FuzzyBoolean.NO); checkMatches(preinitpc,initjp2,FuzzyBoolean.YES); checkMatches(preinitpc,initjp3,FuzzyBoolean.NO); checkMatches(staticinitpc,sinitjp1,FuzzyBoolean.YES); checkMatches(staticinitpc,sinitjp2,FuzzyBoolean.NO); checkMatches(getpc,getjp1,FuzzyBoolean.YES); checkMatches(getpc,getjp2,FuzzyBoolean.YES); checkMatches(setpc,setjp1,FuzzyBoolean.YES); checkMatches(setpc,setjp2,FuzzyBoolean.NO); checkMatches(adviceexepc,advjp,FuzzyBoolean.YES); } private void checkMatches(Pointcut p, JoinPoint.StaticPart jpsp, FuzzyBoolean expected) { assertEquals(expected,p.match(jpsp)); } protected void setUp() throws Exception { super.setUp(); callpc = new PatternParser("call(* main(..))").parsePointcut().resolve(); exepc = new PatternParser("execution(void org.aspectj.weaver.patterns.KindedTestCase.Hello.sayHi(String))").parsePointcut().resolve(); exepcplus = new PatternParser("execution(void Object+.sayHi(String))").parsePointcut().resolve(); exepcCons = new PatternParser("execution(org.aspectj.weaver.patterns.KindedTestCase.Hello.new(..))").parsePointcut().resolve(); initpc = new PatternParser("initialization(new(..))").parsePointcut().resolve(); preinitpc = new PatternParser("preinitialization(*..H*.new(int,int))").parsePointcut().resolve(); staticinitpc = new PatternParser("staticinitialization(org.aspectj.weaver.patterns.KindedTestCase.Hello)").parsePointcut().resolve(); getpc = new PatternParser("get(* *)").parsePointcut().resolve(); setpc = new PatternParser("set(int x)").parsePointcut().resolve(); adviceexepc = new PatternParser("adviceexecution()").parsePointcut().resolve(); } private static class Hello {}; }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/patterns/PatternsTests.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 junit.framework.*; public class PatternsTests extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(PatternsTests.class.getName()); //$JUnit-BEGIN$ suite.addTestSuite(AndOrNotTestCase.class); suite.addTestSuite(BindingTestCase.class); suite.addTestSuite(DeclareErrorOrWarningTestCase.class); suite.addTestSuite(ModifiersPatternTestCase.class); suite.addTestSuite(NamePatternParserTestCase.class); suite.addTestSuite(NamePatternTestCase.class); suite.addTestSuite(ParserTestCase.class); suite.addTestSuite(SignaturePatternTestCase.class); suite.addTestSuite(ThisOrTargetTestCase.class); suite.addTestSuite(TypePatternListTestCase.class); suite.addTestSuite(TypePatternTestCase.class); suite.addTestSuite(WithinTestCase.class); suite.addTestSuite(PointcutTestCase.class); suite.addTestSuite(ArgsTestCase.class); suite.addTestSuite(HandlerTestCase.class); suite.addTestSuite(KindedTestCase.class); suite.addTestSuite(WithinCodeTestCase.class); suite.addTestSuite(AnnotationPatternTestCase.class); suite.addTestSuite(AnnotationPatternMatchingTestCase.class); suite.addTestSuite(PointcutRewriterTest.class); suite.addTestSuite(VisitorTestCase.class); //$JUnit-END$ return suite; } public PatternsTests(String name) { super(name); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/patterns/PointcutTestCase.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.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import java.util.Set; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.runtime.reflect.Factory; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ast.Test; import junit.framework.TestCase; public class PointcutTestCase extends TestCase { public void testMatchJP() { Pointcut p = new Pointcut() { public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } public Set couldMatchKinds() { return null; } public FuzzyBoolean fastMatch(FastMatchInfo info) { return null; } public FuzzyBoolean fastMatch(Class targetClass) { return null; } protected FuzzyBoolean matchInternal(Shadow shadow) { return null; } protected void resolveBindings(IScope scope, Bindings bindings) { } protected void resolveBindingsFromRTTI() {} protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { return null; } public Pointcut parameterizeWith(Map typeVariableMap) { return null; } protected Test findResidueInternal(Shadow shadow, ExposedState state) { return null; } public void write(DataOutputStream s) throws IOException { }}; Factory f = new Factory("PointcutTestCase.java",PointcutTestCase.class); Signature methodSig = f.makeMethodSig("void aMethod()"); JoinPoint.StaticPart jpsp = f.makeSJP(JoinPoint.METHOD_EXECUTION,methodSig,1); JoinPoint jp = Factory.makeJP(jpsp,this,this); try { p.match(jp,null); fail("Expected UnsupportedOperationException to be thrown"); } catch (UnsupportedOperationException unEx) { // ok } try { p.match(jpsp); fail("Expected UnsupportedOperationException to be thrown"); } catch (UnsupportedOperationException unEx) { // ok } } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/patterns/ThisOrTargetTestCase.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.*; import org.aspectj.lang.JoinPoint; import org.aspectj.runtime.reflect.Factory; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.bcel.*; import junit.framework.TestCase; import org.aspectj.weaver.*; /** * @author hugunin * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class ThisOrTargetTestCase extends TestCase { /** * Constructor for PatternTestCase. * @param name */ public ThisOrTargetTestCase(String name) { super(name); } World world; public void testMatch() throws IOException { world = new BcelWorld(); } public void testMatchJP() { Factory f = new Factory("ThisOrTargetTestCase.java",ThisOrTargetTestCase.class); Pointcut thisEx = new PatternParser("this(Exception)").parsePointcut().resolve(); Pointcut thisIOEx = new PatternParser("this(java.io.IOException)").parsePointcut().resolve(); Pointcut targetEx = new PatternParser("target(Exception)").parsePointcut().resolve(); Pointcut targetIOEx = new PatternParser("target(java.io.IOException)").parsePointcut().resolve(); JoinPoint.StaticPart jpsp1 = f.makeSJP(JoinPoint.EXCEPTION_HANDLER,f.makeCatchClauseSig(HandlerTestCase.class,Exception.class,"ex"),1); JoinPoint thisExJP = Factory.makeJP(jpsp1,new Exception(),this); JoinPoint thisIOExJP = Factory.makeJP(jpsp1,new IOException(),this); JoinPoint targetExJP = Factory.makeJP(jpsp1,this,new Exception()); JoinPoint targetIOExJP = Factory.makeJP(jpsp1,this,new IOException()); checkMatches(thisEx,thisExJP,null,FuzzyBoolean.YES); checkMatches(thisIOEx,thisExJP,null,FuzzyBoolean.NO); checkMatches(targetEx,thisExJP,null,FuzzyBoolean.NO); checkMatches(targetIOEx,thisExJP,null,FuzzyBoolean.NO); checkMatches(thisEx,thisIOExJP,null,FuzzyBoolean.YES); checkMatches(thisIOEx,thisIOExJP,null,FuzzyBoolean.YES); checkMatches(targetEx,thisIOExJP,null,FuzzyBoolean.NO); checkMatches(targetIOEx,thisIOExJP,null,FuzzyBoolean.NO); checkMatches(thisEx,targetExJP,null,FuzzyBoolean.NO); checkMatches(thisIOEx,targetExJP,null,FuzzyBoolean.NO); checkMatches(targetEx,targetExJP,null,FuzzyBoolean.YES); checkMatches(targetIOEx,targetExJP,null,FuzzyBoolean.NO); checkMatches(thisEx,targetIOExJP,null,FuzzyBoolean.NO); checkMatches(thisIOEx,targetIOExJP,null,FuzzyBoolean.NO); checkMatches(targetEx,targetIOExJP,null,FuzzyBoolean.YES); checkMatches(targetIOEx,targetIOExJP,null,FuzzyBoolean.YES); } private void checkMatches(Pointcut p, JoinPoint jp, JoinPoint.StaticPart jpsp, FuzzyBoolean expected) { assertEquals(expected,p.match(jp,jpsp)); } // private Pointcut makePointcut(String pattern) { // return new PatternParser(pattern).parsePointcut(); // } // private void checkEquals(String pattern, Pointcut p) throws IOException { // assertEquals(pattern, p, makePointcut(pattern)); // checkSerialization(pattern); // } // private void checkMatch(Pointcut p, Signature[] matches, boolean shouldMatch) { // for (int i=0; i<matches.length; i++) { // boolean result = p.matches(matches[i]); // String msg = "matches " + p + " to " + matches[i] + " expected "; // if (shouldMatch) { // assertTrue(msg + shouldMatch, result); // } else { // assertTrue(msg + shouldMatch, !result); // } // } // } // // public void testSerialization() throws IOException { // String[] patterns = new String[] { // "public * *(..)", "void *.foo(A, B)", "A b()" // }; // // for (int i=0, len=patterns.length; i < len; i++) { // checkSerialization(patterns[i]); // } // } /** * Method checkSerialization. * @param string */ // private void checkSerialization(String string) throws IOException { // Pointcut p = makePointcut(string); // ByteArrayOutputStream bo = new ByteArrayOutputStream(); // DataOutputStream out = new DataOutputStream(bo); // p.write(out); // out.close(); // // ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); // DataInputStream in = new DataInputStream(bi); // Pointcut newP = Pointcut.read(in, null); // // assertEquals("write/read", p, newP); // } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/patterns/WithinCodeTestCase.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.weaver.patterns; import org.aspectj.lang.JoinPoint; import org.aspectj.runtime.reflect.Factory; import org.aspectj.util.FuzzyBoolean; import junit.framework.TestCase; public class WithinCodeTestCase extends TestCase { Pointcut withinCode1; Pointcut withinCode2; Pointcut withinCode3; public void testMatchJP() { Factory f = new Factory("WithinCodeTestCase.java",WithinCodeTestCase.class); // JoinPoints to match against... JoinPoint.StaticPart exejp1 = f.makeSJP(JoinPoint.METHOD_EXECUTION,f.makeMethodSig(0,"toString",Object.class,new Class[] {},new String[] {},new Class[0],String.class),1); JoinPoint.StaticPart exejp2 = f.makeSJP(JoinPoint.METHOD_EXECUTION,f.makeMethodSig(0,"sayHi",Hello.class,new Class[] {String.class},new String[] {"s"},new Class[0],void.class),1); JoinPoint.StaticPart execonsjp1 = f.makeSJP(JoinPoint.CONSTRUCTOR_EXECUTION,f.makeConstructorSig(0,Object.class,new Class[0],new String[0],new Class[0]),1); JoinPoint.StaticPart execonsjp2 = f.makeSJP(JoinPoint.CONSTRUCTOR_EXECUTION,f.makeConstructorSig(0,String.class,new Class[] {String.class},new String[]{"s"},new Class[0]),1); checkMatches(withinCode1,exejp1,FuzzyBoolean.YES); checkMatches(withinCode1,exejp2,FuzzyBoolean.NO); checkMatches(withinCode1,execonsjp1,FuzzyBoolean.NO); checkMatches(withinCode1,execonsjp2,FuzzyBoolean.NO); checkMatches(withinCode2,exejp1,FuzzyBoolean.NO); checkMatches(withinCode2,exejp2,FuzzyBoolean.NO); checkMatches(withinCode2,execonsjp1,FuzzyBoolean.YES); checkMatches(withinCode2,execonsjp2,FuzzyBoolean.YES); checkMatches(withinCode3,exejp1,FuzzyBoolean.NO); checkMatches(withinCode3,exejp2,FuzzyBoolean.NO); checkMatches(withinCode3,execonsjp1,FuzzyBoolean.NO); checkMatches(withinCode3,execonsjp2,FuzzyBoolean.YES); } private void checkMatches(Pointcut p, JoinPoint.StaticPart jpsp, FuzzyBoolean expected) { assertEquals(expected,p.match(null,jpsp)); } protected void setUp() throws Exception { super.setUp(); withinCode1 = new PatternParser("withincode(String Object.toString())").parsePointcut().resolve(); withinCode2 = new PatternParser("withincode(new(..))").parsePointcut().resolve(); withinCode3 = new PatternParser("withincode(String.new(..))").parsePointcut().resolve(); } private static class Hello {}; }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/patterns/WithinTestCase.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.*; import junit.framework.TestCase; import org.aspectj.weaver.*; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.lang.JoinPoint; import org.aspectj.runtime.reflect.Factory; import org.aspectj.util.FuzzyBoolean; public class WithinTestCase extends TestCase { World world = new BcelWorld(); public WithinTestCase(String name) { super(name); } public void testMatch() throws IOException { Shadow getOutFromArrayList = new TestShadow( Shadow.FieldGet, MemberImpl.fieldFromString("java.io.PrintStream java.lang.System.out"), UnresolvedType.forName("java.util.ArrayList"), world); checkMatch(makePointcut("within(*)"), getOutFromArrayList, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.util.*)"), getOutFromArrayList, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.lang.*)"), getOutFromArrayList, FuzzyBoolean.NO); checkMatch(makePointcut("within(java.util.List+)"), getOutFromArrayList, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.uti*.List+)"), getOutFromArrayList, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.uti*..*)"), getOutFromArrayList, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.util.*List)"), getOutFromArrayList, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.util.List*)"), getOutFromArrayList, FuzzyBoolean.NO); Shadow getOutFromEntry = new TestShadow( Shadow.FieldGet, MemberImpl.fieldFromString("java.io.PrintStream java.lang.System.out"), UnresolvedType.forName("java.util.Map$Entry"), world); checkMatch(makePointcut("within(*)"), getOutFromEntry, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.util.*)"), getOutFromEntry, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.util.Map.*)"), getOutFromEntry, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.util..*)"), getOutFromEntry, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.util.Map..*)"), getOutFromEntry, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.lang.*)"), getOutFromEntry, FuzzyBoolean.NO); checkMatch(makePointcut("within(java.util.List+)"), getOutFromEntry, FuzzyBoolean.NO); checkMatch(makePointcut("within(java.util.Map+)"), getOutFromEntry, FuzzyBoolean.YES); checkMatch(makePointcut("within(java.lang.Object+)"), getOutFromEntry, FuzzyBoolean.YES); //this is something we should in type patterns tests //checkMatch(makePointcut("within(*List)"), getOut, FuzzyBoolean.NO); } public void testMatchJP() { Factory f = new Factory("WithinTestCase.java",WithinTestCase.class); JoinPoint.StaticPart inString = f.makeSJP(JoinPoint.CONSTRUCTOR_EXECUTION,f.makeConstructorSig(0,String.class,new Class[] {String.class},new String[]{"s"},new Class[0]),1); JoinPoint.StaticPart inObject = f.makeSJP(JoinPoint.CONSTRUCTOR_EXECUTION,f.makeConstructorSig(0,Object.class,new Class[] {},new String[]{},new Class[0]),1); Pointcut withinString = new PatternParser("within(String)").parsePointcut().resolve(); Pointcut withinObject = new PatternParser("within(Object)").parsePointcut().resolve(); Pointcut withinObjectPlus = new PatternParser("within(Object+)").parsePointcut().resolve(); checkMatches(withinString,inString,FuzzyBoolean.YES); checkMatches(withinString,inObject,FuzzyBoolean.NO); checkMatches(withinObject,inString,FuzzyBoolean.NO); checkMatches(withinObject,inObject, FuzzyBoolean.YES); checkMatches(withinObjectPlus,inString,FuzzyBoolean.YES); checkMatches(withinObjectPlus,inObject,FuzzyBoolean.YES); } private void checkMatches(Pointcut p, JoinPoint.StaticPart jpsp, FuzzyBoolean expected) { assertEquals(expected,p.match(null,jpsp)); } public Pointcut makePointcut(String pattern) { Pointcut pointcut0 = Pointcut.fromString(pattern); Bindings bindingTable = new Bindings(0); IScope scope = new SimpleScope(world, FormalBinding.NONE); pointcut0.resolveBindings(scope, bindingTable); Pointcut pointcut1 = pointcut0; return pointcut1.concretize1(null, null, new IntMap()); } private void checkMatch(Pointcut p, Shadow s, FuzzyBoolean shouldMatch) throws IOException { FuzzyBoolean doesMatch = p.match(s); assertEquals(p + " matches " + s, shouldMatch, doesMatch); checkSerialization(p); } private void checkSerialization(Pointcut p) throws IOException { ByteArrayOutputStream bo = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bo); p.write(out); out.close(); ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); VersionedDataInputStream in = new VersionedDataInputStream(bi); Pointcut newP = Pointcut.read(in, null); assertEquals("write/read", p, newP); } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/reflect/ReflectionWorldTest.java
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/tools/PointcutExpressionTest.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.weaver.tools; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import junit.framework.TestCase; public class PointcutExpressionTest extends TestCase { PointcutParser p; Constructor asCons; Constructor bsCons; Constructor bsStringCons; Method a; Method aa; Method aaa; Field x; Field y; Method b; Method bsaa; Field n; Method foo; Method bar; public void testMatchesMethodCall() { PointcutExpression ex = p.parsePointcutExpression("call(* *..A.a*(..))"); assertEquals("Should match call to A.a()",FuzzyBoolean.YES,ex.matchesMethodCall(a,Client.class,A.class,null)); assertEquals("Should match call to A.aaa()",FuzzyBoolean.YES,ex.matchesMethodCall(aaa,Client.class,A.class,null)); assertEquals("Should match call to B.aa()",FuzzyBoolean.YES,ex.matchesMethodCall(bsaa,Client.class,A.class,null)); assertEquals("Should not match call to B.b()",FuzzyBoolean.NO,ex.matchesMethodCall(b,Client.class,A.class,null)); ex = p.parsePointcutExpression("call(* *..A.a*(int))"); assertEquals("Should match call to A.aa()",FuzzyBoolean.YES,ex.matchesMethodCall(aa,Client.class,A.class,null)); assertEquals("Should not match call to A.a()",FuzzyBoolean.NO,ex.matchesMethodCall(a,Client.class,A.class,null)); ex = p.parsePointcutExpression("call(void aaa(..)) && this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("Should match call to A.aaa() from Client",FuzzyBoolean.YES,ex.matchesMethodCall(aaa,Client.class,A.class,null)); ex = p.parsePointcutExpression("call(void aaa(..)) && this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Should match call to A.aaa() from B",FuzzyBoolean.YES,ex.matchesMethodCall(aaa,B.class,A.class,null)); assertEquals("May match call to A.aaa() from A",FuzzyBoolean.MAYBE,ex.matchesMethodCall(aaa,A.class,A.class,null)); ex = p.parsePointcutExpression("execution(* *.*(..))"); assertEquals("Should not match call to A.aa",FuzzyBoolean.NO,ex.matchesMethodCall(aa,A.class,A.class,null)); // this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("Should match Client",FuzzyBoolean.YES,ex.matchesMethodCall(a,Client.class,A.class,null)); assertEquals("Should not match A",FuzzyBoolean.NO,ex.matchesMethodCall(a,A.class,A.class,null)); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Should maybe match B",FuzzyBoolean.MAYBE,ex.matchesMethodCall(bsaa,A.class,B.class,null)); // target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("Should not match Client",FuzzyBoolean.NO,ex.matchesMethodCall(a,Client.class,A.class,null)); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("Should match A",FuzzyBoolean.YES,ex.matchesMethodCall(a,Client.class,A.class,null)); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Should maybe match A",FuzzyBoolean.MAYBE,ex.matchesMethodCall(aa,A.class,A.class,null)); // test args ex = p.parsePointcutExpression("args(..,int)"); assertEquals("Should match A.aa",FuzzyBoolean.YES,ex.matchesMethodCall(aa,A.class,A.class,null)); assertEquals("Should match A.aaa",FuzzyBoolean.YES,ex.matchesMethodCall(aaa,A.class,A.class,null)); assertEquals("Should not match A.a",FuzzyBoolean.NO,ex.matchesMethodCall(a,A.class,A.class,null)); // within ex = p.parsePointcutExpression("within(*..A)"); assertEquals("Matches in class A",FuzzyBoolean.YES,ex.matchesMethodCall(a,A.class,A.class,null)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesMethodCall(a,B.class,A.class,null)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Should match",FuzzyBoolean.YES,ex.matchesMethodCall(b,B.class,B.class,bsaa)); assertEquals("Should not match",FuzzyBoolean.NO,ex.matchesMethodCall(b,B.class,B.class,b)); } public void testMatchesMethodExecution() { PointcutExpression ex = p.parsePointcutExpression("execution(* *..A.aa(..))"); assertEquals("Should match execution of A.aa",FuzzyBoolean.YES,ex.matchesMethodExecution(aa,A.class)); assertEquals("Should match execution of B.aa",FuzzyBoolean.YES,ex.matchesMethodExecution(bsaa,B.class)); assertEquals("Should not match execution of A.a",FuzzyBoolean.NO,ex.matchesMethodExecution(a,B.class)); ex = p.parsePointcutExpression("call(* *..A.a*(int))"); assertEquals("Should not match execution of A.a",FuzzyBoolean.NO,ex.matchesMethodExecution(a,B.class)); // test this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("Should match A",FuzzyBoolean.YES,ex.matchesMethodExecution(a,A.class)); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesMethodExecution(a,A.class)); assertEquals("Should match B",FuzzyBoolean.YES,ex.matchesMethodExecution(a,B.class)); assertEquals("Does not match client",FuzzyBoolean.NO,ex.matchesMethodExecution(a,Client.class)); // test target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("Should match A",FuzzyBoolean.YES,ex.matchesMethodExecution(a,A.class)); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesMethodExecution(a,A.class)); assertEquals("Should match B",FuzzyBoolean.YES,ex.matchesMethodExecution(a,B.class)); assertEquals("Does not match client",FuzzyBoolean.NO,ex.matchesMethodExecution(a,Client.class)); // test args ex = p.parsePointcutExpression("args(..,int)"); assertEquals("Should match A.aa",FuzzyBoolean.YES,ex.matchesMethodExecution(aa,A.class)); assertEquals("Should match A.aaa",FuzzyBoolean.YES,ex.matchesMethodExecution(aaa,A.class)); assertEquals("Should not match A.a",FuzzyBoolean.NO,ex.matchesMethodExecution(a,A.class)); // within ex = p.parsePointcutExpression("within(*..A)"); assertEquals("Matches in class A",FuzzyBoolean.YES,ex.matchesMethodExecution(a,A.class)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesMethodExecution(bsaa,B.class)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Should not match",FuzzyBoolean.NO,ex.matchesMethodExecution(a,A.class)); } public void testMatchesConstructorCall() { PointcutExpression ex = p.parsePointcutExpression("call(new(String))"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesConstructorCall(asCons,A.class,null)); assertEquals("Should match B(String)", FuzzyBoolean.YES, ex.matchesConstructorCall(bsStringCons,Client.class,null)); assertEquals("Should not match B()", FuzzyBoolean.NO,ex.matchesConstructorCall(bsCons,Client.class,null)); ex = p.parsePointcutExpression("call(*..A.new(String))"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesConstructorCall(asCons,A.class,null)); assertEquals("Should not match B(String)", FuzzyBoolean.NO, ex.matchesConstructorCall(bsStringCons,Client.class,null)); // this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("Should match Client",FuzzyBoolean.YES,ex.matchesConstructorCall(asCons,Client.class,null)); assertEquals("Should not match A",FuzzyBoolean.NO,ex.matchesConstructorCall(asCons,A.class,null)); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Should maybe match B",FuzzyBoolean.MAYBE,ex.matchesConstructorCall(asCons,A.class,null)); // target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("Should not match Client",FuzzyBoolean.NO,ex.matchesConstructorCall(asCons,Client.class,null)); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("Should match A",FuzzyBoolean.YES,ex.matchesConstructorCall(asCons,A.class,null)); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Should maybe match A",FuzzyBoolean.MAYBE,ex.matchesConstructorCall(asCons,A.class,null)); // args ex = p.parsePointcutExpression("args(String)"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesConstructorCall(asCons,A.class,null)); assertEquals("Should match B(String)", FuzzyBoolean.YES, ex.matchesConstructorCall(bsStringCons,Client.class,null)); assertEquals("Should not match B()", FuzzyBoolean.NO,ex.matchesConstructorCall(bsCons,Client.class,null)); // within ex = p.parsePointcutExpression("within(*..A)"); assertEquals("Matches in class A",FuzzyBoolean.YES,ex.matchesConstructorCall(asCons,A.class,null)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesConstructorCall(asCons,B.class,null)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Should match",FuzzyBoolean.YES,ex.matchesConstructorCall(bsCons,B.class,aa)); assertEquals("Should not match",FuzzyBoolean.NO,ex.matchesConstructorCall(bsCons,B.class,b)); } public void testMatchesConstructorExecution() { PointcutExpression ex = p.parsePointcutExpression("execution(new(String))"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesConstructorExecution(asCons,A.class)); assertEquals("Should match B(String)", FuzzyBoolean.YES, ex.matchesConstructorExecution(bsStringCons,Client.class)); assertEquals("Should not match B()", FuzzyBoolean.NO,ex.matchesConstructorExecution(bsCons,Client.class)); ex = p.parsePointcutExpression("execution(*..A.new(String))"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesConstructorExecution(asCons,A.class)); assertEquals("Should not match B(String)", FuzzyBoolean.NO, ex.matchesConstructorExecution(bsStringCons,Client.class)); // test this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("Should match A",FuzzyBoolean.YES,ex.matchesConstructorExecution(asCons,A.class)); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesConstructorExecution(asCons,A.class)); assertEquals("Should match B",FuzzyBoolean.YES,ex.matchesConstructorExecution(asCons,B.class)); assertEquals("Does not match client",FuzzyBoolean.NO,ex.matchesConstructorExecution(asCons,Client.class)); // test target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("Should match A",FuzzyBoolean.YES,ex.matchesConstructorExecution(asCons,A.class)); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesConstructorExecution(asCons,A.class)); assertEquals("Should match B",FuzzyBoolean.YES,ex.matchesConstructorExecution(asCons,B.class)); assertEquals("Does not match client",FuzzyBoolean.NO,ex.matchesConstructorExecution(asCons,Client.class)); // within ex = p.parsePointcutExpression("within(*..A)"); assertEquals("Matches in class A",FuzzyBoolean.YES,ex.matchesConstructorExecution(asCons,B.class)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesConstructorExecution(bsCons,B.class)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Does not match",FuzzyBoolean.NO,ex.matchesConstructorExecution(bsCons,B.class)); // args ex = p.parsePointcutExpression("args(String)"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesConstructorExecution(asCons,A.class)); assertEquals("Should match B(String)", FuzzyBoolean.YES, ex.matchesConstructorExecution(bsStringCons,Client.class)); assertEquals("Should not match B()", FuzzyBoolean.NO,ex.matchesConstructorExecution(bsCons,Client.class)); } public void testMatchesAdviceExecution() { PointcutExpression ex = p.parsePointcutExpression("adviceexecution()"); assertEquals("Should match (advice) A.a",FuzzyBoolean.YES,ex.matchesAdviceExecution(a,A.class)); // test this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("Should match Client",FuzzyBoolean.YES,ex.matchesAdviceExecution(a,Client.class)); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesAdviceExecution(a,A.class)); assertEquals("Does not match client",FuzzyBoolean.NO,ex.matchesAdviceExecution(a,Client.class)); // test target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("Should match Client",FuzzyBoolean.YES,ex.matchesAdviceExecution(a,Client.class)); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesAdviceExecution(a,A.class)); assertEquals("Does not match client",FuzzyBoolean.NO,ex.matchesAdviceExecution(a,Client.class)); // test within ex = p.parsePointcutExpression("within(*..A)"); assertEquals("Matches in class A",FuzzyBoolean.YES,ex.matchesAdviceExecution(a,A.class)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesAdviceExecution(b,B.class)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Does not match",FuzzyBoolean.NO,ex.matchesAdviceExecution(a,A.class)); // test args ex = p.parsePointcutExpression("args(..,int)"); assertEquals("Should match A.aa",FuzzyBoolean.YES,ex.matchesAdviceExecution(aa,A.class)); assertEquals("Should match A.aaa",FuzzyBoolean.YES,ex.matchesAdviceExecution(aaa,A.class)); assertEquals("Should not match A.a",FuzzyBoolean.NO,ex.matchesAdviceExecution(a,A.class)); } public void testMatchesHandler() { PointcutExpression ex = p.parsePointcutExpression("handler(Exception)"); assertEquals("Should match catch(Exception)",FuzzyBoolean.YES,ex.matchesHandler(Exception.class,Client.class,null)); assertEquals("Should not match catch(Throwable)",FuzzyBoolean.NO,ex.matchesHandler(Throwable.class,Client.class,null)); // test this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("Should match Client",FuzzyBoolean.YES,ex.matchesHandler(Exception.class,Client.class,null)); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesHandler(Exception.class,A.class,null)); assertEquals("Does not match client",FuzzyBoolean.NO,ex.matchesHandler(Exception.class,Client.class,null)); // target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("Should match Client",FuzzyBoolean.YES,ex.matchesHandler(Exception.class,Client.class,null)); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesHandler(Exception.class,A.class,null)); assertEquals("Does not match client",FuzzyBoolean.NO,ex.matchesHandler(Exception.class,Client.class,null)); // args ex = p.parsePointcutExpression("args(Exception)"); assertEquals("Should match Exception",FuzzyBoolean.YES, ex.matchesHandler(Exception.class,Client.class,null)); assertEquals("Should match RuntimeException",FuzzyBoolean.YES, ex.matchesHandler(RuntimeException.class,Client.class,null)); assertEquals("Should not match String",FuzzyBoolean.NO,ex.matchesHandler(String.class,Client.class,null)); assertEquals("Maybe matches Throwable",FuzzyBoolean.MAYBE,ex.matchesHandler(Throwable.class,Client.class,null)); // within ex = p.parsePointcutExpression("within(*..Client)"); assertEquals("Matches in class Client",FuzzyBoolean.YES,ex.matchesHandler(Exception.class,Client.class,null)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesHandler(Exception.class,B.class,null)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Matches within aa",FuzzyBoolean.YES,ex.matchesHandler(Exception.class,Client.class,aa)); assertEquals("Does not match within b",FuzzyBoolean.NO,ex.matchesHandler(Exception.class,Client.class,b)); } public void testMatchesInitialization() { PointcutExpression ex = p.parsePointcutExpression("initialization(new(String))"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesInitialization(asCons)); assertEquals("Should match B(String)", FuzzyBoolean.YES, ex.matchesInitialization(bsStringCons)); assertEquals("Should not match B()", FuzzyBoolean.NO,ex.matchesInitialization(bsCons)); ex = p.parsePointcutExpression("initialization(*..A.new(String))"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesInitialization(asCons)); assertEquals("Should not match B(String)", FuzzyBoolean.NO, ex.matchesInitialization(bsStringCons)); // test this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("Should match A",FuzzyBoolean.YES,ex.matchesInitialization(asCons)); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesInitialization(asCons)); // test target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("Should match A",FuzzyBoolean.YES,ex.matchesInitialization(asCons)); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesInitialization(asCons)); // within ex = p.parsePointcutExpression("within(*..A)"); assertEquals("Matches in class A",FuzzyBoolean.YES,ex.matchesInitialization(asCons)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesInitialization(bsCons)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Does not match",FuzzyBoolean.NO,ex.matchesInitialization(bsCons)); // args ex = p.parsePointcutExpression("args(String)"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesInitialization(asCons)); assertEquals("Should match B(String)", FuzzyBoolean.YES, ex.matchesInitialization(bsStringCons)); assertEquals("Should not match B()", FuzzyBoolean.NO,ex.matchesInitialization(bsCons)); } public void testMatchesPreInitialization() { PointcutExpression ex = p.parsePointcutExpression("preinitialization(new(String))"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesPreInitialization(asCons)); assertEquals("Should match B(String)", FuzzyBoolean.YES, ex.matchesPreInitialization(bsStringCons)); assertEquals("Should not match B()", FuzzyBoolean.NO,ex.matchesPreInitialization(bsCons)); ex = p.parsePointcutExpression("preinitialization(*..A.new(String))"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesPreInitialization(asCons)); assertEquals("Should not match B(String)", FuzzyBoolean.NO, ex.matchesPreInitialization(bsStringCons)); // test this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("Should match A",FuzzyBoolean.YES,ex.matchesPreInitialization(asCons)); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesPreInitialization(asCons)); // test target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("Should match A",FuzzyBoolean.YES,ex.matchesPreInitialization(asCons)); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("Maybe matches B",FuzzyBoolean.MAYBE,ex.matchesPreInitialization(asCons)); // within ex = p.parsePointcutExpression("within(*..A)"); assertEquals("Matches in class A",FuzzyBoolean.YES,ex.matchesPreInitialization(asCons)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesPreInitialization(bsCons)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Does not match",FuzzyBoolean.NO,ex.matchesPreInitialization(bsCons)); // args ex = p.parsePointcutExpression("args(String)"); assertEquals("Should match A(String)",FuzzyBoolean.YES, ex.matchesPreInitialization(asCons)); assertEquals("Should match B(String)", FuzzyBoolean.YES, ex.matchesPreInitialization(bsStringCons)); assertEquals("Should not match B()", FuzzyBoolean.NO,ex.matchesPreInitialization(bsCons)); } public void testMatchesStaticInitialization() { // staticinit PointcutExpression ex = p.parsePointcutExpression("staticinitialization(*..A+)"); assertEquals("Matches A",FuzzyBoolean.YES,ex.matchesStaticInitialization(A.class)); assertEquals("Matches B",FuzzyBoolean.YES,ex.matchesStaticInitialization(B.class)); assertEquals("Doesn't match Client",FuzzyBoolean.NO,ex.matchesStaticInitialization(Client.class)); // this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("No this",FuzzyBoolean.NO,ex.matchesStaticInitialization(A.class)); // target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertEquals("No target",FuzzyBoolean.NO,ex.matchesStaticInitialization(A.class)); // args ex = p.parsePointcutExpression("args()"); assertEquals("No args",FuzzyBoolean.NO,ex.matchesStaticInitialization(A.class)); // within ex = p.parsePointcutExpression("within(*..A)"); assertEquals("Matches in class A",FuzzyBoolean.YES,ex.matchesStaticInitialization(A.class)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesStaticInitialization(B.class)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Does not match",FuzzyBoolean.NO,ex.matchesStaticInitialization(A.class)); } public void testMatchesFieldSet() { PointcutExpression ex = p.parsePointcutExpression("set(* *..A+.*)"); assertEquals("matches x",FuzzyBoolean.YES,ex.matchesFieldSet(x,Client.class,A.class,null)); assertEquals("matches y",FuzzyBoolean.YES,ex.matchesFieldSet(y,Client.class,B.class,null)); assertEquals("does not match n",FuzzyBoolean.NO,ex.matchesFieldSet(n,A.class,Client.class,null)); // this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("matches Client",FuzzyBoolean.YES,ex.matchesFieldSet(x,Client.class,A.class,null)); assertEquals("does not match A",FuzzyBoolean.NO,ex.matchesFieldSet(n,A.class,Client.class,null)); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("maybe matches A",FuzzyBoolean.MAYBE,ex.matchesFieldSet(x,A.class,A.class,null)); // target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("matches B",FuzzyBoolean.YES,ex.matchesFieldSet(y,Client.class,B.class,null)); assertEquals("maybe matches A",FuzzyBoolean.MAYBE,ex.matchesFieldSet(x,Client.class,A.class,null)); // args ex = p.parsePointcutExpression("args(int)"); assertEquals("matches x",FuzzyBoolean.YES,ex.matchesFieldSet(x,Client.class,A.class,null)); assertEquals("matches y",FuzzyBoolean.YES,ex.matchesFieldSet(y,Client.class,B.class,null)); assertEquals("does not match n",FuzzyBoolean.NO,ex.matchesFieldSet(n,A.class,Client.class,null)); // within ex = p.parsePointcutExpression("within(*..A)"); assertEquals("Matches in class A",FuzzyBoolean.YES,ex.matchesFieldSet(x,A.class,A.class,null)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesFieldSet(x,B.class,A.class,null)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Should match",FuzzyBoolean.YES,ex.matchesFieldSet(x,A.class,A.class,aa)); assertEquals("Should not match",FuzzyBoolean.NO,ex.matchesFieldSet(x,A.class,A.class,b)); } public void testMatchesFieldGet() { PointcutExpression ex = p.parsePointcutExpression("get(* *..A+.*)"); assertEquals("matches x",FuzzyBoolean.YES,ex.matchesFieldGet(x,Client.class,A.class,null)); assertEquals("matches y",FuzzyBoolean.YES,ex.matchesFieldGet(y,Client.class,B.class,null)); assertEquals("does not match n",FuzzyBoolean.NO,ex.matchesFieldGet(n,A.class,Client.class,null)); // this ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); assertEquals("matches Client",FuzzyBoolean.YES,ex.matchesFieldGet(x,Client.class,A.class,null)); assertEquals("does not match A",FuzzyBoolean.NO,ex.matchesFieldGet(n,A.class,Client.class,null)); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("maybe matches A",FuzzyBoolean.MAYBE,ex.matchesFieldGet(x,A.class,A.class,null)); // target ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); assertEquals("matches B",FuzzyBoolean.YES,ex.matchesFieldGet(y,Client.class,B.class,null)); assertEquals("maybe matches A",FuzzyBoolean.MAYBE,ex.matchesFieldGet(x,Client.class,A.class,null)); // args ex = p.parsePointcutExpression("args(int)"); assertEquals("matches x",FuzzyBoolean.NO,ex.matchesFieldGet(x,Client.class,A.class,null)); assertEquals("matches y",FuzzyBoolean.NO,ex.matchesFieldGet(y,Client.class,B.class,null)); assertEquals("does not match n",FuzzyBoolean.NO,ex.matchesFieldGet(n,A.class,Client.class,null)); // within ex = p.parsePointcutExpression("within(*..A)"); assertEquals("Matches in class A",FuzzyBoolean.YES,ex.matchesFieldGet(x,A.class,A.class,null)); assertEquals("Does not match in class B",FuzzyBoolean.NO,ex.matchesFieldGet(x,B.class,A.class,null)); // withincode ex = p.parsePointcutExpression("withincode(* a*(..))"); assertEquals("Should match",FuzzyBoolean.YES,ex.matchesFieldGet(x,A.class,A.class,aa)); assertEquals("Should not match",FuzzyBoolean.NO,ex.matchesFieldGet(x,A.class,A.class,b)); } public void testArgsMatching() { // too few args PointcutExpression ex = p.parsePointcutExpression("args(*,*,*,*)"); assertEquals("Too few args",FuzzyBoolean.NO,ex.matchesMethodExecution(foo,Client.class)); assertEquals("Matching #args",FuzzyBoolean.YES,ex.matchesMethodExecution(bar,Client.class)); // one too few + ellipsis ex = p.parsePointcutExpression("args(*,*,*,..)"); assertEquals("Matches with ellipsis",FuzzyBoolean.YES,ex.matchesMethodExecution(foo,Client.class)); // exact number + ellipsis assertEquals("Matches with ellipsis",FuzzyBoolean.YES,ex.matchesMethodExecution(bar,Client.class)); assertEquals("Does not match with ellipsis",FuzzyBoolean.NO,ex.matchesMethodExecution(a,A.class)); // too many + ellipsis ex = p.parsePointcutExpression("args(*,..,*)"); assertEquals("Matches with ellipsis",FuzzyBoolean.YES,ex.matchesMethodExecution(bar,Client.class)); assertEquals("Does not match with ellipsis",FuzzyBoolean.NO,ex.matchesMethodExecution(a,A.class)); assertEquals("Matches with ellipsis",FuzzyBoolean.YES,ex.matchesMethodExecution(aaa,A.class)); // exact match ex = p.parsePointcutExpression("args(String,int,Number)"); assertEquals("Matches exactly",FuzzyBoolean.YES,ex.matchesMethodExecution(foo,Client.class)); // maybe match ex = p.parsePointcutExpression("args(String,int,Double)"); assertEquals("Matches maybe",FuzzyBoolean.MAYBE,ex.matchesMethodExecution(foo,Client.class)); // never match ex = p.parsePointcutExpression("args(String,Integer,Number)"); assertEquals("Does not match",FuzzyBoolean.NO,ex.matchesMethodExecution(foo,Client.class)); } public void testMatchesDynamically() { // everything other than this,target,args should just return true PointcutExpression ex = p.parsePointcutExpression("call(* *.*(..)) && execution(* *.*(..)) &&" + "get(* *) && set(* *) && initialization(new(..)) && preinitialization(new(..)) &&" + "staticinitialization(X) && adviceexecution() && within(Y) && withincode(* *.*(..)))"); assertTrue("Matches dynamically",ex.matchesDynamically(a,b,new Object[0])); // this ex = p.parsePointcutExpression("this(String)"); assertTrue("String matches",ex.matchesDynamically("",this,new Object[0])); assertFalse("Object doesn't match",ex.matchesDynamically(new Object(),this,new Object[0])); ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertTrue("A matches",ex.matchesDynamically(new A(""),this,new Object[0])); assertTrue("B matches",ex.matchesDynamically(new B(""),this,new Object[0])); // target ex = p.parsePointcutExpression("target(String)"); assertTrue("String matches",ex.matchesDynamically(this,"",new Object[0])); assertFalse("Object doesn't match",ex.matchesDynamically(this,new Object(),new Object[0])); ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); assertTrue("A matches",ex.matchesDynamically(this,new A(""),new Object[0])); assertTrue("B matches",ex.matchesDynamically(this,new B(""),new Object[0])); // args ex = p.parsePointcutExpression("args(*,*,*,*)"); assertFalse("Too few args",ex.matchesDynamically(null,null,new Object[]{a,b})); assertTrue("Matching #args",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); // one too few + ellipsis ex = p.parsePointcutExpression("args(*,*,*,..)"); assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); // exact number + ellipsis assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa})); assertFalse("Does not match with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b})); // too many + ellipsis ex = p.parsePointcutExpression("args(*,..,*)"); assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); assertFalse("Does not match with ellipsis",ex.matchesDynamically(null,null,new Object[]{a})); assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b})); // exact match ex = p.parsePointcutExpression("args(String,int,Number)"); assertTrue("Matches exactly",ex.matchesDynamically(null,null,new Object[]{"",new Integer(5),new Double(5.0)})); ex = p.parsePointcutExpression("args(String,Integer,Number)"); assertTrue("Matches exactly",ex.matchesDynamically(null,null,new Object[]{"",new Integer(5),new Double(5.0)})); // never match ex = p.parsePointcutExpression("args(String,Integer,Number)"); assertFalse("Does not match",ex.matchesDynamically(null,null,new Object[]{a,b,aa})); } public void testGetPointcutExpression() { PointcutExpression ex = p.parsePointcutExpression("staticinitialization(*..A+)"); assertEquals("staticinitialization(*..A+)",ex.getPointcutExpression()); } public void testCouldMatchJoinPointsInType() { PointcutExpression ex = p.parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..))"); assertFalse("Could never match String",ex.couldMatchJoinPointsInType(String.class)); assertTrue("Will always match B",ex.couldMatchJoinPointsInType(B.class)); assertFalse("Does not match A",ex.couldMatchJoinPointsInType(A.class)); } public void testMayNeedDynamicTest() { PointcutExpression ex = p.parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..))"); assertFalse("No dynamic test needed",ex.mayNeedDynamicTest()); ex = p.parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..)) && args(X)"); assertTrue("Dynamic test needed",ex.mayNeedDynamicTest()); } protected void setUp() throws Exception { super.setUp(); p = new PointcutParser(); asCons = A.class.getConstructor(new Class[]{String.class}); bsCons = B.class.getConstructor(new Class[0]); bsStringCons = B.class.getConstructor(new Class[]{String.class}); a = A.class.getMethod("a",new Class[0]); aa = A.class.getMethod("aa",new Class[]{int.class}); aaa = A.class.getMethod("aaa",new Class[]{String.class,int.class}); x = A.class.getDeclaredField("x"); y = B.class.getDeclaredField("y"); b = B.class.getMethod("b",new Class[0]); bsaa = B.class.getMethod("aa",new Class[]{int.class}); n = Client.class.getDeclaredField("n"); foo = Client.class.getDeclaredMethod("foo",new Class[]{String.class,int.class,Number.class}); bar = Client.class.getDeclaredMethod("bar",new Class[]{String.class,int.class,Integer.class,Number.class}); } static class A { public A(String s) {} public void a() {} public void aa(int i) {} public void aaa(String s, int i) {} int x; } static class B extends A { public B() {super("");} public B(String s) {super(s);} public String b() { return null; } public void aa(int i) {} int y; } static class Client { Number n; public void foo(String s, int i, Number n) {} public void bar(String s, int i, Integer i2, Number n) {} } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/org/aspectj/weaver/tools/PointcutParserTest.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.tools; import java.util.HashSet; import java.util.Set; import junit.framework.TestCase; /** * Test cases for the PointcutParser class */ public class PointcutParserTest extends TestCase { public void testGetAllSupportedPointcutPrimitives() { Set s = PointcutParser.getAllSupportedPointcutPrimitives(); assertEquals("Should be 14 elements in the set",14,s.size()); assertFalse("Should not contain if pcd",s.contains(PointcutPrimitive.IF)); assertFalse("Should not contain cflow pcd",s.contains(PointcutPrimitive.CFLOW)); assertFalse("Should not contain cflowbelow pcd",s.contains(PointcutPrimitive.CFLOW_BELOW)); } public void testEmptyConstructor() { PointcutParser parser = new PointcutParser(); Set s = parser.getSupportedPrimitives(); assertEquals("Should be 14 elements in the set",14,s.size()); assertFalse("Should not contain if pcd",s.contains(PointcutPrimitive.IF)); assertFalse("Should not contain cflow pcd",s.contains(PointcutPrimitive.CFLOW)); assertFalse("Should not contain cflowbelow pcd",s.contains(PointcutPrimitive.CFLOW_BELOW)); } public void testSetConstructor() { Set p = PointcutParser.getAllSupportedPointcutPrimitives(); PointcutParser parser = new PointcutParser(p); assertEquals("Should use the set we pass in",p,parser.getSupportedPrimitives()); Set q = new HashSet(); q.add(PointcutPrimitive.ARGS); parser = new PointcutParser(q); assertEquals("Should have only one element in set",1,parser.getSupportedPrimitives().size()); assertEquals("Should only have ARGS pcd",PointcutPrimitive.ARGS, parser.getSupportedPrimitives().iterator().next()); } public void testParsePointcutExpression() { PointcutParser p = new PointcutParser(); PointcutExpression pEx = p.parsePointcutExpression( "(adviceexecution() || execution(* *.*(..)) || handler(Exception) || " + "call(Foo Bar+.*(Goo)) || get(* foo) || set(Foo+ (Goo||Moo).s*) || " + "initialization(Foo.new(..)) || preinitialization(*.new(Foo,..)) || " + "staticinitialization(org.xzy.abc..*)) && (this(Foo) || target(Boo) ||" + "args(A,B,C)) && !handler(X)"); try { pEx = p.parsePointcutExpression("gobble-de-gook()"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException ex) {} } public void testParseExceptionErrorMessages() { PointcutParser p = new PointcutParser(); try { PointcutExpression pEx = p.parsePointcutExpression("execution(int Foo.*(..) && args(Double)"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertTrue("Pointcut is not well-formed message",ex.getMessage().startsWith("Pointcut is not well-formed: expecting ')' at character position 24")); } } public void testParseIfPCD() { PointcutParser p = new PointcutParser(); try { p.parsePointcutExpression("if(true)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Should not support IF",PointcutPrimitive.IF,ex.getUnsupportedPrimitive()); } } public void testParseCflowPCDs() { PointcutParser p = new PointcutParser(); try { p.parsePointcutExpression("cflow(this(t))"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Should not support CFLOW",PointcutPrimitive.CFLOW,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("cflowbelow(this(t))"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Should not support CFLOW_BELOW",PointcutPrimitive.CFLOW_BELOW,ex.getUnsupportedPrimitive()); } } public void testParseReferencePCDs() { PointcutParser p = new PointcutParser(); try { p.parsePointcutExpression("bananas(x)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertTrue(ex.getUnsupportedPrimitive() == PointcutPrimitive.REFERENCE); } } public void testParseUnsupportedPCDs() { Set s = new HashSet(); PointcutParser p = new PointcutParser(s); try { p.parsePointcutExpression("args(x)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Args",PointcutPrimitive.ARGS,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("within(x)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Within",PointcutPrimitive.WITHIN,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("withincode(new(..))"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Withincode",PointcutPrimitive.WITHIN_CODE,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("handler(Exception)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("handler",PointcutPrimitive.HANDLER,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("this(X)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("this",PointcutPrimitive.THIS,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("target(X)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("target",PointcutPrimitive.TARGET,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("this(X) && target(Y)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("This",PointcutPrimitive.THIS,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("this(X) || target(Y)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("This",PointcutPrimitive.THIS,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("!this(X)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("This",PointcutPrimitive.THIS,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("call(* *.*(..))"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Call",PointcutPrimitive.CALL,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("execution(* *.*(..))"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Execution",PointcutPrimitive.EXECUTION,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("get(* *)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Get",PointcutPrimitive.GET,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("set(* *)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Set",PointcutPrimitive.SET,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("initialization(new(..))"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Initialization",PointcutPrimitive.INITIALIZATION,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("preinitialization(new(..))"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Prc-init",PointcutPrimitive.PRE_INITIALIZATION,ex.getUnsupportedPrimitive()); } try { p.parsePointcutExpression("staticinitialization(T)"); fail("Expected UnsupportedPointcutPrimitiveException"); } catch(UnsupportedPointcutPrimitiveException ex) { assertEquals("Staticinit",PointcutPrimitive.STATIC_INITIALIZATION,ex.getUnsupportedPrimitive()); } } }
108,120
Bug 108120 Complete implemenation of runtime pointcut parsing and matching
The weaver API for runtime pointcut parsing and matching needs extending for all of the new pointcuts we have added in AJ5. Recommended approach is to implement JavaLangReflectObjectType as a new ReferenceTypeDelegate, and a JavaLangReflectWorld in place of BcelWorld.
resolved fixed
a39f595
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T14:59:55Z
2005-08-26T15:26:40Z
weaver/testsrc/reflect/tests/C.java
104,957
Bug 104957 NullPointerException when running ajc on gij
When running ajc 1.2.1 on the GNU Interpreter for Java 4.0.1, I received this error: java.lang.NullPointerException at org.aspectj.apache.bcel.generic.InstructionComparator$1.equals(org.aspectj.apache.bcel.generic.Instruction, org.aspectj.apache.bcel.g eneric.Instruction) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.apache.bcel.generic.Instruction.equals(java.lang.Object) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so) at java.util.AbstractMap.equals(java.lang.Object, java.lang.Object) (/usr/lib/libgcj.so.6.0.0) at java.util.HashMap.put(java.lang.Object, java.lang.Object) (/usr/lib/libgcj.so.6.0.0) at java.util.HashSet.add(java.lang.Object) (/usr/lib/libgcj.so.6.0.0) at org.aspectj.apache.bcel.generic.InstructionHandle.addTargeter(org.aspectj.apache.bcel.generic.InstructionTargeter) (/tmp/cache/local/ aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.apache.bcel.generic.BranchInstruction.notifyTarget(org.aspectj.apache.bcel.generic.InstructionHandle, org.aspectj.apache. bcel.generic.InstructionHandle, org.aspectj.apache.bcel.generic.InstructionTargeter) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.apache.bcel.generic.BranchInstruction.setTarget(org.aspectj.apache.bcel.generic.InstructionHandle) (/tmp/cache/local/aspe ctj1.2/lib/aspectjweaver.jar.so) at org.aspectj.apache.bcel.generic.BranchInstruction.BranchInstruction(short, org.aspectj.apache.bcel.generic.InstructionHandle) (/tmp/c ache/local/aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.apache.bcel.generic.Select.Select(short, int[], org.aspectj.apache.bcel.generic.InstructionHandle[], org.aspectj.apache.b cel.generic.InstructionHandle) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.apache.bcel.generic.LOOKUPSWITCH.LOOKUPSWITCH(int[], org.aspectj.apache.bcel.generic.InstructionHandle[], org.aspectj.apa che.bcel.generic.InstructionHandle) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.apache.bcel.generic.SWITCH.SWITCH(int[], org.aspectj.apache.bcel.generic.InstructionHandle[], org.aspectj.apache.bcel.gen eric.InstructionHandle, int) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.apache.bcel.generic.SWITCH.SWITCH(int[], org.aspectj.apache.bcel.generic.InstructionHandle[], org.aspectj.apache.bcel.gen eric.InstructionHandle) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.weaver.bcel.Utility.copyInstruction(org.aspectj.apache.bcel.generic.Instruction) (/tmp/cache/local/aspectj1.2/lib/aspectj weaver.jar.so) at org.aspectj.weaver.bcel.LazyMethodGen.packBody(org.aspectj.apache.bcel.generic.MethodGen) (/tmp/cache/local/aspectj1.2/lib/aspectjwea ver.jar.so) at org.aspectj.weaver.bcel.LazyMethodGen.pack() (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.weaver.bcel.LazyMethodGen.getMethod() (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.weaver.bcel.LazyClassGen.writeBack(org.aspectj.weaver.bcel.BcelWorld) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar. so) at org.aspectj.weaver.bcel.LazyClassGen.getJavaClass(org.aspectj.weaver.bcel.BcelWorld) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.j ar.so) at org.aspectj.weaver.bcel.BcelWeaver.getClassFilesFor(org.aspectj.weaver.bcel.LazyClassGen) (/tmp/cache/local/aspectj1.2/lib/aspectjwea ver.jar.so) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(org.aspectj.weaver.bcel.UnwovenClassFile, org.aspectj.weaver.bcel.BcelObjectType, o rg.aspectj.weaver.IWeaveRequestor) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so) at org.aspectj.weaver.bcel.BcelWeaver.weave(org.aspectj.weaver.IClassFileProvider) (/tmp/cache/local/aspectj1.2/lib/aspectjweaver.jar.so ) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave() (Unknown Source) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling() (Unknown Source) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit[]) (Unknown Source) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(java.util.List) (Unknown Source) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(org.aspectj.ajdt.internal.core.builder.AjBuildConfig, org.aspectj.bridg e.IMessageHandler, boolean) (Unknown Source) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(org.aspectj.ajdt.internal.core.builder.AjBuildConfig, org.aspectj.br idge.IMessageHandler) (Unknown Source) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(org.aspectj.bridge.IMessageHandler, boolean) (Unknown Source) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(java.lang.String[], org.aspectj.bridge.IMessageHandler) (Unknown Source) at org.aspectj.tools.ajc.Main.run(java.lang.String[], org.aspectj.bridge.IMessageHolder) (Unknown Source) at org.aspectj.tools.ajc.Main.runMain(java.lang.String[], boolean) (Unknown Source) at org.aspectj.tools.ajc.Main.main(java.lang.String[]) (Unknown Source) at gnu.java.lang.MainThread.call_main() (/usr/lib/libgcj.so.6.0.0) at gnu.java.lang.MainThread.run() (/usr/lib/libgcj.so.6.0.0) Unfortunately, the above stack trace contains no line number information; however, by running the program under the gdb debugger, I was able to get a backtrace with line numbers for the relevant part of the stack trace: (gdb) bt #0 0x011a0246 in org.aspectj.apache.bcel.generic.InstructionComparator$1.equals(org.aspectj.apache.bcel.generic.Instruction, org.aspectj.apache.bcel.generic.Instruction) (this=@5c71ea8, i1=@610fe70, i2=@610fc60) at org/aspectj/apache/bcel/generic/InstructionComparator.java:79 #1 0x011a004e in org.aspectj.apache.bcel.generic.Instruction.equals(java.lang.Object) (this=@610fe70, that=@610fc60) at org/aspectj/apache/bcel/generic/Instruction.java:499 #2 0x031b5f9b in java.util.AbstractMap.equals(java.lang.Object, java.lang.Object) (o1=@610fe70, o2=@610fc60) at ../../../libjava/java/util/AbstractMap.java:603 #3 0x031cc0ae in java.util.HashMap.put(java.lang.Object, java.lang.Object) (this=@6483690, key=@610fe70, value=@2dfc0) at ../../../libjava/java/util/HashMap.java:349 #4 0x031cca00 in java.util.HashSet.add(java.lang.Object) (this=null, o=@610fe70) at ../../../libjava/java/util/HashSet.java:151 #5 0x011b30ad in org.aspectj.apache.bcel.generic.InstructionHandle.addTargeter(org.aspectj.apache.bcel.generic.InstructionTargeter) ( this=@6949d20, t=@610fe70) at org/aspectj/apache/bcel/generic/InstructionHandle.java:208 #6 0x011861e6 in org.aspectj.apache.bcel.generic.BranchInstruction.notifyTarget(org.aspectj.apache.bcel.generic.InstructionHandle, org.aspectj.apache.bcel.generic.InstructionHandle, org.aspectj.apache.bcel.generic.InstructionTargeter) (old_ih=null, new_ih=@6949d20, t=@610fe70) at org/aspectj/apache/bcel/generic/BranchInstruction.java:217 #7 0x01186133 in org.aspectj.apache.bcel.generic.BranchInstruction.setTarget(org.aspectj.apache.bcel.generic.InstructionHandle) ( this=@610fe70, target=@6949d20) at org/aspectj/apache/bcel/generic/BranchInstruction.java:205 #8 0x011857ef in org.aspectj.apache.bcel.generic.BranchInstruction.BranchInstruction(short, org.aspectj.apache.bcel.generic.InstructionHandle) (this=@610fe70, opcode=171, target=@6949d20) at org/aspectj/apache/bcel/generic/BranchInstruction.java:86 #9 0x011d3489 in org.aspectj.apache.bcel.generic.Select.Select(short, int[], org.aspectj.apache.bcel.generic.InstructionHandle[], org.aspectj.apache.bcel.generic.InstructionHandle) (this=@610fe70, opcode=171, match=@6f63b90, targets=@6eeabe0, target=@6949d20) at org/aspectj/apache/bcel/generic/Select.java:106 #10 0x011c3152 in org.aspectj.apache.bcel.generic.LOOKUPSWITCH.LOOKUPSWITCH(int[], org.aspectj.apache.bcel.generic.InstructionHandle[], org.aspectj.apache.bcel.generic.InstructionHandle) (this=@610fe70, match=@6f63b90, targets=@6eeabe0, target=@6949d20) at org/aspectj/apache/bcel/generic/LOOKUPSWITCH.java:80 #11 0x011d4f94 in org.aspectj.apache.bcel.generic.SWITCH.SWITCH(int[], org.aspectj.apache.bcel.generic.InstructionHandle[], org.aspectj.apache.bcel.generic.InstructionHandle, int) (this=@6a20978, match=@5b1ccd0, targets=@6eeac08, target=@6949d20, max_gap=1) at org/aspectj/apache/bcel/generic/SWITCH.java:104 #12 0x011d5002 in org.aspectj.apache.bcel.generic.SWITCH.SWITCH(int[], org.aspectj.apache.bcel.generic.InstructionHandle[], org.aspectj.apache.bcel.generic.InstructionHandle) (this=@6a20978, match=@5b1ccd0, targets=@6eeac08, target=@6949d20) at org/aspectj/apache/bcel/generic/SWITCH.java:109 #13 0x01332eb6 in org.aspectj.weaver.bcel.Utility.copyInstruction(org.aspectj.apache.bcel.generic.Instruction) (i=@610fc60) at org/aspectj/weaver/bcel/Utility.java:474 #14 0x01326f66 in org.aspectj.weaver.bcel.LazyMethodGen.packBody(org.aspectj.apache.bcel.generic.MethodGen) (this=@6d98000, gen=@6d983c0) at org/aspectj/weaver/bcel/LazyMethodGen.java:813 #15 0x01326d08 in org.aspectj.weaver.bcel.LazyMethodGen.pack() (this=@6d98000) at org/aspectj/weaver/bcel/LazyMethodGen.java:790 #16 0x01324c81 in org.aspectj.weaver.bcel.LazyMethodGen.getMethod() (this=@6d98000) at org/aspectj/weaver/bcel/LazyMethodGen.java:336 #17 0x0131b502 in org.aspectj.weaver.bcel.LazyClassGen.writeBack(org.aspectj.weaver.bcel.BcelWorld) (this=@610ff00, world=@5642d20) at org/aspectj/weaver/bcel/LazyClassGen.java:418 #18 0x0131b95e in org.aspectj.weaver.bcel.LazyClassGen.getJavaClass(org.aspectj.weaver.bcel.BcelWorld) (this=@610ff00, world=@5642d20) at org/aspectj/weaver/bcel/LazyClassGen.java:446 #19 0x01311589 in org.aspectj.weaver.bcel.BcelWeaver.getClassFilesFor(org.aspectj.weaver.bcel.LazyClassGen) (this=@a33c0, clazz=@610ff00) <snip> It might be difficult for me to provide a reproducable test case (it might depend on the gij version, but I can try if wanted). However, happily, having examined the bytecode of the BCEL classes from the first few lines of the stack trace, I think I can explain why this exception occurs without needing to provide a test case. It's very simple. Whoever wrote the BCEL code in question, obviously never ran it with a data set and on a virtual machine where a hash collision in the HashSet would occur. Because, with this BCEL snapshot, if a hash collision does occur, the object being added to the HashSet is *guaranteed* to cause a NullPointerException in the Comparator method. This can be seen merely by examining the code path described by this stack trace. The field "targets" in the LOOKUPSWITCH object has not been initialized when notifyTarget is called, so if there is a hash collision in the HashSet, the InstructionComparator will be called - and it is guaranteed to call getTargets () and access its array length, which will cause a NullPointerException. I hope this explanation is sufficiently clear. If not, I will be happy to provide further details.
resolved fixed
0e1bb19
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T16:28:36Z
2005-07-25T00:06:40Z
bcel-builder/src/org/aspectj/apache/bcel/generic/InstructionComparator.java
package org.aspectj.apache.bcel.generic; /* ==================================================================== * 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/>. */ /** * Equality of instructions isn't clearly to be defined. You might * wish, for example, to compare whether instructions have the same * meaning. E.g., whether two INVOKEVIRTUALs describe the same * call.<br>The DEFAULT comparator however, considers two instructions * to be equal if they have same opcode and point to the same indexes * (if any) in the constant pool or the same local variable index. Branch * instructions must have the same target. * * @see Instruction * @version $Id: InstructionComparator.java,v 1.2 2004/11/19 16:45:19 aclement Exp $ * @author <A HREF="mailto:[email protected]">M. Dahm</A> */ public interface InstructionComparator { public static final InstructionComparator DEFAULT = new InstructionComparator() { public boolean equals(Instruction i1, Instruction i2) { if(i1.opcode == i2.opcode) { if(i1 instanceof Select) { InstructionHandle[] t1 = ((Select)i1).getTargets(); InstructionHandle[] t2 = ((Select)i2).getTargets(); if(t1.length == t2.length) { for(int i = 0; i < t1.length; i++) { if(t1[i] != t2[i]) { return false; } } return true; } } else if(i1 instanceof BranchInstruction) { return ((BranchInstruction)i1).target == ((BranchInstruction)i2).target; } else if(i1 instanceof ConstantPushInstruction) { return ((ConstantPushInstruction)i1).getValue(). equals(((ConstantPushInstruction)i2).getValue()); } else if(i1 instanceof IndexedInstruction) { return ((IndexedInstruction)i1).getIndex() == ((IndexedInstruction)i2).getIndex(); } else if(i1 instanceof NEWARRAY) { return ((NEWARRAY)i1).getTypecode() == ((NEWARRAY)i2).getTypecode(); } else { return true; } } return false; } }; public boolean equals(Instruction i1, Instruction i2); }
76,374
Bug 76374 Problem with declare parents when using non-public classes
Non-public classes, when explicitly named, do not get woven. The test case below exhibits this problem when the package declaration is uncommented. If the package declaration is commented out, the class is woven correctly. If the package declaration is uncommented, a compilation failure occurs with AspectJ 1.2. According to Andrew Clement, AspectJ 1.2.1 compiles, but does not weave. If the "MyInnerClass" is changed to be public [regardless of the package declaration status], the class is woven correctly. Also: When the "MyInnerClass" is moved out of "MyClass", but kept in the MyClass.java file, then the following behavior is exhibited: If the package declaration is commented out, the class is woven correctly. If the package declaration is uncommented out, a compilation failure occurs with AspectJ 1.2. Note, in this case, MyInnerClass cannot be declared as public. It also appears that if the RunnableAspect is placed in the same package as "MyClass", weaving occurs correctly, regardless of any class access modifiers <MyClass.java> // package mypackage; public class MyClass { public MyClass() { MyInnerClass mic = new MyInnerClass(); if (mic instanceof Runnable) mic.run(); } class MyInnerClass { public void run() { System.out.println("In MyInnerClass.run()!!"); } } public static void main(String args[]) { new MyClass(); } } </MyClass.java> <RunnableAspect.aj> public aspect RunnableAspect { declare parents: MyClass$MyInnerClass implements Runnable; // declare parents: mypackage.MyClass$MyInnerClass implements Runnable; } </RunnableAspect.aj>
resolved fixed
ca9c1f7
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-21T16:51:15Z
2004-10-15T17: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 junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; 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; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ 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 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");} // 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); } }
109,283
Bug 109283 Invalid "indirect static access" warning on EnumSet.noneOf
When compiling AspectJ enabled projects in Java 5.0 source mode with "Indirect access to static modifier" warnings on, the following code incorrectly gives a compiler warning (this doesn't occur in non-AspectJ enabled projects): public class Test { enum Foo { Wibble, Wobble, Woo; } public static void main(String[] args) { EnumSet<Foo> set = EnumSet.noneOf(Foo.class); } }
resolved fixed
8a0f59a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-22T15:45:06Z
2005-09-12T13:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.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 java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope; import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType; import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger; import org.aspectj.ajdt.internal.compiler.lookup.HelperInterfaceBinding; import org.aspectj.ajdt.internal.compiler.lookup.InlineAccessFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; 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.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Clinit; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream; import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.ExceptionLabel; import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.Label; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.InvocationSite; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.PerFromSuper; import org.aspectj.weaver.patterns.PerSingleton; import org.aspectj.weaver.patterns.TypePattern; //import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; // (we used to...) making all aspects member types avoids a nasty hierarchy pain // switched from MemberTypeDeclaration to TypeDeclaration public class AspectDeclaration extends TypeDeclaration { //public IAjDeclaration[] ajDeclarations; private AjAttribute.Aspect aspectAttribute; public PerClause perClause; public ResolvedMember aspectOfMethod; public ResolvedMember hasAspectMethod; public Map accessForInline = new HashMap(); public Map superAccessForInline = new HashMap(); public boolean isPrivileged; private int declaredModifiers; public EclipseSourceType concreteName; public ReferenceType typeX; public EclipseFactory factory; //??? should use this consistently public int adviceCounter = 1; // Used as a part of the generated name for advice methods public int declareCounter= 1; // Used as a part of the generated name for methods representing declares // for better error messages in 1.0 to 1.1 transition public TypePattern dominatesPattern; public AspectDeclaration(CompilationResult compilationResult) { super(compilationResult); //perClause = new PerSingleton(); } public boolean isAbstract() { return (modifiers & AccAbstract) != 0; } public void resolve() { declaredModifiers = modifiers; // remember our modifiers, we're going to be public in generateCode if (binding == null) { ignoreFurtherInvestigation = true; return; } super.resolve(); } public void checkSpec(ClassScope scope) { if (ignoreFurtherInvestigation) return; if (dominatesPattern != null) { scope.problemReporter().signalError( dominatesPattern.getStart(), dominatesPattern.getEnd(), "dominates has changed for 1.1, use 'declare precedence: " + new String(this.name) + ", " + dominatesPattern.toString() + ";' " + "in the body of the aspect instead"); } if (!isAbstract()) { MethodBinding[] methods = binding.methods(); for (int i=0, len = methods.length; i < len; i++) { MethodBinding m = methods[i]; if (m.isConstructor()) { // this make all constructors in aspects invisible and thus uncallable //XXX this only works for aspects that come from source methods[i] = new MethodBinding(m, binding) { public boolean canBeSeenBy( InvocationSite invocationSite, Scope scope) { return false; } }; if (m.parameters != null && m.parameters.length != 0) { scope.problemReporter().signalError(m.sourceStart(), m.sourceEnd(), "only zero-argument constructors allowed in concrete aspect"); } } } // check the aspect was not declared generic, only abstract aspects can have type params if (typeParameters != null && typeParameters.length > 0) { scope.problemReporter().signalError(sourceStart(), sourceEnd(), "only abstract aspects can have type parameters"); } } if (this.enclosingType != null) { if (!Modifier.isStatic(modifiers)) { scope.problemReporter().signalError(sourceStart, sourceEnd, "inner aspects must be static"); ignoreFurtherInvestigation = true; return; } } EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); ResolvedType myType = typeX; //if (myType == null) System.err.println("bad myType for: " + this); ResolvedType superType = myType.getSuperclass(); // can't be Serializable/Cloneable unless -XserializableAspects if (!world.isXSerializableAspects()) { if (world.getWorld().getCoreType(UnresolvedType.SERIALIZABLE).isAssignableFrom(myType)) { scope.problemReporter().signalError(sourceStart, sourceEnd, "aspects may not implement Serializable"); ignoreFurtherInvestigation = true; return; } if (world.getWorld().getCoreType(UnresolvedType.CLONEABLE).isAssignableFrom(myType)) { scope.problemReporter().signalError(sourceStart, sourceEnd, "aspects may not implement Cloneable"); ignoreFurtherInvestigation = true; return; } } if (superType.isAspect()) { if (!superType.isAbstract()) { scope.problemReporter().signalError(sourceStart, sourceEnd, "can not extend a concrete aspect"); ignoreFurtherInvestigation = true; return; } // if super type is generic, check that we have fully parameterized it if (superType.isRawType()) { scope.problemReporter().signalError(sourceStart, sourceEnd, "a generic super-aspect must be fully parameterized in an extends clause"); ignoreFurtherInvestigation = true; return; } } } private FieldBinding initFailureField= null; /** * AMC - this method is called by the AtAspectJVisitor during beforeCompilation processing in * the AjCompiler adapter. We use this hook to add in the @AspectJ annotations. */ public void addAtAspectJAnnotations() { Annotation atAspectAnnotation = AtAspectJAnnotationFactory.createAspectAnnotation(perClause.toDeclarationString(), declarationSourceStart); Annotation privilegedAnnotation = null; if (isPrivileged) privilegedAnnotation = AtAspectJAnnotationFactory.createPrivilegedAnnotation(declarationSourceStart); Annotation[] toAdd = new Annotation[isPrivileged ? 2 : 1]; toAdd[0] = atAspectAnnotation; if (isPrivileged) toAdd[1] = privilegedAnnotation; if (annotations == null) { annotations = toAdd; } else { Annotation[] old = annotations; annotations = new Annotation[annotations.length + toAdd.length]; System.arraycopy(old,0,annotations,0,old.length); System.arraycopy(toAdd,0,annotations,old.length,toAdd.length); } } public void generateCode(ClassFile enclosingClassFile) { if (ignoreFurtherInvestigation) { if (binding == null) return; ClassFile.createProblemType( this, scope.referenceCompilationUnit().compilationResult); return; } // make me and my binding public this.modifiers = AstUtil.makePublic(this.modifiers); this.binding.modifiers = AstUtil.makePublic(this.binding.modifiers); if (!isAbstract()) { initFailureField = factory.makeFieldBinding(AjcMemberMaker.initFailureCauseField(typeX)); binding.addField(initFailureField); if (perClause == null) { // we've already produced an error for this } else if (perClause.getKind() == PerClause.SINGLETON) { binding.addField(factory.makeFieldBinding(AjcMemberMaker.perSingletonField( typeX))); methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, false, true, initFailureField); } else if (perClause.getKind() == PerClause.PERCFLOW) { binding.addField( factory.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false, null); } else if (perClause.getKind() == PerClause.PEROBJECT) { // binding.addField( // world.makeFieldBinding( // AjcMemberMaker.perCflowField( // typeX))); } else if (perClause.getKind() == PerClause.PERTYPEWITHIN) { //PTWIMPL Add field for storing typename in aspect for which the aspect instance exists binding.addField(factory.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX))); } else { throw new RuntimeException("unimplemented"); } } if (EclipseFactory.DEBUG) System.out.println(toString()); super.generateCode(enclosingClassFile); } public boolean needClassInitMethod() { return true; } protected void generateAttributes(ClassFile classFile) { if (!isAbstract()) generatePerSupportMembers(classFile); generateInlineAccessMembers(classFile); addVersionAttributeIfNecessary(classFile); classFile.extraAttributes.add( new EclipseAttributeAdapter(new AjAttribute.Aspect(perClause))); if (binding.privilegedHandler != null) { ResolvedMember[] members = ((PrivilegedHandler)binding.privilegedHandler).getMembers(); classFile.extraAttributes.add( new EclipseAttributeAdapter(new AjAttribute.PrivilegedAttribute(members))); } //XXX need to get this attribute on anyone with a pointcut for good errors classFile.extraAttributes.add( new EclipseAttributeAdapter(new AjAttribute.SourceContextAttribute( new String(compilationResult().getFileName()), compilationResult().lineSeparatorPositions))); super.generateAttributes(classFile); } /** * A pointcut might have already added the attribute, let's not add it again. */ private void addVersionAttributeIfNecessary(ClassFile classFile) { for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) { EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next(); if (CharOperation.equals(element.getNameChars(),weaverVersionChars)) return; } classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.WeaverVersionInfo())); } private static char[] weaverVersionChars = "org.aspectj.weaver.WeaverVersion".toCharArray(); private void generateInlineAccessMembers(ClassFile classFile) { for (Iterator i = superAccessForInline.values().iterator(); i.hasNext(); ) { AccessForInlineVisitor.SuperAccessMethodPair pair = (AccessForInlineVisitor.SuperAccessMethodPair)i.next(); generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod); } for (Iterator i = accessForInline.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry)i.next(); generateInlineAccessMethod(classFile, (Binding)e.getValue(), (ResolvedMember)e.getKey()); } } private void generatePerSupportMembers(ClassFile classFile) { if (isAbstract()) return; //XXX otherwise we need to have this (error handling?) if (aspectOfMethod == null) return; if (perClause == null) { System.err.println("has null perClause: " + this); return; } EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); if (perClause.getKind() == PerClause.SINGLETON) { generatePerSingletonAspectOfMethod(classFile); generatePerSingletonHasAspectMethod(classFile); generatePerSingletonAjcClinitMethod(classFile); } else if (perClause.getKind() == PerClause.PERCFLOW) { generatePerCflowAspectOfMethod(classFile); generatePerCflowHasAspectMethod(classFile); generatePerCflowPushMethod(classFile); generatePerCflowAjcClinitMethod(classFile); } else if (perClause.getKind() == PerClause.PEROBJECT) { TypeBinding interfaceType = generatePerObjectInterface(classFile); world.addTypeBinding(interfaceType); generatePerObjectAspectOfMethod(classFile, interfaceType); generatePerObjectHasAspectMethod(classFile, interfaceType); generatePerObjectBindMethod(classFile, interfaceType); } else if (perClause.getKind() == PerClause.PERTYPEWITHIN) { //PTWIMPL Generate the methods required *in the aspect* generatePerTypeWithinAspectOfMethod(classFile); // public static <aspecttype> aspectOf(java.lang.Class) generatePerTypeWithinGetInstanceMethod(classFile); // private static <aspecttype> ajc$getInstance(Class c) throws Exception generatePerTypeWithinHasAspectMethod(classFile); generatePerTypeWithinCreateAspectInstanceMethod(classFile); // generate public static X ajc$createAspectInstance(Class forClass) { // PTWIMPL getWithinType() would need this... // generatePerTypeWithinGetWithinTypeMethod(classFile); // generate public Class getWithinType() { } else { throw new RuntimeException("unimplemented"); } } private static interface BodyGenerator { public void generate(CodeStream codeStream); } private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(member), gen); } private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) { generateMethod(classFile,methodBinding,null,gen); } protected List makeEffectiveSignatureAttribute(ResolvedMember sig,Shadow.Kind kind,boolean weaveBody) { List l = new ArrayList(1); l.add(new EclipseAttributeAdapter( new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody))); return l; } /* * additionalAttributes allows us to pass some optional attributes we want to attach to the method we generate. * Currently this is used for inline accessor methods that have been generated to allow private field references or * private method calls to be inlined (PR71377). In these cases the optional attribute is an effective signature * attribute which means calls to these methods are able to masquerade as any join point (a field set, field get or * method call). The effective signature attribute is 'unwrapped' in BcelClassWeaver.matchInvokeInstruction() */ private void generateMethod(ClassFile classFile, MethodBinding methodBinding, List additionalAttributes/*ResolvedMember realMember*/, BodyGenerator gen) { // EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); classFile.generateMethodInfoHeader(methodBinding); int methodAttributeOffset = classFile.contentsOffset; int attributeNumber; if (additionalAttributes!=null) { // mini optimization List attrs = new ArrayList(); attrs.addAll(AstUtil.getAjSyntheticAttribute()); attrs.addAll(additionalAttributes); attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, attrs); } else { attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, AstUtil.getAjSyntheticAttribute()); } int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; // Use reset() rather than init() // XXX We need a scope to keep reset happy, initializerScope is *not* the right one, but it works ! // codeStream.init(classFile); // codeStream.initializeMaxLocals(methodBinding); MethodDeclaration md = AstUtil.makeMethodDeclaration(methodBinding); md.scope = initializerScope; codeStream.reset(md,classFile); // body starts here gen.generate(codeStream); // body ends here classFile.completeCodeAttribute(codeAttributeOffset); attributeNumber++; classFile.completeMethodInfo(methodAttributeOffset, attributeNumber); } private void generatePerCflowAspectOfMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.invokevirtual(world.makeMethodBindingForCall( AjcMemberMaker.cflowStackPeekInstance())); codeStream.checkcast(binding); codeStream.areturn(); // body ends here }}); } private void generatePerCflowHasAspectMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.invokevirtual(world.makeMethodBindingForCall( AjcMemberMaker.cflowStackIsValid())); codeStream.ireturn(); // body ends here }}); } private void generatePerCflowPushMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush( factory.fromBinding(binding))), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.new_(binding); codeStream.dup(); codeStream.invokespecial( new MethodBinding(0, "<init>".toCharArray(), BaseTypes.VoidBinding, new TypeBinding[0], new ReferenceBinding[0], binding)); codeStream.invokevirtual(world.makeMethodBindingForCall( AjcMemberMaker.cflowStackPushInstance())); codeStream.return_(); // body ends here }}); } private void generatePerCflowAjcClinitMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod( world.fromBinding(binding))), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE)); codeStream.dup(); codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit())); codeStream.putstatic( world.makeFieldBinding( AjcMemberMaker.perCflowField( typeX))); codeStream.return_(); // body ends here }}); } private TypeBinding generatePerObjectInterface( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); UnresolvedType interfaceTypeX = AjcMemberMaker.perObjectInterfaceType(typeX); HelperInterfaceBinding interfaceType = new HelperInterfaceBinding(this.binding, interfaceTypeX); world.addTypeBinding(interfaceType); interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX)); interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX)); interfaceType.generateClass(compilationResult, classFile); return interfaceType; } // PTWIMPL Generate aspectOf() method private void generatePerTypeWithinAspectOfMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { Label instanceFound = new Label(codeStream); ExceptionLabel anythingGoesWrong = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); codeStream.aload_0(); codeStream.invokestatic(world.makeMethodBindingForCall(AjcMemberMaker.perTypeWithinGetInstance(typeX))); codeStream.astore_1(); codeStream.aload_1(); codeStream.ifnonnull(instanceFound); codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); codeStream.dup(); codeStream.ldc(typeX.getName()); codeStream.aconst_null(); codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit2())); codeStream.athrow(); instanceFound.place(); codeStream.aload_1(); codeStream.areturn(); anythingGoesWrong.placeEnd(); anythingGoesWrong.place(); codeStream.astore_1(); codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); codeStream.dup(); // Run the simple ctor for NABE codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit())); codeStream.athrow(); }}); } private void generatePerObjectAspectOfMethod( ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here Label wrongType = new Label(codeStream); Label popWrongType = new Label(codeStream); codeStream.aload_0(); codeStream.instance_of(interfaceType); codeStream.ifeq(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceGet(typeX))); codeStream.dup(); codeStream.ifnull(popWrongType); codeStream.areturn(); popWrongType.place(); codeStream.pop(); wrongType.place(); codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); codeStream.dup(); codeStream.invokespecial(world.makeMethodBindingForCall( AjcMemberMaker.noAspectBoundExceptionInit() )); codeStream.athrow(); // body ends here }}); } private void generatePerObjectHasAspectMethod(ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here Label wrongType = new Label(codeStream); codeStream.aload_0(); codeStream.instance_of(interfaceType); codeStream.ifeq(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceGet(typeX))); codeStream.ifnull(wrongType); codeStream.iconst_1(); codeStream.ireturn(); wrongType.place(); codeStream.iconst_0(); codeStream.ireturn(); // body ends here }}); } // PTWIMPL Generate hasAspect() method private void generatePerTypeWithinHasAspectMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { ExceptionLabel goneBang = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); Label noInstanceExists = new Label(codeStream); Label leave = new Label(codeStream); goneBang.placeStart(); codeStream.aload_0(); codeStream.invokestatic(world.makeMethodBinding(AjcMemberMaker.perTypeWithinGetInstance(typeX))); codeStream.ifnull(noInstanceExists); codeStream.iconst_1(); codeStream.goto_(leave); noInstanceExists.place(); codeStream.iconst_0(); leave.place(); goneBang.placeEnd(); codeStream.ireturn(); goneBang.place(); codeStream.astore_1(); codeStream.iconst_0(); codeStream.ireturn(); }}); } private void generatePerObjectBindMethod( ClassFile classFile, final TypeBinding interfaceType) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, AjcMemberMaker.perObjectBind(world.fromBinding(binding)), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here Label wrongType = new Label(codeStream); codeStream.aload_0(); codeStream.instance_of(interfaceType); codeStream.ifeq(wrongType); //XXX this case might call for screaming codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceGet(typeX))); //XXX should do a check for null here and throw a NoAspectBound codeStream.ifnonnull(wrongType); codeStream.aload_0(); codeStream.checkcast(interfaceType); codeStream.new_(binding); codeStream.dup(); codeStream.invokespecial( new MethodBinding(0, "<init>".toCharArray(), BaseTypes.VoidBinding, new TypeBinding[0], new ReferenceBinding[0], binding)); codeStream.invokeinterface(world.makeMethodBindingForCall( AjcMemberMaker.perObjectInterfaceSet(typeX))); wrongType.place(); codeStream.return_(); // body ends here }}); } // PTWIMPL Generate getInstance method private void generatePerTypeWithinGetInstanceMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, AjcMemberMaker.perTypeWithinGetInstance(world.fromBinding(binding)), new BodyGenerator() { public void generate(CodeStream codeStream) { ExceptionLabel exc = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION)); exc.placeStart(); codeStream.aload_0(); codeStream.ldc(NameMangler.perTypeWithinLocalAspectOf(typeX)); codeStream.aconst_null(); codeStream.invokevirtual( new MethodBinding( 0, "getDeclaredMethod".toCharArray(), world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/reflect/Method;")), // return type new TypeBinding[]{world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/String;")), world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Class;"))}, new ReferenceBinding[0], (ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_CLASS))); codeStream.astore_1(); codeStream.aload_1(); codeStream.aconst_null(); codeStream.aconst_null(); codeStream.invokevirtual( new MethodBinding( 0, "invoke".toCharArray(), world.makeTypeBinding(UnresolvedType.OBJECT), new TypeBinding[]{world.makeTypeBinding(UnresolvedType.OBJECT),world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Object;"))}, new ReferenceBinding[0], (ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_REFLECT_METHOD))); codeStream.checkcast(world.makeTypeBinding(typeX)); codeStream.astore_2(); codeStream.aload_2(); exc.placeEnd(); codeStream.areturn(); exc.place(); codeStream.astore_1(); // this just returns null now - the old version used to throw the caught exception! codeStream.aconst_null(); codeStream.areturn(); }}); } private void generatePerTypeWithinCreateAspectInstanceMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, AjcMemberMaker.perTypeWithinCreateAspectInstance(world.fromBinding(binding)), new BodyGenerator() { public void generate(CodeStream codeStream) { codeStream.new_(world.makeTypeBinding(typeX)); codeStream.dup(); codeStream.invokespecial(new MethodBinding(0, "<init>".toCharArray(), BaseTypes.VoidBinding, new TypeBinding[0], new ReferenceBinding[0], binding)); codeStream.astore_1(); codeStream.aload_1(); codeStream.aload_0(); codeStream.putfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX))); codeStream.aload_1(); codeStream.areturn(); }}); } private void generatePerSingletonAspectOfMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, aspectOfMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // Old style aspectOf() method which confused decompilers // // body starts here // codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField( // typeX))); // Label isNull = new Label(codeStream); // codeStream.dup(); // codeStream.ifnull(isNull); // codeStream.areturn(); // isNull.place(); // // codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter // codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // codeStream.dup(); // codeStream.ldc(typeX.getNameAsIdentifier()); // codeStream.getstatic(initFailureField); // codeStream.invokespecial(world.makeMethodBindingForCall( // AjcMemberMaker.noAspectBoundExceptionInitWithCause() // )); // codeStream.athrow(); // // body ends here // The stuff below generates code that looks like this: /* * if (ajc$perSingletonInstance == null) * throw new NoAspectBoundException("A", ajc$initFailureCause); * else * return ajc$perSingletonInstance; */ // body starts here (see end of each line for what it is doing!) FieldBinding fb = world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX)); codeStream.getstatic(fb); // GETSTATIC Label isNonNull = new Label(codeStream); codeStream.ifnonnull(isNonNull); // IFNONNULL codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW codeStream.dup(); // DUP codeStream.ldc(typeX.getNameAsIdentifier()); // LDC codeStream.getstatic(initFailureField); // GETSTATIC codeStream.invokespecial(world.makeMethodBindingForCall( AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL codeStream.athrow(); // ATHROW isNonNull.place(); codeStream.getstatic(fb); // GETSTATIC codeStream.areturn(); // ARETURN // body ends here }}); } private void generatePerSingletonHasAspectMethod(ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, hasAspectMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField( typeX))); Label isNull = new Label(codeStream); codeStream.ifnull(isNull); codeStream.iconst_1(); codeStream.ireturn(); isNull.place(); codeStream.iconst_0(); codeStream.ireturn(); // body ends here }}); } private void generatePerSingletonAjcClinitMethod( ClassFile classFile) { final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope); generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod( world.fromBinding(binding))), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.new_(binding); codeStream.dup(); codeStream.invokespecial( new MethodBinding(0, "<init>".toCharArray(), BaseTypes.VoidBinding, new TypeBinding[0], new ReferenceBinding[0], binding)); codeStream.putstatic( world.makeFieldBinding( AjcMemberMaker.perSingletonField( typeX))); codeStream.return_(); // body ends here }}); } private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) { generateMethod(classFile, accessMethod, new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here codeStream.aload_0(); AstUtil.generateParameterLoads(accessMethod.parameters, codeStream); codeStream.invokespecial( factory.makeMethodBinding(method)); AstUtil.generateReturn(accessMethod.returnType, codeStream); // body ends here }}); } private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) { if (binding instanceof InlineAccessFieldBinding) { generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member); } else { generateInlineAccessMethod(classFile, (MethodBinding)binding, member); } } private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) { final FieldBinding fieldBinding = factory.makeFieldBinding(field); generateMethod(classFile, accessField.reader, makeEffectiveSignatureAttribute(field,Shadow.FieldGet,false), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here if (field.isStatic()) { codeStream.getstatic(fieldBinding); } else { codeStream.aload_0(); codeStream.getfield(fieldBinding); } AstUtil.generateReturn(accessField.reader.returnType, codeStream); // body ends here }}); generateMethod(classFile, accessField.writer, makeEffectiveSignatureAttribute(field,Shadow.FieldSet,false), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here if (field.isStatic()) { codeStream.load(fieldBinding.type, 0); codeStream.putstatic(fieldBinding); } else { codeStream.aload_0(); codeStream.load(fieldBinding.type, 1); codeStream.putfield(fieldBinding); } codeStream.return_(); // body ends here }}); } private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) { generateMethod(classFile, accessMethod, makeEffectiveSignatureAttribute(method, Shadow.MethodCall, false), new BodyGenerator() { public void generate(CodeStream codeStream) { // body starts here AstUtil.generateParameterLoads(accessMethod.parameters, codeStream); if (method.isStatic()) { codeStream.invokestatic(factory.makeMethodBinding(method)); } else { codeStream.invokevirtual(factory.makeMethodBinding(method)); } AstUtil.generateReturn(accessMethod.returnType, codeStream); // body ends here }}); } private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) { PerClause perClause; if (binding instanceof BinaryTypeBinding) { ResolvedType superTypeX = factory.fromEclipse(binding); perClause = superTypeX.getPerClause(); } else if (binding instanceof SourceTypeBinding ) { SourceTypeBinding sourceSc = (SourceTypeBinding)binding; if (sourceSc.scope.referenceContext instanceof AspectDeclaration) { perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause; } else { return null; } } else { //XXX need to handle this too return null; } if (perClause == null) { return lookupPerClauseKind(binding.superclass()); } else { return perClause.getKind(); } } private void buildPerClause(ClassScope scope) { EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope); if (perClause == null) { PerClause.Kind kind = lookupPerClauseKind(binding.superclass); if (kind == null) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(kind); } } aspectAttribute = new AjAttribute.Aspect(perClause); if (ignoreFurtherInvestigation) return; //??? if (!isAbstract()) { if (perClause.getKind() == PerClause.SINGLETON) { aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX); } else if (perClause.getKind() == PerClause.PERCFLOW) { aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX); } else if (perClause.getKind() == PerClause.PEROBJECT) { aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX); } else if (perClause.getKind() == PerClause.PERTYPEWITHIN) { // PTWIMPL Use these variants of aspectOf()/hasAspect() aspectOfMethod = AjcMemberMaker.perTypeWithinAspectOfMethod(typeX); hasAspectMethod = AjcMemberMaker.perTypeWithinHasAspectMethod(typeX); } else { throw new RuntimeException("bad per clause: " + perClause); } binding.addMethod(world.makeMethodBinding(aspectOfMethod)); binding.addMethod(world.makeMethodBinding(hasAspectMethod)); } resolvePerClause(); //XXX might be too soon for some error checking } private PerClause resolvePerClause() { EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope); perClause.resolve(iscope); return perClause; } public void buildInterTypeAndPerClause(ClassScope classScope) { factory = EclipseFactory.fromScopeLookupEnvironment(scope); if (isPrivileged) { binding.privilegedHandler = new PrivilegedHandler(this); } checkSpec(classScope); if (ignoreFurtherInvestigation) return; buildPerClause(scope); if (methods != null) { for (int i = 0; i < methods.length; i++) { if (methods[i] instanceof InterTypeDeclaration) { EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope); if (m != null) concreteName.typeMungers.add(m); } else if (methods[i] instanceof DeclareDeclaration) { Declare d = ((DeclareDeclaration)methods[i]).build(classScope); if (d != null) concreteName.declares.add(d); } } } concreteName.getDeclaredPointcuts(); } // public String toString(int tab) { // return tabString(tab) + toStringHeader() + toStringBody(tab); // } // // public String toStringBody(int tab) { // // String s = " {"; //$NON-NLS-1$ // // // if (memberTypes != null) { // for (int i = 0; i < memberTypes.length; i++) { // if (memberTypes[i] != null) { // s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$ // } // } // } // if (fields != null) { // for (int fieldI = 0; fieldI < fields.length; fieldI++) { // if (fields[fieldI] != null) { // s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$ // if (fields[fieldI].isField()) // s += ";"; //$NON-NLS-1$ // } // } // } // if (methods != null) { // for (int i = 0; i < methods.length; i++) { // if (methods[i] != null) { // s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$ // } // } // } // s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$ // return s; // } public StringBuffer printHeader(int indent, StringBuffer output) { printModifiers(this.modifiers, output); output.append("aspect " ); output.append(name); if (superclass != null) { output.append(" extends "); //$NON-NLS-1$ superclass.print(0, output); } if (superInterfaces != null && superInterfaces.length > 0) { output.append((kind() == IGenericType.INTERFACE_DECL) ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$ for (int i = 0; i < superInterfaces.length; i++) { if (i > 0) output.append( ", "); //$NON-NLS-1$ superInterfaces[i].print(0, output); } } return output; //XXX we should append the per-clause } /** * All aspects are made public after type checking etc. and before generating code * (so that the advice can be called!). * This method returns the modifiers as specified in the original source code declaration * so that the structure model sees the right thing. */ public int getDeclaredModifiers() { return declaredModifiers; } }
109,283
Bug 109283 Invalid "indirect static access" warning on EnumSet.noneOf
When compiling AspectJ enabled projects in Java 5.0 source mode with "Indirect access to static modifier" warnings on, the following code incorrectly gives a compiler warning (this doesn't occur in non-AspectJ enabled projects): public class Test { enum Foo { Wibble, Wobble, Woo; } public static void main(String[] args) { EnumSet<Foo> set = EnumSet.noneOf(Foo.class); } }
resolved fixed
8a0f59a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-22T15:45:06Z
2005-09-12T13:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.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 2004-07-26 extended to allow overloading of * hierarchy builder * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.AstUtil; import org.aspectj.ajdt.internal.core.builder.AjBuildManager; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.Member; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableDeclaringElement; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.UnresolvedTypeVariableReferenceType; import org.aspectj.weaver.World; /** * @author Jim Hugunin */ public class EclipseFactory { public static boolean DEBUG = false; private AjBuildManager buildManager; private LookupEnvironment lookupEnvironment; private boolean xSerializableAspects; private World world; private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap(); //XXX currently unused // private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap(); public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) { AjLookupEnvironment aenv = (AjLookupEnvironment)env; return aenv.factory; } public static EclipseFactory fromScopeLookupEnvironment(Scope scope) { return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment); } public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) { this.lookupEnvironment = lookupEnvironment; this.buildManager = buildManager; this.world = buildManager.getWorld(); this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects(); } public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) { this.lookupEnvironment = lookupEnvironment; this.world = world; this.xSerializableAspects = xSer; this.buildManager = null; } public World getWorld() { return world; } public void showMessage( Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { getWorld().showMessage(kind, message, loc1, loc2); } public ResolvedType fromEclipse(ReferenceBinding binding) { if (binding == null) return ResolvedType.MISSING; //??? this seems terribly inefficient //System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding)); ResolvedType ret = getWorld().resolve(fromBinding(binding)); //System.err.println(" got: " + ret); return ret; } public ResolvedType fromTypeBindingToRTX(TypeBinding tb) { if (tb == null) return ResolvedType.MISSING; ResolvedType ret = getWorld().resolve(fromBinding(tb)); return ret; } public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) { if (bindings == null) { return ResolvedType.NONE; } int len = bindings.length; ResolvedType[] ret = new ResolvedType[len]; for (int i=0; i < len; i++) { ret[i] = fromEclipse(bindings[i]); } return ret; } public static String getName(TypeBinding binding) { if (binding instanceof TypeVariableBinding) { // The first bound may be null - so default to object? TypeVariableBinding tvb = (TypeVariableBinding)binding; if (tvb.firstBound!=null) { return getName(tvb.firstBound); } else { return getName(tvb.superclass); } } if (binding instanceof ReferenceBinding) { return new String( CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.')); } String packageName = new String(binding.qualifiedPackageName()); String className = new String(binding.qualifiedSourceName()).replace('.', '$'); if (packageName.length() > 0) { className = packageName + "." + className; } //XXX doesn't handle arrays correctly (or primitives?) return new String(className); } /** * Some generics notes: * * Andy 6-May-05 * We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we * see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not * sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back * the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to * remember the type variable. * Adrian 10-July-05 * When we forget it's a type variable we come unstuck when getting the declared members of a parameterized * type - since we don't know it's a type variable we can't replace it with the type parameter. */ //??? going back and forth between strings and bindings is a waste of cycles public UnresolvedType fromBinding(TypeBinding binding) { if (binding instanceof HelperInterfaceBinding) { return ((HelperInterfaceBinding) binding).getTypeX(); } if (binding == null || binding.qualifiedSourceName() == null) { return ResolvedType.MISSING; } // first piece of generics support! if (binding instanceof TypeVariableBinding) { return fromTypeVariableBinding((TypeVariableBinding)binding); } // handle arrays since the component type may need special treatment too... if (binding instanceof ArrayBinding) { ArrayBinding aBinding = (ArrayBinding) binding; UnresolvedType componentType = fromBinding(aBinding.leafComponentType); return UnresolvedType.makeArray(componentType, aBinding.dimensions); } if (binding instanceof WildcardBinding) { WildcardBinding eWB = (WildcardBinding) binding; UnresolvedType ut = TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature())); // If the bound for the wildcard is a typevariable, e.g. '? extends E' then // the type variable in the unresolvedtype will be correct only in name. In that // case let's set it correctly based on the one in the eclipse WildcardBinding if (eWB.bound instanceof TypeVariableBinding) { UnresolvedType tVar = fromTypeVariableBinding((TypeVariableBinding)eWB.bound); if (ut.isGenericWildcard() && ut.isSuper()) ut.setLowerBound(tVar); if (ut.isGenericWildcard() && ut.isExtends()) ut.setUpperBound(tVar); } return ut; } if (binding instanceof ParameterizedTypeBinding) { if (binding instanceof RawTypeBinding) { // special case where no parameters are specified! return UnresolvedType.forRawTypeName(getName(binding)); } ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding; UnresolvedType[] arguments = null; if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227) arguments = new UnresolvedType[ptb.arguments.length]; for (int i = 0; i < arguments.length; i++) { arguments[i] = fromBinding(ptb.arguments[i]); } } String baseTypeSignature = null; ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true); if (baseType != ResolvedType.MISSING) { // can legitimately be missing if a bound refers to a type we haven't added to the world yet... if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType(); baseTypeSignature = baseType.getErasureSignature(); } else { baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature(); } // Create an unresolved parameterized type. We can't create a resolved one as the // act of resolution here may cause recursion problems since the parameters may // be type variables that we haven't fixed up yet. if (arguments==null) arguments=new UnresolvedType[0]; String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1); return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments); } // Convert the source type binding for a generic type into a generic UnresolvedType // notice we can easily determine the type variables from the eclipse object // and we can recover the generic signature from it too - so we pass those // to the forGenericType() method. if (binding.isGenericType() && !binding.isParameterizedType() && !binding.isRawType()) { TypeVariableBinding[] tvbs = binding.typeVariables(); TypeVariable[] tVars = new TypeVariable[tvbs.length]; for (int i = 0; i < tvbs.length; i++) { TypeVariableBinding eclipseV = tvbs[i]; String name = CharOperation.charToString(eclipseV.sourceName); tVars[i] = new TypeVariable(name,fromBinding(eclipseV.superclass()),fromBindings(eclipseV.superInterfaces())); } //TODO asc generics - temporary guard.... if (!(binding instanceof SourceTypeBinding)) throw new RuntimeException("Cant get the generic sig for "+binding.debugName()); return UnresolvedType.forGenericType(getName(binding),tVars, CharOperation.charToString(((SourceTypeBinding)binding).genericSignature())); } // LocalTypeBinding have a name $Local$, we can get the real name by using the signature.... if (binding instanceof LocalTypeBinding) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { return UnresolvedType.forSignature(new String(binding.signature())); } else { // we're reporting a problem and don't have a resolved name for an // anonymous local type yet, report the issue on the enclosing type return UnresolvedType.forSignature(new String(ltb.enclosingType.signature())); } } return UnresolvedType.forName(getName(binding)); } /** * Some type variables refer to themselves recursively, this enables us to avoid * recursion problems. */ private static Map typeVariableBindingsInProgress = new HashMap(); /** * Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ * form (TypeVariable). */ private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) { // first, check for recursive call to this method for the same tvBinding if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) { return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding); } if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) { return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName)); } // Create the UnresolvedTypeVariableReferenceType for the type variable String name = CharOperation.charToString(aTypeVariableBinding.sourceName()); UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType(); typeVariableBindingsInProgress.put(aTypeVariableBinding,ret); // Dont set any bounds here, you'll get in a recursive mess // TODO -- what about lower bounds?? UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass()); UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length]; for (int i = 0; i < superinterfaces.length; i++) { superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]); } TypeVariable tv = new TypeVariable(name,superclassType,superinterfaces); tv.setUpperBound(superclassType); tv.setAdditionalInterfaceBounds(superinterfaces); tv.setRank(aTypeVariableBinding.rank); if (aTypeVariableBinding.declaringElement instanceof MethodBinding) { tv.setDeclaringElementKind(TypeVariable.METHOD); // tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement); } else { tv.setDeclaringElementKind(TypeVariable.TYPE); // // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement)); } ret.setTypeVariable(tv); if (aTypeVariableBinding.declaringElement instanceof MethodBinding) typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret); typeVariableBindingsInProgress.remove(aTypeVariableBinding); return ret; } public UnresolvedType[] fromBindings(TypeBinding[] bindings) { if (bindings == null) return UnresolvedType.NONE; int len = bindings.length; UnresolvedType[] ret = new UnresolvedType[len]; for (int i=0; i<len; i++) { ret[i] = fromBinding(bindings[i]); } return ret; } public static ASTNode astForLocation(IHasPosition location) { return new EmptyStatement(location.getStart(), location.getEnd()); } public Collection getDeclareParents() { return getWorld().getDeclareParents(); } public Collection getDeclareAnnotationOnTypes() { return getWorld().getDeclareAnnotationOnTypes(); } public Collection getDeclareAnnotationOnFields() { return getWorld().getDeclareAnnotationOnFields(); } public Collection getDeclareAnnotationOnMethods() { return getWorld().getDeclareAnnotationOnMethods(); } public Collection finishedTypeMungers = null; public boolean areTypeMungersFinished() { return finishedTypeMungers != null; } public void finishTypeMungers() { // make sure that type mungers are Collection ret = new ArrayList(); Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers(); baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers()); for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next(); EclipseTypeMunger etm = makeEclipseTypeMunger(munger); if (etm != null) ret.add(etm); } finishedTypeMungers = ret; } public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) { //System.err.println("make munger: " + concrete); //!!! can't do this if we want incremental to work right //if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete; //System.err.println(" was not eclipse"); if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) { AbstractMethodDeclaration method = null; if (concrete instanceof EclipseTypeMunger) { method = ((EclipseTypeMunger)concrete).getSourceMethod(); } EclipseTypeMunger ret = new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method); if (ret.getSourceLocation() == null) { ret.setSourceLocation(concrete.getSourceLocation()); } return ret; } else { return null; } } public Collection getTypeMungers() { //??? assert finishedTypeMungers != null return finishedTypeMungers; } public ResolvedMember makeResolvedMember(MethodBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } /** * Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done * in the scope of some type variables. Before converting the parts of a methodbinding * (params, return type) we store the type variables in this structure, then should any * component of the method binding refer to them, we grab them from the map. */ // FIXME asc convert to array, indexed by rank private Map typeVariablesForThisMember = new HashMap(); public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) { //System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName)); // Convert the type variables and store them UnresolvedType[] ajTypeRefs = null; typeVariablesForThisMember.clear(); // This is the set of type variables available whilst building the resolved member... if (binding.typeVariables!=null) { ajTypeRefs = new UnresolvedType[binding.typeVariables.length]; for (int i = 0; i < binding.typeVariables.length; i++) { ajTypeRefs[i] = fromBinding(binding.typeVariables[i]); typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]); } } // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType)); if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType(); ResolvedMember ret = new ResolvedMemberImpl( binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD, realDeclaringType, binding.modifiers, fromBinding(binding.returnType), new String(binding.selector), fromBindings(binding.parameters), fromBindings(binding.thrownExceptions) ); if (typeVariablesForThisMember.size()!=0) { UnresolvedType[] tvars = new UnresolvedType[typeVariablesForThisMember.size()]; int i =0; for (Iterator iter = typeVariablesForThisMember.values().iterator(); iter.hasNext();) { tvars[i++] = (UnresolvedType)iter.next(); } ret.setTypeVariables(tvars); } typeVariablesForThisMember.clear(); ret.resolve(world); return ret; } public ResolvedMember makeResolvedMember(FieldBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) { // AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType)); if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType(); return new ResolvedMemberImpl( Member.FIELD, realDeclaringType, binding.modifiers, world.resolve(fromBinding(binding.type)), new String(binding.name), UnresolvedType.NONE); } public TypeBinding makeTypeBinding(UnresolvedType typeX) { TypeBinding ret = null; // looking up type variables can get us into trouble if (!typeX.isTypeVariableReference()) ret = (TypeBinding)typexToBinding.get(typeX); if (ret == null) { ret = makeTypeBinding1(typeX); // FIXME asc keep type variables *out* of the map for now, they go in typeVariableToTypeBinding if (!(typeX instanceof BoundedReferenceType) && !(typeX instanceof UnresolvedTypeVariableReferenceType)) typexToBinding.put(typeX, ret); } if (ret == null) { System.out.println("can't find: " + typeX); } return ret; } private TypeBinding makeTypeBinding1(UnresolvedType typeX) { if (typeX.isPrimitiveType()) { if (typeX == ResolvedType.BOOLEAN) return BaseTypes.BooleanBinding; if (typeX == ResolvedType.BYTE) return BaseTypes.ByteBinding; if (typeX == ResolvedType.CHAR) return BaseTypes.CharBinding; if (typeX == ResolvedType.DOUBLE) return BaseTypes.DoubleBinding; if (typeX == ResolvedType.FLOAT) return BaseTypes.FloatBinding; if (typeX == ResolvedType.INT) return BaseTypes.IntBinding; if (typeX == ResolvedType.LONG) return BaseTypes.LongBinding; if (typeX == ResolvedType.SHORT) return BaseTypes.ShortBinding; if (typeX == ResolvedType.VOID) return BaseTypes.VoidBinding; throw new RuntimeException("weird primitive type " + typeX); } else if (typeX.isArray()) { int dim = 0; while (typeX.isArray()) { dim++; typeX = typeX.getComponentType(); } return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim); } else if (typeX.isParameterizedType()) { // Converting back to a binding from a UnresolvedType UnresolvedType[] typeParameters = typeX.getTypeParameters(); ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName()); TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length]; for (int i = 0; i < argumentBindings.length; i++) { argumentBindings[i] = makeTypeBinding(typeParameters[i]); } ParameterizedTypeBinding ptb = lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType()); return ptb; } else if (typeX.isTypeVariableReference()) { return makeTypeVariableBinding((TypeVariableReference)typeX); } else if (typeX.isRawType()) { ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName()); RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType()); return rtb; } else if (typeX.isGenericWildcard()) { // translate from boundedreferencetype to WildcardBinding BoundedReferenceType brt = (BoundedReferenceType)typeX; // Work out 'kind' for the WildcardBinding int boundkind = Wildcard.UNBOUND; TypeBinding bound = null; if (brt.isExtends()) { boundkind = Wildcard.EXTENDS; bound = makeTypeBinding(brt.getUpperBound()); } else if (brt.isSuper()) { boundkind = Wildcard.SUPER; bound = makeTypeBinding(brt.getLowerBound()); } TypeBinding[] otherBounds = null; if (brt.getAdditionalBounds()!=null && brt.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(brt.getAdditionalBounds()); // FIXME asc rank should not always be 0 ... WildcardBinding wb = lookupEnvironment.createWildcard(null,0,bound,otherBounds,boundkind); return wb; } else { return lookupBinding(typeX.getName()); } } private ReferenceBinding lookupBinding(String sname) { char[][] name = CharOperation.splitOn('.', sname.toCharArray()); ReferenceBinding rb = lookupEnvironment.getType(name); // XXX We do this because the pertypewithin aspectOf(Class) generated method needs it. Without this // we don't get a 'rawtype' as the argument type for a messagesend to aspectOf() and this leads to // a compile error if some client class calls aspectOf(A.class) or similar as it says Class<A> isn't // compatible with Class<T> if (sname.equals("java.lang.Class")) rb = lookupEnvironment.createRawType(rb,rb.enclosingType()); return rb; } public TypeBinding[] makeTypeBindings(UnresolvedType[] types) { int len = types.length; TypeBinding[] ret = new TypeBinding[len]; for (int i = 0; i < len; i++) { ret[i] = makeTypeBinding(types[i]); } return ret; } // just like the code above except it returns an array of ReferenceBindings private ReferenceBinding[] makeReferenceBindings(UnresolvedType[] types) { int len = types.length; ReferenceBinding[] ret = new ReferenceBinding[len]; for (int i = 0; i < len; i++) { ret[i] = (ReferenceBinding)makeTypeBinding(types[i]); } return ret; } public FieldBinding makeFieldBinding(ResolvedMember member) { currentType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType()); FieldBinding fb = new FieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers(), currentType, Constant.NotAConstant); currentType = null; return fb; } private ReferenceBinding currentType = null; public MethodBinding makeMethodBinding(ResolvedMember member) { typeVariableToTypeBinding.clear(); TypeVariableBinding[] tvbs = null; if (member.getTypeVariables()!=null) { if (member.getTypeVariables().length==0) { tvbs = MethodBinding.NoTypeVariables; } else { tvbs = makeTypeVariableBindings(member.getTypeVariables()); // fixup the declaring element, we couldn't do it whilst processing the typevariables as we'll end up in recursion. for (int i = 0; i < tvbs.length; i++) { TypeVariableBinding binding = tvbs[i]; // if (binding.declaringElement==null && ((TypeVariableReference)member.getTypeVariables()[i]).getTypeVariable().getDeclaringElement() instanceof Member) { // tvbs[i].declaringElement = mb; // } else { // tvbs[i].declaringElement = declaringType; // } } } } ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType()); currentType = declaringType; MethodBinding mb = new MethodBinding(member.getModifiers(), member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), makeReferenceBindings(member.getExceptions()), declaringType); if (tvbs!=null) mb.typeVariables = tvbs; typeVariableToTypeBinding.clear(); currentType = null; return mb; } /** * Convert a bunch of type variables in one go, from AspectJ form to Eclipse form. */ private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) { int len = typeVariables.length; TypeVariableBinding[] ret = new TypeVariableBinding[len]; for (int i = 0; i < len; i++) { ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]); } return ret; } // only accessed through private methods in this class. Ensures all type variables we encounter // map back to the same type binding - this is important later when Eclipse code is processing // a methodbinding trying to come up with possible bindings for the type variables. // key is currently the name of the type variable...is that ok? private Map typeVariableToTypeBinding = new HashMap(); /** * Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference * in AspectJ world holds a TypeVariable and it is this type variable that is converted * to the TypeVariableBinding. */ private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) { TypeVariable tVar = tvReference.getTypeVariable(); TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tVar.getName()); if (currentType!=null) { TypeVariableBinding tvb = currentType.getTypeVariable(tVar.getName().toCharArray()); if (tvb!=null) return tvb; } if (tvBinding==null) { Binding declaringElement = null; // this will cause an infinite loop or NPE... not required yet luckily. // if (tVar.getDeclaringElement() instanceof Member) { // declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement()); // } else { // declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement()); // } tvBinding = new TypeVariableBinding(tVar.getName().toCharArray(),declaringElement,tVar.getRank()); typeVariableToTypeBinding.put(tVar.getName(),tvBinding); tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tVar.getUpperBound()); tvBinding.firstBound=tvBinding.superclass; // FIXME asc is this correct? possibly it could be first superinterface if (tVar.getAdditionalInterfaceBounds()==null) { tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces; } else { TypeBinding tbs[] = makeTypeBindings(tVar.getAdditionalInterfaceBounds()); ReferenceBinding[] rbs= new ReferenceBinding[tbs.length]; for (int i = 0; i < tbs.length; i++) { rbs[i] = (ReferenceBinding)tbs[i]; } tvBinding.superInterfaces=rbs; } } return tvBinding; } public MethodBinding makeMethodBindingForCall(Member member) { return new MethodBinding(member.getCallsiteModifiers(), member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), new ReferenceBinding[0], (ReferenceBinding)makeTypeBinding(member.getDeclaringType())); } public void finishedCompilationUnit(CompilationUnitDeclaration unit) { if ((buildManager != null) && buildManager.doGenerateModel()) { AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig); } } public void addTypeBinding(TypeBinding binding) { typexToBinding.put(fromBinding(binding), binding); } public Shadow makeShadow(ASTNode location, ReferenceContext context) { return EclipseShadow.makeShadow(this, location, context); } public Shadow makeShadow(ReferenceContext context) { return EclipseShadow.makeShadow(this, (ASTNode) context, context); } public void addSourceTypeBinding(SourceTypeBinding binding, CompilationUnitDeclaration unit) { TypeDeclaration decl = binding.scope.referenceContext; // Deal with the raw/basic type to give us an entry in the world type map UnresolvedType simpleTx = null; if (binding.isGenericType()) { simpleTx = UnresolvedType.forRawTypeName(getName(binding)); } else if (binding.isLocalType()) { LocalTypeBinding ltb = (LocalTypeBinding) binding; if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) { simpleTx = UnresolvedType.forSignature(new String(binding.signature())); } else { simpleTx = UnresolvedType.forName(getName(binding)); } }else { simpleTx = UnresolvedType.forName(getName(binding)); } ReferenceType name = getWorld().lookupOrCreateName(simpleTx); EclipseSourceType t = new EclipseSourceType(name, this, binding, decl, unit); // For generics, go a bit further - build a typex for the generic type // give it the same delegate and link it to the raw type if (binding.isGenericType()) { UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info ReferenceType complexName = new ReferenceType(complexTx,world);//getWorld().lookupOrCreateName(complexTx); name.setGenericType(complexName); complexName.setDelegate(t); complexName.setSourceContext(t.getResolvedTypeX().getSourceContext()); } name.setDelegate(t); if (decl instanceof AspectDeclaration) { ((AspectDeclaration)decl).typeX = name; ((AspectDeclaration)decl).concreteName = t; } ReferenceBinding[] memberTypes = binding.memberTypes; for (int i = 0, length = memberTypes.length; i < length; i++) { addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit); } } // XXX this doesn't feel like it belongs here, but it breaks a hard dependency on // exposing AjBuildManager (needed by AspectDeclaration). public boolean isXSerializableAspects() { return xSerializableAspects; } public ResolvedMember fromBinding(MethodBinding binding) { return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers, fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters)); } public TypeVariableDeclaringElement fromBinding(Binding declaringElement) { if (declaringElement instanceof TypeBinding) { return fromBinding(((TypeBinding)declaringElement)); } else { return fromBinding((MethodBinding)declaringElement); } } }
109,283
Bug 109283 Invalid "indirect static access" warning on EnumSet.noneOf
When compiling AspectJ enabled projects in Java 5.0 source mode with "Indirect access to static modifier" warnings on, the following code incorrectly gives a compiler warning (this doesn't occur in non-AspectJ enabled projects): public class Test { enum Foo { Wibble, Wobble, Woo; } public static void main(String[] args) { EnumSet<Foo> set = EnumSet.noneOf(Foo.class); } }
resolved fixed
8a0f59a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-22T15:45:06Z
2005-09-12T13:00: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.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ 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 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"); } // 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); } }
109,283
Bug 109283 Invalid "indirect static access" warning on EnumSet.noneOf
When compiling AspectJ enabled projects in Java 5.0 source mode with "Indirect access to static modifier" warnings on, the following code incorrectly gives a compiler warning (this doesn't occur in non-AspectJ enabled projects): public class Test { enum Foo { Wibble, Wobble, Woo; } public static void main(String[] args) { EnumSet<Foo> set = EnumSet.noneOf(Foo.class); } }
resolved fixed
8a0f59a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-22T15:45:06Z
2005-09-12T13:00:00Z
weaver/src/org/aspectj/weaver/AjcMemberMaker.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 org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import java.lang.reflect.Modifier; //import org.aspectj.weaver.ResolvedType.Name; public class AjcMemberMaker { private static final int PUBLIC_STATIC_FINAL = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL; private static final int PRIVATE_STATIC = Modifier.PRIVATE | Modifier.STATIC; private static final int PUBLIC_STATIC = Modifier.PUBLIC | Modifier.STATIC; private static final int VISIBILITY = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; public static final UnresolvedType CFLOW_STACK_TYPE = UnresolvedType.forName(NameMangler.CFLOW_STACK_TYPE); public static final UnresolvedType AROUND_CLOSURE_TYPE = UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"); public static final UnresolvedType CONVERSIONS_TYPE = UnresolvedType.forName("org.aspectj.runtime.internal.Conversions"); public static final UnresolvedType NO_ASPECT_BOUND_EXCEPTION = UnresolvedType.forName("org.aspectj.lang.NoAspectBoundException"); public static ResolvedMember ajcPreClinitMethod(UnresolvedType declaringType) { return new ResolvedMemberImpl( Member.METHOD, declaringType, PRIVATE_STATIC, NameMangler.AJC_PRE_CLINIT_NAME, "()V"); } public static ResolvedMember ajcPostClinitMethod(UnresolvedType declaringType) { return new ResolvedMemberImpl( Member.METHOD, declaringType, PRIVATE_STATIC, NameMangler.AJC_POST_CLINIT_NAME, "()V"); } public static Member noAspectBoundExceptionInit() { return new ResolvedMemberImpl( Member.METHOD, NO_ASPECT_BOUND_EXCEPTION, Modifier.PUBLIC, "<init>", "()V"); } public static Member noAspectBoundExceptionInit2() { return new ResolvedMemberImpl( Member.METHOD, NO_ASPECT_BOUND_EXCEPTION, Modifier.PUBLIC, "<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V"); } public static Member noAspectBoundExceptionInitWithCause() { return new ResolvedMemberImpl( Member.METHOD, NO_ASPECT_BOUND_EXCEPTION, Modifier.PUBLIC, "<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V"); } public static ResolvedMember perCflowPush(UnresolvedType declaringType) { return new ResolvedMemberImpl( Member.METHOD, declaringType, PUBLIC_STATIC, NameMangler.PERCFLOW_PUSH_METHOD, "()V"); } public static ResolvedMember perCflowField(UnresolvedType declaringType) { return new ResolvedMemberImpl( Member.FIELD, declaringType, PUBLIC_STATIC_FINAL, NameMangler.PERCFLOW_FIELD_NAME, CFLOW_STACK_TYPE.getSignature()); } public static ResolvedMember perSingletonField(UnresolvedType declaringType) { return new ResolvedMemberImpl( Member.FIELD, declaringType, PUBLIC_STATIC_FINAL, NameMangler.PERSINGLETON_FIELD_NAME, declaringType.getSignature()); } public static ResolvedMember initFailureCauseField(UnresolvedType declaringType) { return new ResolvedMemberImpl( Member.FIELD, declaringType, PRIVATE_STATIC, NameMangler.INITFAILURECAUSE_FIELD_NAME, UnresolvedType.THROWABLE.getSignature()); } public static ResolvedMember perObjectField(UnresolvedType declaringType, ResolvedType aspectType) { int modifiers = Modifier.PRIVATE; if (!UnresolvedType.SERIALIZABLE.resolve(aspectType.getWorld()).isAssignableFrom(aspectType)) { modifiers |= Modifier.TRANSIENT; } return new ResolvedMemberImpl( Member.FIELD, declaringType, modifiers, aspectType, NameMangler.perObjectInterfaceField(aspectType), UnresolvedType.NONE); } // PTWIMPL ResolvedMember for aspect instance field, declared in matched type public static ResolvedMember perTypeWithinField(UnresolvedType declaringType, ResolvedType aspectType) { int modifiers = Modifier.PRIVATE | Modifier.STATIC; if (!isSerializableAspect(aspectType)) { modifiers |= Modifier.TRANSIENT; } return new ResolvedMemberImpl(Member.FIELD, declaringType, modifiers, aspectType, NameMangler.perTypeWithinFieldForTarget(aspectType), UnresolvedType.NONE); } // PTWIMPL ResolvedMember for type instance field, declared in aspect // (holds typename for which aspect instance exists) public static ResolvedMember perTypeWithinWithinTypeField(UnresolvedType declaringType, ResolvedType aspectType) { int modifiers = Modifier.PRIVATE; if (!isSerializableAspect(aspectType)) { modifiers |= Modifier.TRANSIENT; } return new ResolvedMemberImpl(Member.FIELD, declaringType, modifiers, UnresolvedType.forSignature("Ljava/lang/String;"), NameMangler.PERTYPEWITHIN_WITHINTYPEFIELD, UnresolvedType.NONE); } private static boolean isSerializableAspect(ResolvedType aspectType) { return UnresolvedType.SERIALIZABLE.resolve(aspectType.getWorld()).isAssignableFrom(aspectType); } public static ResolvedMember perObjectBind(UnresolvedType declaringType) { return new ResolvedMemberImpl( Member.METHOD, declaringType, PUBLIC_STATIC, NameMangler.PEROBJECT_BIND_METHOD, "(Ljava/lang/Object;)V"); } // PTWIMPL ResolvedMember for getInstance() method, declared in aspect public static ResolvedMember perTypeWithinGetInstance(UnresolvedType declaringType) { // private static a.X ajc$getInstance(java.lang.Class) ResolvedMemberImpl rm = new ResolvedMemberImpl( Member.METHOD, declaringType, PRIVATE_STATIC, declaringType, // return value NameMangler.PERTYPEWITHIN_GETINSTANCE_METHOD, new UnresolvedType[]{UnresolvedType.JAVA_LANG_CLASS} ); return rm; } public static ResolvedMember perTypeWithinCreateAspectInstance(UnresolvedType declaringType) { // public static a.X ajc$createAspectInstance(java.lang.String) ResolvedMemberImpl rm = new ResolvedMemberImpl( Member.METHOD, declaringType, PUBLIC_STATIC, declaringType, // return value NameMangler.PERTYPEWITHIN_CREATEASPECTINSTANCE_METHOD, new UnresolvedType[]{UnresolvedType.forSignature("Ljava/lang/String;")},new UnresolvedType[]{} ); return rm; } public static UnresolvedType perObjectInterfaceType(UnresolvedType aspectType) { return UnresolvedType.forName(aspectType.getName()+"$ajcMightHaveAspect"); } public static ResolvedMember perObjectInterfaceGet(UnresolvedType aspectType) { return new ResolvedMemberImpl( Member.METHOD, perObjectInterfaceType(aspectType), Modifier.PUBLIC | Modifier.ABSTRACT, NameMangler.perObjectInterfaceGet(aspectType), "()" + aspectType.getSignature()); } public static ResolvedMember perObjectInterfaceSet(UnresolvedType aspectType) { return new ResolvedMemberImpl( Member.METHOD, perObjectInterfaceType(aspectType), Modifier.PUBLIC | Modifier.ABSTRACT, NameMangler.perObjectInterfaceSet(aspectType), "(" + aspectType.getSignature() + ")V"); } // PTWIMPL ResolvedMember for localAspectOf() method, declared in matched type public static ResolvedMember perTypeWithinLocalAspectOf(UnresolvedType shadowType,UnresolvedType aspectType) { return new ResolvedMemberImpl( Member.METHOD, shadowType,//perTypeWithinInterfaceType(aspectType), Modifier.PUBLIC | Modifier.STATIC, NameMangler.perTypeWithinLocalAspectOf(aspectType), "()" + aspectType.getSignature()); } public static ResolvedMember perSingletonAspectOfMethod(UnresolvedType declaringType) { return new ResolvedMemberImpl(Member.METHOD, declaringType, PUBLIC_STATIC, "aspectOf", "()" + declaringType.getSignature()); } public static ResolvedMember perSingletonHasAspectMethod(UnresolvedType declaringType) { return new ResolvedMemberImpl(Member.METHOD, declaringType, PUBLIC_STATIC, "hasAspect", "()Z"); }; public static ResolvedMember perCflowAspectOfMethod(UnresolvedType declaringType) { return perSingletonAspectOfMethod(declaringType); } public static ResolvedMember perCflowHasAspectMethod(UnresolvedType declaringType) { return perSingletonHasAspectMethod(declaringType); }; public static ResolvedMember perObjectAspectOfMethod(UnresolvedType declaringType) { return new ResolvedMemberImpl(Member.METHOD, declaringType, PUBLIC_STATIC, "aspectOf", "(Ljava/lang/Object;)" + declaringType.getSignature()); } public static ResolvedMember perObjectHasAspectMethod(UnresolvedType declaringType) { return new ResolvedMemberImpl(Member.METHOD, declaringType, PUBLIC_STATIC, "hasAspect", "(Ljava/lang/Object;)Z"); }; // PTWIMPL ResolvedMember for aspectOf(), declared in aspect public static ResolvedMember perTypeWithinAspectOfMethod(UnresolvedType declaringType) { return new ResolvedMemberImpl(Member.METHOD, declaringType, PUBLIC_STATIC, "aspectOf", "(Ljava/lang/Class;)" + declaringType.getSignature()); } // PTWIMPL ResolvedMember for hasAspect(), declared in aspect public static ResolvedMember perTypeWithinHasAspectMethod(UnresolvedType declaringType) { return new ResolvedMemberImpl(Member.METHOD, declaringType, PUBLIC_STATIC, "hasAspect", "(Ljava/lang/Class;)Z"); }; // -- privileged accessors public static ResolvedMember privilegedAccessMethodForMethod(UnresolvedType aspectType, ResolvedMember method) { return new ResolvedMemberImpl( Member.METHOD, method.getDeclaringType(), Modifier.PUBLIC | (method.isStatic() ? Modifier.STATIC : 0), method.getReturnType(), NameMangler.privilegedAccessMethodForMethod(method.getName(),method.getDeclaringType(), aspectType), method.getParameterTypes(), method.getExceptions()); } public static ResolvedMember privilegedAccessMethodForFieldGet(UnresolvedType aspectType, Member field) { String sig; if (field.isStatic()) { sig = "()" + field.getReturnType().getSignature(); } else { sig = "(" + field.getDeclaringType().getSignature() + ")" + field.getReturnType().getSignature(); } return new ResolvedMemberImpl(Member.METHOD, field.getDeclaringType(), PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0), NameMangler.privilegedAccessMethodForFieldGet(field.getName(), field.getDeclaringType(), aspectType), sig); } public static ResolvedMember privilegedAccessMethodForFieldSet(UnresolvedType aspectType, Member field) { String sig; if (field.isStatic()) { sig = "(" + field.getReturnType().getSignature() + ")V"; } else { sig = "(" + field.getDeclaringType().getSignature() + field.getReturnType().getSignature() + ")V"; } return new ResolvedMemberImpl(Member.METHOD, field.getDeclaringType(), PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0), NameMangler.privilegedAccessMethodForFieldSet(field.getName(), field.getDeclaringType(), aspectType), sig); } // --- inline accessors //??? can eclipse handle a transform this weird without putting synthetics into the mix public static ResolvedMember superAccessMethod(UnresolvedType baseType, ResolvedMember method) { return new ResolvedMemberImpl(Member.METHOD, baseType, Modifier.PUBLIC, method.getReturnType(), NameMangler.superDispatchMethod(baseType, method.getName()), method.getParameterTypes(), method.getExceptions()); } public static ResolvedMember inlineAccessMethodForMethod(UnresolvedType aspectType, ResolvedMember method) { UnresolvedType[] paramTypes = method.getParameterTypes(); if (!method.isStatic()) { paramTypes = UnresolvedType.insert(method.getDeclaringType(), paramTypes); } return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC, //??? what about privileged and super access //???Modifier.PUBLIC | (method.isStatic() ? Modifier.STATIC : 0), method.getReturnType(), NameMangler.inlineAccessMethodForMethod(method.getName(), method.getDeclaringType(), aspectType), paramTypes, method.getExceptions()); } public static ResolvedMember inlineAccessMethodForFieldGet(UnresolvedType aspectType, Member field) { String sig; if (field.isStatic()) { sig = "()" + field.getReturnType().getSignature(); } else { sig = "(" + field.getDeclaringType().getSignature() + ")" + field.getReturnType().getSignature(); } return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0), NameMangler.inlineAccessMethodForFieldGet(field.getName(), field.getDeclaringType(), aspectType), sig); } public static ResolvedMember inlineAccessMethodForFieldSet(UnresolvedType aspectType, Member field) { String sig; if (field.isStatic()) { sig = "(" + field.getReturnType().getSignature() + ")V"; } else { sig = "(" + field.getDeclaringType().getSignature() + field.getReturnType().getSignature() + ")V"; } return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0), NameMangler.inlineAccessMethodForFieldSet(field.getName(), field.getDeclaringType(), aspectType), sig); } // --- runtimeLibrary api stuff public static Member cflowStackPeekInstance() { return new MemberImpl( Member.METHOD, CFLOW_STACK_TYPE, 0, "peekInstance", "()Ljava/lang/Object;"); } public static Member cflowStackPushInstance() { return new MemberImpl( Member.METHOD, CFLOW_STACK_TYPE, 0, "pushInstance", "(Ljava/lang/Object;)V"); } public static Member cflowStackIsValid() { return new MemberImpl( Member.METHOD, CFLOW_STACK_TYPE, 0, "isValid", "()Z"); } public static Member cflowStackInit() { return new MemberImpl( Member.CONSTRUCTOR, CFLOW_STACK_TYPE, 0, "<init>", "()V"); } public static Member aroundClosurePreInitializationField() { return new MemberImpl( Member.FIELD, AROUND_CLOSURE_TYPE, 0, "preInitializationState", "[Ljava/lang/Object;"); } public static Member aroundClosurePreInitializationGetter() { return new MemberImpl( Member.METHOD, AROUND_CLOSURE_TYPE, 0, "getPreInitializationState", "()[Ljava/lang/Object;"); } public static ResolvedMember preIntroducedConstructor( UnresolvedType aspectType, UnresolvedType targetType, UnresolvedType[] paramTypes) { return new ResolvedMemberImpl( Member.METHOD, aspectType, PUBLIC_STATIC_FINAL, UnresolvedType.OBJECTARRAY, NameMangler.preIntroducedConstructor(aspectType, targetType), paramTypes); } public static ResolvedMember postIntroducedConstructor( UnresolvedType aspectType, UnresolvedType targetType, UnresolvedType[] paramTypes) { return new ResolvedMemberImpl( Member.METHOD, aspectType, PUBLIC_STATIC_FINAL, ResolvedType.VOID, NameMangler.postIntroducedConstructor(aspectType, targetType), UnresolvedType.insert(targetType, paramTypes)); } public static ResolvedMember interConstructor(ResolvedType targetType, ResolvedMember constructor, UnresolvedType aspectType) { // // ResolvedType targetType, // UnresolvedType[] argTypes, // int modifiers) // { ResolvedMember ret = new ResolvedMemberImpl( Member.CONSTRUCTOR, targetType, Modifier.PUBLIC, ResolvedType.VOID, "<init>", constructor.getParameterTypes(), constructor.getExceptions()); //System.out.println("ret: " + ret + " mods: " + Modifier.toString(modifiers)); if (Modifier.isPublic(constructor.getModifiers())) return ret; while (true) { ret = addCookieTo(ret, aspectType); if (targetType.lookupMemberNoSupers(ret) == null) return ret; } } public static ResolvedMember interFieldInitializer(ResolvedMember field, UnresolvedType aspectType) { return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC, NameMangler.interFieldInitializer(aspectType, field.getDeclaringType(), field.getName()), field.isStatic() ? "()V" : "(" + field.getDeclaringType().getSignature() + ")V" ); } /** * Makes public and non-final */ private static int makePublicNonFinal(int modifiers) { return (modifiers & ~VISIBILITY & ~Modifier.FINAL) | Modifier.PUBLIC; } /** * This static method goes on the aspect that declares the inter-type field */ public static ResolvedMember interFieldSetDispatcher(ResolvedMember field, UnresolvedType aspectType) { return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC, ResolvedType.VOID, NameMangler.interFieldSetDispatcher(aspectType, field.getDeclaringType(), field.getName()), field.isStatic() ? new UnresolvedType[] {field.getReturnType()} : new UnresolvedType[] {field.getDeclaringType(), field.getReturnType()} ); } /** * This static method goes on the aspect that declares the inter-type field */ public static ResolvedMember interFieldGetDispatcher(ResolvedMember field, UnresolvedType aspectType) { return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC, field.getReturnType(), NameMangler.interFieldGetDispatcher(aspectType, field.getDeclaringType(), field.getName()), field.isStatic() ? UnresolvedType.NONE : new UnresolvedType[] {field.getDeclaringType()}, UnresolvedType.NONE ); } // private static int makeFieldModifiers(int declaredModifiers) { // int ret = Modifier.PUBLIC; // if (Modifier.isTransient(declaredModifiers)) ret |= Modifier.TRANSIENT; // if (Modifier.isVolatile(declaredModifiers)) ret |= Modifier.VOLATILE; // return ret; // } /** * This field goes on the class the field * is declared onto */ public static ResolvedMember interFieldClassField(ResolvedMember field, UnresolvedType aspectType) { return new ResolvedMemberImpl(Member.FIELD, field.getDeclaringType(), makePublicNonFinal(field.getModifiers()), field.getReturnType(), NameMangler.interFieldClassField(field.getModifiers(), aspectType, field.getDeclaringType(), field.getName()), UnresolvedType.NONE, UnresolvedType.NONE ); } /** * This field goes on top-most implementers of the interface the field * is declared onto */ public static ResolvedMember interFieldInterfaceField(ResolvedMember field, UnresolvedType onClass, UnresolvedType aspectType) { return new ResolvedMemberImpl(Member.FIELD, onClass, makePublicNonFinal(field.getModifiers()), field.getReturnType(), NameMangler.interFieldInterfaceField(aspectType, field.getDeclaringType(), field.getName()), UnresolvedType.NONE, UnresolvedType.NONE ); } /** * This instance method goes on the interface the field is declared onto * as well as its top-most implementors */ public static ResolvedMember interFieldInterfaceSetter(ResolvedMember field, ResolvedType onType, UnresolvedType aspectType) { int modifiers = Modifier.PUBLIC; if (onType.isInterface()) modifiers |= Modifier.ABSTRACT; return new ResolvedMemberImpl(Member.METHOD, onType, modifiers, ResolvedType.VOID, NameMangler.interFieldInterfaceSetter(aspectType, field.getDeclaringType(), field.getName()), new UnresolvedType[] {field.getReturnType()}, UnresolvedType.NONE ); } /** * This instance method goes on the interface the field is declared onto * as well as its top-most implementors */ public static ResolvedMember interFieldInterfaceGetter(ResolvedMember field, ResolvedType onType, UnresolvedType aspectType) { int modifiers = Modifier.PUBLIC; if (onType.isInterface()) modifiers |= Modifier.ABSTRACT; return new ResolvedMemberImpl(Member.METHOD, onType, modifiers, field.getReturnType(), NameMangler.interFieldInterfaceGetter(aspectType, field.getDeclaringType(), field.getName()), UnresolvedType.NONE, UnresolvedType.NONE ); } /** * This method goes on the target type of the inter-type method. (and possibly the topmost-implementors, * if the target type is an interface). The implementation will call the interMethodDispatch method on the * aspect. */ public static ResolvedMember interMethod(ResolvedMember meth, UnresolvedType aspectType, boolean onInterface) { if (Modifier.isPublic(meth.getModifiers()) && !onInterface) return meth; int modifiers = makePublicNonFinal(meth.getModifiers()); if (onInterface) modifiers |= Modifier.ABSTRACT; return new ResolvedMemberImpl(Member.METHOD, meth.getDeclaringType(), modifiers, meth.getReturnType(), NameMangler.interMethod(meth.getModifiers(), aspectType, meth.getDeclaringType(), meth.getName()), meth.getParameterTypes(), meth.getExceptions()); } /** * This static method goes on the declaring aspect of the inter-type method. The implementation * calls the interMethodBody() method on the aspect. */ public static ResolvedMember interMethodDispatcher(ResolvedMember meth, UnresolvedType aspectType) { UnresolvedType[] paramTypes = meth.getParameterTypes(); if (!meth.isStatic()) { paramTypes = UnresolvedType.insert(meth.getDeclaringType(), paramTypes); } return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC, meth.getReturnType(), NameMangler.interMethodDispatcher(aspectType, meth.getDeclaringType(), meth.getName()), paramTypes, meth.getExceptions()); } /** * This method goes on the declaring aspect of the inter-type method. * It contains the real body of the ITD method. */ public static ResolvedMember interMethodBody(ResolvedMember meth, UnresolvedType aspectType) { UnresolvedType[] paramTypes = meth.getParameterTypes(); if (!meth.isStatic()) { paramTypes = UnresolvedType.insert(meth.getDeclaringType(), paramTypes); } int modifiers = PUBLIC_STATIC; if (Modifier.isStrict(meth.getModifiers())) { modifiers |= Modifier.STRICT; } return new ResolvedMemberImpl(Member.METHOD, aspectType, modifiers, meth.getReturnType(), NameMangler.interMethodBody(aspectType, meth.getDeclaringType(), meth.getName()), paramTypes, meth.getExceptions()); } private static ResolvedMember addCookieTo(ResolvedMember ret, UnresolvedType aspectType) { UnresolvedType[] params = ret.getParameterTypes(); UnresolvedType[] freshParams = UnresolvedType.add(params, aspectType); return new ResolvedMemberImpl( ret.getKind(), ret.getDeclaringType(), ret.getModifiers(), ret.getReturnType(), ret.getName(), freshParams, ret.getExceptions()); } public static ResolvedMember toObjectConversionMethod(UnresolvedType fromType) { if (fromType.isPrimitiveType()) { String name = fromType.toString() + "Object"; return new ResolvedMemberImpl( Member.METHOD, CONVERSIONS_TYPE, PUBLIC_STATIC, UnresolvedType.OBJECT, name, new UnresolvedType[] { fromType }, UnresolvedType.NONE); } else { return null; } } public static Member interfaceConstructor(ResolvedType resolvedTypeX) { // AMC next two lines should not be needed when sig for generic type is changed ResolvedType declaringType = resolvedTypeX; if (declaringType.isRawType()) declaringType = declaringType.getGenericType(); return new ResolvedMemberImpl( Member.CONSTRUCTOR, declaringType, Modifier.PUBLIC, "<init>", "()V"); } //-- common types we use. Note: Java 5 dependand types are refered to as String public final static UnresolvedType ASPECT_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.Aspect"); public final static UnresolvedType BEFORE_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.Before"); public final static UnresolvedType AROUND_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.Around"); public final static UnresolvedType AFTERRETURNING_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.AfterReturning"); public final static UnresolvedType AFTERTHROWING_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.AfterThrowing"); public final static UnresolvedType AFTER_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.After"); public final static UnresolvedType POINTCUT_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.Pointcut"); public final static UnresolvedType DECLAREERROR_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.DeclareError"); public final static UnresolvedType DECLAREWARNING_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.DeclareWarning"); public final static UnresolvedType DECLAREPRECEDENCE_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.DeclarePrecedence"); public final static UnresolvedType TYPEX_JOINPOINT = UnresolvedType.forName(JoinPoint.class.getName().replace('/','.')); public final static UnresolvedType TYPEX_PROCEEDINGJOINPOINT = UnresolvedType.forName(ProceedingJoinPoint.class.getName().replace('/','.')); public final static UnresolvedType TYPEX_STATICJOINPOINT = UnresolvedType.forName(JoinPoint.StaticPart.class.getName().replace('/','.')); public final static UnresolvedType TYPEX_ENCLOSINGSTATICJOINPOINT = UnresolvedType.forName(JoinPoint.EnclosingStaticPart.class.getName().replace('/','.')); }
109,283
Bug 109283 Invalid "indirect static access" warning on EnumSet.noneOf
When compiling AspectJ enabled projects in Java 5.0 source mode with "Indirect access to static modifier" warnings on, the following code incorrectly gives a compiler warning (this doesn't occur in non-AspectJ enabled projects): public class Test { enum Foo { Wibble, Wobble, Woo; } public static void main(String[] args) { EnumSet<Foo> set = EnumSet.noneOf(Foo.class); } }
resolved fixed
8a0f59a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-22T15:45:06Z
2005-09-12T13:00:00Z
weaver/src/org/aspectj/weaver/bcel/BcelPerClauseAspectAdder.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: * initial implementation Alexandre Vasseur *******************************************************************************/ package org.aspectj.weaver.bcel; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.generic.ATHROW; import org.aspectj.apache.bcel.generic.BranchInstruction; 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.NOP; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.POP; import org.aspectj.apache.bcel.generic.PUSH; import org.aspectj.apache.bcel.generic.ReferenceType; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.patterns.PerClause; /** * Adds aspectOf, hasAspect etc to the annotation defined aspects * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class BcelPerClauseAspectAdder extends BcelTypeMunger { private PerClause.Kind kind; private boolean hasGeneratedInner = false; public BcelPerClauseAspectAdder(ResolvedType aspect, PerClause.Kind kind) { super(null,aspect); this.kind = kind; if (kind == PerClause.SINGLETON || kind == PerClause.PERTYPEWITHIN || kind == PerClause.PERCFLOW) { // no inner needed hasGeneratedInner = true; } } public boolean munge(BcelClassWeaver weaver) { LazyClassGen gen = weaver.getLazyClassGen(); // agressively generate the inner interface if any // Note: we do so because of the bug #75442 that leads to have this interface implemented by all classes and not // only those matched by the per clause, which fails under LTW since the very first class // gets weaved and impl this interface that is still not defined. if (!hasGeneratedInner) { if (kind == PerClause.PEROBJECT) {//redundant test - see constructor, but safer //inner class UnresolvedType interfaceTypeX = AjcMemberMaker.perObjectInterfaceType(aspectType); LazyClassGen interfaceGen = new LazyClassGen( interfaceTypeX.getName(), "java.lang.Object", null, Constants.ACC_INTERFACE + Constants.ACC_PUBLIC + Constants.ACC_ABSTRACT, new String[0], getWorld() ); interfaceGen.addMethodGen(makeMethodGen(interfaceGen, AjcMemberMaker.perObjectInterfaceGet(aspectType))); interfaceGen.addMethodGen(makeMethodGen(interfaceGen, AjcMemberMaker.perObjectInterfaceSet(aspectType))); //not really an inner class of it but that does not matter, we pass back to the LTW gen.addGeneratedInner(interfaceGen); } hasGeneratedInner = true; } // Only munge the aspect type if (!gen.getType().equals(aspectType)) { return false; } generatePerClauseMembers(gen); if (kind == PerClause.SINGLETON) { generatePerSingletonAspectOfMethod(gen); generatePerSingletonHasAspectMethod(gen); generatePerSingletonAjcClinitMethod(gen); } else if (kind == PerClause.PEROBJECT) { generatePerObjectAspectOfMethod(gen); generatePerObjectHasAspectMethod(gen); generatePerObjectBindMethod(gen); generatePerObjectGetSetMethods(gen); } else if (kind == PerClause.PERCFLOW) { generatePerCflowAspectOfMethod(gen); generatePerCflowHasAspectMethod(gen); generatePerCflowPushMethod(gen); generatePerCflowAjcClinitMethod(gen); } else if (kind == PerClause.PERTYPEWITHIN) { generatePerTWAspectOfMethod(gen); generatePerTWHasAspectMethod(gen); generatePerTWGetInstanceMethod(gen); generatePerTWCreateAspectInstanceMethod(gen); } else { throw new Error("should not happen - not such kind " + kind.getName()); } return true; } public ResolvedMember getMatchingSyntheticMember(Member member) { return null; } public ResolvedMember getSignature() { return null; } public boolean matches(ResolvedType onType) { //we cannot return onType.equals(aspectType) //since we need to eagerly create the nested ajcMighHaveAspect interface on LTW return true; //return aspectType.equals(onType); } private void generatePerClauseMembers(LazyClassGen classGen) { //FIXME Alex handle when field already there - or handle it with / similar to isAnnotationDefinedAspect() // for that use aspectType and iterate on the fields. //FIXME Alex percflowX is not using this one but AJ code style does generate it so.. ResolvedMember failureFieldInfo = AjcMemberMaker.initFailureCauseField(aspectType); classGen.addField(makeFieldGen(classGen, failureFieldInfo).getField(), null); if (kind == PerClause.SINGLETON) { ResolvedMember perSingletonFieldInfo = AjcMemberMaker.perSingletonField(aspectType); classGen.addField(makeFieldGen(classGen, perSingletonFieldInfo).getField(), null); } else if (kind == PerClause.PEROBJECT) { ResolvedMember perObjectFieldInfo = AjcMemberMaker.perObjectField(aspectType, aspectType); classGen.addField(makeFieldGen(classGen, perObjectFieldInfo).getField(), null); // if lazy generation of the inner interface MayHaveAspect works on LTW (see previous note) // it should be done here. } else if (kind == PerClause.PERCFLOW) { ResolvedMember perCflowFieldInfo = AjcMemberMaker.perCflowField(aspectType); classGen.addField(makeFieldGen(classGen, perCflowFieldInfo).getField(), null); } else if (kind == PerClause.PERTYPEWITHIN) { ResolvedMember perTypeWithinForField = AjcMemberMaker.perTypeWithinWithinTypeField(aspectType, aspectType); classGen.addField(makeFieldGen(classGen, perTypeWithinForField).getField(), null); } else { throw new Error("Should not happen - no such kind " + kind.toString()); } } private void generatePerSingletonAspectOfMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perSingletonAspectOfMethod(aspectType)); flagAsSynthetic(method, false); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(Utility.createGet(factory, AjcMemberMaker.perSingletonField(aspectType))); BranchInstruction ifNotNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null); il.append(ifNotNull); il.append(factory.createNew(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName())); il.append(InstructionConstants.DUP); il.append(new PUSH(classGen.getConstantPoolGen(), aspectType.getName())); il.append(Utility.createGet(factory, AjcMemberMaker.initFailureCauseField(aspectType))); il.append(factory.createInvoke(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName(), "<init>", Type.VOID, new Type[] { Type.STRING, new ObjectType("java.lang.Throwable") }, Constants.INVOKESPECIAL)); il.append(InstructionConstants.ATHROW); InstructionHandle ifElse = il.append(Utility.createGet(factory, AjcMemberMaker.perSingletonField(aspectType))); il.append(InstructionFactory.createReturn(Type.OBJECT)); ifNotNull.setTarget(ifElse); } private void generatePerSingletonHasAspectMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perSingletonHasAspectMethod(aspectType)); flagAsSynthetic(method, false); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(Utility.createGet(factory, AjcMemberMaker.perSingletonField(aspectType))); BranchInstruction ifNull = InstructionFactory.createBranchInstruction(Constants.IFNULL, null); il.append(ifNull); il.append(new PUSH(classGen.getConstantPoolGen(), true)); il.append(InstructionFactory.createReturn(Type.INT)); InstructionHandle ifElse = il.append(new PUSH(classGen.getConstantPoolGen(), false)); il.append(InstructionFactory.createReturn(Type.INT)); ifNull.setTarget(ifElse); } private void generatePerSingletonAjcClinitMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.ajcPostClinitMethod(aspectType)); flagAsSynthetic(method, true); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(factory.createNew(aspectType.getName())); il.append(InstructionConstants.DUP); il.append(factory.createInvoke(aspectType.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); il.append(Utility.createSet(factory, AjcMemberMaker.perSingletonField(aspectType))); il.append(InstructionFactory.createReturn(Type.VOID)); // patch <clinit> to delegate to ajc$postClinit at the end LazyMethodGen clinit = classGen.getStaticInitializer(); il = new InstructionList(); InstructionHandle tryStart = il.append(factory.createInvoke(aspectType.getName(), NameMangler.AJC_POST_CLINIT_NAME, Type.VOID, Type.NO_ARGS, Constants.INVOKESTATIC)); BranchInstruction tryEnd = InstructionFactory.createBranchInstruction(Constants.GOTO, null); il.append(tryEnd); InstructionHandle handler = il.append(InstructionConstants.ASTORE_0); il.append(InstructionConstants.ALOAD_0); il.append(Utility.createSet(factory, AjcMemberMaker.initFailureCauseField(aspectType))); il.append(InstructionFactory.createReturn(Type.VOID)); tryEnd.setTarget(il.getEnd()); // replace the original "return" with a "nop" //TODO AV - a bit odd, looks like Bcel alters bytecode and has a IMPDEP1 in its representation if (clinit.getBody().getEnd().getInstruction().getOpcode() == Constants.IMPDEP1) { clinit.getBody().getEnd().getPrev().setInstruction(new NOP()); } clinit.getBody().getEnd().setInstruction(new NOP()); clinit.getBody().append(il); clinit.addExceptionHandler( tryStart, handler, handler, new ObjectType("java.lang.Throwable"), false ); } private void generatePerObjectAspectOfMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); ReferenceType interfaceType = (ReferenceType) BcelWorld.makeBcelType(AjcMemberMaker.perObjectInterfaceType(aspectType)); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perObjectAspectOfMethod(aspectType)); flagAsSynthetic(method, false); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(InstructionConstants.ALOAD_0); il.append(factory.createInstanceOf(interfaceType)); BranchInstruction ifEq = InstructionFactory.createBranchInstruction(Constants.IFEQ, null); il.append(ifEq); il.append(InstructionConstants.ALOAD_0); il.append(factory.createCheckCast(interfaceType)); il.append(Utility.createInvoke(factory, Constants.INVOKEINTERFACE, AjcMemberMaker.perObjectInterfaceGet(aspectType))); il.append(InstructionConstants.DUP); BranchInstruction ifNull = InstructionFactory.createBranchInstruction(Constants.IFNULL, null); il.append(ifNull); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(aspectType))); InstructionHandle ifNullElse = il.append(new POP()); ifNull.setTarget(ifNullElse); InstructionHandle ifEqElse = il.append(factory.createNew(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName())); ifEq.setTarget(ifEqElse); il.append(InstructionConstants.DUP); il.append(factory.createInvoke(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); il.append(new ATHROW()); } private void generatePerObjectHasAspectMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); ReferenceType interfaceType = (ReferenceType) BcelWorld.makeBcelType(AjcMemberMaker.perObjectInterfaceType(aspectType)); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perObjectHasAspectMethod(aspectType)); flagAsSynthetic(method, false); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(InstructionConstants.ALOAD_0); il.append(factory.createInstanceOf(interfaceType)); BranchInstruction ifEq = InstructionFactory.createBranchInstruction(Constants.IFEQ, null); il.append(ifEq); il.append(InstructionConstants.ALOAD_0); il.append(factory.createCheckCast(interfaceType)); il.append(Utility.createInvoke(factory, Constants.INVOKEINTERFACE, AjcMemberMaker.perObjectInterfaceGet(aspectType))); BranchInstruction ifNull = InstructionFactory.createBranchInstruction(Constants.IFNULL, null); il.append(ifNull); il.append(InstructionConstants.ICONST_1); il.append(InstructionFactory.createReturn(Type.INT)); InstructionHandle ifEqElse = il.append(InstructionConstants.ICONST_0); ifEq.setTarget(ifEqElse); ifNull.setTarget(ifEqElse); il.append(InstructionFactory.createReturn(Type.INT)); } private void generatePerObjectBindMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); ReferenceType interfaceType = (ReferenceType) BcelWorld.makeBcelType(AjcMemberMaker.perObjectInterfaceType(aspectType)); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perObjectBind(aspectType)); flagAsSynthetic(method, true); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(InstructionConstants.ALOAD_0); il.append(factory.createInstanceOf(interfaceType)); BranchInstruction ifEq = InstructionFactory.createBranchInstruction(Constants.IFEQ, null); il.append(ifEq); il.append(InstructionConstants.ALOAD_0); il.append(factory.createCheckCast(interfaceType)); il.append(Utility.createInvoke(factory, Constants.INVOKEINTERFACE, AjcMemberMaker.perObjectInterfaceGet(aspectType))); BranchInstruction ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null); il.append(ifNonNull); il.append(InstructionConstants.ALOAD_0); il.append(factory.createCheckCast(interfaceType)); il.append(factory.createNew(aspectType.getName())); il.append(InstructionConstants.DUP); il.append(factory.createInvoke(aspectType.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); il.append(Utility.createInvoke(factory, Constants.INVOKEINTERFACE, AjcMemberMaker.perObjectInterfaceSet(aspectType))); InstructionHandle end = il.append(InstructionFactory.createReturn(Type.VOID)); ifEq.setTarget(end); ifNonNull.setTarget(end); } private void generatePerObjectGetSetMethods(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen methodGet = makeMethodGen(classGen, AjcMemberMaker.perObjectInterfaceGet(aspectType)); flagAsSynthetic(methodGet, true); classGen.addMethodGen(methodGet); InstructionList ilGet = methodGet.getBody(); ilGet = new InstructionList(); ilGet.append(InstructionConstants.ALOAD_0); ilGet.append(Utility.createGet(factory, AjcMemberMaker.perObjectField(aspectType, aspectType))); ilGet.append(InstructionFactory.createReturn(Type.OBJECT)); LazyMethodGen methodSet = makeMethodGen(classGen, AjcMemberMaker.perObjectInterfaceSet(aspectType)); flagAsSynthetic(methodSet, true); classGen.addMethodGen(methodSet); InstructionList ilSet = methodSet.getBody(); ilSet = new InstructionList(); ilSet.append(InstructionConstants.ALOAD_0); ilSet.append(InstructionConstants.ALOAD_1); ilSet.append(Utility.createSet(factory, AjcMemberMaker.perObjectField(aspectType, aspectType))); ilSet.append(InstructionFactory.createReturn(Type.VOID)); } private void generatePerCflowAspectOfMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perCflowAspectOfMethod(aspectType)); flagAsSynthetic(method, false); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(Utility.createGet(factory, AjcMemberMaker.perCflowField(aspectType))); il.append(Utility.createInvoke(factory, Constants.INVOKEVIRTUAL, AjcMemberMaker.cflowStackPeekInstance())); il.append(factory.createCheckCast((ReferenceType)BcelWorld.makeBcelType(aspectType))); il.append(InstructionFactory.createReturn(Type.OBJECT)); } private void generatePerCflowHasAspectMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perCflowHasAspectMethod(aspectType)); flagAsSynthetic(method, false); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(Utility.createGet(factory, AjcMemberMaker.perCflowField(aspectType))); il.append(Utility.createInvoke(factory, Constants.INVOKEVIRTUAL, AjcMemberMaker.cflowStackIsValid())); il.append(InstructionFactory.createReturn(Type.INT)); } private void generatePerCflowPushMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perCflowPush(aspectType)); flagAsSynthetic(method, true); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(Utility.createGet(factory, AjcMemberMaker.perCflowField(aspectType))); il.append(factory.createNew(aspectType.getName())); il.append(InstructionConstants.DUP); il.append(factory.createInvoke(aspectType.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); il.append(Utility.createInvoke(factory, Constants.INVOKEVIRTUAL, AjcMemberMaker.cflowStackPushInstance())); il.append(InstructionFactory.createReturn(Type.VOID)); } private void generatePerCflowAjcClinitMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.ajcPreClinitMethod(aspectType)); flagAsSynthetic(method, true); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(factory.createNew(AjcMemberMaker.CFLOW_STACK_TYPE.getName())); il.append(InstructionConstants.DUP); il.append(factory.createInvoke(AjcMemberMaker.CFLOW_STACK_TYPE.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); il.append(Utility.createSet(factory, AjcMemberMaker.perCflowField(aspectType))); il.append(InstructionFactory.createReturn(Type.VOID)); // patch <clinit> to delegate to ajc$preClinit at the beginning LazyMethodGen clinit = classGen.getStaticInitializer(); il = new InstructionList(); il.append(factory.createInvoke(aspectType.getName(), NameMangler.AJC_PRE_CLINIT_NAME, Type.VOID, Type.NO_ARGS, Constants.INVOKESTATIC)); clinit.getBody().insert(il); } private void generatePerTWAspectOfMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perTypeWithinAspectOfMethod(aspectType)); flagAsSynthetic(method, false); classGen.addMethodGen(method); InstructionList il = method.getBody(); InstructionHandle tryStart = il.append(InstructionConstants.ALOAD_0); il.append(Utility.createInvoke( factory, Constants.INVOKESTATIC, AjcMemberMaker.perTypeWithinGetInstance(aspectType) )); il.append(InstructionConstants.ASTORE_1); il.append(InstructionConstants.ALOAD_1); BranchInstruction ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null); il.append(ifNonNull); il.append(factory.createNew(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName())); il.append(InstructionConstants.DUP); il.append(new PUSH(classGen.getConstantPoolGen(), aspectType.getName())); il.append(InstructionConstants.ACONST_NULL); il.append(factory.createInvoke(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName(), "<init>", Type.VOID, new Type[] { Type.STRING, new ObjectType("java.lang.Throwable") }, Constants.INVOKESPECIAL)); il.append(InstructionConstants.ATHROW); InstructionHandle ifElse = il.append(InstructionConstants.ALOAD_1); ifNonNull.setTarget(ifElse); il.append(InstructionFactory.createReturn(Type.OBJECT)); InstructionHandle handler = il.append(InstructionConstants.ASTORE_1); il.append(factory.createNew(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName())); il.append(InstructionConstants.DUP); il.append(factory.createInvoke(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); il.append(InstructionConstants.ATHROW); method.addExceptionHandler( tryStart, handler.getPrev(), handler, new ObjectType("java.lang.Exception"), false ); } private void generatePerTWHasAspectMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perTypeWithinHasAspectMethod(aspectType)); flagAsSynthetic(method, false); classGen.addMethodGen(method); InstructionList il = method.getBody(); InstructionHandle tryStart = il.append(InstructionConstants.ALOAD_0); il.append(Utility.createInvoke( factory, Constants.INVOKESTATIC, AjcMemberMaker.perTypeWithinGetInstance(aspectType) )); BranchInstruction ifNull = InstructionFactory.createBranchInstruction(Constants.IFNULL, null); il.append(ifNull); il.append(InstructionConstants.ICONST_1); il.append(InstructionConstants.IRETURN); InstructionHandle ifElse = il.append(InstructionConstants.ICONST_0); ifNull.setTarget(ifElse); il.append(InstructionConstants.IRETURN); InstructionHandle handler = il.append(InstructionConstants.ASTORE_1); il.append(InstructionConstants.ICONST_0); il.append(InstructionConstants.IRETURN); method.addExceptionHandler( tryStart, handler.getPrev(), handler, new ObjectType("java.lang.Exception"), false ); } private void generatePerTWGetInstanceMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perTypeWithinGetInstance(aspectType)); flagAsSynthetic(method, true); classGen.addMethodGen(method); InstructionList il = method.getBody(); InstructionHandle tryStart = il.append(InstructionConstants.ALOAD_0); il.append(new PUSH(factory.getConstantPool(), NameMangler.perTypeWithinLocalAspectOf(aspectType))); il.append(InstructionConstants.ACONST_NULL);//Class[] for "getDeclaredMethod" il.append(factory.createInvoke( "java/lang/Class", "getDeclaredMethod", Type.getType("Ljava/lang/reflect/Method;"), new Type[]{Type.getType("Ljava/lang/String;"), Type.getType("[Ljava/lang/Class;")}, Constants.INVOKEVIRTUAL )); il.append(InstructionConstants.ACONST_NULL);//Object for "invoke", static method il.append(InstructionConstants.ACONST_NULL);//Object[] for "invoke", no arg il.append(factory.createInvoke( "java/lang/reflect/Method", "invoke", Type.OBJECT, new Type[]{Type.getType("Ljava/lang/Object;"), Type.getType("[Ljava/lang/Object;")}, Constants.INVOKEVIRTUAL )); il.append(factory.createCheckCast((ReferenceType) BcelWorld.makeBcelType(aspectType))); il.append(InstructionConstants.ARETURN); InstructionHandle handler = il.append(InstructionConstants.ASTORE_1); il.append(InstructionConstants.ACONST_NULL); il.append(InstructionConstants.ARETURN); method.addExceptionHandler( tryStart, handler.getPrev(), handler, new ObjectType("java.lang.Exception"), false ); } private void generatePerTWCreateAspectInstanceMethod(LazyClassGen classGen) { InstructionFactory factory = classGen.getFactory(); LazyMethodGen method = makeMethodGen(classGen, AjcMemberMaker.perTypeWithinCreateAspectInstance(aspectType)); flagAsSynthetic(method, true); classGen.addMethodGen(method); InstructionList il = method.getBody(); il.append(factory.createNew(aspectType.getName())); il.append(InstructionConstants.DUP); il.append(factory.createInvoke( aspectType.getName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL )); il.append(InstructionConstants.ASTORE_1); il.append(InstructionConstants.ALOAD_1); il.append(InstructionConstants.ALOAD_0); il.append(Utility.createSet( factory, AjcMemberMaker.perTypeWithinWithinTypeField(aspectType, aspectType) )); il.append(InstructionConstants.ALOAD_1); il.append(InstructionConstants.ARETURN); } /** * Add standard Synthetic (if wished) and AjSynthetic (always) attributes * @param methodGen * @param makeJavaSynthetic true if standard Synthetic attribute must be set as well (invisible to user) */ private static void flagAsSynthetic(LazyMethodGen methodGen, boolean makeJavaSynthetic) { if (makeJavaSynthetic) { methodGen.makeSynthetic(); } methodGen.addAttribute( BcelAttributes.bcelAttribute( new AjAttribute.AjSynthetic(), methodGen.getEnclosingClass().getConstantPoolGen() ) ); } }
109,173
Bug 109173 Weaving Adaptor enhancements for performance, configuration and diagnosis
Here are some suggested enhancements as a result of exhaustive testing in the Eclipse/OSGi environment. 1. If no aspects are declared for a particular class loader, either because there are no visible aop.xml files or they contain no aspect definitions, then we should short-circuit the implementation of weaveClass() so that byte-code is not unnecessarily passed to the weaver. This is especially important under OSGi where there may be hundreds of class bundles, each with their own class loader only some of which are being woven. We can use the existing enabled flag. 2. As previously discussed on aspectj-dev the META-INF directory is considered private in OSGi and is therefore an inappropriate location for aop.xml files declaring shared aspects. I therefore propose a System property to set the a resource names for finding aop.xml files which would default to META-INF/aop.xml e.g. -Dorg.aspectj.weaver.loadtime.configuration=META- INF/aop.xml;org/aspectj/aop.xml. 3. We should not be catching Throwable in Aj. Instead we should catch known exceptions e.g. BCException and issue messages while letting other runtime exceptions pass back to the class loader. A user provided IMessageHandler implementation can decide under what circumstances to abort. Alternatively if Aj is considered to be a safe interface for weaving agents e.g. JVMTI then the dump logic it contains should be moved to the WeavingAdaptor so that it can be used directly from a class loader.
resolved fixed
03b20bc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-23T14:40:27Z
2005-09-09T15: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 { /** * Initialization */ public void initialize() { ; } /** * Weave * * @param className * @param bytes * @param loader * @return */ 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); 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) { synchronized(loader) {//FIXME AV - temp fix for #99861 synchronized (weavingAdaptors) { WeavingAdaptor weavingAdaptor = (WeavingAdaptor) weavingAdaptors.get(loader); if (weavingAdaptor == null) { weavingAdaptor = new ClassLoaderWeavingAdaptor(loader); weavingAdaptors.put(loader, weavingAdaptor); } 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(); } }
109,173
Bug 109173 Weaving Adaptor enhancements for performance, configuration and diagnosis
Here are some suggested enhancements as a result of exhaustive testing in the Eclipse/OSGi environment. 1. If no aspects are declared for a particular class loader, either because there are no visible aop.xml files or they contain no aspect definitions, then we should short-circuit the implementation of weaveClass() so that byte-code is not unnecessarily passed to the weaver. This is especially important under OSGi where there may be hundreds of class bundles, each with their own class loader only some of which are being woven. We can use the existing enabled flag. 2. As previously discussed on aspectj-dev the META-INF directory is considered private in OSGi and is therefore an inappropriate location for aop.xml files declaring shared aspects. I therefore propose a System property to set the a resource names for finding aop.xml files which would default to META-INF/aop.xml e.g. -Dorg.aspectj.weaver.loadtime.configuration=META- INF/aop.xml;org/aspectj/aop.xml. 3. We should not be catching Throwable in Aj. Instead we should catch known exceptions e.g. BCException and issue messages while letting other runtime exceptions pass back to the class loader. A user provided IMessageHandler implementation can decide under what circumstances to abort. Alternatively if Aj is considered to be a safe interface for weaving agents e.g. JVMTI then the dump logic it contains should be moved to the WeavingAdaptor so that it can be used directly from a class loader.
resolved fixed
03b20bc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-23T14:40:27Z
2005-09-09T15: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 *******************************************************************************/ 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.Iterator; import java.util.List; import java.util.Properties; /** * @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(); public ClassLoaderWeavingAdaptor(final ClassLoader loader) { 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 } }; 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 Enumeration xmls = loader.getResources(AOP_XML); 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())); } } 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); 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); } } } //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; } }
109,173
Bug 109173 Weaving Adaptor enhancements for performance, configuration and diagnosis
Here are some suggested enhancements as a result of exhaustive testing in the Eclipse/OSGi environment. 1. If no aspects are declared for a particular class loader, either because there are no visible aop.xml files or they contain no aspect definitions, then we should short-circuit the implementation of weaveClass() so that byte-code is not unnecessarily passed to the weaver. This is especially important under OSGi where there may be hundreds of class bundles, each with their own class loader only some of which are being woven. We can use the existing enabled flag. 2. As previously discussed on aspectj-dev the META-INF directory is considered private in OSGi and is therefore an inappropriate location for aop.xml files declaring shared aspects. I therefore propose a System property to set the a resource names for finding aop.xml files which would default to META-INF/aop.xml e.g. -Dorg.aspectj.weaver.loadtime.configuration=META- INF/aop.xml;org/aspectj/aop.xml. 3. We should not be catching Throwable in Aj. Instead we should catch known exceptions e.g. BCException and issue messages while letting other runtime exceptions pass back to the class loader. A user provided IMessageHandler implementation can decide under what circumstances to abort. Alternatively if Aj is considered to be a safe interface for weaving agents e.g. JVMTI then the dump logic it contains should be moved to the WeavingAdaptor so that it can be used directly from a class loader.
resolved fixed
03b20bc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-23T14:40:27Z
2005-09-09T15:33:20Z
loadtime/src/org/aspectj/weaver/loadtime/DefaultWeavingContext.java
109,173
Bug 109173 Weaving Adaptor enhancements for performance, configuration and diagnosis
Here are some suggested enhancements as a result of exhaustive testing in the Eclipse/OSGi environment. 1. If no aspects are declared for a particular class loader, either because there are no visible aop.xml files or they contain no aspect definitions, then we should short-circuit the implementation of weaveClass() so that byte-code is not unnecessarily passed to the weaver. This is especially important under OSGi where there may be hundreds of class bundles, each with their own class loader only some of which are being woven. We can use the existing enabled flag. 2. As previously discussed on aspectj-dev the META-INF directory is considered private in OSGi and is therefore an inappropriate location for aop.xml files declaring shared aspects. I therefore propose a System property to set the a resource names for finding aop.xml files which would default to META-INF/aop.xml e.g. -Dorg.aspectj.weaver.loadtime.configuration=META- INF/aop.xml;org/aspectj/aop.xml. 3. We should not be catching Throwable in Aj. Instead we should catch known exceptions e.g. BCException and issue messages while letting other runtime exceptions pass back to the class loader. A user provided IMessageHandler implementation can decide under what circumstances to abort. Alternatively if Aj is considered to be a safe interface for weaving agents e.g. JVMTI then the dump logic it contains should be moved to the WeavingAdaptor so that it can be used directly from a class loader.
resolved fixed
03b20bc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-23T14:40:27Z
2005-09-09T15:33:20Z
loadtime/src/org/aspectj/weaver/loadtime/IWeavingContext.java
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06: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.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.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(); 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; try { if (batch) { this.state = new AjState(this); } boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !batch) { // retry as batch? 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); 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()) { return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) 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()) { 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())) { 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()) { 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(); } } 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()); 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 bcelWorld.resolve("org.aspectj.lang.JoinPoint"); } 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; } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/core/builder/OutjarTest.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: * Matthew Webster - initial implementation *******************************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import org.aspectj.tools.ajc.AjcTestCase; import org.aspectj.tools.ajc.CompilationResult; import org.aspectj.weaver.WeaverMessages; public class OutjarTest extends AjcTestCase { public static final String PROJECT_DIR = "OutjarTest"; public static final String injarName = "child.jar"; public static final String aspectjarName = "aspects.jar"; public static final String outjarName = "outjar.jar"; private File baseDir; /** * Make copies of JARs used for -injars/-inpath and -aspectpath because so * they are not overwritten when a test fails. */ protected void setUp() throws Exception { super.setUp(); baseDir = new File("../org.aspectj.ajdt.core/testdata",PROJECT_DIR); } /** * Aim: Check that -outjar does not coincide with a member of -injars. This * is because if a binary weave fails -outjar is deleted. * * Inputs to the compiler: * -injar * -aspectpath * -outjar * * Expected result = Compile aborts with error message. */ public void testOutjarInInjars () { String[] args = new String[] {"-aspectpath", aspectjarName, "-injars", injarName, "-outjar", injarName}; Message error = new Message(WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH)); Message fail = new Message("Usage:"); MessageSpec spec = new MessageSpec(null,null,newMessageList(error),newMessageList(fail),null); CompilationResult result = ajc(baseDir,args); // System.out.println(result); assertMessages(result,spec); } /** * Aim: Check that -outjar does not coincide with a member of -inpath. This * is because if a binary weave fails -outjar is deleted. * * Inputs to the compiler: * -injar * -aspectpath * -outjar * * Expected result = Compile aborts with error message. */ public void testOutjarInInpath () { String[] args = new String[] {"-aspectpath", aspectjarName, "-inpath", injarName, "-outjar", injarName}; Message error = new Message(WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH)); Message fail = new Message("Usage:"); MessageSpec spec = new MessageSpec(null,null,newMessageList(error),newMessageList(fail),null); CompilationResult result = ajc(baseDir,args); // System.out.println(result); assertMessages(result,spec); } /** * Aim: Check that -outjar does not coincide with a member of -aspectpath. This * is because if a binary weave fails -outjar is deleted. * * Inputs to the compiler: * -injar * -aspectpath * -outjar * * Expected result = Compile aborts with error message. */ public void testOutjarInAspectpath () { String[] args = new String[] {"-aspectpath", aspectjarName, "-inpath", injarName, "-outjar", aspectjarName}; Message error = new Message(WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH)); Message fail = new Message("Usage:"); MessageSpec spec = new MessageSpec(null,null,newMessageList(error),newMessageList(fail),null); CompilationResult result = ajc(baseDir,args); // System.out.println(result); assertMessages(result,spec); } /** * Aim: Check that -outjar is not present when compile fails. * * Inputs to the compiler: * -injar * -aspectpath * -outjar * * Expected result = Compile fails with error message. */ public void testOutjarDeletedOnError () { String[] args = new String[] {"-aspectpath", aspectjarName, "-injars", injarName, "-outjar", outjarName}; Message error = new Message(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,"jar1.Parent")); MessageSpec spec = new MessageSpec(null,newMessageList(error)); CompilationResult result = ajc(baseDir,args); // System.out.println(result); assertMessages(result,spec); File outjar = new File(ajc.getSandboxDirectory(),outjarName); assertFalse("-outjar " + outjar.getPath() + " should be deleted",outjar.exists()); } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/JoinPointSignature.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: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collection; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute.EffectiveSignatureAttribute; /** * @author colyer * Instances of this class are created by ResolvedMember.getSignatures() when collating * all of the signatures for a member. We need to create entries in the set for the "gaps" * in the hierarchy. For example: * * class A { * void foo(); * } * * class B extends A {} * * Join Point : call(* B.foo()) * * has signatures: * * B.foo() AND A.foo() * B.foo() will be created as a ResolvedMemberWithSubstituteDeclaringType * * Oh for a JDK 1.4 dynamic proxy.... we have to run on 1.3 :( */ public class JoinPointSignature implements ResolvedMember { private ResolvedMember realMember; private ResolvedType substituteDeclaringType; public JoinPointSignature(ResolvedMember backing, ResolvedType aType) { this.realMember = backing; this.substituteDeclaringType = aType; } public UnresolvedType getDeclaringType() { return substituteDeclaringType; } public int getModifiers(World world) { return realMember.getModifiers(world); } public int getModifiers() { return realMember.getModifiers(); } public UnresolvedType[] getExceptions(World world) { return realMember.getExceptions(world); } public UnresolvedType[] getExceptions() { return realMember.getExceptions(); } public ShadowMunger getAssociatedShadowMunger() { return realMember.getAssociatedShadowMunger(); } public boolean isAjSynthetic() { return realMember.isAjSynthetic(); } public boolean hasAnnotations() { return realMember.hasAnnotations(); } public boolean hasAnnotation(UnresolvedType ofType) { return realMember.hasAnnotation(ofType); } public ResolvedType[] getAnnotationTypes() { return realMember.getAnnotationTypes(); } public void setAnnotationTypes(UnresolvedType[] annotationtypes) { realMember.setAnnotationTypes(annotationtypes); } public void addAnnotation(AnnotationX annotation) { realMember.addAnnotation(annotation); } public boolean isBridgeMethod() { return realMember.isBridgeMethod(); } public boolean isVarargsMethod() { return realMember.isVarargsMethod(); } public boolean isSynthetic() { return realMember.isSynthetic(); } public void write(DataOutputStream s) throws IOException { realMember.write(s); } public ISourceContext getSourceContext(World world) { return realMember.getSourceContext(world); } public String[] getParameterNames() { return realMember.getParameterNames(); } public String[] getParameterNames(World world) { return realMember.getParameterNames(world); } public EffectiveSignatureAttribute getEffectiveSignature() { return realMember.getEffectiveSignature(); } public ISourceLocation getSourceLocation() { return realMember.getSourceLocation(); } public int getEnd() { return realMember.getEnd(); } public ISourceContext getSourceContext() { return realMember.getSourceContext(); } public int getStart() { return realMember.getStart(); } public void setPosition(int sourceStart, int sourceEnd) { realMember.setPosition(sourceStart,sourceEnd); } public void setSourceContext(ISourceContext sourceContext) { realMember.setSourceContext(sourceContext); } public boolean isAbstract() { return realMember.isAbstract(); } public boolean isPublic() { return realMember.isPublic(); } public boolean isProtected() { return realMember.isProtected(); } public boolean isNative() { return realMember.isNative(); } public boolean isDefault() { return realMember.isDefault(); } public boolean isVisible(ResolvedType fromType) { return realMember.isVisible(fromType); } public void setCheckedExceptions(UnresolvedType[] checkedExceptions) { realMember.setCheckedExceptions(checkedExceptions); } public void setAnnotatedElsewhere(boolean b) { realMember.setAnnotatedElsewhere(b); } public boolean isAnnotatedElsewhere() { return realMember.isAnnotatedElsewhere(); } public UnresolvedType getGenericReturnType() { return realMember.getGenericReturnType(); } public UnresolvedType[] getGenericParameterTypes() { return realMember.getGenericParameterTypes(); } public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters, ResolvedType newDeclaringType, boolean isParameterized) { return realMember.parameterizedWith(typeParameters, newDeclaringType, isParameterized); } public void setTypeVariables(UnresolvedType[] types) { realMember.setTypeVariables(types); } public UnresolvedType[] getTypeVariables() { return realMember.getTypeVariables(); } public ResolvedMember getErasure() { throw new UnsupportedOperationException("Adrian doesn't think you should be asking for the erasure of one of these..."); } public boolean matches(ResolvedMember aCandidateMatch) { return realMember.matches(aCandidateMatch); } public ResolvedMember resolve(World world) { return realMember.resolve(world); } public int compareTo(Object other) { return realMember.compareTo(other); } public String toLongString() { return realMember.toLongString(); } public Kind getKind() { return realMember.getKind(); } public UnresolvedType getReturnType() { return realMember.getReturnType(); } public UnresolvedType getType() { return realMember.getType(); } public String getName() { return realMember.getName(); } public UnresolvedType[] getParameterTypes() { return realMember.getParameterTypes(); } public String getSignature() { return realMember.getSignature(); } public String getDeclaredSignature() { return realMember.getDeclaredSignature(); } public int getArity() { return realMember.getArity(); } public String getParameterSignature() { return realMember.getParameterSignature(); } public boolean isCompatibleWith(Member am) { return realMember.isCompatibleWith(am); } public boolean isProtected(World world) { return realMember.isProtected(world); } public boolean isStatic(World world) { return realMember.isStatic(world); } public boolean isStrict(World world) { return realMember.isStrict(world); } public boolean isStatic() { return realMember.isStatic(); } public boolean isInterface() { return realMember.isInterface(); } public boolean isPrivate() { return realMember.isPrivate(); } public boolean canBeParameterized() { return realMember.canBeParameterized(); } public int getCallsiteModifiers() { return realMember.getCallsiteModifiers(); } public String getExtractableName() { return realMember.getExtractableName(); } public AnnotationX[] getAnnotations() { return realMember.getAnnotations(); } public Collection getDeclaringTypes(World world) { throw new UnsupportedOperationException("Adrian doesn't think you should be calling this..."); } public String getSignatureMakerName() { return realMember.getSignatureMakerName(); } public String getSignatureType() { return realMember.getSignatureType(); } public String getSignatureString(World world) { return realMember.getSignatureString(world); } public JoinPointSignature[] getJoinPointSignatures(World world) { return realMember.getJoinPointSignatures(world); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(getReturnType().getName()); buf.append(' '); buf.append(getDeclaringType().getName()); buf.append('.'); buf.append(getName()); if (getKind() != FIELD) { buf.append("("); UnresolvedType[] parameterTypes = getParameterTypes(); 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(); } public String toGenericString() { return realMember.toGenericString(); } public void resetName(String newName) { realMember.resetName(newName); } public void resetKind(Kind newKind) { realMember.resetKind(newKind); } public void resetModifiers(int newModifiers) { realMember.resetModifiers(newModifiers); } public void resetReturnTypeToObjectArray() { realMember.resetReturnTypeToObjectArray(); } public boolean equals(Object obj) { if (! (obj instanceof JoinPointSignature)) return false; JoinPointSignature other = (JoinPointSignature) obj; if (!realMember.equals(other.realMember)) return false; if (!substituteDeclaringType.equals(other.substituteDeclaringType)) return false; return true; } public int hashCode() { return 17 + (37 * realMember.hashCode()) + (37 * substituteDeclaringType.hashCode()); } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/JoinPointSignatureIterator.java
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04: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 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 JoinPointSignature[] 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); }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04: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 JoinPointSignature[] 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 buf.append(paramTypes[i].getSignature()); } buf.append(")"); if (returnType.isParameterizedType() && 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 JoinPointSignature[] getJoinPointSignatures(World inAWorld) { if (joinPointSignatures == null) { joinPointSignatures = ResolvedMemberImpl.getJoinPointSignatures(this, inAWorld); } return joinPointSignatures; } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/MissingResolvedTypeWithKnownSignature.java
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/ReferenceType.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 - June 2005 - separated out from ResolvedType * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; /** * A reference type represents some 'real' type, not a primitive, not an array - but * a real type, for example java.util.List. Each ReferenceType has a delegate * that is the underlying artifact - either an eclipse artifact or a * bcel artifact. If the type represents a raw type (i.e. there is * a generic form) then the genericType field is set to point to the * generic type. If it is for a parameterized type then the generic type * is also set to point to the generic form. */ public class ReferenceType extends ResolvedType { /** * For parameterized types (or the raw type) - this field points to the actual * reference type from which they are derived. */ ReferenceType genericType = null; ReferenceTypeDelegate delegate = null; ISourceContext sourceContext = null; int startPos = 0; int endPos = 0; public static ReferenceType fromTypeX(UnresolvedType tx, World world) { ReferenceType rt = new ReferenceType(tx.getErasureSignature(),world); rt.typeKind = tx.typeKind; return rt; } // cached values for members ResolvedMember[] parameterizedMethods = null; ResolvedMember[] parameterizedFields = null; ResolvedMember[] parameterizedPointcuts = null; ResolvedType[] parameterizedInterfaces = null; Collection parameterizedDeclares = null; //??? should set delegate before any use public ReferenceType(String signature, World world) { super(signature, world); } /** * Constructor used when creating a parameterized type. */ public ReferenceType( ResolvedType theGenericType, ResolvedType[] theParameters, World aWorld) { super(makeParameterizedSignature(theGenericType,theParameters), theGenericType.signatureErasure, aWorld); ReferenceType genericReferenceType = (ReferenceType) theGenericType; this.typeParameters = theParameters; this.genericType = genericReferenceType; this.typeKind = TypeKind.PARAMETERIZED; this.delegate = genericReferenceType.getDelegate(); } /** * Constructor used when creating a raw type. */ public ReferenceType( ResolvedType theGenericType, World aWorld) { super(theGenericType.getErasureSignature(), theGenericType.getErasureSignature(), aWorld); ReferenceType genericReferenceType = (ReferenceType) theGenericType; this.typeParameters = null; this.genericType = genericReferenceType; this.typeKind = TypeKind.RAW; this.delegate = genericReferenceType.getDelegate(); } public String getSignatureForAttribute() { return makeDeclaredSignature(genericType,typeParameters); } /** * Create a reference type for a generic type */ public ReferenceType(UnresolvedType genericType, World world) { super(genericType.getSignature(),world); typeKind=TypeKind.GENERIC; } public final boolean isClass() { return delegate.isClass(); } public final boolean isGenericType() { return !isParameterizedType() && !isRawType() && delegate.isGeneric(); } public AnnotationX[] getAnnotations() { return delegate.getAnnotations(); } public void addAnnotation(AnnotationX annotationX) { delegate.addAnnotation(annotationX); } public boolean hasAnnotation(UnresolvedType ofType) { return delegate.hasAnnotation(ofType); } public ResolvedType[] getAnnotationTypes() { return delegate.getAnnotationTypes(); } public boolean isAspect() { return delegate.isAspect(); } public boolean isAnnotationStyleAspect() { return delegate.isAnnotationStyleAspect(); } public boolean isEnum() { return delegate.isEnum(); } public boolean isAnnotation() { return delegate.isAnnotation(); } public boolean isAnnotationWithRuntimeRetention() { return delegate.isAnnotationWithRuntimeRetention(); } // true iff the statement "this = (ThisType) other" would compile public final boolean isCoerceableFrom(ResolvedType o) { ResolvedType other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } if (this.isParameterizedType() && other.isParameterizedType()) { return isCoerceableFromParameterizedType(other); } if (!this.isInterface() && !other.isInterface()) { return false; } if (this.isFinal() || other.isFinal()) { return false; } // ??? needs to be Methods, not just declared methods? JLS 5.5 unclear ResolvedMember[] a = getDeclaredMethods(); ResolvedMember[] b = other.getDeclaredMethods(); //??? is this cast always safe for (int ai = 0, alen = a.length; ai < alen; ai++) { for (int bi = 0, blen = b.length; bi < blen; bi++) { if (! b[bi].isCompatibleWith(a[ai])) return false; } } return true; } private final boolean isCoerceableFromParameterizedType(ResolvedType other) { if (!other.isParameterizedType()) return false; ResolvedType myRawType = (ResolvedType) getRawType(); ResolvedType theirRawType = (ResolvedType) other.getRawType(); if (myRawType == theirRawType) { if (getTypeParameters().length == other.getTypeParameters().length) { // there's a chance it can be done ResolvedType[] myTypeParameters = getResolvedTypeParameters(); ResolvedType[] theirTypeParameters = other.getResolvedTypeParameters(); for (int i = 0; i < myTypeParameters.length; i++) { if (myTypeParameters[i] != theirTypeParameters[i]) { // thin ice now... but List<String> may still be coerceable from e.g. List<T> if (myTypeParameters[i].isGenericWildcard()) { BoundedReferenceType wildcard = (BoundedReferenceType) myTypeParameters[i]; if (!wildcard.canBeCoercedTo(theirTypeParameters[i])) return false; } else if (myTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) myTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(theirTypeParameters[i])) return false; } else if (theirTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) theirTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(myTypeParameters[i])) return false; } else { return false; } } } return true; } } else { // we do this walk for situations like the following: // Base<T>, Sub<S,T> extends Base<S> // is Sub<Y,Z> coerceable from Base<X> ??? for(Iterator i = getDirectSupertypes(); i.hasNext(); ) { ReferenceType parent = (ReferenceType) i.next(); if (parent.isCoerceableFromParameterizedType(other)) return true; } } return false; } // true iff the statement "this = other" would compile. public final boolean isAssignableFrom(ResolvedType other) { if (other.isPrimitiveType()) { if (!world.isInJava5Mode()) return false; if (ResolvedType.validBoxing.contains(this.getSignature()+other.getSignature())) return true; } if (this == other) return true; if ((this.isRawType() || this.isGenericType()) && other.isParameterizedType()) { if (isAssignableFrom((ResolvedType)other.getRawType())) return true; } if (this.isRawType() && other.isGenericType()) { if (isAssignableFrom((ResolvedType)other.getRawType())) return true; } if (this.isGenericType() && other.isRawType()) { if (isAssignableFrom((ResolvedType)other.getGenericType())) return true; } if (this.isParameterizedType()) { // look at wildcards... if (((ReferenceType)this.getRawType()).isAssignableFrom(other)) { boolean wildcardsAllTheWay = true; ResolvedType[] myParameters = this.getResolvedTypeParameters(); for (int i = 0; i < myParameters.length; i++) { if (!myParameters[i].isGenericWildcard()) { wildcardsAllTheWay = false; } else if (myParameters[i].isExtends() || myParameters[i].isSuper()) { wildcardsAllTheWay = false; } } if (wildcardsAllTheWay && !other.isParameterizedType()) return true; // we have to match by parameters one at a time ResolvedType[] theirParameters = other.getResolvedTypeParameters(); boolean parametersAssignable = true; if (myParameters.length == theirParameters.length) { for (int i = 0; i < myParameters.length; i++) { if (myParameters[i] == theirParameters[i]) continue; if (!myParameters[i].isGenericWildcard()) { parametersAssignable = false; break; } else { BoundedReferenceType wildcardType = (BoundedReferenceType) myParameters[i]; if (!wildcardType.alwaysMatches(theirParameters[i])) { parametersAssignable = false; break; } } } } else { parametersAssignable = false; } if (parametersAssignable) return true; } } if (other.isTypeVariableReference()) { TypeVariableReferenceType otherType = (TypeVariableReferenceType) other; return this.isAssignableFrom(otherType.getUpperBound().resolve(world)); } for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { if (this.isAssignableFrom((ResolvedType) i.next())) return true; } return false; } public ISourceContext getSourceContext() { return sourceContext; } public ISourceLocation getSourceLocation() { if (sourceContext == null) return null; return sourceContext.makeSourceLocation(new Position(startPos, endPos)); } public boolean isExposedToWeaver() { return (delegate == null) || delegate.isExposedToWeaver(); //??? where does this belong } public WeaverStateInfo getWeaverState() { return delegate.getWeaverState(); } public ResolvedMember[] getDeclaredFields() { if (parameterizedFields != null) return parameterizedFields; if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateFields = delegate.getDeclaredFields(); parameterizedFields = new ResolvedMember[delegateFields.length]; for (int i = 0; i < delegateFields.length; i++) { parameterizedFields[i] = delegateFields[i].parameterizedWith(getTypesForMemberParameterization(),this, isParameterizedType()); } return parameterizedFields; } else { return delegate.getDeclaredFields(); } } /** * Find out from the generic signature the true signature of any interfaces * I implement. If I am parameterized, these may then need to be parameterized * before returning. */ public ResolvedType[] getDeclaredInterfaces() { if (parameterizedInterfaces != null) return parameterizedInterfaces; if (isParameterizedType()) { ResolvedType[] delegateInterfaces = delegate.getDeclaredInterfaces(); UnresolvedType[] paramTypes = getTypesForMemberParameterization(); parameterizedInterfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0; i < delegateInterfaces.length; i++) { parameterizedInterfaces[i] = delegateInterfaces[i].parameterizedWith(paramTypes); } return parameterizedInterfaces; } else if (isRawType()){ ResolvedType[] delegateInterfaces = delegate.getDeclaredInterfaces(); UnresolvedType[] paramTypes = getTypesForMemberParameterization(); parameterizedInterfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0; i < parameterizedInterfaces.length; i++) { parameterizedInterfaces[i] = delegateInterfaces[i]; if (parameterizedInterfaces[i].isGenericType()) { // a generic supertype of a raw type is replaced by its raw equivalent parameterizedInterfaces[i] = parameterizedInterfaces[i].getRawType().resolve(getWorld()); } else if (parameterizedInterfaces[i].isParameterizedType()) { // a parameterized supertype collapses any type vars to their upper // bounds parameterizedInterfaces[i] = parameterizedInterfaces[i].parameterizedWith(paramTypes); } } return parameterizedInterfaces; } return delegate.getDeclaredInterfaces(); } public ResolvedMember[] getDeclaredMethods() { if (parameterizedMethods != null) return parameterizedMethods; if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateMethods = delegate.getDeclaredMethods(); UnresolvedType[] parameters = getTypesForMemberParameterization(); parameterizedMethods = new ResolvedMember[delegateMethods.length]; for (int i = 0; i < delegateMethods.length; i++) { parameterizedMethods[i] = delegateMethods[i].parameterizedWith(parameters,this,isParameterizedType()); } return parameterizedMethods; } else { return delegate.getDeclaredMethods(); } } public ResolvedMember[] getDeclaredPointcuts() { if (parameterizedPointcuts != null) return parameterizedPointcuts; if (isParameterizedType()) { ResolvedMember[] delegatePointcuts = delegate.getDeclaredPointcuts(); parameterizedPointcuts = new ResolvedMember[delegatePointcuts.length]; for (int i = 0; i < delegatePointcuts.length; i++) { parameterizedPointcuts[i] = delegatePointcuts[i].parameterizedWith(getTypesForMemberParameterization(),this,isParameterizedType()); } return parameterizedPointcuts; } else { return delegate.getDeclaredPointcuts(); } } private UnresolvedType[] getTypesForMemberParameterization() { UnresolvedType[] parameters = null; if (isParameterizedType()) { parameters = getTypeParameters(); } else if (isRawType()){ // raw type, use upper bounds of type variables on generic type TypeVariable[] tvs = getGenericType().getTypeVariables(); parameters = new UnresolvedType[tvs.length]; for (int i = 0; i < tvs.length; i++) { parameters[i] = tvs[i].getUpperBound(); } } return parameters; } public UnresolvedType getRawType() { return super.getRawType().resolve(getWorld()); } public TypeVariable[] getTypeVariables() { if (this.typeVariables == null) { this.typeVariables = delegate.getTypeVariables(); for (int i = 0; i < this.typeVariables.length; i++) { this.typeVariables[i].resolve(world); } } return this.typeVariables; } public PerClause getPerClause() { return delegate.getPerClause(); } protected Collection getDeclares() { if (parameterizedDeclares != null) return parameterizedDeclares; Collection declares = null; if (isParameterizedType()) { Collection genericDeclares = delegate.getDeclares(); parameterizedDeclares = new ArrayList(); Map parameterizationMap = getMemberParameterizationMap(); for (Iterator iter = genericDeclares.iterator(); iter.hasNext();) { Declare declareStatement = (Declare) iter.next(); parameterizedDeclares.add(declareStatement.parameterizeWith(parameterizationMap)); } declares = parameterizedDeclares; } else { declares = delegate.getDeclares(); } for (Iterator iter = declares.iterator(); iter.hasNext();) { Declare d = (Declare) iter.next(); d.setDeclaringType(this); } return declares; } protected Collection getTypeMungers() { return delegate.getTypeMungers(); } protected Collection getPrivilegedAccesses() { return delegate.getPrivilegedAccesses(); } public int getModifiers() { return delegate.getModifiers(); } public ResolvedType getSuperclass() { return delegate.getSuperclass(); } public ReferenceTypeDelegate getDelegate() { return delegate; } public void setDelegate(ReferenceTypeDelegate delegate) { this.delegate = delegate; // If we are raw, we have a generic type - we should ensure it uses the // same delegate if (isRawType() && getGenericType()!=null) { ((ReferenceType)getGenericType()).setDelegate(delegate); } clearParameterizationCaches(); } private void clearParameterizationCaches() { parameterizedFields = null; parameterizedInterfaces = null; parameterizedMethods = null; parameterizedPointcuts = null; } public int getEndPos() { return endPos; } public int getStartPos() { return startPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public void setSourceContext(ISourceContext sourceContext) { this.sourceContext = sourceContext; } public void setStartPos(int startPos) { this.startPos = startPos; } public boolean doesNotExposeShadowMungers() { return delegate.doesNotExposeShadowMungers(); } public String getDeclaredGenericSignature() { return delegate.getDeclaredGenericSignature(); } public void setGenericType(ReferenceType rt) { genericType = rt; // Should we 'promote' this reference type from simple to raw? // makes sense if someone is specifying that it has a generic form if ( typeKind == TypeKind.SIMPLE ) { typeKind = TypeKind.RAW; signatureErasure = signature; } } public ResolvedType getGenericType() { if (isGenericType()) return this; return genericType; } /** * a parameterized signature starts with a "P" in place of the "L", * see the comment on signatures in UnresolvedType. * @param aGenericType * @param someParameters * @return */ private static String makeParameterizedSignature(ResolvedType aGenericType, ResolvedType[] someParameters) { String rawSignature = aGenericType.getErasureSignature(); String prefix = PARAMETERIZED_TYPE_IDENTIFIER + rawSignature.substring(1,rawSignature.length()-1); StringBuffer ret = new StringBuffer(); ret.append(prefix); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { ret.append(someParameters[i].getSignature()); } ret.append(">;"); return ret.toString(); } private static String makeDeclaredSignature(ResolvedType aGenericType, UnresolvedType[] someParameters) { StringBuffer ret = new StringBuffer(); String rawSig = aGenericType.getErasureSignature(); ret.append(rawSig.substring(0,rawSig.length()-1)); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { ret.append(someParameters[i].getSignature()); } ret.append(">;"); return ret.toString(); } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/ResolvedMemberImpl.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.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; 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.bridge.ISourceLocation; /** * This is the declared member, i.e. it will always correspond to an * actual method/... declaration */ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, AnnotatedElement, TypeVariableDeclaringElement, ResolvedMember { public String[] parameterNames = null; protected UnresolvedType[] checkedExceptions = UnresolvedType.NONE; /** * if this member is a parameterized version of a member in a generic type, * then this field holds a reference to the member we parameterize. */ protected ResolvedMember backingGenericMember = null; protected Set annotationTypes = null; // Some members are 'created' to represent other things (for example ITDs). These // members have their annotations stored elsewhere, and this flag indicates that is // the case. It is up to the caller to work out where that is! // Once determined the caller may choose to stash the annotations in this member... private boolean isAnnotatedElsewhere = false; // this field is not serialized. private boolean isAjSynthetic = true; // generic methods have type variables private UnresolvedType[] typeVariables; // these three fields hold the source location of this member protected int start, end; protected ISourceContext sourceContext = null; //XXX deprecate this in favor of the constructor below public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes) { super(kind, declaringType, modifiers, returnType, name, parameterTypes); } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes, UnresolvedType[] checkedExceptions) { super(kind, declaringType, modifiers, returnType, name, parameterTypes); this.checkedExceptions = checkedExceptions; } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes, UnresolvedType[] checkedExceptions, ResolvedMember backingGenericMember) { this(kind, declaringType, modifiers, returnType, name, parameterTypes,checkedExceptions); this.backingGenericMember = backingGenericMember; this.isAjSynthetic = backingGenericMember.isAjSynthetic(); } public ResolvedMemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, String name, String signature) { super(kind, declaringType, modifiers, name, signature); } /** * Compute the full set of signatures for a member. This walks up the hierarchy * giving the ResolvedMember in each defining type in the hierarchy. A shadowMember * can be created with a target type (declaring type) that does not actually define * the member. This is ok as long as the member is inherited in the declaring type. * Each declaring type in the line to the actual declaring type is added as an additional * signature. For example: * * class A { void foo(); } * class B extends A {} * * shadowMember : void B.foo() * * gives { void B.foo(), void A.foo() } * @param joinPointSignature * @param inAWorld */ public static JoinPointSignature[] getJoinPointSignatures(Member joinPointSignature, World inAWorld) { // Walk up hierarchy creating one member for each type up to and including the // first defining type ResolvedType originalDeclaringType = joinPointSignature.getDeclaringType().resolve(inAWorld); ResolvedMemberImpl firstDefiningMember = (ResolvedMemberImpl) joinPointSignature.resolve(inAWorld); if (firstDefiningMember == null) { return new JoinPointSignature[0]; } // declaringType can be unresolved if we matched a synthetic member generated by Aj... // should be fixed elsewhere but add this resolve call on the end for now so that we can // focus on one problem at a time... ResolvedType firstDefiningType = firstDefiningMember.getDeclaringType().resolve(inAWorld); if (firstDefiningType != originalDeclaringType) { if (joinPointSignature.getKind() == Member.CONSTRUCTOR) { return new JoinPointSignature[0]; } // else if (shadowMember.isStatic()) { // return new ResolvedMember[] {firstDefiningMember}; // } } List declaringTypes = new ArrayList(); accumulateTypesInBetween(originalDeclaringType, firstDefiningType, declaringTypes); Set memberSignatures = new HashSet(); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType declaringType = (ResolvedType) iter.next(); ResolvedMember member = firstDefiningMember.withSubstituteDeclaringType(declaringType); memberSignatures.add(member); } if (shouldWalkUpHierarchyFor(firstDefiningMember)) { // now walk up the hierarchy from the firstDefiningMember and include the signature for // every type between the firstDefiningMember and the root defining member. Iterator superTypeIterator = firstDefiningType.getDirectSupertypes(); List typesAlreadyVisited = new ArrayList(); accumulateMembersMatching(firstDefiningMember,superTypeIterator,typesAlreadyVisited,memberSignatures); } JoinPointSignature[] ret = new JoinPointSignature[memberSignatures.size()]; memberSignatures.toArray(ret); return ret; } private static boolean shouldWalkUpHierarchyFor(Member aMember) { if (aMember.getKind() == Member.CONSTRUCTOR) return false; if (aMember.getKind() == Member.FIELD) return false; if (aMember.isStatic()) return false; return true; } /** * Build a list containing every type between subtype and supertype, inclusively. */ private static void accumulateTypesInBetween(ResolvedType subType, ResolvedType superType, List types) { types.add(subType); if (subType == superType) { return; } else { for (Iterator iter = subType.getDirectSupertypes(); iter.hasNext();) { ResolvedType parent = (ResolvedType) iter.next(); if (superType.isAssignableFrom(parent)) { accumulateTypesInBetween(parent, superType,types); } } } } /** * We have a resolved member, possibly with type parameter references as parameters or return * type. We need to find all its ancestor members. When doing this, a type parameter matches * regardless of bounds (bounds can be narrowed down the hierarchy). */ private static void accumulateMembersMatching( ResolvedMemberImpl memberToMatch, Iterator typesToLookIn, List typesAlreadyVisited, Set foundMembers) { while(typesToLookIn.hasNext()) { ResolvedType toLookIn = (ResolvedType) typesToLookIn.next(); if (!typesAlreadyVisited.contains(toLookIn)) { typesAlreadyVisited.add(toLookIn); ResolvedMemberImpl foundMember = (ResolvedMemberImpl) toLookIn.lookupResolvedMember(memberToMatch); if (foundMember != null && isVisibleTo(memberToMatch,foundMember)) { List declaringTypes = new ArrayList(); // declaring type can be unresolved if the member can from an ITD... ResolvedType resolvedDeclaringType = foundMember.getDeclaringType().resolve(toLookIn.getWorld()); accumulateTypesInBetween(toLookIn, resolvedDeclaringType, declaringTypes); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType declaringType = (ResolvedType) iter.next(); // typesAlreadyVisited.add(declaringType); ResolvedMember member = foundMember.withSubstituteDeclaringType(declaringType); foundMembers.add(member); } if (toLookIn.isParameterizedType() && (foundMember.backingGenericMember != null)) { foundMembers.add(new JoinPointSignature(foundMember.backingGenericMember,foundMember.declaringType.resolve(toLookIn.getWorld()))); } accumulateMembersMatching(foundMember,toLookIn.getDirectSupertypes(),typesAlreadyVisited,foundMembers); // if this was a parameterized type, look in the generic type that backs it too } } } } /** * Returns true if the parent member is visible to the child member * In the same declaring type this is always true, otherwise if parent is private * it is false. * @param childMember * @param parentMember * @return */ private static boolean isVisibleTo(ResolvedMember childMember, ResolvedMember parentMember) { if (childMember.getDeclaringType().equals(parentMember.getDeclaringType())) return true; if (Modifier.isPrivate(parentMember.getModifiers())) { return false; } else { return true; } } // ---- public final int getModifiers(World world) { return modifiers; } public final int getModifiers() { return modifiers; } // ---- public final UnresolvedType[] getExceptions(World world) { return getExceptions(); } public UnresolvedType[] getExceptions() { return checkedExceptions; } public ShadowMunger getAssociatedShadowMunger() { return null; } // ??? true or false? public boolean isAjSynthetic() { return isAjSynthetic; } public boolean hasAnnotations() { return (annotationTypes!=null); } public boolean hasAnnotation(UnresolvedType ofType) { // The ctors don't allow annotations to be specified ... yet - but // that doesn't mean it is an error to call this method. // Normally the weaver will be working with subtypes of // this type - BcelField/BcelMethod if (annotationTypes==null) return false; return annotationTypes.contains(ofType); } public ResolvedType[] getAnnotationTypes() { // The ctors don't allow annotations to be specified ... yet - but // that doesn't mean it is an error to call this method. // Normally the weaver will be working with subtypes of // this type - BcelField/BcelMethod if (annotationTypes == null) return null; return (ResolvedType[])annotationTypes.toArray(new ResolvedType[]{}); } public void setAnnotationTypes(UnresolvedType[] annotationtypes) { if (annotationTypes == null) annotationTypes = new HashSet(); for (int i = 0; i < annotationtypes.length; i++) { UnresolvedType typeX = annotationtypes[i]; annotationTypes.add(typeX); } } public void addAnnotation(AnnotationX annotation) { // FIXME asc only allows for annotation types, not instances - should it? if (annotationTypes == null) annotationTypes = new HashSet(); annotationTypes.add(annotation.getSignature()); } public boolean isBridgeMethod() { return (modifiers & Constants.ACC_BRIDGE)!=0; } public boolean isVarargsMethod() { return (modifiers & Constants.ACC_VARARGS)!=0; } public boolean isSynthetic() { return false; } public void write(DataOutputStream s) throws IOException { getKind().write(s); getDeclaringType().write(s); s.writeInt(modifiers); s.writeUTF(getName()); s.writeUTF(getSignature()); UnresolvedType.writeArray(getExceptions(), s); s.writeInt(getStart()); s.writeInt(getEnd()); // Write out any type variables... if (typeVariables==null) { s.writeInt(0); } else { s.writeInt(typeVariables.length); for (int i = 0; i < typeVariables.length; i++) { typeVariables[i].write(s); } } } public static void writeArray(ResolvedMember[] members, DataOutputStream s) throws IOException { s.writeInt(members.length); for (int i = 0, len = members.length; i < len; i++) { members[i].write(s); } } public static ResolvedMemberImpl readResolvedMember(VersionedDataInputStream s, ISourceContext sourceContext) throws IOException { ResolvedMemberImpl m = new ResolvedMemberImpl(Kind.read(s), UnresolvedType.read(s), s.readInt(), s.readUTF(), s.readUTF()); m.checkedExceptions = UnresolvedType.readArray(s); m.start = s.readInt(); m.end = s.readInt(); m.sourceContext = sourceContext; // Read in the type variables... if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { int tvcount = s.readInt(); if (tvcount!=0) { m.typeVariables = new UnresolvedType[tvcount]; for (int i=0;i<tvcount;i++) { m.typeVariables[i]=UnresolvedType.read(s); } } } return m; } public static ResolvedMember[] readResolvedMemberArray(VersionedDataInputStream s, ISourceContext context) throws IOException { int len = s.readInt(); ResolvedMember[] members = new ResolvedMember[len]; for (int i=0; i < len; i++) { members[i] = ResolvedMemberImpl.readResolvedMember(s, context); } return members; } public ResolvedMember resolve(World world) { // make sure all the pieces of a resolvedmember really are resolved if (annotationTypes!=null) { Set r = new HashSet(); for (Iterator iter = annotationTypes.iterator(); iter.hasNext();) { UnresolvedType element = (UnresolvedType) iter.next(); r.add(world.resolve(element)); } annotationTypes = r; } declaringType = declaringType.resolve(world); if (declaringType.isRawType()) declaringType = ((ReferenceType)declaringType).getGenericType(); if (typeVariables!=null && typeVariables.length>0) { for (int i = 0; i < typeVariables.length; i++) { UnresolvedType array_element = typeVariables[i]; typeVariables[i] = typeVariables[i].resolve(world); } } if (parameterTypes!=null && parameterTypes.length>0) { for (int i = 0; i < parameterTypes.length; i++) { UnresolvedType array_element = parameterTypes[i]; parameterTypes[i] = parameterTypes[i].resolve(world); } } returnType = returnType.resolve(world);return this; } public ISourceContext getSourceContext(World world) { return getDeclaringType().resolve(world).getSourceContext(); } public final String[] getParameterNames() { return parameterNames; } public final String[] getParameterNames(World world) { return getParameterNames(); } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { return null; } public ISourceLocation getSourceLocation() { //System.out.println("get context: " + this + " is " + sourceContext); if (sourceContext == null) { //System.err.println("no context: " + this); return null; } return sourceContext.makeSourceLocation(this); } public int getEnd() { return end; } public ISourceContext getSourceContext() { return sourceContext; } public int getStart() { return start; } public void setPosition(int sourceStart, int sourceEnd) { this.start = sourceStart; this.end = sourceEnd; } public void setSourceContext(ISourceContext sourceContext) { this.sourceContext = sourceContext; } public boolean isAbstract() { return Modifier.isAbstract(modifiers); } public boolean isPublic() { return Modifier.isPublic(modifiers); } public boolean isProtected() { return Modifier.isProtected(modifiers); } public boolean isNative() { return Modifier.isNative(modifiers); } public boolean isDefault() { return !(isPublic() || isProtected() || isPrivate()); } public boolean isVisible(ResolvedType fromType) { World world = fromType.getWorld(); return ResolvedType.isVisible(getModifiers(), getDeclaringType().resolve(world), fromType); } public void setCheckedExceptions(UnresolvedType[] checkedExceptions) { this.checkedExceptions = checkedExceptions; } public void setAnnotatedElsewhere(boolean b) { isAnnotatedElsewhere = b; } public boolean isAnnotatedElsewhere() { return isAnnotatedElsewhere; } /** * Get the UnresolvedType for the return type, taking generic signature into account */ public UnresolvedType getGenericReturnType() { return getReturnType(); } /** * Get the TypeXs of the parameter types, taking generic signature into account */ public UnresolvedType[] getGenericParameterTypes() { return getParameterTypes(); } // return a resolved member in which all type variables in the signature of this // member have been replaced with the given bindings. // the isParameterized flag tells us whether we are creating a raw type version or not // if isParameterized List<T> will turn into List<String> (for example), // but if !isParameterized List<T> will turn into List. public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters,ResolvedType newDeclaringType, boolean isParameterized) { if (!this.getDeclaringType().isGenericType()) { throw new IllegalStateException("Can't ask to parameterize a member of a non-generic type"); } TypeVariable[] typeVariables = getDeclaringType().getTypeVariables(); if (typeVariables.length != typeParameters.length) { throw new IllegalStateException("Wrong number of type parameters supplied"); } Map typeMap = new HashMap(); for (int i = 0; i < typeVariables.length; i++) { typeMap.put(typeVariables[i].getName(), typeParameters[i]); } UnresolvedType parameterizedReturnType = parameterize(getGenericReturnType(),typeMap,isParameterized); UnresolvedType[] parameterizedParameterTypes = new UnresolvedType[getGenericParameterTypes().length]; for (int i = 0; i < parameterizedParameterTypes.length; i++) { parameterizedParameterTypes[i] = parameterize(getGenericParameterTypes()[i], typeMap,isParameterized); } ResolvedMemberImpl ret = new ResolvedMemberImpl( getKind(), newDeclaringType, getModifiers(), parameterizedReturnType, getName(), parameterizedParameterTypes, getExceptions(), this ); ret.setSourceContext(getSourceContext()); return ret; } public void setTypeVariables(UnresolvedType[] types) { typeVariables = types; } public UnresolvedType[] getTypeVariables() { return typeVariables; } private UnresolvedType parameterize(UnresolvedType aType, Map typeVariableMap, boolean inParameterizedType) { if (aType instanceof TypeVariableReferenceType) { String variableName = ((TypeVariableReferenceType)aType).getTypeVariable().getName(); if (!typeVariableMap.containsKey(variableName)) { return aType; // if the type variable comes from the method (and not the type) thats OK } return (UnresolvedType) typeVariableMap.get(variableName); } else if (aType.isParameterizedType()) { if (inParameterizedType) { return aType.parameterize(typeVariableMap); } else { return aType.getRawType(); } } return aType; } /** * If this member is defined by a parameterized super-type, return the erasure * of that member. * For example: * interface I<T> { T foo(T aTea); } * class C implements I<String> { * String foo(String aString) { return "something"; } * } * The resolved member for C.foo has signature String foo(String). The * erasure of that member is Object foo(Object) -- use upper bound of type * variable. * A type is a supertype of itself. */ public ResolvedMember getErasure() { if (calculatedMyErasure) return myErasure; calculatedMyErasure = true; ResolvedType resolvedDeclaringType = (ResolvedType) getDeclaringType(); // this next test is fast, and the result is cached. if (!resolvedDeclaringType.hasParameterizedSuperType()) { return null; } else { // we have one or more parameterized super types. // this member may be defined by one of them... we need to find out. Collection declaringTypes = this.getDeclaringTypes(resolvedDeclaringType.getWorld()); for (Iterator iter = declaringTypes.iterator(); iter.hasNext();) { ResolvedType aDeclaringType = (ResolvedType) iter.next(); if (aDeclaringType.isParameterizedType()) { // we've found the (a?) parameterized type that defines this member. // now get the erasure of it ResolvedMemberImpl matchingMember = (ResolvedMemberImpl) aDeclaringType.lookupMemberNoSupers(this); if (matchingMember != null && matchingMember.backingGenericMember != null) { myErasure = matchingMember.backingGenericMember; return myErasure; } } } } return null; } private ResolvedMember myErasure = null; private boolean calculatedMyErasure = false; /** * For ITDs, we use the default factory methods to build a resolved member, then alter a couple of characteristics * using this method - this is safe. */ public void resetName(String newName) {this.name = newName;} public void resetKind(Kind newKind) {this.kind=newKind; } public void resetModifiers(int newModifiers) {this.modifiers=newModifiers;} public void resetReturnTypeToObjectArray() { returnType = UnresolvedType.OBJECTARRAY; } /** * Returns a copy of this member but with the declaring type swapped. * Copy only needs to be shallow. * @param newDeclaringType */ private JoinPointSignature withSubstituteDeclaringType(ResolvedType newDeclaringType) { JoinPointSignature ret = new JoinPointSignature(this,newDeclaringType); return ret; } /** * Returns true if this member matches the other. The matching takes into account * name and parameter types only. When comparing parameter types, we allow any type * variable to match any other type variable regardless of bounds. */ public boolean matches(ResolvedMember aCandidateMatch) { ResolvedMemberImpl candidateMatchImpl = (ResolvedMemberImpl)aCandidateMatch; if (!getName().equals(aCandidateMatch.getName())) return false; UnresolvedType[] myParameterTypes = getGenericParameterTypes(); UnresolvedType[] candidateParameterTypes = aCandidateMatch.getGenericParameterTypes(); if (myParameterTypes.length != candidateParameterTypes.length) return false; String myParameterSignature = getParameterSigWithBoundsRemoved(); String candidateParameterSignature = candidateMatchImpl.getParameterSigWithBoundsRemoved(); if (myParameterSignature.equals(candidateParameterSignature)) { return true; } else { // try erasure myParameterSignature = getParameterSigErasure(); candidateParameterSignature = candidateMatchImpl.getParameterSigErasure(); return myParameterSignature.equals(candidateParameterSignature); } } /** converts e.g. <T extends Number>.... List<T> to just Ljava/util/List<T;>; * whereas the full signature would be Ljava/util/List<T:Ljava/lang/Number;>; */ private String myParameterSignatureWithBoundsRemoved = null; /** * converts e.g. <T extends Number>.... List<T> to just Ljava/util/List; */ private String myParameterSignatureErasure = null; // does NOT produce a meaningful java signature, but does give a unique string suitable for // comparison. private String getParameterSigWithBoundsRemoved() { if (myParameterSignatureWithBoundsRemoved != null) return myParameterSignatureWithBoundsRemoved; StringBuffer sig = new StringBuffer(); UnresolvedType[] myParameterTypes = getGenericParameterTypes(); for (int i = 0; i < myParameterTypes.length; i++) { appendSigWithTypeVarBoundsRemoved(myParameterTypes[i], sig); } myParameterSignatureWithBoundsRemoved = sig.toString(); return myParameterSignatureWithBoundsRemoved; } private String getParameterSigErasure() { if (myParameterSignatureErasure != null) return myParameterSignatureErasure; StringBuffer sig = new StringBuffer(); UnresolvedType[] myParameterTypes = getParameterTypes(); for (int i = 0; i < myParameterTypes.length; i++) { UnresolvedType thisParameter = myParameterTypes[i]; if (thisParameter.isTypeVariableReference()) { sig.append(thisParameter.getUpperBound().getSignature()); } else { sig.append(thisParameter.getSignature()); } } myParameterSignatureErasure = sig.toString(); return myParameterSignatureErasure; } // does NOT produce a meaningful java signature, but does give a unique string suitable for // comparison. private void appendSigWithTypeVarBoundsRemoved(UnresolvedType aType, StringBuffer toBuffer) { if (aType.isTypeVariableReference()) { toBuffer.append("T;"); } else if (aType.isParameterizedType()) { toBuffer.append(aType.getRawType().getSignature()); toBuffer.append("<"); for (int i = 0; i < aType.getTypeParameters().length; i++) { appendSigWithTypeVarBoundsRemoved(aType.getTypeParameters()[i], toBuffer); } toBuffer.append(">;"); } else { toBuffer.append(aType.getSignature()); } } public String toGenericString() { StringBuffer buf = new StringBuffer(); buf.append(getGenericReturnType().getSimpleName()); buf.append(' '); buf.append(declaringType.getName()); buf.append('.'); buf.append(name); if (kind != FIELD) { buf.append("("); UnresolvedType[] params = getGenericParameterTypes(); if (params.length != 0) { buf.append(params[0].getSimpleName()); for (int i=1, len = params.length; i < len; i++) { buf.append(", "); buf.append(params[i].getSimpleName()); } } buf.append(")"); } return buf.toString(); } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/ResolvedType.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.Arrays; import java.util.Collection; import java.util.Collections; 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.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.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement { private static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0]; public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P"; private ResolvedType[] resolvedTypeParams; protected World world; protected ResolvedType(String signature, World world) { super(signature); this.world = world; } protected ResolvedType(String signature, String signatureErasure, World world) { super(signature,signatureErasure); this.world = world; } // ---- things that don't require a world /** * Returns an iterator through ResolvedType objects representing all the direct * supertypes of this type. That is, through the superclass, if any, and * all declared interfaces. */ public final Iterator getDirectSupertypes() { Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedType superclass = getSuperclass(); if (superclass == null) { return ifacesIterator; } else { return Iterators.snoc(ifacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedType[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); /** * Returns a ResolvedType object representing the superclass of this type, or null. * If this represents a java.lang.Object, a primitive type, or void, this * method returns null. */ public abstract ResolvedType getSuperclass(); /** * Returns the modifiers for this type. * * See {@link java.lang.Class#getModifiers()} for a description * of the weirdness of this methods on primitives and arrays. * * @param world the {@link World} in which the lookup is made. * @return an int representing the modifiers for this type * @see java.lang.reflect.Modifier */ public abstract int getModifiers(); public ResolvedType[] getAnnotationTypes() { return EMPTY_RESOLVED_TYPE_ARRAY; } public final UnresolvedType getSuperclass(World world) { return getSuperclass(); } // This set contains pairs of types whose signatures are concatenated // together, this means with a fast lookup we can tell if two types // are equivalent. static Set validBoxing = new HashSet(); static { validBoxing.add("Ljava/lang/Byte;B"); validBoxing.add("Ljava/lang/Character;C"); validBoxing.add("Ljava/lang/Double;D"); validBoxing.add("Ljava/lang/Float;F"); validBoxing.add("Ljava/lang/Integer;I"); validBoxing.add("Ljava/lang/Long;J"); validBoxing.add("Ljava/lang/Short;S"); validBoxing.add("Ljava/lang/Boolean;Z"); validBoxing.add("BLjava/lang/Byte;"); validBoxing.add("CLjava/lang/Character;"); validBoxing.add("DLjava/lang/Double;"); validBoxing.add("FLjava/lang/Float;"); validBoxing.add("ILjava/lang/Integer;"); validBoxing.add("JLjava/lang/Long;"); validBoxing.add("SLjava/lang/Short;"); validBoxing.add("ZLjava/lang/Boolean;"); } // utilities public ResolvedType getResolvedComponentType() { return null; } public World getWorld() { return world; } // ---- things from object public final boolean equals(Object other) { if (other instanceof ResolvedType) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order * for checking from JVM spec 2ed 5.4.3.2. This means that the order is * * <ul><li> fields from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getFields() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterators.Getter fieldGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedType)o).getDeclaredFields()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), fieldGetter); } /** * returns an iterator through all of the methods of this type, in order * for checking from JVM spec 2ed 5.4.3.3. This means that the order is * * <ul><li> methods from current class </li> * <li> recur into superclass, all the way up, not touching interfaces </li> * <li> recur into all superinterfaces, in some unspecified order </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. * NOTE: Take a look at the javadoc on getMethodsWithoutIterator() to see if * you are sensitive to a quirk in getMethods() */ public Iterator getMethods() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter ifaceGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( Iterators.array(((ResolvedType)o).getDeclaredInterfaces()) ); } }; Iterators.Getter methodGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedType)o).getDeclaredMethods()); } }; return Iterators.mapOver( Iterators.append( new Iterator() { ResolvedType curr = ResolvedType.this; public boolean hasNext() { return curr != null; } public Object next() { ResolvedType ret = curr; curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }, Iterators.recur(this, ifaceGetter)), methodGetter); } /** * Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those declared * on the superinterfaces. The getMethods() call above doesn't quite work the same as it will (through the iterator) return methods * declared on *this* class twice, once at the start and once at the end - I couldn't debug that problem, so created this alternative. */ public List getMethodsWithoutIterator(boolean includeITDs) { List methods = new ArrayList(); Set knowninterfaces = new HashSet(); addAndRecurse(knowninterfaces,methods,this,includeITDs); return methods; } private void addAndRecurse(Set knowninterfaces,List collector, ResolvedType rtx, boolean includeITDs) { collector.addAll(Arrays.asList(rtx.getDeclaredMethods())); // Add the methods declared on this type // now add all the inter-typed members too if (includeITDs && rtx.interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); ResolvedMember rm = tm.getSignature(); if (rm != null) { // new parent type munger can have null signature... collector.add(tm.getSignature()); } } } if (!rtx.equals(ResolvedType.OBJECT)) { ResolvedType superType = rtx.getSuperclass(); if (rtx == null || rtx == ResolvedType.MISSING) { // can't find type message - with context! world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_FIND_PARENT_TYPE,rtx.getSignature()), null,null); } else { addAndRecurse(knowninterfaces,collector,superType,includeITDs); // Recurse if we aren't at the top } } ResolvedType[] interfaces = rtx.getDeclaredInterfaces(); // Go through the interfaces on the way back down for (int i = 0; i < interfaces.length; i++) { ResolvedType iface = interfaces[i]; if (!knowninterfaces.contains(iface)) { // Dont do interfaces more than once knowninterfaces.add(iface); addAndRecurse(knowninterfaces,collector,iface,includeITDs); } } } public ResolvedType[] getResolvedTypeParameters() { if (resolvedTypeParams == null) { resolvedTypeParams = world.resolve(typeParameters); } return resolvedTypeParams; } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member m) { return lookupMember(m, getFields()); } /** * described in JVM spec 2ed 5.4.3.3. * Doesnt check ITDs. */ public ResolvedMember lookupMethod(Member m) { return lookupMember(m, getMethods()); } public ResolvedMember lookupMethodInITDs(Member m) { if (interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), m)) { return tm.getSignature(); } } } return null; } /** return null if not found */ private ResolvedMember lookupMember(Member m, Iterator i) { while (i.hasNext()) { ResolvedMember f = (ResolvedMember) i.next(); if (matches(f, m)) return f; } return null; //ResolvedMember.Missing; //throw new BCException("can't find " + m); } /** return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) return f; } return null; } /** * Looks for the first member in the hierarchy matching aMember. This method * differs from lookupMember(Member) in that it takes into account parameters * which are type variables - which clearly an unresolved Member cannot do since * it does not know anything about type variables. */ public ResolvedMember lookupResolvedMember(ResolvedMember aMember) { Iterator toSearch = null; ResolvedMember found = null; if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) { toSearch = getMethodsWithoutIterator(true).iterator(); } else { if (aMember.getKind() != Member.FIELD) throw new IllegalStateException("I didn't know you would look for members of kind " + aMember.getKind()); toSearch = getFields(); } while(toSearch.hasNext()) { ResolvedMemberImpl candidate = (ResolvedMemberImpl) toSearch.next(); if (candidate.matches(aMember)) { found = candidate; break; } } return found; } public static boolean matches(Member m1, Member m2) { if (m1 == null) return m2 == null; if (m2 == null) return false; // Check the names boolean equalNames = m1.getName().equals(m2.getName()); if (!equalNames) return false; // Check the signatures boolean equalSignatures = m1.getSignature().equals(m2.getSignature()); if (equalSignatures) return true; // If they aren't the same, we need to allow for covariance ... where one sig might be ()LCar; and // the subsig might be ()LFastCar; - where FastCar is a subclass of Car boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature()); if (equalCovariantSignatures) return true; return false; } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) return false; if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } UnresolvedType[] p1 = m1.getParameterTypes(); UnresolvedType[] p2 = m2.getParameterTypes(); int n = p1.length; if (n != p2.length) return false; for (int i=0; i < n; i++) { if (!p1[i].equals(p2[i])) return false; } return true; } /** * returns an iterator through all of the pointcuts of this type, in order * for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is * * <ul><li> pointcuts from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getPointcuts() { final Iterators.Filter dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterators.Getter pointcutGetter = new Iterators.Getter() { public Iterator get(Object o) { //System.err.println("getting for " + o); return Iterators.array(((ResolvedType)o).getDeclaredPointcuts()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), pointcutGetter); } public ResolvedPointcutDefinition findPointcut(String name) { //System.err.println("looking for pointcuts " + this); for (Iterator i = getPointcuts(); i.hasNext(); ) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); //System.err.println(f); if (name.equals(f.getName())) { return f; } } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers //??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; public CrosscuttingMembers collectCrosscuttingMembers() { crosscuttingMembers = new CrosscuttingMembers(this); crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); //FIXME AV - skip but needed ?? or ?? crosscuttingMembers.addLateTypeMungers(getLateTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers())); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); //System.err.println("collected cc members: " + this + ", " + collectDeclares()); return crosscuttingMembers; } public final Collection collectDeclares(boolean includeAdviceLike) { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { // for (Iterator i = getDeclares().iterator(); i.hasNext();) { // Declare dec = (Declare) i.next(); // if (!dec.isAdviceLike()) ret.add(dec); // } // // if (!includeAdviceLike) return ret; if (!this.isAbstract()) { //ret.addAll(getDeclares()); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); //System.out.println("super: " + ty + ", " + ); for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (dec.isAdviceLike()) { if (includeAdviceLike) ret.add(dec); } else { ret.add(dec); } } } } return ret; } private final Collection collectShadowMungers() { if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST; ArrayList acc = new ArrayList(); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedType)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedType ty = (ResolvedType) typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } protected boolean doesNotExposeShadowMungers() { return false; } public PerClause getPerClause() { return null; } protected Collection getDeclares() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return Collections.EMPTY_LIST; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public boolean isAnnotationStyleAspect() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isEnum() { return false; } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotation() { return false; } /** * Note: Only overridden by Name subtype */ public void addAnnotation(AnnotationX annotationX) { throw new RuntimeException("ResolvedType.addAnnotation() should never be called"); } /** * Note: Only overridden by Name subtype */ public AnnotationX[] getAnnotations() { throw new RuntimeException("ResolvedType.getAnnotations() should never be called"); } /** * Note: Only overridden by Name subtype. */ public boolean isAnnotationWithRuntimeRetention() { return false; } public boolean isSynthetic() { return signature.indexOf("$ajc") != -1; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } protected Map /*Type variable name -> UnresolvedType*/ getMemberParameterizationMap() { if (!isParameterizedType()) return Collections.EMPTY_MAP; TypeVariable[] tvs = getGenericType().getTypeVariables(); Map parameterizationMap = new HashMap(); for (int i = 0; i < tvs.length; i++) { parameterizationMap.put(tvs[i].getName(), typeParameters[i]); } return parameterizationMap; } public Collection getDeclaredAdvice() { List l = new ArrayList(); ResolvedMember[] methods = getDeclaredMethods(); if (isParameterizedType()) methods = getGenericType().getDeclaredMethods(); Map typeVariableMap = getMemberParameterizationMap(); for (int i=0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) { if (this.isParameterizedType()) { munger.setPointcut(munger.getPointcut().parameterizeWith(typeVariableMap)); } munger.setDeclaringType(this); l.add(munger); } } return l; } public Collection getDeclaredShadowMungers() { Collection c = getDeclaredAdvice(); return c; } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } public ShadowMunger[] getDeclaredShadowMungersArray() { List l = (List) getDeclaredShadowMungers(); return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List l = new ArrayList(); for (int i=0, len = ms.length; i < len; i++) { if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedType[] NONE = new ResolvedType[0]; public static final Primitive BYTE = new Primitive("B", 1, 0); public static final Primitive CHAR = new Primitive("C", 1, 1); public static final Primitive DOUBLE = new Primitive("D", 2, 2); public static final Primitive FLOAT = new Primitive("F", 1, 3); public static final Primitive INT = new Primitive("I", 1, 4); public static final Primitive LONG = new Primitive("J", 2, 5); public static final Primitive SHORT = new Primitive("S", 1, 6); public static final Primitive VOID = new Primitive("V", 0, 8); public static final Primitive BOOLEAN = new Primitive("Z", 1, 7); public static final Missing MISSING = new Missing(); // ---- types public static ResolvedType makeArray(ResolvedType type, int dim) { if (dim == 0) return type; ResolvedType array = new Array("[" + type.getSignature(),type.getWorld(),type); return makeArray(array,dim-1); } static class Array extends ResolvedType { ResolvedType componentType; Array(String s, World world, ResolvedType componentType) { super(s, world); this.componentType = componentType; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { // ??? should this return clone? Probably not... // If it ever does, here is the code: // ResolvedMember cloneMethod = // new ResolvedMember(Member.METHOD,this,Modifier.PUBLIC,UnresolvedType.OBJECT,"clone",new UnresolvedType[]{}); // return new ResolvedMember[]{cloneMethod}; return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return new ResolvedType[] { world.getCoreType(CLONEABLE), world.getCoreType(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final ResolvedType getSuperclass() { return world.getCoreType(OBJECT); } public final boolean isAssignableFrom(ResolvedType o) { if (! o.isArray()) return false; if (o.getComponentType().isPrimitiveType()) { return o.equals(this); } else { return getComponentType().resolve(world).isAssignableFrom(o.getComponentType().resolve(world)); } } public final boolean isCoerceableFrom(ResolvedType o) { if (o.equals(UnresolvedType.OBJECT) || o.equals(UnresolvedType.SERIALIZABLE) || o.equals(UnresolvedType.CLONEABLE)) { return true; } if (! o.isArray()) return false; if (o.getComponentType().isPrimitiveType()) { return o.equals(this); } else { return getComponentType().resolve(world).isCoerceableFrom(o.getComponentType().resolve(world)); } } public final int getModifiers() { int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (componentType.getModifiers() & mask) | Modifier.FINAL; } public UnresolvedType getComponentType() { return componentType; } public ResolvedType getResolvedComponentType() { return componentType; } public ISourceContext getSourceContext() { return getResolvedComponentType().getSourceContext(); } } static class Primitive extends ResolvedType { private int size; private int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; } public final int getSize() { return size; } public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } public final boolean isPrimitiveType() { return true; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final boolean isAssignableFrom(ResolvedType other) { if (!other.isPrimitiveType()) { if (!world.isInJava5Mode()) return false; return validBoxing.contains(this.getSignature()+other.getSignature()); } return assignTable[((Primitive)other).index][index]; } public final boolean isCoerceableFrom(ResolvedType other) { if (this == other) return true; if (! other.isPrimitiveType()) return false; if (index > 6 || ((Primitive)other).index > 6) return false; return true; } public ResolvedType resolve(World world) { this.world = world; return super.resolve(world); } public final boolean needsNoConversionFrom(ResolvedType other) { if (! other.isPrimitiveType()) return false; return noConvertTable[((Primitive)other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z from { true , true , true , true , true , true , true , false, false }, // B { false, true , true , true , true , true , false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, true , true , false, false, false, false, false }, // F { false, false, true , true , true , true , false, false, false }, // I { false, false, true , true , false, true , false, false, false }, // J { false, false, true , true , true , true , true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S V Z from { true , true , false, false, true , false, true , false, false }, // B { false, true , false, false, true , false, false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, false, true , false, false, false, false, false }, // F { false, false, false, false, true , false, false, false, false }, // I { false, false, false, false, false, true , false, false, false }, // J { false, false, false, false, true , false, true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedType getSuperclass() { return null; } public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedType { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } public final String getName() { return MISSING_NAME; } public boolean hasAnnotation(UnresolvedType ofType) { return false; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedType[] getDeclaredInterfaces() { return ResolvedType.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedType getSuperclass() { return null; } public final int getModifiers() { return 0; } public final boolean isAssignableFrom(ResolvedType other) { return false; } public final boolean isCoerceableFrom(ResolvedType other) { return false; } public boolean needsNoConversionFrom(ResolvedType other) { return false; } public ISourceContext getSourceContext() { return null; } } /** * Look up a member, takes into account any ITDs on this type. * return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member); if (ret == null && interTypeMungers != null) { for (Iterator i = interTypeMungers.iterator(); i.hasNext();) { ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next(); if (matches(tm.getSignature(), member)) { return tm.getSignature(); } } } return ret; } public ResolvedMember lookupMemberWithSupersAndITDs(Member member) { ResolvedMember ret = lookupMemberNoSupers(member); if (ret != null) return ret; ResolvedType supert = getSuperclass(); if (supert != null) { ret = supert.lookupMemberNoSupers(member); } return ret; } /** * as lookupMemberNoSupers, but does not include ITDs * @param member * @return */ public ResolvedMember lookupDirectlyDeclaredMemberNoSupers(Member member) { ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR ret = lookupMember(member, getDeclaredMethods()); } return ret; } /** * This lookup has specialized behaviour - a null result tells the * EclipseTypeMunger that it should make a default implementation of a * method on this type. * @param member * @return */ public ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member) { return lookupMemberIncludingITDsOnInterfaces(member, this); } private ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member, ResolvedType onType) { ResolvedMember ret = onType.lookupMemberNoSupers(member); if (ret != null) { return ret; } else { ResolvedType superType = onType.getSuperclass(); if (superType != null) { ret = lookupMemberIncludingITDsOnInterfaces(member,superType); } if (ret == null) { // try interfaces then, but only ITDs now... ResolvedType[] superInterfaces = onType.getDeclaredInterfaces(); for (int i = 0; i < superInterfaces.length; i++) { ret = superInterfaces[i].lookupMethodInITDs(member); if (ret != null) return ret; } } } return ret; } protected List interTypeMungers = new ArrayList(0); public List getInterTypeMungers() { return interTypeMungers; } public List getInterTypeParentMungers() { List l = new ArrayList(); for (Iterator iter = interTypeMungers.iterator(); iter.hasNext();) { ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next(); if (element.getMunger() instanceof NewParentTypeMunger) l.add(element); } return l; } /** * ??? This method is O(N*M) where N = number of methods and M is number of * inter-type declarations in my super */ public List getInterTypeMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeMungers(ret); return ret; } public List getInterTypeParentMungersIncludingSupers() { ArrayList ret = new ArrayList(); collectInterTypeParentMungers(ret); return ret; } private void collectInterTypeParentMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = (ResolvedType) iter.next(); superType.collectInterTypeParentMungers(collector); } collector.addAll(getInterTypeParentMungers()); } private void collectInterTypeMungers(List collector) { for (Iterator iter = getDirectSupertypes(); iter.hasNext();) { ResolvedType superType = (ResolvedType) iter.next(); superType.collectInterTypeMungers(collector); } outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext(); ) { ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next(); if ( superMunger.getSignature() == null) continue; if ( !superMunger.getSignature().isAbstract()) continue; for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) { ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next(); if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) { iter1.remove(); continue outer; } } if (!superMunger.getSignature().isPublic()) continue; for (Iterator iter = getMethods(); iter.hasNext(); ) { ResolvedMember method = (ResolvedMember)iter.next(); if (conflictingSignature(method, superMunger.getSignature())) { iter1.remove(); continue outer; } } } collector.addAll(getInterTypeMungers()); } /** * Check: * 1) That we don't have any abstract type mungers unless this type is abstract. * 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794) */ public void checkInterTypeMungers() { if (isAbstract()) return; boolean itdProblem = false; for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2 } if (itdProblem) return; // If the rules above are broken, return right now for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) { ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next(); if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1 world.getMessageHandler().handleMessage( new Message("must implement abstract inter-type declaration: " + munger.getSignature(), "", IMessage.ERROR, getSourceLocation(), null, new ISourceLocation[] { getMungerLocation(munger) })); } } } /** * See PR70794. This method checks that if an abstract inter-type method declaration is made on * an interface then it must also be public. * This is a compiler limitation that could be made to work in the future (if someone * provides a worthwhile usecase) * * @return indicates if the munger failed the check */ private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) { if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) { ResolvedMember itdMember = munger.getSignature(); ResolvedType onType = itdMember.getDeclaringType().resolve(world); if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) { world.getMessageHandler().handleMessage( new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"", Message.ERROR,getSourceLocation(),null, new ISourceLocation[]{getMungerLocation(munger)}) ); return true; } } return false; } /** * Get a source location for the munger. * Until intertype mungers remember where they came from, the source location * for the munger itself is null. In these cases use the * source location for the aspect containing the ITD. * */ private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) { ISourceLocation sloc = munger.getSourceLocation(); if (sloc == null) { sloc = munger.getAspectType().getSourceLocation(); } return sloc; } /** * Returns a ResolvedType object representing the declaring type of this type, or * null if this type does not represent a non-package-level-type. * * <strong>Warning</strong>: This is guaranteed to work for all member types. * For anonymous/local types, the only guarantee is given in JLS 13.1, where * it guarantees that if you call getDeclaringType() repeatedly, you will eventually * get the top-level class, but it does not say anything about classes in between. * * @return the declaring UnresolvedType object, or null. */ public ResolvedType getDeclaringType() { if (isArray()) return null; String name = getName(); int lastDollar = name.lastIndexOf('$'); while (lastDollar != -1) { ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true); if (ret != ResolvedType.MISSING) return ret; lastDollar = name.lastIndexOf('$', lastDollar-1); } return null; } public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) { //System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return targetType.getOutermostType().equals(fromType.getOutermostType()); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } public static boolean hasBridgeModifier(int modifiers) { return (modifiers & Constants.ACC_BRIDGE)!=0; } private static boolean samePackage( ResolvedType targetType, ResolvedType fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } public void addInterTypeMunger(ConcreteTypeMunger munger) { ResolvedMember sig = munger.getSignature(); if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } //System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers); if (sig.getKind() == Member.METHOD) { if (!compareToExistingMembers(munger, getMethodsWithoutIterator(false) /*getMethods()*/)) return; if (this.isInterface()) { if (!compareToExistingMembers(munger, Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType()); } //System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature()); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature()); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } //System.err.println("adding: " + munger + " to " + this); interTypeMungers.add(munger); } private boolean compareToExistingMembers(ConcreteTypeMunger munger, List existingMembersList) { return compareToExistingMembers(munger,existingMembersList.iterator()); } //??? returning too soon private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) { ResolvedMember sig = munger.getSignature(); while (existingMembers.hasNext()) { ResolvedMember existingMember = (ResolvedMember)existingMembers.next(); //System.err.println("Comparing munger: "+sig+" with member "+existingMember); if (conflictingSignature(existingMember, munger.getSignature())) { //System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger); //System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) { int c = compareMemberPrecedence(sig, existingMember); //System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(munger.getSignature(), existingMember); return false; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, munger.getSignature()); //interTypeMungers.add(munger); //??? might need list of these overridden abstracts continue; } else { // bridge methods can differ solely in return type. // FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it // could do with a rewrite ! boolean sameReturnTypes = (existingMember.getReturnType().equals(sig.getReturnType())); if (sameReturnTypes) getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) ); } } else if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) { getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(), existingMember), munger.getSourceLocation()) );; } //return; } } return true; } // we know that the member signature matches, but that the member in the target type is not visible to the aspect. // this may still be disallowed if it would result in two members within the same declaring type with the same // signature AND more than one of them is concrete AND they are both visible within the target type. private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType,ResolvedMember itdMember) { if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false; UnresolvedType declaringType = existingMember.getDeclaringType(); if (!targetType.equals(declaringType)) return false; // now have to test that itdMember is visible from targetType if (itdMember.isPrivate()) return false; if (itdMember.isPublic()) return true; // must be in same package to be visible then... if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) return false; // trying to put two members with the same signature into the exact same type..., and both visible in that type. return true; } /** * @return true if the override is legal * note: calling showMessage with two locations issues TWO messages, not ONE message * with an additional source location. */ public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) { //System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType()); if (Modifier.isFinal(parent.getModifiers())) { world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER,parent), child.getSourceLocation(),null); return false; } boolean incompatibleReturnTypes = false; // In 1.5 mode, allow for covariance on return type if (world.isInJava5Mode() && parent.getKind()==Member.METHOD) { ResolvedType rtParentReturnType = parent.getReturnType().resolve(world); ResolvedType rtChildReturnType = child.getReturnType().resolve(world); incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType); } else { incompatibleReturnTypes =!parent.getReturnType().equals(child.getReturnType()); } if (incompatibleReturnTypes) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { UnresolvedType[] pTypes = parent.getParameterTypes(); UnresolvedType[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } } //System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION,parent,child), child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedType[] childExceptions = world.resolve(child.getExceptions()); ResolvedType[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedType runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedType error = world.resolve("java.lang.Error"); outer: for (int i=0, leni = childExceptions.length; i < leni; i++) { //System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) continue; if (error.isAssignableFrom(childExceptions[i])) continue; for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer; } // this message is now better handled my MethodVerifier in JDT core. // world.showMessage(IMessage.ERROR, // WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()), // child.getSourceLocation(), null); return false; } if (parent.isStatic() && !child.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent), child.getSourceLocation(),null); return false; } else if (child.isStatic() && !parent.isStatic()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent), child.getSourceLocation(),null); return false; } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { //if (!m1.getReturnType().equals(m2.getReturnType())) return 0; // need to allow for the special case of 'clone' - which is like abstract but is // not marked abstract. The code below this next line seems to make assumptions // about what will have gotten through the compiler based on the normal // java rules. clone goes against these... if (m2.isProtected() && m2.isNative() && m2.getName().equals("clone")) return +1; if (Modifier.isAbstract(m1.getModifiers())) return -1; if (Modifier.isAbstract(m2.getModifiers())) return +1; if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0; ResolvedType t1 = m1.getDeclaringType().resolve(world); ResolvedType t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) return false; if (isPackage(m1)) return Modifier.isPrivate(m2); if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2)); if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2); throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError( ConcreteTypeMunger m1, ConcreteTypeMunger m2) { //XXX this works only if we ignore separate compilation issues //XXX dual errors possible if (this instanceof BcelObjectType) return; //System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_CONFLICT,m1.getAspectType().getName(), m2.getSignature(),m2.getAspectType().getName()), m2.getSourceLocation(), getSourceLocation()); } public ResolvedMember lookupSyntheticMember(Member member) { //??? horribly inefficient //for (Iterator i = //System.err.println("lookup " + member + " in " + interTypeMungers); for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { //System.err.println(" found: " + ret); return ret; } } // if (this.getSuperclass() != ResolvedType.OBJECT && this.getSuperclass() != null) { // return getSuperclass().lookupSyntheticMember(member); // } return null; } public void clearInterTypeMungers() { if (isRawType()) getGenericType().clearInterTypeMungers(); interTypeMungers = new ArrayList(); } public boolean isTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) return false; if (!interfaceType.isAssignableFrom(this)) return false; // check that I'm truly the topmost implementor if (interfaceType.isAssignableFrom(this.getSuperclass())) { return false; } return true; } public ResolvedType getTopmostImplementor(ResolvedType interfaceType) { if (isInterface()) return null; if (!interfaceType.isAssignableFrom(this)) return null; // Check if my super class is an implementor? ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType); if (higherType!=null) return higherType; return this; } private ResolvedType findHigher(ResolvedType other) { if (this == other) return this; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { ResolvedType rtx = (ResolvedType)i.next(); boolean b = this.isAssignableFrom(rtx); if (b) return rtx; } return null; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { ResolvedType t = (ResolvedType)i.next(); addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next(); // System.err.println("looking at: " + inherited + " in " + this); // System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract()); if (inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) { for (Iterator i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); //System.err.println("adding: " + toAdd); for (Iterator j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (existing == toAdd) continue; if (!isVisible(existing.getModifiers(), existing.getDeclaringType().resolve(getWorld()), this)) { continue; } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } public WeaverStateInfo getWeaverState() { return null; } /** * Overridden by ReferenceType to return a sensible answer for parameterized and raw types. * @return */ public ResolvedType getGenericType() { if (!(isParameterizedType() || isRawType())) throw new BCException("The type "+getBaseName()+" is not parameterized or raw - it has no generic type"); return null; } public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) { if (!(isGenericType() || isParameterizedType())) return this; return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld()); } /** * Iff I am a parameterized type, and any of my parameters are type variable * references, return a version with those type parameters replaced in accordance * with the passed bindings. */ public UnresolvedType parameterize(Map typeBindings) { if (!isParameterizedType()) throw new IllegalStateException("Can't parameterize a type that is not a parameterized type"); boolean workToDo = false; for (int i = 0; i < typeParameters.length; i++) { if (typeParameters[i].isTypeVariableReference()) { workToDo = true; } } if (!workToDo) { return this; } else { UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length]; for (int i = 0; i < newTypeParams.length; i++) { newTypeParams[i] = typeParameters[i]; if (newTypeParams[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i]; UnresolvedType binding = (UnresolvedType) typeBindings.get(tvrt.getTypeVariable().getName()); if (binding != null) newTypeParams[i] = binding; } } return TypeFactory.createParameterizedType(getGenericType(), newTypeParams, getWorld()); } } public boolean hasParameterizedSuperType() { getParameterizedSuperTypes(); return parameterizedSuperTypes.length > 0; } public boolean hasGenericSuperType() { ResolvedType[] superTypes = getDeclaredInterfaces(); for (int i = 0; i < superTypes.length; i++) { if (superTypes[i].isGenericType()) return true; } return false; } private ResolvedType[] parameterizedSuperTypes = null; /** * Similar to the above method, but accumulates the super types * @return */ public ResolvedType[] getParameterizedSuperTypes() { if (parameterizedSuperTypes != null) return parameterizedSuperTypes; List accumulatedTypes = new ArrayList(); accumulateParameterizedSuperTypes(this,accumulatedTypes); ResolvedType[] ret = new ResolvedType[accumulatedTypes.size()]; parameterizedSuperTypes = (ResolvedType[]) accumulatedTypes.toArray(ret); return parameterizedSuperTypes; } private void accumulateParameterizedSuperTypes(ResolvedType forType, List parameterizedTypeList) { if (forType.isParameterizedType()) { parameterizedTypeList.add(forType); } if (forType.getSuperclass() != null) { accumulateParameterizedSuperTypes(forType.getSuperclass(), parameterizedTypeList); } ResolvedType[] interfaces = forType.getDeclaredInterfaces(); for (int i = 0; i < interfaces.length; i++) { accumulateParameterizedSuperTypes(interfaces[i], parameterizedTypeList); } } /** * Types may have pointcuts just as they have methods and fields. */ public ResolvedPointcutDefinition findPointcut(String name, World world) { throw new UnsupportedOperationException("Not yet implemenented"); } /** * Determines if variables of this type could be assigned values of another * with lots of help. * java.lang.Object is convertable from all types. * A primitive type is convertable from X iff it's assignable from X. * A reference type is convertable from X iff it's coerceable from X. * In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y * could be assignable to a variable of type X without loss of precision. * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other with possible conversion */ public final boolean isConvertableFrom(ResolvedType other) { // // version from TypeX // if (this.equals(OBJECT)) return true; // if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other); // return this.isCoerceableFrom(other); // // version from ResolvedTypeX if (this.equals(OBJECT)) return true; if (world.isInJava5Mode()) { if (this.isPrimitiveType()^other.isPrimitiveType()) { // If one is primitive and the other isnt if (validBoxing.contains(this.getSignature()+other.getSignature())) return true; } } if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other); return this.isCoerceableFrom(other); } /** * Determines if the variables of this type could be assigned values * of another type without casting. This still allows for assignment conversion * as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER). * * @param other the other type * @param world the {@link World} in which the possible assignment should be checked. * @return true iff variables of this type could be assigned values of other without casting * @exception NullPointerException if other is null */ public abstract boolean isAssignableFrom(ResolvedType other); /** * Determines if values of another type could possibly be cast to * this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion". * * <p> This method should be commutative, i.e., for all UnresolvedType a, b and all World w: * * <blockquote><pre> * a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w) * </pre></blockquote> * * @param other the other type * @param world the {@link World} in which the possible coersion should be checked. * @return true iff values of other could possibly be cast to this type. * @exception NullPointerException if other is null. */ public abstract boolean isCoerceableFrom(ResolvedType other); public boolean needsNoConversionFrom(ResolvedType o) { return isAssignableFrom(o); } /** * Implemented by ReferenceTypes */ public String getSignatureForAttribute() { throw new RuntimeException("Cannot ask this type "+this+" for a generic sig attribute"); } private FuzzyBoolean parameterizedWithAMemberTypeVariable = FuzzyBoolean.MAYBE; /** * return true if the parameterization of this type includes a member type variable. Member * type variables occur in generic methods/ctors. */ public boolean isParameterizedWithAMemberTypeVariable() { // MAYBE means we haven't worked it out yet... if (parameterizedWithAMemberTypeVariable==FuzzyBoolean.MAYBE) { // if there are no type parameters then we cant be... if (typeParameters==null || typeParameters.length==0) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.NO; return false; } for (int i = 0; i < typeParameters.length; i++) { UnresolvedType aType = (ResolvedType)typeParameters[i]; if (aType.isTypeVariableReference() && ((TypeVariableReference)aType).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } if (aType.isParameterizedType()) { boolean b = aType.isParameterizedWithAMemberTypeVariable(); if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } } if (aType.isGenericWildcard()) { if (aType.isExtends()) { boolean b = false; UnresolvedType upperBound = aType.getUpperBound(); if (upperBound.isParameterizedType()) { b = upperBound.isParameterizedWithAMemberTypeVariable(); } else if (upperBound.isTypeVariableReference() && ((TypeVariableReference)upperBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } // FIXME asc need to check additional interface bounds } if (aType.isSuper()) { boolean b = false; UnresolvedType lowerBound = aType.getLowerBound(); if (lowerBound.isParameterizedType()) { b = lowerBound.isParameterizedWithAMemberTypeVariable(); } else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference)lowerBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) { b = true; } if (b) { parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES; return true; } } } } parameterizedWithAMemberTypeVariable=FuzzyBoolean.NO; } return parameterizedWithAMemberTypeVariable.alwaysTrue(); } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/WeaverMessages.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.weaver; import java.text.MessageFormat; import java.util.ResourceBundle; public class WeaverMessages { private static ResourceBundle bundle = ResourceBundle.getBundle("org.aspectj.weaver.weaver-messages"); public static final String ARGS_IN_DECLARE = "argsInDeclare"; public static final String CFLOW_IN_DECLARE = "cflowInDeclare"; public static final String IF_IN_DECLARE = "ifInDeclare"; public static final String THIS_OR_TARGET_IN_DECLARE = "thisOrTargetInDeclare"; public static final String ABSTRACT_POINTCUT = "abstractPointcut"; public static final String POINCUT_NOT_CONCRETE = "abstractPointcutNotMadeConcrete"; public static final String CONFLICTING_INHERITED_POINTCUTS = "conflictingInheritedPointcuts"; public static final String CIRCULAR_POINTCUT = "circularPointcutDeclaration"; public static final String CANT_FIND_POINTCUT = "cantFindPointcut"; public static final String EXACT_TYPE_PATTERN_REQD = "exactTypePatternRequired"; public static final String CANT_BIND_TYPE = "cantBindType"; public static final String WILDCARD_NOT_ALLOWED = "wildcardTypePatternNotAllowed"; public static final String FIELDS_CANT_HAVE_VOID_TYPE = "fieldCantBeVoid"; public static final String DECP_OBJECT = "decpObject"; public static final String CANT_EXTEND_SELF="cantExtendSelf"; public static final String INTERFACE_CANT_EXTEND_CLASS="interfaceExtendClass"; public static final String DECP_HIERARCHY_ERROR = "decpHierarchy"; public static final String MULTIPLE_MATCHES_IN_PRECEDENCE = "multipleMatchesInPrecedence"; public static final String TWO_STARS_IN_PRECEDENCE = "circularityInPrecedenceStar"; public static final String CLASSES_IN_PRECEDENCE = "nonAspectTypesInPrecedence"; public static final String TWO_PATTERN_MATCHES_IN_PRECEDENCE = "circularityInPrecedenceTwo"; public static final String NOT_THROWABLE = "notThrowable"; public static final String ITD_CONS_ON_ASPECT = "itdConsOnAspect"; public static final String ITD_RETURN_TYPE_MISMATCH = "returnTypeMismatch"; public static final String ITD_PARAM_TYPE_MISMATCH = "paramTypeMismatch"; public static final String ITD_VISIBILITY_REDUCTION = "visibilityReduction"; public static final String ITD_DOESNT_THROW = "doesntThrow"; public static final String ITD_OVERRIDDEN_STATIC = "overriddenStatic"; public static final String ITD_OVERIDDING_STATIC = "overridingStatic"; public static final String ITD_CONFLICT = "itdConflict"; public static final String ITD_MEMBER_CONFLICT = "itdMemberConflict"; public static final String ITD_NON_EXPOSED_IMPLEMENTOR = "itdNonExposedImplementor"; public static final String ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE = "itdAbstractMustBePublicOnInterface"; public static final String CANT_OVERRIDE_FINAL_MEMBER = "cantOverrideFinalMember"; public static final String NON_VOID_RETURN = "nonVoidReturn"; public static final String INCOMPATIBLE_RETURN_TYPE="incompatibleReturnType"; public static final String CANT_THROW_CHECKED = "cantThrowChecked"; public static final String CIRCULAR_DEPENDENCY = "circularDependency"; public static final String MISSING_PER_CLAUSE = "missingPerClause"; public static final String WRONG_PER_CLAUSE = "wrongPerClause"; public static final String ALREADY_WOVEN = "alreadyWoven"; public static final String REWEAVABLE_MODE = "reweavableMode"; public static final String PROCESSING_REWEAVABLE = "processingReweavable"; public static final String MISSING_REWEAVABLE_TYPE = "missingReweavableType"; public static final String VERIFIED_REWEAVABLE_TYPE = "verifiedReweavableType"; public static final String ASPECT_NEEDED = "aspectNeeded"; public static final String CANT_FIND_TYPE = "cantFindType"; public static final String CANT_FIND_CORE_TYPE = "cantFindCoreType"; public static final String CANT_FIND_TYPE_WITHINPCD = "cantFindTypeWithinpcd"; public static final String CANT_FIND_TYPE_DURING_AROUND_WEAVE = "cftDuringAroundWeave"; public static final String CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT = "cftDuringAroundWeavePreinit"; public static final String CANT_FIND_TYPE_EXCEPTION_TYPE = "cftExceptionType"; public static final String CANT_FIND_TYPE_ARG_TYPE = "cftArgType"; public static final String CANT_FIND_PARENT_TYPE = "cantFindParentType"; public static final String DECP_BINARY_LIMITATION = "decpBinaryLimitation"; public static final String OVERWRITE_JSR45 = "overwriteJSR45"; public static final String IF_IN_PERCLAUSE = "ifInPerClause"; public static final String IF_LEXICALLY_IN_CFLOW = "ifLexicallyInCflow"; public static final String ONLY_BEFORE_ON_HANDLER = "onlyBeforeOnHandler"; public static final String AROUND_ON_PREINIT = "aroundOnPreInit"; public static final String AROUND_ON_INIT = "aroundOnInit"; public static final String AROUND_ON_INTERFACE_STATICINIT = "aroundOnInterfaceStaticInit"; public static final String PROBLEM_GENERATING_METHOD = "problemGeneratingMethod"; public static final String CLASS_TOO_BIG = "classTooBig"; public static final String ZIPFILE_ENTRY_MISSING = "zipfileEntryMissing"; public static final String ZIPFILE_ENTRY_INVALID = "zipfileEntryInvalid"; public static final String DIRECTORY_ENTRY_MISSING = "directoryEntryMissing"; public static final String OUTJAR_IN_INPUT_PATH = "outjarInInputPath"; public static final String XLINT_LOAD_ERROR = "problemLoadingXLint"; public static final String XLINTDEFAULT_LOAD_ERROR = "unableToLoadXLintDefault"; public static final String XLINTDEFAULT_LOAD_PROBLEM = "errorLoadingXLintDefault"; public static final String XLINT_KEY_ERROR = "invalidXLintKey"; public static final String XLINT_VALUE_ERROR = "invalidXLintMessageKind"; public static final String UNBOUND_FORMAL = "unboundFormalInPC"; public static final String AMBIGUOUS_BINDING = "ambiguousBindingInPC"; public static final String AMBIGUOUS_BINDING_IN_OR = "ambiguousBindingInOrPC"; public static final String NEGATION_DOESNT_ALLOW_BINDING = "negationDoesntAllowBinding"; // Java5 messages public static final String ITDC_ON_ENUM_NOT_ALLOWED = "itdcOnEnumNotAllowed"; public static final String ITDM_ON_ENUM_NOT_ALLOWED = "itdmOnEnumNotAllowed"; public static final String ITDF_ON_ENUM_NOT_ALLOWED = "itdfOnEnumNotAllowed"; public static final String CANT_DECP_ON_ENUM_TO_IMPL_INTERFACE = "cantDecpOnEnumToImplInterface"; public static final String CANT_DECP_ON_ENUM_TO_EXTEND_CLASS = "cantDecpOnEnumToExtendClass"; public static final String CANT_DECP_TO_MAKE_ENUM_SUPERTYPE = "cantDecpToMakeEnumSupertype"; public static final String ITDC_ON_ANNOTATION_NOT_ALLOWED = "itdcOnAnnotationNotAllowed"; public static final String ITDM_ON_ANNOTATION_NOT_ALLOWED = "itdmOnAnnotationNotAllowed"; public static final String ITDF_ON_ANNOTATION_NOT_ALLOWED = "itdfOnAnnotationNotAllowed"; public static final String CANT_DECP_ON_ANNOTATION_TO_IMPL_INTERFACE = "cantDecpOnAnnotationToImplInterface"; public static final String CANT_DECP_ON_ANNOTATION_TO_EXTEND_CLASS = "cantDecpOnAnnotationToExtendClass"; public static final String CANT_DECP_TO_MAKE_ANNOTATION_SUPERTYPE = "cantDecpToMakeAnnotationSupertype"; public static final String REFERENCE_TO_NON_ANNOTATION_TYPE = "referenceToNonAnnotationType"; public static final String BINDING_NON_RUNTIME_RETENTION_ANNOTATION = "bindingNonRuntimeRetentionAnnotation"; public static final String INCORRECT_TARGET_FOR_DECLARE_ANNOTATION = "incorrectTargetForDeclareAnnotation"; // Generics public static final String CANT_DECP_MULTIPLE_PARAMETERIZATIONS="cantDecpMultipleParameterizations"; public static final String HANDLER_PCD_DOESNT_SUPPORT_PARAMETERS="noParameterizedTypePatternInHandler"; public static final String INCORRECT_NUMBER_OF_TYPE_ARGUMENTS = "incorrectNumberOfTypeArguments"; public static final String VIOLATES_TYPE_VARIABLE_BOUNDS = "violatesTypeVariableBounds"; public static final String NO_STATIC_INIT_JPS_FOR_PARAMETERIZED_TYPES = "noStaticInitJPsForParameterizedTypes"; public static final String NOT_A_GENERIC_TYPE="notAGenericType"; public static final String WITHIN_PCD_DOESNT_SUPPORT_PARAMETERS="noParameterizedTypePatternInWithin"; public static final String THIS_AND_TARGET_DONT_SUPPORT_PARAMETERS="noParameterizedTypesInThisAndTarget"; public static final String GET_AND_SET_DONT_SUPPORT_DEC_TYPE_PARAMETERS="noParameterizedTypesInGetAndSet"; public static final String NO_INIT_JPS_FOR_PARAMETERIZED_TYPES = "noInitJPsForParameterizedTypes"; public static final String NO_GENERIC_THROWABLES = "noGenericThrowables"; public static final String WITHINCODE_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES="noParameterizedDeclaringTypesWithinCode"; public static final String EXECUTION_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES="noParameterizedDeclaringTypesInExecution"; public static final String CALL_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES="noParameterizedDeclaringTypesInCall"; public static final String CANT_REFERENCE_POINTCUT_IN_RAW_TYPE="noRawTypePointcutReferences"; public static final String HAS_MEMBER_NOT_ENABLED="hasMemberNotEnabled"; // @AspectJ public static final String RETURNING_FORMAL_NOT_DECLARED_IN_ADVICE = "returningFormalNotDeclaredInAdvice"; public static final String THROWN_FORMAL_NOT_DECLARED_IN_ADVICE = "thrownFormalNotDeclaredInAdvice"; public static String format(String key) { return bundle.getString(key); } public static String format(String key, Object insert) { return MessageFormat.format(bundle.getString(key),new Object[] {insert}); } public static String format(String key, Object insert1, Object insert2) { return MessageFormat.format(bundle.getString(key),new Object[] {insert1,insert2}); } public static String format(String key, Object insert1, Object insert2, Object insert3) { return MessageFormat.format(bundle.getString(key),new Object[] {insert1, insert2, insert3}); } public static String format(String key, Object insert1, Object insert2, Object insert3, Object insert4) { return MessageFormat.format(bundle.getString(key),new Object[] {insert1, insert2, insert3, insert4}); } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06: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.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; /** 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; /** 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) { 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 void handleRequiredMissingTypeDuringResolution(UnresolvedType ty) { 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())); } /** * 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.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) { this.messageHandler = messageHandler; } /** * convenenience method for creating and issuing messages via the message handler */ 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 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 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(); } } } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/bcel/BcelAccessForInlineMunger.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.bcel; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.GETFIELD; import org.aspectj.apache.bcel.generic.GETSTATIC; 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.InvokeInstruction; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; 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.UnresolvedType; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.List; /** * Looks for all access to method or field that are not public within the body of the around advices and replace * the invocations to a wrapper call so that the around advice can further be inlined. * <p/> * This munger is used for @AJ aspects for which inlining wrapper is not done at compile time. * <p/> * Specific state and logic is kept in the munger ala ITD so that call/get/set pointcuts can still be matched * on the wrapped member thanks to the EffectiveSignature attribute. * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class BcelAccessForInlineMunger extends BcelTypeMunger { /** * Wrapper member cache, key is wrapper name. * This structure is queried when regular shadow matching in the advice body (call/get/set) occurs */ private Map m_inlineAccessorBcelMethods; /** * The aspect we act for */ private LazyClassGen m_aspectGen; /** * The wrapper method we need to add. Those are added at the end of the munging */ private Set m_inlineAccessorMethodGens; public BcelAccessForInlineMunger(ResolvedType aspectType) { super(null, aspectType); if (aspectType.getWorld().isXnoInline()) { throw new Error("This should not happen"); } } public boolean munge(BcelClassWeaver weaver) { m_aspectGen = weaver.getLazyClassGen(); m_inlineAccessorBcelMethods = new HashMap(0); m_inlineAccessorMethodGens = new HashSet(); // look for all @Around advices for (Iterator iterator = m_aspectGen.getMethodGens().iterator(); iterator.hasNext();) { LazyMethodGen methodGen = (LazyMethodGen) iterator.next(); if (methodGen.hasAnnotation(UnresolvedType.forName("org/aspectj/lang/annotation/Around"))) { openAroundAdvice(methodGen); } } // add the accessors for (Iterator iterator = m_inlineAccessorMethodGens.iterator(); iterator.hasNext();) { LazyMethodGen lazyMethodGen = (LazyMethodGen) iterator.next(); m_aspectGen.addMethodGen(lazyMethodGen); } // flush some m_inlineAccessorMethodGens = null; // we keep m_inlineAccessorsResolvedMembers for shadow matching return true; } /** * Looks in the wrapper we have added so that we can find their effective signature if needed * * @param member * @return */ public ResolvedMember getMatchingSyntheticMember(Member member) { return (ResolvedMember) m_inlineAccessorBcelMethods.get(member.getName()); } public ResolvedMember getSignature() { return null; } /** * Match only the aspect for which we act * * @param onType * @return */ public boolean matches(ResolvedType onType) { return aspectType.equals(onType); } /** * Prepare the around advice, flag it as cannot be inlined if it can't be * * @param aroundAdvice */ private void openAroundAdvice(LazyMethodGen aroundAdvice) { InstructionHandle curr = aroundAdvice.getBody().getStart(); InstructionHandle end = aroundAdvice.getBody().getEnd(); ConstantPoolGen cpg = aroundAdvice.getEnclosingClass().getConstantPoolGen(); InstructionFactory factory = aroundAdvice.getEnclosingClass().getFactory(); boolean realizedCannotInline = false; while (curr != end) { if (realizedCannotInline) { // we know we cannot inline this advice so no need for futher handling break; } InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); // open-up method call if ((inst instanceof InvokeInstruction)) { InvokeInstruction invoke = (InvokeInstruction) inst; ResolvedType callee = m_aspectGen.getWorld().resolve(UnresolvedType.forName(invoke.getClassName(cpg))); // look in the whole method list and not just declared for super calls and alike List methods = callee.getMethodsWithoutIterator(false); for (Iterator iter = methods.iterator(); iter.hasNext();) { ResolvedMember resolvedMember = (ResolvedMember) iter.next(); if (invoke.getName(cpg).equals(resolvedMember.getName()) && invoke.getSignature(cpg).equals(resolvedMember.getSignature()) && !resolvedMember.isPublic()) { if ("<init>".equals(invoke.getName(cpg))) { // skipping open up for private constructor // can occur when aspect new a private inner type // too complex to handle new + dup + .. + invokespecial here. aroundAdvice.setCanInline(false); realizedCannotInline = true; } else { // specific handling for super.foo() calls, where foo is non public if (aspectType.getSuperclass() != null && aspectType.getSuperclass().getName().equals(callee.getName())) { ResolvedMember accessor = createOrGetInlineAccessorForSuperDispatch(resolvedMember); InvokeInstruction newInst = factory.createInvoke( aspectType.getName(), accessor.getName(), BcelWorld.makeBcelType(accessor.getReturnType()), BcelWorld.makeBcelTypes(accessor.getParameterTypes()), Constants.INVOKEVIRTUAL ); curr.setInstruction(newInst); } else { ResolvedMember accessor = createOrGetInlineAccessorForMethod(resolvedMember); InvokeInstruction newInst = factory.createInvoke( aspectType.getName(), accessor.getName(), BcelWorld.makeBcelType(accessor.getReturnType()), BcelWorld.makeBcelTypes(accessor.getParameterTypes()), Constants.INVOKESTATIC ); curr.setInstruction(newInst); } } break;//ok we found a matching callee member and swapped the instruction with the accessor } } } else if (inst instanceof FieldInstruction) { FieldInstruction invoke = (FieldInstruction) inst; ResolvedType callee = m_aspectGen.getWorld().resolve(UnresolvedType.forName(invoke.getClassName(cpg))); for (int i = 0; i < callee.getDeclaredJavaFields().length; i++) { ResolvedMember resolvedMember = callee.getDeclaredJavaFields()[i]; if (invoke.getName(cpg).equals(resolvedMember.getName()) && invoke.getSignature(cpg).equals(resolvedMember.getSignature()) && !resolvedMember.isPublic()) { final ResolvedMember accessor; if ((inst instanceof GETFIELD) || (inst instanceof GETSTATIC)) { accessor = createOrGetInlineAccessorForFieldGet(resolvedMember); } else { accessor = createOrGetInlineAccessorForFieldSet(resolvedMember); } InvokeInstruction newInst = factory.createInvoke( aspectType.getName(), accessor.getName(), BcelWorld.makeBcelType(accessor.getReturnType()), BcelWorld.makeBcelTypes(accessor.getParameterTypes()), Constants.INVOKESTATIC ); curr.setInstruction(newInst); break;//ok we found a matching callee member and swapped the instruction with the accessor } } } curr = next; } // no reason for not inlining this advice // since it is used for @AJ advice that cannot be inlined by defauilt // make sure we set inline to true since we have done this analysis if (!realizedCannotInline) { aroundAdvice.setCanInline(true); } } /** * Add an inline wrapper for a non public method call * * @param resolvedMember * @return */ private ResolvedMember createOrGetInlineAccessorForMethod(ResolvedMember resolvedMember) { String accessor = NameMangler.inlineAccessMethodForMethod( resolvedMember.getName(), resolvedMember.getDeclaringType(), aspectType ); ResolvedMember inlineAccessor = (ResolvedMember) m_inlineAccessorBcelMethods.get(accessor); if (inlineAccessor == null) { // add static method to aspect inlineAccessor = AjcMemberMaker.inlineAccessMethodForMethod( aspectType, resolvedMember ); //add new accessor method to aspect bytecode InstructionFactory factory = m_aspectGen.getFactory(); LazyMethodGen method = makeMethodGen(m_aspectGen, inlineAccessor); // flag it synthetic, AjSynthetic method.makeSynthetic(); method.addAttribute( BcelAttributes.bcelAttribute(new AjAttribute.AjSynthetic(), m_aspectGen.getConstantPoolGen()) ); // flag the effective signature, so that we can deobfuscate the signature to apply method call pointcut method.addAttribute( BcelAttributes.bcelAttribute( new AjAttribute.EffectiveSignatureAttribute(resolvedMember, Shadow.MethodCall, false), m_aspectGen.getConstantPoolGen() ) ); m_inlineAccessorMethodGens.add(method); InstructionList il = method.getBody(); int register = 0; for (int i = 0; i < inlineAccessor.getParameterTypes().length; i++) { UnresolvedType typeX = inlineAccessor.getParameterTypes()[i]; Type type = BcelWorld.makeBcelType(typeX); il.append(InstructionFactory.createLoad(type, register)); register += type.getSize(); } il.append( Utility.createInvoke( factory, resolvedMember.isStatic() ? Constants.INVOKESTATIC : Constants.INVOKESPECIAL, resolvedMember ) ); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(inlineAccessor.getReturnType()))); m_inlineAccessorBcelMethods.put( accessor, new BcelMethod(m_aspectGen.getBcelObjectType(), method.getMethod()) ); } return inlineAccessor; } /** * Add an inline wrapper for a non public super.method call * * @param resolvedMember * @return */ private ResolvedMember createOrGetInlineAccessorForSuperDispatch(ResolvedMember resolvedMember) { String accessor = NameMangler.superDispatchMethod( aspectType, resolvedMember.getName() ); ResolvedMember inlineAccessor = (ResolvedMember) m_inlineAccessorBcelMethods.get(accessor); if (inlineAccessor == null) { // add static method to aspect inlineAccessor = AjcMemberMaker.superAccessMethod( aspectType, resolvedMember ); //add new accessor method to aspect bytecode InstructionFactory factory = m_aspectGen.getFactory(); LazyMethodGen method = makeMethodGen(m_aspectGen, inlineAccessor); // flag it synthetic, AjSynthetic method.makeSynthetic(); method.addAttribute( BcelAttributes.bcelAttribute(new AjAttribute.AjSynthetic(), m_aspectGen.getConstantPoolGen()) ); // flag the effective signature, so that we can deobfuscate the signature to apply method call pointcut method.addAttribute( BcelAttributes.bcelAttribute( new AjAttribute.EffectiveSignatureAttribute(resolvedMember, Shadow.MethodCall, false), m_aspectGen.getConstantPoolGen() ) ); m_inlineAccessorMethodGens.add(method); InstructionList il = method.getBody(); il.append(InstructionConstants.ALOAD_0); int register = 0; for (int i = 0; i < inlineAccessor.getParameterTypes().length; i++) { UnresolvedType typeX = inlineAccessor.getParameterTypes()[i]; Type type = BcelWorld.makeBcelType(typeX); il.append(InstructionFactory.createLoad(type, register)); register += type.getSize(); } il.append( Utility.createInvoke( factory, Constants.INVOKESPECIAL, resolvedMember ) ); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(inlineAccessor.getReturnType()))); m_inlineAccessorBcelMethods.put( accessor, new BcelMethod(m_aspectGen.getBcelObjectType(), method.getMethod()) ); } return inlineAccessor; } /** * Add an inline wrapper for a non public field get * * @param resolvedMember * @return */ private ResolvedMember createOrGetInlineAccessorForFieldGet(ResolvedMember resolvedMember) { String accessor = NameMangler.inlineAccessMethodForFieldGet( resolvedMember.getName(), resolvedMember.getDeclaringType(), aspectType ); ResolvedMember inlineAccessor = (ResolvedMember) m_inlineAccessorBcelMethods.get(accessor); if (inlineAccessor == null) { // add static method to aspect inlineAccessor = AjcMemberMaker.inlineAccessMethodForFieldGet( aspectType, resolvedMember ); //add new accessor method to aspect bytecode InstructionFactory factory = m_aspectGen.getFactory(); LazyMethodGen method = makeMethodGen(m_aspectGen, inlineAccessor); // flag it synthetic, AjSynthetic method.makeSynthetic(); method.addAttribute( BcelAttributes.bcelAttribute(new AjAttribute.AjSynthetic(), m_aspectGen.getConstantPoolGen()) ); // flag the effective signature, so that we can deobfuscate the signature to apply method call pointcut method.addAttribute( BcelAttributes.bcelAttribute( new AjAttribute.EffectiveSignatureAttribute(resolvedMember, Shadow.FieldGet, false), m_aspectGen.getConstantPoolGen() ) ); m_inlineAccessorMethodGens.add(method); InstructionList il = method.getBody(); if (resolvedMember.isStatic()) { // field accessed is static so no "this" as accessor sole parameter } else { il.append(InstructionConstants.ALOAD_0); } il.append( Utility.createGet( factory, resolvedMember ) ); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(inlineAccessor.getReturnType()))); m_inlineAccessorBcelMethods.put( accessor, new BcelMethod(m_aspectGen.getBcelObjectType(), method.getMethod()) ); } return inlineAccessor; } /** * Add an inline wrapper for a non public field set * * @param resolvedMember * @return */ private ResolvedMember createOrGetInlineAccessorForFieldSet(ResolvedMember resolvedMember) { String accessor = NameMangler.inlineAccessMethodForFieldSet( resolvedMember.getName(), resolvedMember.getDeclaringType(), aspectType ); ResolvedMember inlineAccessor = (ResolvedMember) m_inlineAccessorBcelMethods.get(accessor); if (inlineAccessor == null) { // add static method to aspect inlineAccessor = AjcMemberMaker.inlineAccessMethodForFieldSet( aspectType, resolvedMember ); //add new accessor method to aspect bytecode InstructionFactory factory = m_aspectGen.getFactory(); LazyMethodGen method = makeMethodGen(m_aspectGen, inlineAccessor); // flag it synthetic, AjSynthetic method.makeSynthetic(); method.addAttribute( BcelAttributes.bcelAttribute(new AjAttribute.AjSynthetic(), m_aspectGen.getConstantPoolGen()) ); // flag the effective signature, so that we can deobfuscate the signature to apply method call pointcut method.addAttribute( BcelAttributes.bcelAttribute( new AjAttribute.EffectiveSignatureAttribute(resolvedMember, Shadow.FieldSet, false), m_aspectGen.getConstantPoolGen() ) ); m_inlineAccessorMethodGens.add(method); InstructionList il = method.getBody(); if (resolvedMember.isStatic()) { // field accessed is static so sole parameter is field value to be set il.append(InstructionFactory.createLoad(BcelWorld.makeBcelType(resolvedMember.getReturnType()), 0)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(BcelWorld.makeBcelType(resolvedMember.getReturnType()), 1)); } il.append( Utility.createSet( factory, resolvedMember ) ); il.append(InstructionConstants.RETURN); m_inlineAccessorBcelMethods.put( accessor, new BcelMethod(m_aspectGen.getBcelObjectType(), method.getMethod()) ); } return inlineAccessor; } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06: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.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) { 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())); } } 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); 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); 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); 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; } } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06: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 (UnresolvedType.SERIALIZABLE.resolve(getType().getWorld()).isAssignableFrom(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)); } } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/patterns/SignaturePattern.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.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.reflect.AdviceSignature; import org.aspectj.lang.reflect.ConstructorSignature; import org.aspectj.lang.reflect.FieldSignature; import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.Constants; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.JoinPointSignature; 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.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelTypeMunger; public class SignaturePattern extends PatternNode { private Member.Kind kind; private ModifiersPattern modifiers; private TypePattern returnType; private TypePattern declaringType; private NamePattern name; private TypePatternList parameterTypes; private ThrowsPattern throwsPattern; private AnnotationTypePattern annotationPattern; public SignaturePattern(Member.Kind kind, ModifiersPattern modifiers, TypePattern returnType, TypePattern declaringType, NamePattern name, TypePatternList parameterTypes, ThrowsPattern throwsPattern, AnnotationTypePattern annotationPattern) { this.kind = kind; this.modifiers = modifiers; this.returnType = returnType; this.name = name; this.declaringType = declaringType; this.parameterTypes = parameterTypes; this.throwsPattern = throwsPattern; this.annotationPattern = annotationPattern; } public SignaturePattern resolveBindings(IScope scope, Bindings bindings) { if (returnType != null) { returnType = returnType.resolveBindings(scope, bindings, false, false); } if (declaringType != null) { declaringType = declaringType.resolveBindings(scope, bindings, false, false); } if (parameterTypes != null) { parameterTypes = parameterTypes.resolveBindings(scope, bindings, false, false); } if (throwsPattern != null) { throwsPattern = throwsPattern.resolveBindings(scope, bindings); } if (annotationPattern != null) { annotationPattern = annotationPattern.resolveBindings(scope,bindings,false); } return this; } public void postRead(ResolvedType enclosingType) { if (returnType != null) { returnType.postRead(enclosingType); } if (declaringType != null) { declaringType.postRead(enclosingType); } if (parameterTypes != null) { parameterTypes.postRead(enclosingType); } } /** * return a copy of this signature pattern in which every type variable reference * is replaced by the corresponding entry in the map. */ public SignaturePattern parameterizeWith(Map typeVariableMap) { SignaturePattern ret = new SignaturePattern( kind, modifiers, returnType.parameterizeWith(typeVariableMap), declaringType.parameterizeWith(typeVariableMap), name, parameterTypes.parameterizeWith(typeVariableMap), throwsPattern.parameterizeWith(typeVariableMap), annotationPattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public boolean matches(Member joinPointSignature, World world, boolean allowBridgeMethods) { // fail (or succeed!) fast tests... if (joinPointSignature == null) return false; if (kind != joinPointSignature.getKind()) return false; if (kind == Member.ADVICE) return true; // do the hard work then... JoinPointSignature[] candidateMatches = joinPointSignature.getJoinPointSignatures(world); for (int i = 0; i < candidateMatches.length; i++) { if (matchesExactly(candidateMatches[i],world,allowBridgeMethods)) return true; } return false; } // Does this pattern match this exact signature (no declaring type mucking about // or chasing up the hierarchy) private boolean matchesExactly(JoinPointSignature aMember, World inAWorld, boolean allowBridgeMethods) { // Java5 introduces bridge methods, we match a call to them but nothing else... if (aMember.isBridgeMethod() && !allowBridgeMethods) { return false; } if (!modifiers.matches(aMember.getModifiers())) return false; boolean matchesIgnoringAnnotations = true; if (kind == Member.STATIC_INITIALIZATION) { matchesIgnoringAnnotations = matchesExactlyStaticInitialization(aMember, inAWorld); } else if (kind == Member.FIELD) { matchesIgnoringAnnotations = matchesExactlyField(aMember,inAWorld); } else if (kind == Member.METHOD) { matchesIgnoringAnnotations = matchesExactlyMethod(aMember,inAWorld); } else if (kind == Member.CONSTRUCTOR) { matchesIgnoringAnnotations = matchesExactlyConstructor(aMember, inAWorld); } if (!matchesIgnoringAnnotations) return false; return matchesAnnotations(aMember, inAWorld); } /** * Matches on declaring type */ private boolean matchesExactlyStaticInitialization(JoinPointSignature aMember,World world) { return declaringType.matchesStatically(aMember.getDeclaringType().resolve(world)); } /** * Matches on name, declaring type, field type */ private boolean matchesExactlyField(JoinPointSignature aField, World world) { if (!name.matches(aField.getName())) return false; if (!declaringType.matchesStatically(aField.getDeclaringType().resolve(world))) return false; if (!returnType.matchesStatically(aField.getReturnType().resolve(world))) { // looking bad, but there might be parameterization to consider... if (!returnType.matchesStatically(aField.getGenericReturnType().resolve(world))) { // ok, it's bad. return false; } } // passed all the guards... return true; } /** * Matches on name, declaring type, return type, parameter types, throws types */ private boolean matchesExactlyMethod(JoinPointSignature aMethod, World world) { if (!name.matches(aMethod.getName())) return false; if (!declaringType.matchesStatically(aMethod.getDeclaringType().resolve(world))) return false; if (!returnType.matchesStatically(aMethod.getReturnType().resolve(world))) { // looking bad, but there might be parameterization to consider... if (!returnType.matchesStatically(aMethod.getGenericReturnType().resolve(world))) { // ok, it's bad. return false; } } ResolvedType[] resolvedParameters = world.resolve(aMethod.getParameterTypes()); if (!parameterTypes.matches(resolvedParameters, TypePattern.STATIC).alwaysTrue()) { // It could still be a match based on the generic sig parameter types of a parameterized type if (!parameterTypes.matches(world.resolve(aMethod.getGenericParameterTypes()),TypePattern.STATIC).alwaysTrue()) { return false; // It could STILL be a match based on the erasure of the parameter types?? // to be determined via test cases... } } // check that varargs specifications match if (!matchesVarArgs(aMethod,world)) return false; // Check the throws pattern if (!throwsPattern.matches(aMethod.getExceptions(), world)) return false; // passed all the guards.. return true; } /** * match on declaring type, parameter types, throws types */ private boolean matchesExactlyConstructor(JoinPointSignature aConstructor, World world) { if (!declaringType.matchesStatically(aConstructor.getDeclaringType().resolve(world))) return false; ResolvedType[] resolvedParameters = world.resolve(aConstructor.getParameterTypes()); if (!parameterTypes.matches(resolvedParameters, TypePattern.STATIC).alwaysTrue()) { // It could still be a match based on the generic sig parameter types of a parameterized type if (!parameterTypes.matches(world.resolve(aConstructor.getGenericParameterTypes()),TypePattern.STATIC).alwaysTrue()) { return false; // It could STILL be a match based on the erasure of the parameter types?? // to be determined via test cases... } } // check that varargs specifications match if (!matchesVarArgs(aConstructor,world)) return false; // Check the throws pattern if (!throwsPattern.matches(aConstructor.getExceptions(), world)) return false; // passed all the guards.. return true; } /** * We've matched against this method or constructor so far, but without considering * varargs (which has been matched as a simple array thus far). Now we do the additional * checks to see if the parties agree on whether the last parameter is varargs or a * straight array. */ private boolean matchesVarArgs(JoinPointSignature aMethodOrConstructor, World inAWorld) { if (parameterTypes.size() == 0) return true; TypePattern lastPattern = parameterTypes.get(parameterTypes.size()-1); boolean canMatchVarArgsSignature = lastPattern.isStar() || lastPattern.isVarArgs() || (lastPattern == TypePattern.ELLIPSIS); if (aMethodOrConstructor.isVarargsMethod()) { // we have at least one parameter in the pattern list, and the method has a varargs signature if (!canMatchVarArgsSignature) { // XXX - Ideally the shadow would be included in the msg but we don't know it... inAWorld.getLint().cantMatchArrayTypeOnVarargs.signal(aMethodOrConstructor.toString(),getSourceLocation()); return false; } } else { // the method ends with an array type, check that we don't *require* a varargs if (lastPattern.isVarArgs()) return false; } return true; } private boolean matchesAnnotations(ResolvedMember member,World world) { if (member == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return false; } world.getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return false; } annotationPattern.resolve(world); // optimization before we go digging around for annotations on ITDs if (annotationPattern instanceof AnyAnnotationTypePattern) return true; // fake members represent ITD'd fields - for their annotations we should go and look up the // relevant member in the original aspect if (member.isAnnotatedElsewhere() && member.getKind()==Member.FIELD) { // FIXME asc duplicate of code in AnnotationPattern.matchInternal()? same fixmes apply here. ResolvedMember [] mems = member.getDeclaringType().resolve(world).getDeclaredFields(); // FIXME asc should include supers with getInterTypeMungersIncludingSupers? List mungers = member.getDeclaringType().resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); if (fakerm.equals(member)) { member = rmm; } } } } return annotationPattern.matches(member).alwaysTrue(); } 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; } public boolean declaringTypeMatchAllowingForCovariance(Member member, UnresolvedType shadowDeclaringType, World world,TypePattern returnTypePattern,ResolvedType sigReturn) { ResolvedType onType = shadowDeclaringType.resolve(world); // fastmatch if (declaringType.matchesStatically(onType) && returnTypePattern.matchesStatically(sigReturn)) return true; Collection declaringTypes = member.getDeclaringTypes(world); boolean checkReturnType = true; // XXX Possible enhancement? Doesn't seem to speed things up // if (returnTypePattern.isStar()) { // if (returnTypePattern instanceof WildTypePattern) { // if (((WildTypePattern)returnTypePattern).getDimensions()==0) checkReturnType = false; // } // } // Sometimes that list includes types that don't explicitly declare the member we are after - // they are on the list because their supertype is on the list, that's why we use // lookupMethod rather than lookupMemberNoSupers() for (Iterator i = declaringTypes.iterator(); i.hasNext(); ) { ResolvedType type = (ResolvedType)i.next(); if (declaringType.matchesStatically(type)) { if (!checkReturnType) return true; ResolvedMember rm = type.lookupMethod(member); if (rm==null) rm = type.lookupMethodInITDs(member); // It must be in here, or we have *real* problems if (rm==null) continue; // might be currently looking at the generic type and we need to continue searching in case we hit a parameterized version of this same type... UnresolvedType returnTypeX = rm.getReturnType(); ResolvedType returnType = returnTypeX.resolve(world); if (returnTypePattern.matchesStatically(returnType)) return true; } } return false; } private Collection getDeclaringTypes(Signature sig) { List l = new ArrayList(); Class onType = sig.getDeclaringType(); String memberName = sig.getName(); if (sig instanceof FieldSignature) { Class fieldType = ((FieldSignature)sig).getFieldType(); Class superType = onType; while(superType != null) { try { Field f = (superType.getDeclaredField(memberName)); if (f.getType() == fieldType) { l.add(superType); } } catch (NoSuchFieldException nsf) {} superType = superType.getSuperclass(); } } else if (sig instanceof MethodSignature) { Class[] paramTypes = ((MethodSignature)sig).getParameterTypes(); Class superType = onType; while(superType != null) { try { superType.getDeclaredMethod(memberName,paramTypes); l.add(superType); } catch (NoSuchMethodException nsm) {} superType = superType.getSuperclass(); } } return l; } public NamePattern getName() { return name; } public TypePattern getDeclaringType() { return declaringType; } public Member.Kind getKind() { return kind; } public String toString() { StringBuffer buf = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append(annotationPattern.toString()); buf.append(' '); } if (modifiers != ModifiersPattern.ANY) { buf.append(modifiers.toString()); buf.append(' '); } if (kind == Member.STATIC_INITIALIZATION) { buf.append(declaringType.toString()); buf.append(".<clinit>()");//FIXME AV - bad, cannot be parsed again } else if (kind == Member.HANDLER) { buf.append("handler("); buf.append(parameterTypes.get(0)); buf.append(")"); } else { if (!(kind == Member.CONSTRUCTOR)) { buf.append(returnType.toString()); buf.append(' '); } if (declaringType != TypePattern.ANY) { buf.append(declaringType.toString()); buf.append('.'); } if (kind == Member.CONSTRUCTOR) { buf.append("new"); } else { buf.append(name.toString()); } if (kind == Member.METHOD || kind == Member.CONSTRUCTOR) { buf.append(parameterTypes.toString()); } //FIXME AV - throws is not printed here, weird } return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof SignaturePattern)) return false; SignaturePattern o = (SignaturePattern)other; return o.kind.equals(this.kind) && o.modifiers.equals(this.modifiers) && o.returnType.equals(this.returnType) && o.declaringType.equals(this.declaringType) && o.name.equals(this.name) && o.parameterTypes.equals(this.parameterTypes) && o.throwsPattern.equals(this.throwsPattern) && o.annotationPattern.equals(this.annotationPattern); } public int hashCode() { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + modifiers.hashCode(); result = 37*result + returnType.hashCode(); result = 37*result + declaringType.hashCode(); result = 37*result + name.hashCode(); result = 37*result + parameterTypes.hashCode(); result = 37*result + throwsPattern.hashCode(); result = 37*result + annotationPattern.hashCode(); return result; } public void write(DataOutputStream s) throws IOException { kind.write(s); modifiers.write(s); returnType.write(s); declaringType.write(s); name.write(s); parameterTypes.write(s); throwsPattern.write(s); annotationPattern.write(s); writeLocation(s); } public static SignaturePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { Member.Kind kind = Member.Kind.read(s); ModifiersPattern modifiers = ModifiersPattern.read(s); TypePattern returnType = TypePattern.read(s, context); TypePattern declaringType = TypePattern.read(s, context); NamePattern name = NamePattern.read(s); TypePatternList parameterTypes = TypePatternList.read(s, context); ThrowsPattern throwsPattern = ThrowsPattern.read(s, context); AnnotationTypePattern annotationPattern = AnnotationTypePattern.ANY; if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { annotationPattern = AnnotationTypePattern.read(s,context); } SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType, name, parameterTypes, throwsPattern,annotationPattern); ret.readLocation(context, s); return ret; } /** * @return */ public ModifiersPattern getModifiers() { return modifiers; } /** * @return */ public TypePatternList getParameterTypes() { return parameterTypes; } /** * @return */ public TypePattern getReturnType() { return returnType; } /** * @return */ public ThrowsPattern getThrowsPattern() { return throwsPattern; } /** * return true if last argument in params is an Object[] but the modifiers say this method * was declared with varargs (Object...). We shouldn't be matching if this is the case. */ private boolean matchedArrayAgainstVarArgs(TypePatternList params,int modifiers) { if (params.size()>0 && (modifiers & Constants.ACC_VARARGS)!=0) { // we have at least one parameter in the pattern list, and the method has a varargs signature TypePattern lastPattern = params.get(params.size()-1); if (lastPattern.isArray() && !lastPattern.isVarArgs) return true; } return false; } public AnnotationTypePattern getAnnotationPattern() { return annotationPattern; } public boolean isStarAnnotation() { return annotationPattern == AnnotationTypePattern.ANY; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/patterns/TypePatternList.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.List; import java.util.Map; import org.aspectj.util.FuzzyBoolean; 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; public class TypePatternList extends PatternNode { private TypePattern[] typePatterns; int ellipsisCount = 0; public static final TypePatternList EMPTY = new TypePatternList(new TypePattern[] {}); public static final TypePatternList ANY = new TypePatternList(new TypePattern[] {new EllipsisTypePattern()}); //can't use TypePattern.ELLIPSIS because of circular static dependency that introduces public TypePatternList() { typePatterns = new TypePattern[0]; ellipsisCount = 0; } public TypePatternList(TypePattern[] arguments) { this.typePatterns = arguments; for (int i=0; i<arguments.length; i++) { if (arguments[i] == TypePattern.ELLIPSIS) ellipsisCount++; } } public TypePatternList(List l) { this((TypePattern[]) l.toArray(new TypePattern[l.size()])); } public int size() { return typePatterns.length; } public TypePattern get(int index) { return typePatterns[index]; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("("); for (int i=0, len=typePatterns.length; i < len; i++) { TypePattern type = typePatterns[i]; if (i > 0) buf.append(", "); if (type == TypePattern.ELLIPSIS) { buf.append(".."); } else { buf.append(type.toString()); } } buf.append(")"); return buf.toString(); } //XXX shares much code with WildTypePattern and with NamePattern /** * When called with TypePattern.STATIC this will always return either * FuzzyBoolean.YES or FuzzyBoolean.NO. * * When called with TypePattern.DYNAMIC this could return MAYBE if * at runtime it would be possible for arguments of the given static * types to dynamically match this, but it is not known for certain. * * This method will never return FuzzyBoolean.NEVER */ public FuzzyBoolean matches(ResolvedType[] types, TypePattern.MatchKind kind) { int nameLength = types.length; int patternLength = typePatterns.length; int nameIndex = 0; int patternIndex = 0; if (ellipsisCount == 0) { if (nameLength != patternLength) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (patternIndex < patternLength) { FuzzyBoolean ret = typePatterns[patternIndex++].matches(types[nameIndex++], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; } return finalReturn; } else if (ellipsisCount == 1) { if (nameLength < patternLength-1) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (patternIndex < patternLength) { TypePattern p = typePatterns[patternIndex++]; if (p == TypePattern.ELLIPSIS) { nameIndex = nameLength - (patternLength-patternIndex); } else { FuzzyBoolean ret = p.matches(types[nameIndex++], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; } } return finalReturn; } else { // System.err.print("match(" + arguments + ", " + types + ") -> "); FuzzyBoolean b = outOfStar(typePatterns, types, 0, 0, patternLength - ellipsisCount, nameLength, ellipsisCount, kind); // System.err.println(b); return b; } } private static FuzzyBoolean outOfStar(final TypePattern[] pattern, final ResolvedType[] target, int pi, int ti, int pLeft, int tLeft, final int starsLeft, TypePattern.MatchKind kind) { if (pLeft > tLeft) return FuzzyBoolean.NO; FuzzyBoolean finalReturn = FuzzyBoolean.YES; while (true) { // invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length) if (tLeft == 0) return finalReturn; if (pLeft == 0) { if (starsLeft > 0) { return finalReturn; } else { return FuzzyBoolean.NO; } } if (pattern[pi] == TypePattern.ELLIPSIS) { return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1, kind); } FuzzyBoolean ret = pattern[pi].matches(target[ti], kind); if (ret == FuzzyBoolean.NO) return ret; if (ret == FuzzyBoolean.MAYBE) finalReturn = ret; pi++; ti++; pLeft--; tLeft--; } } private static FuzzyBoolean inStar(final TypePattern[] pattern, final ResolvedType[] target, int pi, int ti, final int pLeft, int tLeft, int starsLeft, TypePattern.MatchKind kind) { // invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern TypePattern patternChar = pattern[pi]; while (patternChar == TypePattern.ELLIPSIS) { starsLeft--; patternChar = pattern[++pi]; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length) if (pLeft > tLeft) return FuzzyBoolean.NO; FuzzyBoolean ff = patternChar.matches(target[ti], kind); if (ff.maybeTrue()) { FuzzyBoolean xx = outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft, kind); if (xx.maybeTrue()) return ff.and(xx); } ti++; tLeft--; } } /** * Return a version of this type pattern list in which all type variable references * are replaced by their corresponding entry in the map * @param typeVariableMap * @return */ public TypePatternList parameterizeWith(Map typeVariableMap) { TypePattern[] parameterizedPatterns = new TypePattern[typePatterns.length]; for (int i = 0; i < parameterizedPatterns.length; i++) { parameterizedPatterns[i] = typePatterns[i].parameterizeWith(typeVariableMap); } return new TypePatternList(parameterizedPatterns); } public TypePatternList resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { for (int i=0; i<typePatterns.length; i++) { TypePattern p = typePatterns[i]; if (p != null) { typePatterns[i] = typePatterns[i].resolveBindings(scope, bindings, allowBinding, requireExactType); } } return this; } public TypePatternList resolveReferences(IntMap bindings) { int len = typePatterns.length; TypePattern[] ret = new TypePattern[len]; for (int i=0; i < len; i++) { ret[i] = typePatterns[i].remapAdviceFormals(bindings); } return new TypePatternList(ret); } public void postRead(ResolvedType enclosingType) { for (int i=0; i<typePatterns.length; i++) { TypePattern p = typePatterns[i]; p.postRead(enclosingType); } } public boolean equals(Object other) { if (!(other instanceof TypePatternList)) return false; TypePatternList o = (TypePatternList)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 TypePatternList read(VersionedDataInputStream s, ISourceContext context) throws IOException { short len = s.readShort(); TypePattern[] arguments = new TypePattern[len]; for (int i=0; i<len; i++) { arguments[i] = TypePattern.read(s, context); } TypePatternList ret = new TypePatternList(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 TypePattern[] getTypePatterns() { return typePatterns; } public Collection getExactTypes() { ArrayList ret = new ArrayList(); for (int i=0; i<typePatterns.length; i++) { UnresolvedType t = typePatterns[i].getExactType(); if (t != ResolvedType.MISSING) ret.add(t); } return ret; } 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; } public boolean areAllExactWithNoSubtypesAllowed() { for (int i = 0; i < typePatterns.length; i++) { TypePattern array_element = typePatterns[i]; if (!(array_element instanceof ExactTypePattern)) { return false; } else { ExactTypePattern etp = (ExactTypePattern) array_element; if (etp.isIncludeSubtypes()) return false; } } return true; } public String[] maybeGetCleanNames() { String[] theParamNames = new String[typePatterns.length]; for (int i = 0; i < typePatterns.length; i++) { TypePattern string = typePatterns[i]; if (!(string instanceof ExactTypePattern)) return null; theParamNames[i] = ((ExactTypePattern)string).getExactType().getName(); } return theParamNames; } }
77,076
Bug 77076 Weaving into jar fails if some of the referred classes are unavailable
I am trying to profile JDBC access in a Spring-based application. Since all the JDBC interaction is performed through Spring classes, I need to weave into spring.jar. However, many of the classes referred by spring.jar aren't available to me (I am not using the functionality implemented by many of the classes). When I try to weave into spring.jar I get errors complaining that it can't find types for those classes. I expected that ajc would ignore unknown classes unless weaving would be affected by content/API of those classes. Using jar files that refer to foreign classes that one may never have/need is a common scenario. For example, spring.jar refers to Velocity, Struts, JDO, Hibernate, Quartz classes; I am unlikely to use all of these referred frameworks in an application. This bug/limitation prevents using AspectJ with such jars. To reproduce the bug in a controlled environment, I created the following aspect which should make the weaving process a pass-thru filter (no join point is matched by the pointcut) class TemporaryClass { } public aspect NoWeaveAspect { before() : call(* TemporaryClass.*(..)) && within(org.spring..*) { } } Weaving this aspect with spring.jar should result in logically identical jar file. However, when I compile using the following command (or equivalent ant task), I get the following errors: C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -version AspectJ Compiler 1.2.1rc1 built on Friday Oct 22, 2004 at 13:31:47 GMT C:\work\aop\bugs\injar-with-nonexisting-classes>ajc -injars spring.jar -outjar s pring-woven.jar NoWeaveAspect.java C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.xml.JobSchedulingDataProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.StatefulJob (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.SimpleTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe freemarker.cache.TemplateLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.CronTrigger (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.JobDetail (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.Job (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.quartz.impl.jdbcjobstore.JobStoreCMT (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.PlugIn (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.NumberTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.Action (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.tiles.TilesRequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.struts.action.RequestProcessor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.resource.loader.ResourceLoader (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.runtime.log.LogSystem (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe javax.faces.el.VariableResolver (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.velocity.tools.generic.DateTool (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.attributes.AttributeRepositoryClass (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.commons.pool.PoolableObjectFactory (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.Dispatcher (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInvocation (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.NoOp (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.transaction.TransactionManagerLookup (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.connection.ConnectionProvider (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.hibernate.UserType (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.apache.ojb.broker.accesslayer.ConnectionFactoryManagedImpl (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe net.sf.cglib.proxy.CallbackFilter (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) C:\work\aop\bugs\injar-with-nonexisting-classes\spring.jar [error] can't find ty pe org.aopalliance.intercept.MethodInterceptor (no source information available) 41 errors
resolved fixed
a4a9090
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-24T09:34:13Z
2004-10-27T04:06:40Z
weaver/src/org/aspectj/weaver/patterns/WildTypePattern.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.List; import java.util.Map; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.BoundedReferenceType; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeFactory; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.UnresolvedTypeVariableReferenceType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * The PatternParser always creates WildTypePatterns for type patterns in pointcut * expressions (apart from *, which is sometimes directly turned into TypePattern.ANY). * resolveBindings() tries to work out what we've really got and turn it into a type * pattern that we can use for matching. This will normally be either an ExactTypePattern * or a WildTypePattern. * * Here's how the process pans out for various generic and parameterized patterns: * (see GenericsWildTypePatternResolvingTestCase) * * Foo where Foo exists and is generic * Parser creates WildTypePattern namePatterns={Foo} * resolveBindings resolves Foo to RT(Foo - raw) * return ExactTypePattern(LFoo;) * * Foo<String> where Foo exists and String meets the bounds * Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{String} * resolveBindings resolves typeParameters to ExactTypePattern(String) * resolves Foo to RT(Foo) * returns ExactTypePattern(PFoo<String>; - parameterized) * * Foo<Str*> where Foo exists and takes one bound * Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{Str*} * resolveBindings resolves typeParameters to WTP{Str*} * resolves Foo to RT(Foo) * returns WildTypePattern(name = Foo, typeParameters = WTP{Str*} isGeneric=false) * * Fo*<String> * Parser creates WildTypePattern namePatterns = {Fo*}, typeParameters=WTP{String} * resolveBindings resolves typeParameters to ETP{String} * returns WildTypePattern(name = Fo*, typeParameters = ETP{String} isGeneric=false) * * * Foo<?> * * Foo<? extends Number> * * Foo<? extends Number+> * * Foo<? super Number> * */ public class WildTypePattern extends TypePattern { private static final String GENERIC_WILDCARD_CHARACTER = "?"; private NamePattern[] namePatterns; int ellipsisCount; String[] importedPrefixes; String[] knownMatches; int dim; // these next three are set if the type pattern is constrained by extends or super clauses, in which case the // namePatterns must have length 1 // TODO AMC: read/write/resolve of these fields TypePattern upperBound; // extends Foo TypePattern[] additionalInterfaceBounds; // extends Foo & A,B,C TypePattern lowerBound; // super Foo // if we have type parameters, these fields indicate whether we should be a generic type pattern or a parameterized // type pattern. We can only tell during resolve bindings. private boolean isGeneric = true; WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim, boolean isVarArgs, TypePatternList typeParams) { super(includeSubtypes,isVarArgs,typeParams); this.namePatterns = namePatterns; this.dim = dim; ellipsisCount = 0; for (int i=0; i<namePatterns.length; i++) { if (namePatterns[i] == NamePattern.ELLIPSIS) ellipsisCount++; } setLocation(namePatterns[0].getSourceContext(), namePatterns[0].getStart(), namePatterns[namePatterns.length-1].getEnd()); } public WildTypePattern(List names, boolean includeSubtypes, int dim) { this((NamePattern[])names.toArray(new NamePattern[names.size()]), includeSubtypes, dim,false,TypePatternList.EMPTY); } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) { this(names, includeSubtypes, dim); this.end = endPos; } public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg) { this(names, includeSubtypes, dim); this.end = endPos; this.isVarArgs = isVarArg; } public WildTypePattern( List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg, TypePatternList typeParams, TypePattern upperBound, TypePattern[] additionalInterfaceBounds, TypePattern lowerBound) { this((NamePattern[])names.toArray(new NamePattern[names.size()]),includeSubtypes,dim,isVarArg,typeParams); this.end = endPos; this.upperBound = upperBound; this.lowerBound = lowerBound; this.additionalInterfaceBounds = additionalInterfaceBounds; } public WildTypePattern( List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg, TypePatternList typeParams) { this((NamePattern[])names.toArray(new NamePattern[names.size()]),includeSubtypes,dim,isVarArg,typeParams); this.end = endPos; } public NamePattern[] getNamePatterns() { return namePatterns; } public TypePattern getUpperBound() { return upperBound; } public TypePattern getLowerBound() { return lowerBound; } public TypePattern[] getAdditionalIntefaceBounds() { return additionalInterfaceBounds; } // called by parser after parsing a type pattern, must bump dim as well as setting flag public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; if (isVarArgs) this.dim += 1; } /* (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) { if (namePatterns.length > 0) { if (!namePatterns[0].matches(otherType.getName())) return false; } } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String mySimpleName = namePatterns[0].maybeGetSimpleName(); String yourSimpleName = owtp.namePatterns[0].maybeGetSimpleName(); if (mySimpleName != null && yourSimpleName != null) { return (mySimpleName.startsWith(yourSimpleName) || yourSimpleName.startsWith(mySimpleName)); } } return true; } //XXX inefficient implementation public static char[][] splitNames(String s) { List ret = new ArrayList(); int startIndex = 0; while (true) { int breakIndex = s.indexOf('.', startIndex); // what about / if (breakIndex == -1) breakIndex = s.indexOf('$', startIndex); // we treat $ like . here if (breakIndex == -1) break; char[] name = s.substring(startIndex, breakIndex).toCharArray(); ret.add(name); startIndex = breakIndex+1; } ret.add(s.substring(startIndex).toCharArray()); return (char[][])ret.toArray(new char[ret.size()][]); } /** * @see org.aspectj.weaver.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return matchesExactly(type,type); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { String targetTypeName = type.getName(); //System.err.println("match: " + targetTypeName + ", " + knownMatches); //Arrays.asList(importedPrefixes)); // Ensure the annotation pattern is resolved annotationPattern.resolve(type.getWorld()); return matchesExactlyByName(targetTypeName) && matchesParameters(type,STATIC) && matchesBounds(type,STATIC) && annotationPattern.matches(annotatedType).alwaysTrue(); } // we've matched against the base (or raw) type, but if this type pattern specifies parameters or // type variables we need to make sure we match against them too private boolean matchesParameters(ResolvedType aType, MatchKind staticOrDynamic) { if (!isGeneric && typeParameters.size() > 0) { if(!aType.isParameterizedType()) return false; // we have to match type parameters return typeParameters.matches(aType.getResolvedTypeParameters(), staticOrDynamic).alwaysTrue(); } return true; } // we've matched against the base (or raw) type, but if this type pattern specifies bounds because // it is a ? extends or ? super deal then we have to match them too. private boolean matchesBounds(ResolvedType aType, MatchKind staticOrDynamic) { if (upperBound == null && aType.getUpperBound() != null) { // for upper bound, null can also match against Object - but anything else and we're out. if (!aType.getUpperBound().getName().equals(UnresolvedType.OBJECT.getName())) { return false; } } if (lowerBound == null && aType.getLowerBound() != null) return false; if (upperBound != null) { // match ? extends if (aType.isGenericWildcard() && aType.isSuper()) return false; if (aType.getUpperBound() == null) return false; return upperBound.matches((ResolvedType)aType.getUpperBound(),staticOrDynamic).alwaysTrue(); } if (lowerBound != null) { // match ? super if (!(aType.isGenericWildcard() && aType.isSuper())) return false; return lowerBound.matches((ResolvedType)aType.getLowerBound(),staticOrDynamic).alwaysTrue(); } return true; } /** * Used in conjunction with checks on 'isStar()' to tell you if this pattern represents '*' or '*[]' which are * different ! */ public int getDimensions() { return dim; } public boolean isArray() { return dim > 1; } /** * @param targetTypeName * @return */ private boolean matchesExactlyByName(String targetTypeName) { // we deal with parameter matching separately... if (targetTypeName.indexOf('<') != -1) { targetTypeName = targetTypeName.substring(0,targetTypeName.indexOf('<')); } // we deal with bounds matching separately too... if (targetTypeName.startsWith(GENERIC_WILDCARD_CHARACTER)) { targetTypeName = GENERIC_WILDCARD_CHARACTER; } //XXX hack if (knownMatches == null && importedPrefixes == null) { return innerMatchesExactly(targetTypeName); } if (isNamePatternStar()) { // we match if the dimensions match int numDimensionsInTargetType = 0; if (dim > 0) { int index; while((index = targetTypeName.indexOf('[')) != -1) { numDimensionsInTargetType++; targetTypeName = targetTypeName.substring(index+1); } if (numDimensionsInTargetType == dim) { return true; } else { return false; } } } // if our pattern is length 1, then known matches are exact matches // if it's longer than that, then known matches are prefixes of a sort if (namePatterns.length == 1) { for (int i=0, len=knownMatches.length; i < len; i++) { if (knownMatches[i].equals(targetTypeName)) return true; } } else { for (int i=0, len=knownMatches.length; i < len; i++) { String knownPrefix = knownMatches[i] + "$"; if (targetTypeName.startsWith(knownPrefix)) { int pos = lastIndexOfDotOrDollar(knownMatches[i]); if (innerMatchesExactly(targetTypeName.substring(pos+1))) { return true; } } } } // if any prefixes match, strip the prefix and check that the rest matches // assumes that prefixes have a dot at the end for (int i=0, len=importedPrefixes.length; i < len; i++) { String prefix = importedPrefixes[i]; //System.err.println("prefix match? " + prefix + " to " + targetTypeName); if (targetTypeName.startsWith(prefix)) { if (innerMatchesExactly(targetTypeName.substring(prefix.length()))) { return true; } } } return innerMatchesExactly(targetTypeName); } private int lastIndexOfDotOrDollar(String string) { int dot = string.lastIndexOf('.'); int dollar = string.lastIndexOf('$'); return Math.max(dot, dollar); } private boolean innerMatchesExactly(String targetTypeName) { //??? doing this everytime is not very efficient char[][] names = splitNames(targetTypeName); return innerMatchesExactly(names); } private boolean innerMatchesExactly(char[][] names) { int namesLength = names.length; int patternsLength = namePatterns.length; int namesIndex = 0; int patternsIndex = 0; if (ellipsisCount == 0) { if (namesLength != patternsLength) return false; while (patternsIndex < patternsLength) { if (!namePatterns[patternsIndex++].matches(names[namesIndex++])) { return false; } } return true; } else if (ellipsisCount == 1) { if (namesLength < patternsLength-1) return false; while (patternsIndex < patternsLength) { NamePattern p = namePatterns[patternsIndex++]; if (p == NamePattern.ELLIPSIS) { namesIndex = namesLength - (patternsLength-patternsIndex); } else { if (!p.matches(names[namesIndex++])) { return false; } } } return true; } else { // System.err.print("match(\"" + Arrays.asList(namePatterns) + "\", \"" + Arrays.asList(names) + "\") -> "); boolean b = outOfStar(namePatterns, names, 0, 0, patternsLength - ellipsisCount, namesLength, ellipsisCount); // System.err.println(b); return b; } } private static boolean outOfStar(final NamePattern[] pattern, final char[][] target, int pi, int ti, int pLeft, int tLeft, final int starsLeft) { if (pLeft > tLeft) return false; while (true) { // invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length) if (tLeft == 0) return true; if (pLeft == 0) { return (starsLeft > 0); } if (pattern[pi] == NamePattern.ELLIPSIS) { return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1); } if (! pattern[pi].matches(target[ti])) { return false; } pi++; ti++; pLeft--; tLeft--; } } private static boolean inStar(final NamePattern[] pattern, final char[][] target, int pi, int ti, final int pLeft, int tLeft, int starsLeft) { // invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern // of course, we probably can't parse multiple ..'s in a row, but this keeps the algorithm // exactly parallel with that in NamePattern NamePattern patternChar = pattern[pi]; while (patternChar == NamePattern.ELLIPSIS) { starsLeft--; patternChar = pattern[++pi]; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length) if (pLeft > tLeft) return false; if (patternChar.matches(target[ti])) { if (outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft)) return true; } ti++; tLeft--; } } /** * @see org.aspectj.weaver.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { //XXX hack to let unmatched types just silently remain so if (maybeGetSimpleName() != null) return FuzzyBoolean.NO; type.getWorld().getMessageHandler().handleMessage( new Message("can't do instanceof matching on patterns with wildcards", IMessage.ERROR, null, getSourceLocation())); return FuzzyBoolean.NO; } public NamePattern extractName() { if (isIncludeSubtypes() || isVarArgs() || isArray() || (typeParameters.size() > 0)) { // we can't extract a name, the pattern is something like Foo+ and therefore // it is not ok to treat Foo as a method name! return null; } //System.err.println("extract from : " + Arrays.asList(namePatterns)); int len = namePatterns.length; if (len ==1 && !annotationPattern.isAny()) return null; // can't extract NamePattern ret = namePatterns[len-1]; NamePattern[] newNames = new NamePattern[len-1]; System.arraycopy(namePatterns, 0, newNames, 0, len-1); namePatterns = newNames; //System.err.println(" left : " + Arrays.asList(namePatterns)); return ret; } /** * Method maybeExtractName. * @param string * @return boolean */ public boolean maybeExtractName(String string) { int len = namePatterns.length; NamePattern ret = namePatterns[len-1]; String simple = ret.maybeGetSimpleName(); if (simple != null && simple.equals(string)) { extractName(); return true; } return false; } /** * If this type pattern has no '.' or '*' in it, then * return a simple string * * otherwise, this will return null; */ public String maybeGetSimpleName() { if (namePatterns.length == 1) { return namePatterns[0].maybeGetSimpleName(); } return null; } /** * If this type pattern has no '*' or '..' in it */ public String maybeGetCleanName() { if (namePatterns.length == 0) { throw new RuntimeException("bad name: " + namePatterns); } //System.out.println("get clean: " + this); StringBuffer buf = new StringBuffer(); for (int i=0, len=namePatterns.length; i < len; i++) { NamePattern p = namePatterns[i]; String simpleName = p.maybeGetSimpleName(); if (simpleName == null) return null; if (i > 0) buf.append("."); buf.append(simpleName); } //System.out.println(buf); return buf.toString(); } public TypePattern parameterizeWith(Map typeVariableMap) { WildTypePattern ret = new WildTypePattern( namePatterns, includeSubtypes, dim, isVarArgs, typeParameters.parameterizeWith(typeVariableMap) ); ret.annotationPattern = this.annotationPattern.parameterizeWith(typeVariableMap); ret.additionalInterfaceBounds = new TypePattern[additionalInterfaceBounds.length]; for (int i = 0; i < additionalInterfaceBounds.length; i++) { ret.additionalInterfaceBounds[i] = additionalInterfaceBounds[i].parameterizeWith(typeVariableMap); } ret.upperBound = upperBound.parameterizeWith(typeVariableMap); ret.lowerBound = lowerBound.parameterizeWith(typeVariableMap); ret.isGeneric = isGeneric; ret.knownMatches = knownMatches; ret.importedPrefixes = importedPrefixes; ret.copyLocationFrom(this); return ret; } /** * Need to determine if I'm really a pattern or a reference to a formal * * We may wish to further optimize the case of pattern vs. non-pattern * * We will be replaced by what we return */ public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (isNamePatternStar()) { TypePattern anyPattern = maybeResolveToAnyPattern(scope, bindings, allowBinding, requireExactType); if (anyPattern != null) { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } else { return anyPattern; } } } TypePattern bindingTypePattern = maybeResolveToBindingTypePattern(scope, bindings, allowBinding, requireExactType); if (bindingTypePattern != null) return bindingTypePattern; annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); // resolve any type parameters if (typeParameters!=null && typeParameters.size()>0) { typeParameters.resolveBindings(scope,bindings,allowBinding,requireExactType); isGeneric = false; } // resolve any bounds if (upperBound != null) upperBound = upperBound.resolveBindings(scope, bindings, allowBinding, requireExactType); if (lowerBound != null) lowerBound = lowerBound.resolveBindings(scope, bindings, allowBinding, requireExactType); // amc - additional interface bounds only needed if we support type vars again. String fullyQualifiedName = maybeGetCleanName(); if (fullyQualifiedName != null) { return resolveBindingsFromFullyQualifiedTypeName(fullyQualifiedName, scope, bindings, allowBinding, requireExactType); } else { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; // pattern contains wildcards so can't be resolved to an ExactTypePattern... //XXX need to implement behavior for Lint.invalidWildcardTypeName } } private TypePattern maybeResolveToAnyPattern(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { // If there is an annotation specified we have to // use a special variant of Any TypePattern called // AnyWithAnnotation if (annotationPattern == AnnotationTypePattern.ANY) { if (dim == 0 && !isVarArgs && upperBound == null && lowerBound == null && (additionalInterfaceBounds == null || additionalInterfaceBounds.length==0)) { // pr72531 return TypePattern.ANY; //??? loses source location } } else { annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annotationPattern); ret.setLocation(sourceContext,start,end); return ret; } return null; // can't resolve to a simple "any" pattern } private TypePattern maybeResolveToBindingTypePattern(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { String simpleName = maybeGetSimpleName(); if (simpleName != null) { FormalBinding formalBinding = scope.lookupFormal(simpleName); if (formalBinding != null) { if (bindings == null) { scope.message(IMessage.ERROR, this, "negation doesn't allow binding"); return this; } if (!allowBinding) { scope.message(IMessage.ERROR, this, "name binding only allowed in target, this, and args pcds"); return this; } BindingTypePattern binding = new BindingTypePattern(formalBinding,isVarArgs); binding.copyLocationFrom(this); bindings.register(binding, scope); return binding; } } return null; // not possible to resolve to a binding type pattern } private TypePattern resolveBindingsFromFullyQualifiedTypeName(String fullyQualifiedName, IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { String originalName = fullyQualifiedName; ResolvedType resolvedTypeInTheWorld = null; UnresolvedType type; //System.out.println("resolve: " + cleanName); //??? this loop has too many inefficiencies to count resolvedTypeInTheWorld = lookupTypeInWorld(scope.getWorld(), fullyQualifiedName); if (resolvedTypeInTheWorld.isGenericWildcard()) { type = resolvedTypeInTheWorld; } else { type = lookupTypeInScope(scope, fullyQualifiedName, this); } if (type == ResolvedType.MISSING) { return resolveBindingsForMissingType(resolvedTypeInTheWorld, originalName, scope, bindings, allowBinding, requireExactType); } else { return resolveBindingsForExactType(scope,type,fullyQualifiedName,requireExactType); } } private UnresolvedType lookupTypeInScope(IScope scope, String typeName, IHasPosition location) { UnresolvedType type = null; while ((type = scope.lookupType(typeName, location)) == ResolvedType.MISSING) { int lastDot = typeName.lastIndexOf('.'); if (lastDot == -1) break; typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot+1); } return type; } private ResolvedType lookupTypeInWorld(World world, String typeName) { ResolvedType ret = world.resolve(UnresolvedType.forName(typeName),true); while (ret == ResolvedType.MISSING) { int lastDot = typeName.lastIndexOf('.'); if (lastDot == -1) break; typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot+1); ret = world.resolve(UnresolvedType.forName(typeName),true); } return ret; } private TypePattern resolveBindingsForExactType(IScope scope, UnresolvedType aType, String fullyQualifiedName,boolean requireExactType) { TypePattern ret = null; if (aType.isTypeVariableReference()) { // we have to set the bounds on it based on the bounds of this pattern ret = resolveBindingsForTypeVariable(scope, (UnresolvedTypeVariableReferenceType) aType); } else if (typeParameters.size()>0) { ret = resolveParameterizedType(scope, aType, requireExactType); } else if (upperBound != null || lowerBound != null) { // this must be a generic wildcard with bounds ret = resolveGenericWildcard(scope, aType); } else { if (dim != 0) aType = UnresolvedType.makeArray(aType, dim); ret = new ExactTypePattern(aType,includeSubtypes,isVarArgs); } ret.setAnnotationTypePattern(annotationPattern); ret.copyLocationFrom(this); return ret; } private TypePattern resolveGenericWildcard(IScope scope, UnresolvedType aType) { if (!aType.getSignature().equals(GENERIC_WILDCARD_CHARACTER)) throw new IllegalStateException("Can only have bounds for a generic wildcard"); boolean canBeExact = true; if ((upperBound != null) && (upperBound.getExactType() == ResolvedType.MISSING)) canBeExact = false; if ((lowerBound != null) && (lowerBound.getExactType() == ResolvedType.MISSING)) canBeExact = false; if (canBeExact) { ResolvedType type = null; if (upperBound != null) { if (upperBound.isIncludeSubtypes()) { canBeExact = false; } else { ReferenceType upper = (ReferenceType) upperBound.getExactType().resolve(scope.getWorld()); type = new BoundedReferenceType(upper,true,scope.getWorld()); } } else { if (lowerBound.isIncludeSubtypes()) { canBeExact = false; } else { ReferenceType lower = (ReferenceType) lowerBound.getExactType().resolve(scope.getWorld()); type = new BoundedReferenceType(lower,false,scope.getWorld()); } } if (canBeExact) { // might have changed if we find out include subtypes is set on one of the bounds... return new ExactTypePattern(type,includeSubtypes,isVarArgs); } } // we weren't able to resolve to an exact type pattern... // leave as wild type pattern importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } private TypePattern resolveParameterizedType(IScope scope, UnresolvedType aType, boolean requireExactType) { if (!verifyTypeParameters(aType.resolve(scope.getWorld()),scope,requireExactType)) return TypePattern.NO; // messages already isued // Only if the type is exact *and* the type parameters are exact should we create an // ExactTypePattern for this WildTypePattern if (typeParameters.areAllExactWithNoSubtypesAllowed()) { TypePattern[] typePats = typeParameters.getTypePatterns(); UnresolvedType[] typeParameterTypes = new UnresolvedType[typePats.length]; for (int i = 0; i < typeParameterTypes.length; i++) { typeParameterTypes[i] = ((ExactTypePattern)typePats[i]).getExactType(); } ResolvedType type = TypeFactory.createParameterizedType(aType.resolve(scope.getWorld()), typeParameterTypes, scope.getWorld()); if (isGeneric) type = type.getGenericType(); // UnresolvedType tx = UnresolvedType.forParameterizedTypes(aType,typeParameterTypes); // UnresolvedType type = scope.getWorld().resolve(tx,true); if (dim != 0) type = ResolvedType.makeArray(type, dim); return new ExactTypePattern(type,includeSubtypes,isVarArgs); } else { // AMC... just leave it as a wild type pattern then? importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } } private TypePattern resolveBindingsForMissingType(ResolvedType typeFoundInWholeWorldSearch, String nameWeLookedFor, IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { if (requireExactType) { if (!allowBinding) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE,nameWeLookedFor), getSourceLocation())); } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation()); } return NO; } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { // Only put the lint warning out if we can't find it in the world if (typeFoundInWholeWorldSearch == ResolvedType.MISSING) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation()); } } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } /** * We resolved the type to a type variable declared in the pointcut designator. * Now we have to create either an exact type pattern or a wild type pattern for it, * with upper and lower bounds set accordingly. * XXX none of this stuff gets serialized yet * @param scope * @param tvrType * @return */ private TypePattern resolveBindingsForTypeVariable(IScope scope, UnresolvedTypeVariableReferenceType tvrType) { Bindings emptyBindings = new Bindings(0); if (upperBound != null) { upperBound = upperBound.resolveBindings(scope, emptyBindings, false, false); } if (lowerBound != null) { lowerBound = lowerBound.resolveBindings(scope, emptyBindings, false, false); } if (additionalInterfaceBounds != null) { TypePattern[] resolvedIfBounds = new TypePattern[additionalInterfaceBounds.length]; for (int i = 0; i < resolvedIfBounds.length; i++) { resolvedIfBounds[i] = additionalInterfaceBounds[i].resolveBindings(scope, emptyBindings, false, false); } additionalInterfaceBounds = resolvedIfBounds; } if ( upperBound == null && lowerBound == null && additionalInterfaceBounds == null) { // no bounds to worry about... ResolvedType rType = tvrType.resolve(scope.getWorld()); if (dim != 0) rType = ResolvedType.makeArray(rType, dim); return new ExactTypePattern(rType,includeSubtypes,isVarArgs); } else { // we have to set bounds on the TypeVariable held by tvrType before resolving it boolean canCreateExactTypePattern = true; if (upperBound != null && upperBound.getExactType() == ResolvedType.MISSING) canCreateExactTypePattern = false; if (lowerBound != null && lowerBound.getExactType() == ResolvedType.MISSING) canCreateExactTypePattern = false; if (additionalInterfaceBounds != null) { for (int i = 0; i < additionalInterfaceBounds.length; i++) { if (additionalInterfaceBounds[i].getExactType() == ResolvedType.MISSING) canCreateExactTypePattern = false; } } if (canCreateExactTypePattern) { TypeVariable tv = tvrType.getTypeVariable(); if (upperBound != null) tv.setUpperBound(upperBound.getExactType()); if (lowerBound != null) tv.setLowerBound(lowerBound.getExactType()); if (additionalInterfaceBounds != null) { UnresolvedType[] ifBounds = new UnresolvedType[additionalInterfaceBounds.length]; for (int i = 0; i < ifBounds.length; i++) { ifBounds[i] = additionalInterfaceBounds[i].getExactType(); } tv.setAdditionalInterfaceBounds(ifBounds); } ResolvedType rType = tvrType.resolve(scope.getWorld()); if (dim != 0) rType = ResolvedType.makeArray(rType, dim); return new ExactTypePattern(rType,includeSubtypes,isVarArgs); } return this; // leave as wild type pattern then } } /** * When this method is called, we have resolved the base type to an exact type. * We also have a set of type patterns for the parameters. * Time to perform some basic checks: * - can the base type be parameterized? (is it generic) * - can the type parameter pattern list match the number of parameters on the base type * - do all parameter patterns meet the bounds of the respective type variables * If any of these checks fail, a warning message is issued and we return false. * @return */ private boolean verifyTypeParameters(ResolvedType baseType,IScope scope, boolean requireExactType) { ResolvedType genericType = baseType.getGenericType(); if (genericType == null) { // issue message "does not match because baseType.getName() is not generic" scope.message(MessageUtil.warn( WeaverMessages.format(WeaverMessages.NOT_A_GENERIC_TYPE,baseType.getName()), getSourceLocation())); return false; } int minRequiredTypeParameters = typeParameters.size(); boolean foundEllipsis = false; TypePattern[] typeParamPatterns = typeParameters.getTypePatterns(); for (int i = 0; i < typeParamPatterns.length; i++) { if (typeParamPatterns[i] instanceof WildTypePattern) { WildTypePattern wtp = (WildTypePattern) typeParamPatterns[i]; if (wtp.ellipsisCount > 0) { foundEllipsis = true; minRequiredTypeParameters--; } } } TypeVariable[] tvs = genericType.getTypeVariables(); if ((tvs.length < minRequiredTypeParameters) || (!foundEllipsis && minRequiredTypeParameters != tvs.length)) { // issue message "does not match because wrong no of type params" String msg = WeaverMessages.format(WeaverMessages.INCORRECT_NUMBER_OF_TYPE_ARGUMENTS, genericType.getName(),new Integer(tvs.length)); if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation())); else scope.message(MessageUtil.warn(msg,getSourceLocation())); return false; } // now check that each typeParameter pattern, if exact, matches the bounds // of the type variable. if (typeParameters.areAllExactWithNoSubtypesAllowed()) { for (int i = 0; i < tvs.length; i++) { UnresolvedType ut = typeParamPatterns[i].getExactType(); if (!tvs[i].canBeBoundTo(ut.resolve(scope.getWorld()))) { // issue message that type parameter does not meet specification String parameterName = ut.getName(); if (ut.isTypeVariableReference()) parameterName = ((TypeVariableReference)ut).getTypeVariable().getDisplayName(); String msg = WeaverMessages.format( WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS, parameterName, new Integer(i+1), tvs[i].getDisplayName(), genericType.getName()); if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation())); else scope.message(MessageUtil.warn(msg,getSourceLocation())); return false; } } } return true; } public boolean isStar() { boolean annPatternStar = annotationPattern == AnnotationTypePattern.ANY; return (isNamePatternStar() && annPatternStar); } private boolean isNamePatternStar() { return namePatterns.length == 1 && namePatterns[0].isAny(); } /** * returns those possible matches which I match exactly the last element of */ private String[] preMatch(String[] possibleMatches) { //if (namePatterns.length != 1) return CollectionUtil.NO_STRINGS; List ret = new ArrayList(); for (int i=0, len=possibleMatches.length; i < len; i++) { char[][] names = splitNames(possibleMatches[i]); //??? not most efficient if (namePatterns[0].matches(names[names.length-1])) { ret.add(possibleMatches[i]); } } return (String[])ret.toArray(new String[ret.size()]); } // public void postRead(ResolvedType enclosingType) { // this.importedPrefixes = enclosingType.getImportedPrefixes(); // this.knownNames = prematch(enclosingType.getImportedNames()); // } public String toString() { StringBuffer buf = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append('('); buf.append(annotationPattern.toString()); buf.append(' '); } for (int i=0, len=namePatterns.length; i < len; i++) { NamePattern name = namePatterns[i]; if (name == null) { buf.append("."); } else { if (i > 0) buf.append("."); buf.append(name.toString()); } } if (upperBound != null) { buf.append(" extends "); buf.append(upperBound.toString()); } if (lowerBound != null) { buf.append(" super "); buf.append(lowerBound.toString()); } if (typeParameters!=null && typeParameters.size()!=0) { buf.append("<"); buf.append(typeParameters.toString()); buf.append(">"); } if (includeSubtypes) buf.append('+'); if (isVarArgs) buf.append("..."); if (annotationPattern != AnnotationTypePattern.ANY) { buf.append(')'); } return buf.toString(); } public boolean equals(Object other) { if (!(other instanceof WildTypePattern)) return false; WildTypePattern o = (WildTypePattern)other; int len = o.namePatterns.length; if (len != this.namePatterns.length) return false; if (this.includeSubtypes != o.includeSubtypes) return false; if (this.dim != o.dim) return false; if (this.isVarArgs != o.isVarArgs) return false; if (this.upperBound != null) { if (o.upperBound == null) return false; if (!this.upperBound.equals(o.upperBound)) return false; } else { if (o.upperBound != null) return false; } if (this.lowerBound != null) { if (o.lowerBound == null) return false; if (!this.lowerBound.equals(o.lowerBound)) return false; } else { if (o.lowerBound != null) return false; } if (!typeParameters.equals(o.typeParameters)) return false; for (int i=0; i < len; i++) { if (!o.namePatterns[i].equals(this.namePatterns[i])) return false; } return (o.annotationPattern.equals(this.annotationPattern)); } public int hashCode() { int result = 17; for (int i = 0, len = namePatterns.length; i < len; i++) { result = 37*result + namePatterns[i].hashCode(); } result = 37*result + annotationPattern.hashCode(); if (upperBound != null) result = 37*result + upperBound.hashCode(); if (lowerBound != null) result = 37*result + lowerBound.hashCode(); return result; } private static final byte VERSION = 1; // rev on change /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.WILD); s.writeByte(VERSION); s.writeShort(namePatterns.length); for (int i = 0; i < namePatterns.length; i++) { namePatterns[i].write(s); } s.writeBoolean(includeSubtypes); s.writeInt(dim); s.writeBoolean(isVarArgs); typeParameters.write(s); // ! change from M2 //??? storing this information with every type pattern is wasteful of .class // file size. Storing it on enclosing types would be more efficient FileUtil.writeStringArray(knownMatches, s); FileUtil.writeStringArray(importedPrefixes, s); writeLocation(s); annotationPattern.write(s); // generics info, new in M3 s.writeBoolean(isGeneric); s.writeBoolean(upperBound != null); if (upperBound != null) upperBound.write(s); s.writeBoolean(lowerBound != null); if (lowerBound != null) lowerBound.write(s); s.writeInt(additionalInterfaceBounds == null ? 0 : additionalInterfaceBounds.length); if (additionalInterfaceBounds != null) { for (int i = 0; i < additionalInterfaceBounds.length; i++) { additionalInterfaceBounds[i].write(s); } } } 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 > VERSION) { throw new BCException("WildTypePattern was written by a more recent version of AspectJ, cannot read"); } int len = s.readShort(); NamePattern[] namePatterns = new NamePattern[len]; for (int i=0; i < len; i++) { namePatterns[i] = NamePattern.read(s); } boolean includeSubtypes = s.readBoolean(); int dim = s.readInt(); boolean varArg = s.readBoolean(); TypePatternList typeParams = TypePatternList.read(s, context); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, varArg,typeParams); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); // generics info, new in M3 ret.isGeneric = s.readBoolean(); if (s.readBoolean()) { ret.upperBound = TypePattern.read(s,context); } if (s.readBoolean()) { ret.lowerBound = TypePattern.read(s,context); } int numIfBounds = s.readInt(); if (numIfBounds > 0) { ret.additionalInterfaceBounds = new TypePattern[numIfBounds]; for (int i = 0; i < numIfBounds; i++) { ret.additionalInterfaceBounds[i] = TypePattern.read(s,context); } } return ret; } public static TypePattern readTypePatternOldStyle(VersionedDataInputStream s, ISourceContext context) throws IOException { int len = s.readShort(); NamePattern[] namePatterns = new NamePattern[len]; for (int i=0; i < len; i++) { namePatterns[i] = NamePattern.read(s); } boolean includeSubtypes = s.readBoolean(); int dim = s.readInt(); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, false,null); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
88,900
Bug 88900 Unnecessary warning for ITDs
Consider the following aspect: public aspect RunnableDefaultImpl { public void Runnable.run() { } } (Note that it makes little sense to have a default implementation for Runnable. However, I am using it to allow easy reproduction of the bug.) Compiling this aspect leads to the following warning: ...\test\RunnableDefaultImpl.aj:9 [warning] this affected type is not exposed to the weaver: java.lang.Runnable [Xlint:type NotExposedToWeaver] public void Runnable.run() { ^^^ This warning isn't really necessary as weaver doesn't (and shouldn't) need to have Runnable exposed. In fact, everything works as expected already. Now it will be a good warning (or even error), if I was trying to introduce a new method, such as in the following aspect: public aspect RunnableDefaultImpl { public void Runnable.walk() { } }
resolved fixed
e76b370
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-27T15:00:24Z
2005-03-23T17: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 junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; 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; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ 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 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"); } // 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); } }
88,900
Bug 88900 Unnecessary warning for ITDs
Consider the following aspect: public aspect RunnableDefaultImpl { public void Runnable.run() { } } (Note that it makes little sense to have a default implementation for Runnable. However, I am using it to allow easy reproduction of the bug.) Compiling this aspect leads to the following warning: ...\test\RunnableDefaultImpl.aj:9 [warning] this affected type is not exposed to the weaver: java.lang.Runnable [Xlint:type NotExposedToWeaver] public void Runnable.run() { ^^^ This warning isn't really necessary as weaver doesn't (and shouldn't) need to have Runnable exposed. In fact, everything works as expected already. Now it will be a good warning (or even error), if I was trying to introduce a new method, such as in the following aspect: public aspect RunnableDefaultImpl { public void Runnable.walk() { } }
resolved fixed
e76b370
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-27T15:00:24Z
2005-03-23T17:46:40Z
weaver/src/org/aspectj/weaver/ResolvedTypeMunger.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.EOFException; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; 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.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.TypeSafeEnum; /** This is an abstraction over method/field introduction. It might not have the chops * to handle other inter-type declarations. This is the thing that is used on the * eclipse side and serialized into a ConcreteTypeMunger. */ public abstract class ResolvedTypeMunger { protected Kind kind; protected ResolvedMember signature; // This list records the occurences (in order) of any names specified in the <> // for a target type for the ITD. So for example, for List<C,B,A> this list // will be C,B,A - the list is used later to map other occurrences of C,B,A // across the intertype declaration to the right type variables in the generic // type upon which the itd is being made. // might need serializing the class file for binary weaving. protected List /*String*/ typeVariableToGenericTypeVariableIndex; public static transient boolean persistSourceLocation = true; private Set /* resolvedMembers */ superMethodsCalled = Collections.EMPTY_SET; private ISourceLocation location; // Lost during serialize/deserialize ! public ResolvedTypeMunger(Kind kind, ResolvedMember signature) { this.kind = kind; this.signature = signature; UnresolvedType declaringType = signature != null ? signature.getDeclaringType() : null; if (declaringType != null) { if (declaringType.isRawType()) throw new IllegalStateException("Use generic type, not raw type"); if (declaringType.isParameterizedType()) throw new IllegalStateException("Use generic type, not parameterized type"); } } public void setSourceLocation(ISourceLocation isl) { location = isl; } public ISourceLocation getSourceLocation() { return location; } // ---- // fromType is guaranteed to be a non-abstract aspect public ConcreteTypeMunger concretize(World world, ResolvedType aspectType) { ConcreteTypeMunger munger = world.concreteTypeMunger(this, aspectType); return munger; } public boolean matches(ResolvedType matchType, ResolvedType aspectType) { ResolvedType onType = matchType.getWorld().resolve(signature.getDeclaringType()); if (onType.isRawType()) onType = onType.getGenericType(); //System.err.println("matching: " + this + " to " + matchType + " onType = " + onType); if (matchType.equals(onType)) { if (!onType.isExposedToWeaver()) { if (onType.getWeaverState() == null) { if (matchType.getWorld().getLint().typeNotExposedToWeaver.isEnabled()) { matchType.getWorld().getLint().typeNotExposedToWeaver.signal( matchType.getName(), signature.getSourceLocation()); } } } return true; } //System.err.println("NO MATCH DIRECT"); if (onType.isInterface()) { return matchType.isTopmostImplementor(onType); } else { return false; } } // ---- public String toString() { return "ResolvedTypeMunger(" + getKind() + ", " + getSignature() +")"; //.superMethodsCalled + ")"; } // ---- public static ResolvedTypeMunger read(VersionedDataInputStream s, ISourceContext context) throws IOException { Kind kind = Kind.read(s); if (kind == Field) { return NewFieldTypeMunger.readField(s, context); } else if (kind == Method) { return NewMethodTypeMunger.readMethod(s, context); } else if (kind == Constructor) { return NewConstructorTypeMunger.readConstructor(s, context); } else { throw new RuntimeException("unimplemented"); } } protected static Set readSuperMethodsCalled(VersionedDataInputStream s) throws IOException { Set ret = new HashSet(); int n = s.readInt(); for (int i=0; i < n; i++) { ret.add(ResolvedMemberImpl.readResolvedMember(s, null)); } return ret; } protected void writeSuperMethodsCalled(DataOutputStream s) throws IOException { if (superMethodsCalled == null) { s.writeInt(0); return; } List ret = new ArrayList(superMethodsCalled); Collections.sort(ret); int n = ret.size(); s.writeInt(n); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedMember m = (ResolvedMember)i.next(); m.write(s); } } protected static ISourceLocation readSourceLocation(DataInputStream s) throws IOException { if (!persistSourceLocation) return null; SourceLocation ret = null; ObjectInputStream ois = null; try { // This logic copes with the location missing from the attribute - an EOFException will // occur on the next line and we ignore it. ois = new ObjectInputStream(s); Boolean validLocation = (Boolean)ois.readObject(); if (validLocation.booleanValue()) { File f = (File) ois.readObject(); Integer ii = (Integer)ois.readObject(); Integer offset = (Integer)ois.readObject(); ret = new SourceLocation(f,ii.intValue()); ret.setOffset(offset.intValue()); } } catch (EOFException eof) { return null; // This exception occurs if processing an 'old style' file where the // type munger attributes don't include the source location. } catch (IOException ioe) { // Something went wrong, maybe this is an 'old style' file that doesnt attach locations to mungers? // (but I thought that was just an EOFException?) ioe.printStackTrace(); return null; } catch (ClassNotFoundException e) { } finally { if (ois!=null) ois.close(); } return ret; } protected void writeSourceLocation(DataOutputStream s) throws IOException { if (!persistSourceLocation) return; ObjectOutputStream oos = new ObjectOutputStream(s); // oos.writeObject(location); oos.writeObject(new Boolean(location!=null)); if (location !=null) { oos.writeObject(location.getSourceFile()); oos.writeObject(new Integer(location.getLine())); oos.writeObject(new Integer(location.getOffset())); } oos.flush(); oos.close(); } public abstract void write(DataOutputStream s) throws IOException; public Kind getKind() { return kind; } public static class Kind extends TypeSafeEnum { /* private */ 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 Field; case 2: return Method; case 5: return Constructor; } throw new BCException("bad kind: " + key); } } // ---- fields public static final Kind Field = new Kind("Field", 1); public static final Kind Method = new Kind("Method", 2); public static final Kind Constructor = new Kind("Constructor", 5); // not serialized, only created during concretization of aspects public static final Kind PerObjectInterface = new Kind("PerObjectInterface", 3); public static final Kind PrivilegedAccess = new Kind("PrivilegedAccess", 4); public static final Kind Parent = new Kind("Parent", 6); public static final Kind PerTypeWithinInterface = new Kind("PerTypeWithinInterface",7); // PTWIMPL not serialized, used during concretization of aspects public static final Kind AnnotationOnType = new Kind("AnnotationOnType",8); // not serialized public static final String SUPER_DISPATCH_NAME = "superDispatch"; public void setSuperMethodsCalled(Set c) { this.superMethodsCalled = c; } public Set getSuperMethodsCalled() { return superMethodsCalled; } public ResolvedMember getSignature() { return signature; } // ---- public ResolvedMember getMatchingSyntheticMember(Member member, ResolvedType aspectType) { if ((getSignature() != null) && getSignature().isPublic() && member.equals(getSignature())) { return getSignature(); } return null; } public boolean changesPublicSignature() { return kind == Field || kind == Method || kind == Constructor; } public boolean needsAccessToTopmostImplementor() { if (kind == Field) { return true; } else if (kind == Method) { return !signature.isAbstract(); } else { return false; } } }
102,933
Bug 102933 problem with Object arrays and clone() with 1.4 .class compatibility
null
resolved fixed
fb428d0
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-27T15:10:58Z
2005-07-06T20:00: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.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; /** * These are tests that will run on Java 1.4 and use the old harness format for test specification. */ 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 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"); } // 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); } }
101,407
Bug 101407 NullPointerException when selecting Save As in top menu
The Steps of Reproduce: 1. Open BIRT 2. New a project 3. In top menu of File, click New -> Report to create a report 4. Drag a table element from Palette into the report of Layout view 5. Save the report 6. Drag mouse to select two cells in the table 7. Select the report in Navigator view 8. In the top menu, select Save As... 9. In the Save As pop up dialog window, change the file name in the File name field, then click OK button Expected Result: There is no error to click OK button Actual Result: Error window pops up and the error log as follows: java.lang.NullPointerException at org.eclipse.gef.editparts.AbstractEditPart.getRoot (AbstractEditPart.java:587) at org.eclipse.gef.editparts.AbstractEditPart.getRoot (AbstractEditPart.java:587) at org.eclipse.gef.editparts.AbstractEditPart.getViewer (AbstractEditPart.java:637) at org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableU til.getSelectionCells(TableUtil.java:258) at org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableE ditPart.canMerge(TableEditPart.java:1244) at org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.MergeAct ion.calculateEnabled(MergeAction.java:51) at org.eclipse.gef.ui.actions.WorkbenchPartAction.isEnabled (WorkbenchPartAction.java:111) at org.eclipse.ui.actions.RetargetAction.setActionHandler (RetargetAction.java:249) at org.eclipse.ui.actions.RetargetAction.partActivated (RetargetAction.java:144) at org.eclipse.ui.internal.PartListenerList$1.run (PartListenerList.java:49) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:616) at org.eclipse.core.runtime.Platform.run(Platform.java:747) at org.eclipse.ui.internal.PartListenerList.firePartActivated (PartListenerList.java:47) at org.eclipse.ui.internal.WorkbenchPage.firePartActivated (WorkbenchPage.java:1370) at org.eclipse.ui.internal.WorkbenchPage.setActivePart (WorkbenchPage.java:2738) at org.eclipse.ui.internal.WorkbenchPage.requestActivation (WorkbenchPage.java:2415) at org.eclipse.ui.internal.PartPane.requestActivation (PartPane.java:304) at org.eclipse.ui.internal.EditorPane.requestActivation (EditorPane.java:127) at org.eclipse.ui.internal.PartPane.handleEvent(PartPane.java:284) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:820) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:801) at org.eclipse.swt.widgets.Shell.setActiveControl(Shell.java:935) at org.eclipse.swt.widgets.Control.sendFocusEvent(Control.java:1768) at org.eclipse.swt.widgets.Control.WM_SETFOCUS(Control.java:4139) at org.eclipse.swt.widgets.Canvas.WM_SETFOCUS(Canvas.java:239) at org.eclipse.swt.widgets.Control.windowProc(Control.java:3032) at org.eclipse.swt.widgets.Display.windowProc(Display.java:3338) at org.eclipse.swt.internal.win32.OS.SetFocus(Native Method) at org.eclipse.swt.widgets.Control.forceFocus(Control.java:607) at org.eclipse.swt.widgets.Control.setFocus(Control.java:2054) at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:447) at org.eclipse.gef.ui.parts.GraphicalEditor.setFocus (GraphicalEditor.java:346) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:545) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:519) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:545) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:519) at org.eclipse.ui.part.MultiPageEditorPart.pageChange (MultiPageEditorPart.java:433) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.pageChange (ReportEditor.java:1179) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.rebuildReportDesign (ReportEditor.java:584) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.setInput (ReportEditor.java:547) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.performSaveAs (ReportEditor.java:870) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.doSaveAs (ReportEditor.java:812) at org.eclipse.ui.internal.SaveAsAction.run(SaveAsAction.java:64) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:915) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:866) at org.eclipse.jface.action.ActionContributionItem$7.handleEvent (ActionContributionItem.java:785) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2772) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2431) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1377) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1348) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:254) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:96) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:335) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:273) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:129) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:185) at org.eclipse.core.launcher.Main.run(Main.java:704) at org.eclipse.core.launcher.Main.main(Main.java:688)
closed fixed
97520cf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-27T21:08:24Z
2005-06-23T07:00:00Z
bcel-builder/src/org/aspectj/apache/bcel/generic/LocalVariableGen.java
package org.aspectj.apache.bcel.generic; /* ==================================================================== * 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 org.aspectj.apache.bcel.classfile.LocalVariable; /** * This class represents a local variable within a method. It contains its * scope, name and type. The generated LocalVariable object can be obtained * with getLocalVariable which needs the instruction list and the constant * pool as parameters. * * @version $Id: LocalVariableGen.java,v 1.3 2004/11/22 08:31:27 aclement Exp $ * @author <A HREF="mailto:[email protected]">M. Dahm</A> * @see LocalVariable * @see MethodGen */ public class LocalVariableGen implements InstructionTargeter, NamedAndTyped, Cloneable, java.io.Serializable { private int index; private String name; private Type type; private InstructionHandle start, end; /** * Generate a local variable that with index `index'. Note that double and long * variables need two indexs. Index indices have to be provided by the user. * * @param index index of local variable * @param name its name * @param type its type * @param start from where the instruction is valid (null means from the start) * @param end until where the instruction is valid (null means to the end) */ public LocalVariableGen(int index, String name, Type type, InstructionHandle start, InstructionHandle end) { if((index < 0) || (index > Constants.MAX_SHORT)) throw new ClassGenException("Invalid index index: " + index); this.name = name; this.type = type; this.index = index; setStart(start); setEnd(end); } /** * Get LocalVariable object. * * This relies on that the instruction list has already been dumped to byte code or * or that the `setPositions' methods has been called for the instruction list. * * Note that for local variables whose scope end at the last * instruction of the method's code, the JVM specification is ambiguous: * both a start_pc+length ending at the last instruction and * start_pc+length ending at first index beyond the end of the code are * valid. * * @param il instruction list (byte code) which this variable belongs to * @param cp constant pool */ public LocalVariable getLocalVariable(ConstantPoolGen cp) { int start_pc = start.getPosition(); int length = end.getPosition() - start_pc; if(length > 0) length += end.getInstruction().getLength(); int name_index = cp.addUtf8(name); int signature_index = cp.addUtf8(type.getSignature()); return new LocalVariable(start_pc, length, name_index, signature_index, index, cp.getConstantPool()); } public void setIndex(int index) { this.index = index; } public int getIndex() { return index; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setType(Type type) { this.type = type; } public Type getType() { return type; } public InstructionHandle getStart() { return start; } public InstructionHandle getEnd() { return end; } public void setStart(InstructionHandle start) { BranchInstruction.notifyTarget(this.start, start, this); this.start = start; } public void setEnd(InstructionHandle end) { BranchInstruction.notifyTarget(this.end, end, this); this.end = end; } /** * @param old_ih old target, either start or end * @param new_ih new target */ public void updateTarget(InstructionHandle old_ih, InstructionHandle new_ih) { boolean targeted = false; if(start == old_ih) { targeted = true; setStart(new_ih); } if(end == old_ih) { targeted = true; setEnd(new_ih); } if(!targeted) throw new ClassGenException("Not targeting " + old_ih + ", but {" + start + ", " + end + "}"); } /** * @return true, if ih is target of this variable */ public boolean containsTarget(InstructionHandle ih) { return (start == ih) || (end == ih); } /** * We consider to local variables to be equal, if the use the same index and * are valid in the same range. */ public boolean equals(Object o) { if(!(o instanceof LocalVariableGen)) return false; LocalVariableGen l = (LocalVariableGen)o; return (l.index == index) && (l.start == start) && (l.end == end); } public String toString() { return "LocalVariableGen(" + name + ", " + type + ", " + start + ", " + end + ")"; } public Object clone() { try { return super.clone(); } catch(CloneNotSupportedException e) { System.err.println(e); return null; } } }
101,407
Bug 101407 NullPointerException when selecting Save As in top menu
The Steps of Reproduce: 1. Open BIRT 2. New a project 3. In top menu of File, click New -> Report to create a report 4. Drag a table element from Palette into the report of Layout view 5. Save the report 6. Drag mouse to select two cells in the table 7. Select the report in Navigator view 8. In the top menu, select Save As... 9. In the Save As pop up dialog window, change the file name in the File name field, then click OK button Expected Result: There is no error to click OK button Actual Result: Error window pops up and the error log as follows: java.lang.NullPointerException at org.eclipse.gef.editparts.AbstractEditPart.getRoot (AbstractEditPart.java:587) at org.eclipse.gef.editparts.AbstractEditPart.getRoot (AbstractEditPart.java:587) at org.eclipse.gef.editparts.AbstractEditPart.getViewer (AbstractEditPart.java:637) at org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableU til.getSelectionCells(TableUtil.java:258) at org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableE ditPart.canMerge(TableEditPart.java:1244) at org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.MergeAct ion.calculateEnabled(MergeAction.java:51) at org.eclipse.gef.ui.actions.WorkbenchPartAction.isEnabled (WorkbenchPartAction.java:111) at org.eclipse.ui.actions.RetargetAction.setActionHandler (RetargetAction.java:249) at org.eclipse.ui.actions.RetargetAction.partActivated (RetargetAction.java:144) at org.eclipse.ui.internal.PartListenerList$1.run (PartListenerList.java:49) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:616) at org.eclipse.core.runtime.Platform.run(Platform.java:747) at org.eclipse.ui.internal.PartListenerList.firePartActivated (PartListenerList.java:47) at org.eclipse.ui.internal.WorkbenchPage.firePartActivated (WorkbenchPage.java:1370) at org.eclipse.ui.internal.WorkbenchPage.setActivePart (WorkbenchPage.java:2738) at org.eclipse.ui.internal.WorkbenchPage.requestActivation (WorkbenchPage.java:2415) at org.eclipse.ui.internal.PartPane.requestActivation (PartPane.java:304) at org.eclipse.ui.internal.EditorPane.requestActivation (EditorPane.java:127) at org.eclipse.ui.internal.PartPane.handleEvent(PartPane.java:284) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:820) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:801) at org.eclipse.swt.widgets.Shell.setActiveControl(Shell.java:935) at org.eclipse.swt.widgets.Control.sendFocusEvent(Control.java:1768) at org.eclipse.swt.widgets.Control.WM_SETFOCUS(Control.java:4139) at org.eclipse.swt.widgets.Canvas.WM_SETFOCUS(Canvas.java:239) at org.eclipse.swt.widgets.Control.windowProc(Control.java:3032) at org.eclipse.swt.widgets.Display.windowProc(Display.java:3338) at org.eclipse.swt.internal.win32.OS.SetFocus(Native Method) at org.eclipse.swt.widgets.Control.forceFocus(Control.java:607) at org.eclipse.swt.widgets.Control.setFocus(Control.java:2054) at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:447) at org.eclipse.gef.ui.parts.GraphicalEditor.setFocus (GraphicalEditor.java:346) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:545) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:519) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:545) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:519) at org.eclipse.ui.part.MultiPageEditorPart.pageChange (MultiPageEditorPart.java:433) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.pageChange (ReportEditor.java:1179) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.rebuildReportDesign (ReportEditor.java:584) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.setInput (ReportEditor.java:547) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.performSaveAs (ReportEditor.java:870) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.doSaveAs (ReportEditor.java:812) at org.eclipse.ui.internal.SaveAsAction.run(SaveAsAction.java:64) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:915) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:866) at org.eclipse.jface.action.ActionContributionItem$7.handleEvent (ActionContributionItem.java:785) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2772) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2431) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1377) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1348) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:254) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:96) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:335) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:273) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:129) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:185) at org.eclipse.core.launcher.Main.run(Main.java:704) at org.eclipse.core.launcher.Main.main(Main.java:688)
closed fixed
97520cf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-27T21:08:24Z
2005-06-23T07:00:00Z
weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.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.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Stack; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Synthetic; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.BranchHandle; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ClassGenException; import org.aspectj.apache.bcel.generic.CodeExceptionGen; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.Instruction; 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.LineNumberGen; import org.aspectj.apache.bcel.generic.LocalVariableGen; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.MethodGen; import org.aspectj.apache.bcel.generic.ObjectType; 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.weaver.AjAttribute; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.MemberImpl; 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.AjAttribute.WeaverVersionInfo; /** * A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the * low-level Method objects. It converts through {@link MethodGen} to create * and to serialize, but that's it. * * <p> At any rate, there are two ways to create LazyMethodGens. * One is from a method, which * does work through MethodGen to do the correct thing. * The other is the creation of a completely empty * LazyMethodGen, and it is used when we're constructing code from scratch. * * <p> We stay away from targeters for rangey things like Shadows and Exceptions. */ public final class LazyMethodGen { private int accessFlags; private Type returnType; private final String name; private Type[] argumentTypes; //private final String[] argumentNames; private String[] declaredExceptions; private InstructionList body; // leaving null for abstracts private Attribute[] attributes; private List newAnnotations; private final LazyClassGen enclosingClass; private BcelMethod memberView; private AjAttribute.EffectiveSignatureAttribute effectiveSignature; int highestLineNumber = 0; /** This is nonnull if this method is the result of an "inlining". We currently * copy methods into other classes for around advice. We add this field so * we can get JSR45 information correct. If/when we do _actual_ inlining, * we'll need to subtype LineNumberTag to have external line numbers. */ String fromFilename = null; private int maxLocals; private boolean canInline = true; private boolean hasExceptionHandlers; private boolean isSynthetic = false; /** * only used by {@link BcelClassWeaver} */ List /*ShadowMungers*/ matchedShadows; List /*Test*/ matchedShadowTests; // Used for interface introduction // this is the type of the interface the method is technically on public ResolvedType definingType = null; public LazyMethodGen( int accessFlags, Type returnType, String name, Type[] paramTypes, String[] declaredExceptions, LazyClassGen enclosingClass) { //System.err.println("raw create of: " + name + ", " + enclosingClass.getName() + ", " + returnType); this.memberView = null; // ??? should be okay, since constructed ones aren't woven into this.accessFlags = accessFlags; this.returnType = returnType; this.name = name; this.argumentTypes = paramTypes; //this.argumentNames = Utility.makeArgNames(paramTypes.length); this.declaredExceptions = declaredExceptions; if (!Modifier.isAbstract(accessFlags)) { body = new InstructionList(); setMaxLocals(calculateMaxLocals()); } else { body = null; } this.attributes = new Attribute[0]; this.enclosingClass = enclosingClass; assertGoodBody(); // @AJ advice are not inlined by default since requires further analysis // and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects are reweavable // since the inlined version with wrappers and an to be done annotation to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { //TODO we could check for @Around advice as well this.canInline = false; } } } private int calculateMaxLocals() { int ret = 0; if (!Modifier.isStatic(accessFlags)) ret++; for (int i = 0, len = argumentTypes.length; i < len; i++) { ret += argumentTypes[i].getSize(); } return ret; } private Method savedMethod = null; // build from an existing method, lazy build saves most work for initialization public LazyMethodGen(Method m, LazyClassGen enclosingClass) { savedMethod = m; this.enclosingClass = enclosingClass; if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) { throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass); } if ((m.isAbstract() || m.isNative()) && m.getCode() != null) { throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass); } this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m); this.accessFlags = m.getAccessFlags(); this.name = m.getName(); // @AJ advice are not inlined by default since requires further analysis // and weaving ordering control // TODO AV - improve - note: no room for improvement as long as aspects are reweavable // since the inlined version with wrappers and an to be done annotation to keep // inline state will be garbaged due to reweavable impl if (memberView != null && isAdviceMethod()) { if (enclosingClass.getType().isAnnotationStyleAspect()) { //TODO we could check for @Around advice as well this.canInline = false; } } } public boolean hasDeclaredLineNumberInfo() { return (memberView != null && memberView.hasDeclarationLineNumberInfo()); } public int getDeclarationLineNumber() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationLineNumber(); } else { return -1; } } public int getDeclarationOffset() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationOffset(); } else { return 0; } } public void addAnnotation(AnnotationX ax) { initialize(); if (memberView==null) { // If member view is null, we manage them in newAnnotations if (newAnnotations==null) newAnnotations = new ArrayList(); newAnnotations.add(ax); } else { memberView.addAnnotation(ax); } } public boolean hasAnnotation(UnresolvedType annotationTypeX) { initialize(); if (memberView==null) { // Check local annotations first if (newAnnotations!=null) { for (Iterator iter = newAnnotations.iterator(); iter.hasNext();) { AnnotationX element = (AnnotationX) iter.next(); if (element.getBcelAnnotation().getTypeName().equals(annotationTypeX.getName())) return true; } } memberView = new BcelMethod(getEnclosingClass().getBcelObjectType(), getMethod()); return memberView.hasAnnotation(annotationTypeX); } return memberView.hasAnnotation(annotationTypeX); } private void initialize() { if (returnType != null) return; //System.err.println("initializing: " + getName() + ", " + enclosingClass.getName() + ", " + returnType + ", " + savedMethod); MethodGen gen = new MethodGen(savedMethod, enclosingClass.getName(), enclosingClass.getConstantPoolGen()); this.returnType = gen.getReturnType(); this.argumentTypes = gen.getArgumentTypes(); this.declaredExceptions = gen.getExceptions(); this.attributes = gen.getAttributes(); //this.annotations = gen.getAnnotations(); this.maxLocals = gen.getMaxLocals(); // this.returnType = BcelWorld.makeBcelType(memberView.getReturnType()); // this.argumentTypes = BcelWorld.makeBcelTypes(memberView.getParameterTypes()); // // this.declaredExceptions = UnresolvedType.getNames(memberView.getExceptions()); //gen.getExceptions(); // this.attributes = new Attribute[0]; //gen.getAttributes(); // this.maxLocals = savedMethod.getCode().getMaxLocals(); if (gen.isAbstract() || gen.isNative()) { body = null; } else { //body = new InstructionList(savedMethod.getCode().getCode()); body = gen.getInstructionList(); unpackHandlers(gen); unpackLineNumbers(gen); unpackLocals(gen); } assertGoodBody(); //System.err.println("initialized: " + this.getClassName() + "." + this.getName()); } // XXX we're relying on the javac promise I've just made up that we won't have an early exception // in the list mask a later exception: That is, for two exceptions E and F, // if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So when we add F, // we add it on the _OUTSIDE_ of any handlers that share starts or ends with it. // with that in mind, we merrily go adding ranges for exceptions. private void unpackHandlers(MethodGen gen) { CodeExceptionGen[] exns = gen.getExceptionHandlers(); if (exns != null) { int len = exns.length; if (len > 0) hasExceptionHandlers = true; int priority = len - 1; for (int i = 0; i < len; i++, priority--) { CodeExceptionGen exn = exns[i]; InstructionHandle start = Range.genStart( body, getOutermostExceptionStart(exn.getStartPC())); InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC())); // this doesn't necessarily handle overlapping correctly!!! ExceptionRange er = new ExceptionRange( body, exn.getCatchType() == null ? null : BcelWorld.fromBcel(exn.getCatchType()), priority); er.associateWithTargets(start, end, exn.getHandlerPC()); exn.setStartPC(null); // also removes from target exn.setEndPC(null); // also removes from target exn.setHandlerPC(null); // also removes from target } gen.removeExceptionHandlers(); } } private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionStart(ih.getPrev())) { ih = ih.getPrev(); } else { return ih; } } } private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionEnd(ih.getNext())) { ih = ih.getNext(); } else { return ih; } } } private void unpackLineNumbers(MethodGen gen) { LineNumberTag lr = null; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LineNumberGen) { LineNumberGen lng = (LineNumberGen) targeter; lng.updateTarget(ih, null); int lineNumber = lng.getSourceLine(); if (highestLineNumber < lineNumber) highestLineNumber = lineNumber; lr = new LineNumberTag(lineNumber); } } } if (lr != null) { ih.addTargeter(lr); } } gen.removeLineNumbers(); } private void unpackLocals(MethodGen gen) { Set locals = new HashSet(); for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); List ends = new ArrayList(0); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LocalVariableGen) { LocalVariableGen lng = (LocalVariableGen) targeter; LocalVariableTag lr = new LocalVariableTag(BcelWorld.fromBcel(lng.getType()), lng.getName(), lng.getIndex()); if (lng.getStart() == ih) { locals.add(lr); } else { ends.add(lr); } } } } for (Iterator i = locals.iterator(); i.hasNext(); ) { ih.addTargeter((LocalVariableTag) i.next()); } locals.removeAll(ends); } gen.removeLocalVariables(); } // =============== public int allocateLocal(Type type) { return allocateLocal(type.getSize()); } public int allocateLocal(int slots) { int max = getMaxLocals(); setMaxLocals(max + slots); return max; } public Method getMethod() { if (savedMethod != null) return savedMethod; //??? this relies on gentle treatment of constant pool try { MethodGen gen = pack(); return gen.getMethod(); } catch (ClassGenException e) { enclosingClass.getBcelObjectType().getResolvedTypeX().getWorld().showMessage( IMessage.ERROR, WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(), this.getName(), e.getMessage()), this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null); // throw e; PR 70201.... let the normal problem reporting infrastructure deal with this rather than crashing. body = null; MethodGen gen = pack(); return gen.getMethod(); } } public void markAsChanged() { initialize(); savedMethod = null; } // ============================= public String toString() { WeaverVersionInfo weaverVersion = enclosingClass.getBcelObjectType().getWeaverVersionAttribute(); return toLongString(weaverVersion); } public String toShortString() { String access = org.aspectj.apache.bcel.classfile.Utility.accessToString(getAccessFlags()); StringBuffer buf = new StringBuffer(); if (!access.equals("")) { buf.append(access); buf.append(" "); } buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( getReturnType().getSignature(), true)); buf.append(" "); buf.append(getName()); buf.append("("); { int len = argumentTypes.length; if (len > 0) { buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[0].getSignature(), true)); for (int i = 1; i < argumentTypes.length; i++) { buf.append(", "); buf.append( org.aspectj.apache.bcel.classfile.Utility.signatureToString( argumentTypes[i].getSignature(), true)); } } } buf.append(")"); { int len = declaredExceptions != null ? declaredExceptions.length : 0; if (len > 0) { buf.append(" throws "); buf.append(declaredExceptions[0]); for (int i = 1; i < declaredExceptions.length; i++) { buf.append(", "); buf.append(declaredExceptions[i]); } } } return buf.toString(); } public String toLongString(WeaverVersionInfo weaverVersion) { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s),weaverVersion); return new String(s.toByteArray()); } public void print(WeaverVersionInfo weaverVersion) { print(System.out,weaverVersion); } public void print(PrintStream out, WeaverVersionInfo weaverVersion) { out.print(" " + toShortString()); printAspectAttributes(out,weaverVersion); InstructionList body = getBody(); if (body == null) { out.println(";"); return; } out.println(":"); new BodyPrinter(out).run(); out.println(" end " + toShortString()); } private void printAspectAttributes(PrintStream out, WeaverVersionInfo weaverVersion) { ISourceContext context = null; if (enclosingClass != null && enclosingClass.getType() != null) { context = enclosingClass.getType().getSourceContext(); } List as = BcelAttributes.readAjAttributes(getClassName(),attributes, context,null,weaverVersion); if (! as.isEmpty()) { out.println(" " + as.get(0)); // XXX assuming exactly one attribute, munger... } } private class BodyPrinter { Map prefixMap = new HashMap(); Map suffixMap = new HashMap(); Map labelMap = new HashMap(); InstructionList body; PrintStream out; ConstantPool pool; List ranges; BodyPrinter(PrintStream out) { this.pool = enclosingClass.getConstantPoolGen().getConstantPool(); this.body = getBody(); this.out = out; } void run() { //killNops(); assignLabels(); print(); } // label assignment void assignLabels() { LinkedList exnTable = new LinkedList(); String pendingLabel = null; // boolean hasPendingTargeters = false; int lcounter = 0; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { // assert isRangeHandle(h); ExceptionRange r = (ExceptionRange) t; if (r.getStart() == ih) { insertHandler(r, exnTable); } } else if (t instanceof BranchInstruction) { if (pendingLabel == null) { pendingLabel = "L" + lcounter++; } } else { // assert isRangeHandle(h) } } } if (pendingLabel != null) { labelMap.put(ih, pendingLabel); if (! Range.isRangeHandle(ih)) { pendingLabel = null; } } } int ecounter = 0; for (Iterator i = exnTable.iterator(); i.hasNext();) { ExceptionRange er = (ExceptionRange) i.next(); String exceptionLabel = "E" + ecounter++; labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel); labelMap.put(er.getHandler(), exceptionLabel); } } // printing void print() { int depth = 0; int currLine = -1; bodyPrint: for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { Range r = Range.getRange(ih); // don't print empty ranges, that is, ranges who contain no actual instructions for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) { if (xx == r.getEnd()) continue bodyPrint; } // doesn't handle nested: if (r.getStart().getNext() == r.getEnd()) continue; if (r.getStart() == ih) { printRangeString(r, depth++); } else { if (r.getEnd() != ih) throw new RuntimeException("bad"); printRangeString(r, --depth); } } else { printInstruction(ih, depth); int line = getLineNumber(ih, currLine); if (line != currLine) { currLine = line; out.println(" (line " + line + ")"); } else { out.println(); } } } } void printRangeString(Range r, int depth) { printDepth(depth); out.println(getRangeString(r, labelMap)); } String getRangeString(Range r, Map labelMap) { if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; return er.toString() + " -> " + labelMap.get(er.getHandler()); // // + " PRI " + er.getPriority(); } else { return r.toString(); } } void printDepth(int depth) { pad(BODY_INDENT); while (depth > 0) { out.print("| "); depth--; } } void printLabel(String s, int depth) { int space = Math.max(CODE_INDENT - depth * 2, 0); if (s == null) { pad(space); } else { space = Math.max(space - (s.length() + 2), 0); pad(space); out.print(s); out.print(": "); } } void printInstruction(InstructionHandle h, int depth) { printDepth(depth); printLabel((String) labelMap.get(h), depth); Instruction inst = h.getInstruction(); if (inst instanceof CPInstruction) { CPInstruction cpinst = (CPInstruction) inst; out.print(Constants.OPCODE_NAMES[cpinst.getOpcode()].toUpperCase()); out.print(" "); out.print(pool.constantToString(pool.getConstant(cpinst.getIndex()))); } else if (inst instanceof Select) { Select sinst = (Select) inst; out.println(Constants.OPCODE_NAMES[sinst.getOpcode()].toUpperCase()); int[] matches = sinst.getMatchs(); InstructionHandle[] targets = sinst.getTargets(); InstructionHandle defaultTarget = sinst.getTarget(); for (int i = 0, len = matches.length; i < len; i++) { printDepth(depth); printLabel(null, depth); out.print(" "); out.print(matches[i]); out.print(": \t"); out.println(labelMap.get(targets[i])); } printDepth(depth); printLabel(null, depth); out.print(" "); out.print("default: \t"); out.print(labelMap.get(defaultTarget)); } else if (inst instanceof BranchInstruction) { BranchInstruction brinst = (BranchInstruction) inst; out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase()); out.print(" "); out.print(labelMap.get(brinst.getTarget())); } else if (inst instanceof LocalVariableInstruction) { LocalVariableInstruction lvinst = (LocalVariableInstruction) inst; out.print(inst.toString(false).toUpperCase()); int index = lvinst.getIndex(); LocalVariableTag tag = getLocalVariableTag(h, index); if (tag != null) { out.print(" // "); out.print(tag.getType()); out.print(" "); out.print(tag.getName()); } } else { out.print(inst.toString(false).toUpperCase()); } } static final int BODY_INDENT = 4; static final int CODE_INDENT = 16; void pad(int size) { for (int i = 0; i < size; i++) { out.print(" "); } } } static LocalVariableTag getLocalVariableTag( InstructionHandle ih, int index) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return null; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) t; if (lvt.getSlot() == index) return lvt; } } return null; } static int getLineNumber( InstructionHandle ih, int prevLine) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return prevLine; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LineNumberTag) { return ((LineNumberTag)t).getLineNumber(); } } return prevLine; } public boolean isStatic() { return Modifier.isStatic(getAccessFlags()); } public boolean isAbstract() { return Modifier.isAbstract(getAccessFlags()); } public boolean isBridgeMethod() { return (getAccessFlags() & Constants.ACC_BRIDGE) != 0; } public void addExceptionHandler( InstructionHandle start, InstructionHandle end, InstructionHandle handlerStart, ObjectType catchType, boolean highPriority) { InstructionHandle start1 = Range.genStart(body, start); InstructionHandle end1 = Range.genEnd(body, end); ExceptionRange er = new ExceptionRange(body, BcelWorld.fromBcel(catchType), highPriority); er.associateWithTargets(start1, end1, handlerStart); } public int getAccessFlags() { return accessFlags; } public void setAccessFlags(int newFlags) { this.accessFlags = newFlags; } public Type[] getArgumentTypes() { initialize(); return argumentTypes; } public LazyClassGen getEnclosingClass() { return enclosingClass; } public int getMaxLocals() { return maxLocals; } public String getName() { return name; } public Type getReturnType() { initialize(); return returnType; } public void setMaxLocals(int maxLocals) { this.maxLocals = maxLocals; } public InstructionList getBody() { markAsChanged(); return body; } public boolean hasBody() { if (savedMethod != null) return savedMethod.getCode() != null; return body != null; } public Attribute[] getAttributes() { return attributes; } public String[] getDeclaredExceptions() { return declaredExceptions; } public String getClassName() { return enclosingClass.getName(); } // ---- packing! public MethodGen pack() { //killNops(); MethodGen gen = new MethodGen( getAccessFlags(), getReturnType(), getArgumentTypes(), null, //getArgumentNames(), getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPoolGen()); for (int i = 0, len = declaredExceptions.length; i < len; i++) { gen.addException(declaredExceptions[i]); } for (int i = 0, len = attributes.length; i < len; i++) { gen.addAttribute(attributes[i]); } if (newAnnotations!=null) { for (Iterator iter = newAnnotations.iterator(); iter.hasNext();) { AnnotationX element = (AnnotationX) iter.next(); gen.addAnnotation(new AnnotationGen(element.getBcelAnnotation(),gen.getConstantPool(),true)); } } if (memberView!=null && memberView.getAnnotations()!=null && memberView.getAnnotations().length!=0) { AnnotationX[] ans = memberView.getAnnotations(); for (int i = 0, len = ans.length; i < len; i++) { Annotation a= ans[i].getBcelAnnotation(); gen.addAnnotation(new AnnotationGen(a,gen.getConstantPool(),true)); } } if (isSynthetic) { ConstantPoolGen cpg = gen.getConstantPool(); int index = cpg.addUtf8("Synthetic"); gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg.getConstantPool())); } if (hasBody()) { packBody(gen); gen.setMaxLocals(); gen.setMaxStack(); } else { gen.setInstructionList(null); } return gen; } public void makeSynthetic() { isSynthetic = true; } /** fill the newly created method gen with our body, * inspired by InstructionList.copy() */ public void packBody(MethodGen gen) { HashMap map = new HashMap(); InstructionList fresh = gen.getInstructionList(); /* Make copies of all instructions, append them to the new list * and associate old instruction references with the new ones, i.e., * a 1:1 mapping. */ for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { continue; } Instruction i = ih.getInstruction(); Instruction c = Utility.copyInstruction(i); if (c instanceof BranchInstruction) map.put(ih, fresh.append((BranchInstruction) c)); else map.put(ih, fresh.append(c)); } // at this point, no rangeHandles are in fresh. Let's use that... /* Update branch targets and insert various attributes. * Insert our exceptionHandlers * into a sorted list, so they can be added in order later. */ InstructionHandle ih = getBody().getStart(); InstructionHandle jh = fresh.getStart(); LinkedList exnList = new LinkedList(); // map from localvariabletag to instruction handle Map localVariableStarts = new HashMap(); Map localVariableEnds = new HashMap(); int currLine = -1; while (ih != null) { if (map.get(ih) == null) { // we're a range instruction Range r = Range.getRange(ih); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; if (er.getStart() == ih) { //System.err.println("er " + er); if (!er.isEmpty()){ // order is important, insert handlers in order of start insertHandler(er, exnList); } } } else { // we must be a shadow range or something equally useless, // so forget about doing anything } // just increment ih. ih = ih.getNext(); } else { // assert map.get(ih) == jh Instruction i = ih.getInstruction(); Instruction j = jh.getInstruction(); if (i instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) i; BranchInstruction bj = (BranchInstruction) j; InstructionHandle itarget = bi.getTarget(); // old target // try { // New target is in hash map bj.setTarget(remap(itarget, map)); // } catch (NullPointerException e) { // print(); // System.out.println("Was trying to remap " + bi); // System.out.println("who's target was supposedly " + itarget); // throw e; // } if (bi instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH InstructionHandle[] itargets = ((Select) bi).getTargets(); InstructionHandle[] jtargets = ((Select) bj).getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { // Update all targets jtargets[k] = remap(itargets[k], map); jtargets[k].addTargeter(bj); } } } // now deal with line numbers // and store up info for local variables InstructionTargeter[] targeters = ih.getTargeters(); int lineNumberOffset = (fromFilename == null) ? 0 : getEnclosingClass().getSourceDebugExtensionOffset(fromFilename); if (targeters != null) { for (int k = targeters.length - 1; k >= 0; k--) { InstructionTargeter targeter = targeters[k]; if (targeter instanceof LineNumberTag) { int line = ((LineNumberTag)targeter).getLineNumber(); if (line != currLine) { gen.addLineNumber(jh, line + lineNumberOffset); currLine = line; } } else if (targeter instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) targeter; if (localVariableStarts.get(lvt) == null) { localVariableStarts.put(lvt, jh); } localVariableEnds.put(lvt, jh); } } } // now continue ih = ih.getNext(); jh = jh.getNext(); } } // now add exception handlers for (Iterator iter = exnList.iterator(); iter.hasNext();) { ExceptionRange r = (ExceptionRange) iter.next(); if (r.isEmpty()) continue; gen.addExceptionHandler( remap(r.getRealStart(), map), remap(r.getRealEnd(), map), remap(r.getHandler(), map), (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType())); } // now add local variables gen.removeLocalVariables(); // this next iteration _might_ be overkill, but we had problems with // bcel before with duplicate local variables. Now that we're patching // bcel we should be able to do without it if we're paranoid enough // through the rest of the compiler. Map duplicatedLocalMap = new HashMap(); List keys = new ArrayList(); keys.addAll(localVariableStarts.keySet()); for (Iterator iter = keys.iterator(); iter.hasNext(); ) { LocalVariableTag tag = (LocalVariableTag) iter.next(); // have we already added one with the same slot number and start location? // if so, just continue. InstructionHandle start = (InstructionHandle) localVariableStarts.get(tag); Set slots = (Set) duplicatedLocalMap.get(start); if (slots == null) { slots = new HashSet(); duplicatedLocalMap.put(start, slots); } if (slots.contains(new Integer(tag.getSlot()))) { // we already have a var starting at this tag with this slot continue; } slots.add(new Integer(tag.getSlot())); gen.addLocalVariable( tag.getName(), BcelWorld.makeBcelType(tag.getType()), tag.getSlot(), (InstructionHandle) localVariableStarts.get(tag), (InstructionHandle) localVariableEnds.get(tag)); } // JAVAC adds line number tables (with just one entry) to generated accessor methods - this // keeps some tools that rely on finding at least some form of linenumbertable happy. // Let's check if we have one - if we don't then let's add one. // TODO Could be made conditional on whether line debug info is being produced if (gen.getLineNumbers().length==0) { gen.addLineNumber(gen.getInstructionList().getStart(),1); } } /** This procedure should not currently be used. */ // public void killNops() { // InstructionHandle curr = body.getStart(); // while (true) { // if (curr == null) break; // InstructionHandle next = curr.getNext(); // if (curr.getInstruction() instanceof NOP) { // InstructionTargeter[] targeters = curr.getTargeters(); // if (targeters != null) { // for (int i = 0, len = targeters.length; i < len; i++) { // InstructionTargeter targeter = targeters[i]; // targeter.updateTarget(curr, next); // } // } // try { // body.delete(curr); // } catch (TargetLostException e) { // } // } // curr = next; // } // } private static InstructionHandle remap(InstructionHandle ih, Map map) { while (true) { Object ret = map.get(ih); if (ret == null) { ih = ih.getNext(); } else { return (InstructionHandle) ret; } } } // Update to all these comments, ASC 11-01-2005 // The right thing to do may be to do more with priorities as // we create new exception handlers, but that is a relatively // complex task. In the meantime, just taking account of the // priority here enables a couple of bugs to be fixed to do // with using return or break in code that contains a finally // block (pr78021,pr79554). // exception ordering. // What we should be doing is dealing with priority inversions way earlier than we are // and counting on the tree structure. In which case, the below code is in fact right. // XXX THIS COMMENT BELOW IS CURRENTLY WRONG. // An exception A preceeds an exception B in the exception table iff: // * A and B were in the original method, and A preceeded B in the original exception table // * If A has a higher priority than B, than it preceeds B. // * If A and B have the same priority, then the one whose START happens EARLIEST has LEAST priority. // in short, the outermost exception has least priority. // we implement this with a LinkedList. We could possibly implement this with a java.util.SortedSet, // but I don't trust the only implementation, TreeSet, to do the right thing. /* private */ static void insertHandler(ExceptionRange fresh, LinkedList l) { // Old implementation, simply: l.add(0,fresh); for (ListIterator iter = l.listIterator(); iter.hasNext();) { ExceptionRange r = (ExceptionRange) iter.next(); int freal = fresh.getRealStart().getPosition(); int rreal = r.getRealStart().getPosition(); if (fresh.getPriority() >= r.getPriority()) { iter.previous(); iter.add(fresh); return; } } // we have reached the end l.add(fresh); } public boolean isPrivate() { return Modifier.isPrivate(getAccessFlags()); } public boolean isProtected() { return Modifier.isProtected(getAccessFlags()); } public boolean isDefault() { return !(isProtected() || isPrivate() || isPublic()); } public boolean isPublic() { return Modifier.isPublic(getAccessFlags()); } // ---- /** A good body is a body with the following properties: * * <ul> * <li> For each branch instruction S in body, target T of S is in body. * <li> For each branch instruction S in body, target T of S has S as a targeter. * <li> For each instruction T in body, for each branch instruction S that is a * targeter of T, S is in body. * <li> For each non-range-handle instruction T in body, for each instruction S * that is a targeter of T, S is * either a branch instruction, an exception range or a tag * <li> For each range-handle instruction T in body, there is exactly one targeter S * that is a range. * <li> For each range-handle instruction T in body, the range R targeting T is in body. * <li> For each instruction T in body, for each exception range R targeting T, R is * in body. * <li> For each exception range R in body, let T := R.handler. T is in body, and R is one * of T's targeters * <li> All ranges are properly nested: For all ranges Q and R, if Q.start preceeds * R.start, then R.end preceeds Q.end. * </ul> * * Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and * any InstructionHandle stored in a field of R (such as an exception handle) is in body". */ public void assertGoodBody() { if (true) return; // only enable for debugging, consider using cheaper toString() assertGoodBody(getBody(), toString()); //definingType.getNameAsIdentifier() + "." + getName()); //toString()); } public static void assertGoodBody(InstructionList il, String from) { if (true) return; // only to be enabled for debugging if (il == null) return; Set body = new HashSet(); Stack ranges = new Stack(); for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { body.add(ih); if (ih.getInstruction() instanceof BranchInstruction) { body.add(ih.getInstruction()); } } for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { assertGoodHandle(ih, body, ranges, from); InstructionTargeter[] ts = ih.getTargeters(); if (ts != null) { for (int i = ts.length - 1; i >= 0; i--) { assertGoodTargeter(ts[i], ih, body, from); } } } } private static void assertGoodHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Instruction inst = ih.getInstruction(); if ((inst instanceof BranchInstruction) ^ (ih instanceof BranchHandle)) { throw new BCException("bad instruction/handle pair in " + from); } if (Range.isRangeHandle(ih)) { assertGoodRangeHandle(ih, body, ranges, from); } else if (inst instanceof BranchInstruction) { assertGoodBranchInstruction((BranchHandle) ih, (BranchInstruction) inst, body, ranges, from); } } private static void assertGoodBranchInstruction( BranchHandle ih, BranchInstruction inst, Set body, Stack ranges, String from) { if (ih.getTarget() != inst.getTarget()) { throw new BCException("bad branch instruction/handle pair in " + from); } InstructionHandle target = ih.getTarget(); assertInBody(target, body, from); assertTargetedBy(target, inst, from); if (inst instanceof Select) { Select sel = (Select) inst; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { assertInBody(itargets[k], body, from); assertTargetedBy(itargets[k], inst, from); } } } /** ih is an InstructionHandle or a BranchInstruction */ private static void assertInBody(Object ih, Set body, String from) { if (! body.contains(ih)) throw new BCException("thing not in body in " + from); } private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Range r = getRangeAndAssertExactlyOne(ih, from); assertGoodRange(r, body, from); if (r.getStart() == ih) { ranges.push(r); } else if (r.getEnd() == ih) { if (ranges.peek() != r) throw new BCException("bad range inclusion in " + from); ranges.pop(); } } private static void assertGoodRange(Range r, Set body, String from) { assertInBody(r.getStart(), body, from); assertRangeHandle(r.getStart(), from); assertTargetedBy(r.getStart(), r, from); assertInBody(r.getEnd(), body, from); assertRangeHandle(r.getEnd(), from); assertTargetedBy(r.getEnd(), r, from); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; assertInBody(er.getHandler(), body, from); assertTargetedBy(er.getHandler(), r, from); } } private static void assertRangeHandle(InstructionHandle ih, String from) { if (! Range.isRangeHandle(ih)) throw new BCException("bad range handle " + ih + " in " + from); } private static void assertTargetedBy( InstructionHandle target, InstructionTargeter targeter, String from) { InstructionTargeter[] ts = target.getTargeters(); if (ts == null) throw new BCException("bad targeting relationship in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] == targeter) return; } throw new RuntimeException("bad targeting relationship in " + from); } private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) { if (targeter instanceof Range) { Range r = (Range) targeter; if (r.getStart() == target || r.getEnd() == target) return; if (r instanceof ExceptionRange) { if (((ExceptionRange)r).getHandler() == target) return; } } else if (targeter instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) targeter; if (bi.getTarget() == target) return; if (targeter instanceof Select) { Select sel = (Select) targeter; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { if (itargets[k] == target) return; } } } else if (targeter instanceof Tag) { return; } throw new BCException(targeter + " doesn't target " + target + " in " + from ); } private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) { Range ret = null; InstructionTargeter[] ts = ih.getTargeters(); if (ts == null) throw new BCException("range handle with no range in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] instanceof Range) { if (ret != null) throw new BCException("range handle with multiple ranges in " + from); ret = (Range) ts[i]; } } if (ret == null) throw new BCException("range handle with no range in " + from); return ret; } private static void assertGoodTargeter( InstructionTargeter t, InstructionHandle ih, Set body, String from) { assertTargets(t, ih, from); if (t instanceof Range) { assertGoodRange((Range) t, body, from); } else if (t instanceof BranchInstruction) { assertInBody(t, body, from); } } // ---- boolean isAdviceMethod() { return memberView.getAssociatedShadowMunger() != null; } boolean isAjSynthetic() { if (memberView == null) return true; return memberView.isAjSynthetic(); } public ISourceLocation getSourceLocation() { if (memberView!=null) return memberView.getSourceLocation(); return null; } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { //if (memberView == null) return null; if (effectiveSignature != null) return effectiveSignature; return memberView.getEffectiveSignature(); } public void setEffectiveSignature(ResolvedMember member, Shadow.Kind kind, boolean shouldWeave) { this.effectiveSignature = new AjAttribute.EffectiveSignatureAttribute(member,kind,shouldWeave); } public String getSignature() { if (memberView!=null) return memberView.getSignature(); return MemberImpl.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes()),false); } public String getParameterSignature() { if (memberView!=null) return memberView.getParameterSignature(); return MemberImpl.typesToSignature(BcelWorld.fromBcel(getArgumentTypes())); } public BcelMethod getMemberView() { return memberView; } public void forcePublic() { markAsChanged(); accessFlags = Utility.makePublic(accessFlags); } public boolean getCanInline() { return canInline; } public void setCanInline(boolean canInline) { this.canInline = canInline; } /** * Adds an attribute to the method * @param attr */ public void addAttribute(Attribute attr) { Attribute[] newAttributes = new Attribute[attributes.length + 1]; System.arraycopy(attributes, 0, newAttributes, 0, attributes.length); newAttributes[attributes.length] = attr; attributes = newAttributes; } }
101,407
Bug 101407 NullPointerException when selecting Save As in top menu
The Steps of Reproduce: 1. Open BIRT 2. New a project 3. In top menu of File, click New -> Report to create a report 4. Drag a table element from Palette into the report of Layout view 5. Save the report 6. Drag mouse to select two cells in the table 7. Select the report in Navigator view 8. In the top menu, select Save As... 9. In the Save As pop up dialog window, change the file name in the File name field, then click OK button Expected Result: There is no error to click OK button Actual Result: Error window pops up and the error log as follows: java.lang.NullPointerException at org.eclipse.gef.editparts.AbstractEditPart.getRoot (AbstractEditPart.java:587) at org.eclipse.gef.editparts.AbstractEditPart.getRoot (AbstractEditPart.java:587) at org.eclipse.gef.editparts.AbstractEditPart.getViewer (AbstractEditPart.java:637) at org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableU til.getSelectionCells(TableUtil.java:258) at org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableE ditPart.canMerge(TableEditPart.java:1244) at org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.MergeAct ion.calculateEnabled(MergeAction.java:51) at org.eclipse.gef.ui.actions.WorkbenchPartAction.isEnabled (WorkbenchPartAction.java:111) at org.eclipse.ui.actions.RetargetAction.setActionHandler (RetargetAction.java:249) at org.eclipse.ui.actions.RetargetAction.partActivated (RetargetAction.java:144) at org.eclipse.ui.internal.PartListenerList$1.run (PartListenerList.java:49) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:616) at org.eclipse.core.runtime.Platform.run(Platform.java:747) at org.eclipse.ui.internal.PartListenerList.firePartActivated (PartListenerList.java:47) at org.eclipse.ui.internal.WorkbenchPage.firePartActivated (WorkbenchPage.java:1370) at org.eclipse.ui.internal.WorkbenchPage.setActivePart (WorkbenchPage.java:2738) at org.eclipse.ui.internal.WorkbenchPage.requestActivation (WorkbenchPage.java:2415) at org.eclipse.ui.internal.PartPane.requestActivation (PartPane.java:304) at org.eclipse.ui.internal.EditorPane.requestActivation (EditorPane.java:127) at org.eclipse.ui.internal.PartPane.handleEvent(PartPane.java:284) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:820) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:801) at org.eclipse.swt.widgets.Shell.setActiveControl(Shell.java:935) at org.eclipse.swt.widgets.Control.sendFocusEvent(Control.java:1768) at org.eclipse.swt.widgets.Control.WM_SETFOCUS(Control.java:4139) at org.eclipse.swt.widgets.Canvas.WM_SETFOCUS(Canvas.java:239) at org.eclipse.swt.widgets.Control.windowProc(Control.java:3032) at org.eclipse.swt.widgets.Display.windowProc(Display.java:3338) at org.eclipse.swt.internal.win32.OS.SetFocus(Native Method) at org.eclipse.swt.widgets.Control.forceFocus(Control.java:607) at org.eclipse.swt.widgets.Control.setFocus(Control.java:2054) at org.eclipse.swt.widgets.Composite.setFocus(Composite.java:447) at org.eclipse.gef.ui.parts.GraphicalEditor.setFocus (GraphicalEditor.java:346) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:545) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:519) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:545) at org.eclipse.ui.part.MultiPageEditorPart.setFocus (MultiPageEditorPart.java:519) at org.eclipse.ui.part.MultiPageEditorPart.pageChange (MultiPageEditorPart.java:433) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.pageChange (ReportEditor.java:1179) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.rebuildReportDesign (ReportEditor.java:584) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.setInput (ReportEditor.java:547) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.performSaveAs (ReportEditor.java:870) at org.eclipse.birt.report.designer.ui.editors.ReportEditor.doSaveAs (ReportEditor.java:812) at org.eclipse.ui.internal.SaveAsAction.run(SaveAsAction.java:64) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:915) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:866) at org.eclipse.jface.action.ActionContributionItem$7.handleEvent (ActionContributionItem.java:785) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2772) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2431) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1377) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1348) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:254) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:96) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:335) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:273) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:129) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:185) at org.eclipse.core.launcher.Main.run(Main.java:704) at org.eclipse.core.launcher.Main.main(Main.java:688)
closed fixed
97520cf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-27T21:08:24Z
2005-06-23T07:00:00Z
weaver/src/org/aspectj/weaver/bcel/LocalVariableTag.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 org.aspectj.weaver.UnresolvedType; public final class LocalVariableTag extends Tag { private final UnresolvedType type; private final String name; private final int slot; public LocalVariableTag(UnresolvedType type, String name, int slot) { this.type = type; this.name = name; this.slot = slot; } public String getName() { return name; } public int getSlot() { return slot; } public UnresolvedType getType() { return type; } // ---- from Object public String toString() { return "local " + slot + ": " + type + " " + name; } public boolean equals(Object other) { if (!(other instanceof LocalVariableTag)) return false; LocalVariableTag o = (LocalVariableTag)other; return o.type.equals(type) && o.name.equals(name) && o.slot == slot; } private volatile int hashCode = 0; public int hashCode() { if (hashCode == 0) { int ret = 17; ret = 37*ret + type.hashCode(); ret = 37*ret + name.hashCode(); ret = 37*ret + slot; hashCode = ret; } return hashCode; } }
101,047
Bug 101047 Weaver produces wrong local variable table bytecode
AspectJ version: DEVELOPMENT (also observed in 1.2.1) When weaving with a before or after advice, the generated local variable table will, on branch instructions, offset the "length" field of a local variable wrongly by one instruction. Also, the weaver will mix up local variables with the same name, thus violating the java VM specification: // Test.aj aspect Test { before() : ( execution(* Foo.foo(..) ) ) { System.out.println("before"); } // Foo.java public class Foo { private String myString = "A String"; public static void main(String[] args) { new Foo().foo(); } private void foo() { String myLocal = myString; if (myLocal.endsWith("X")) { String local1 = "local1"; System.out.println(local1); } else if (myLocal.endsWith("Y")) { String local2 = "local2"; System.out.println(local2); } else { String local1 = "local3"; System.out.println(local1); } } } --- We compilw with ajc -sourceroots . and dumps Foo with javap: javap -c -l -s -private Foo .... .... private void foo(); Signature: ()V Code: 0: invokestatic #65; //Method Test.aspectOf:()LTest; 3: invokevirtual #68; //Method Test.ajc$before$Test$1$f0485e90:()V 6: aload_0 7: getfield #15; //Field myString:Ljava/lang/String; 10: astore_1 11: aload_1 12: ldc #30; //String X 14: invokevirtual #36; //Method java/lang/String.endsWith: (Ljava/lang/String;)Z 17: ifeq 33 20: ldc #38; //String local1 22: astore_2 23: getstatic #44; //Field java/lang/System.out:Ljava/io/PrintStream; 26: aload_2 27: invokevirtual #50; //Method java/io/PrintStream.println: (Ljava/lang/String;)V 30: goto 65 33: aload_1 34: ldc #52; //String Y 36: invokevirtual #36; //Method java/lang/String.endsWith: (Ljava/lang/String;)Z 39: ifeq 55 42: ldc #54; //String local2 44: astore_2 45: getstatic #44; //Field java/lang/System.out:Ljava/io/PrintStream; 48: aload_2 49: invokevirtual #50; //Method java/io/PrintStream.println: (Ljava/lang/String;)V 52: goto 65 55: ldc #56; //String local3 57: astore_2 58: getstatic #44; //Field java/lang/System.out:Ljava/io/PrintStream; 61: aload_2 62: invokevirtual #50; //Method java/io/PrintStream.println: (Ljava/lang/String;)V 65: return LineNumberTable: line 7: 6 line 8: 11 line 9: 20 line 10: 23 line 11: 33 line 12: 42 line 13: 45 line 15: 55 line 16: 58 line 18: 65 LocalVariableTable: Start Length Slot Name Signature 6 60 0 this LFoo; 11 55 1 myLocal Ljava/lang/String; 45 12 2 local2 Ljava/lang/String; 23 43 2 local1 Ljava/lang/String; We see that the two occurences of the "local1" variable erroneously have been combined into one entry, starting at byte 23 and ending at byte 66. This is obviously wrong, since "local1" has no value in the "local2" block. Secondly, the "local2" variable end is wrongly offset by one instruction offset.
resolved fixed
85a4b0a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-09-28T20:10:19Z
2005-06-21T13:20:00Z
bcel-builder/src/org/aspectj/apache/bcel/generic/MethodGen.java
package org.aspectj.apache.bcel.generic; /* ==================================================================== * 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 java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Stack; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Code; import org.aspectj.apache.bcel.classfile.CodeException; import org.aspectj.apache.bcel.classfile.ExceptionTable; import org.aspectj.apache.bcel.classfile.LineNumber; import org.aspectj.apache.bcel.classfile.LineNumberTable; import org.aspectj.apache.bcel.classfile.LocalVariable; import org.aspectj.apache.bcel.classfile.LocalVariableTable; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Utility; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnotations; import org.aspectj.apache.bcel.classfile.annotation.RuntimeParameterAnnotations; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; /** * Template class for building up a method. This is done by defining exception * handlers, adding thrown exceptions, local variables and attributes, whereas * the `LocalVariableTable' and `LineNumberTable' attributes will be set * automatically for the code. Use stripAttributes() if you don't like this. * * While generating code it may be necessary to insert NOP operations. You can * use the `removeNOPs' method to get rid off them. * The resulting method object can be obtained via the `getMethod()' method. * * @version $Id: MethodGen.java,v 1.4 2005/03/10 12:15:04 aclement Exp $ * @author <A HREF="mailto:[email protected]">M. Dahm</A> * @author <A HREF="http://www.vmeng.com/beard">Patrick C. Beard</A> [setMaxStack()] * @see InstructionList * @see Method */ public class MethodGen extends FieldGenOrMethodGen { private String class_name; private Type[] arg_types; private String[] arg_names; private int max_locals; private int max_stack; private InstructionList il; private boolean strip_attributes; private ArrayList variable_vec = new ArrayList(); private ArrayList line_number_vec = new ArrayList(); private ArrayList exception_vec = new ArrayList(); private ArrayList throws_vec = new ArrayList(); private ArrayList code_attrs_vec = new ArrayList(); private List[] param_annotations; // Array of lists containing AnnotationGen objects private boolean hasParameterAnnotations = false; private boolean haveUnpackedParameterAnnotations = false; /** * Declare method. If the method is non-static the constructor * automatically declares a local variable `$this' in slot 0. The * actual code is contained in the `il' parameter, which may further * manipulated by the user. But he must take care not to remove any * instruction (handles) that are still referenced from this object. * * For example one may not add a local variable and later remove the * instructions it refers to without causing havoc. It is safe * however if you remove that local variable, too. * * @param access_flags access qualifiers * @param return_type method type * @param arg_types argument types * @param arg_names argument names (if this is null, default names will be provided * for them) * @param method_name name of method * @param class_name class name containing this method (may be null, if you don't care) * @param il instruction list associated with this method, may be null only for * abstract or native methods * @param cp constant pool */ public MethodGen(int access_flags, Type return_type, Type[] arg_types, String[] arg_names, String method_name, String class_name, InstructionList il, ConstantPoolGen cp) { setAccessFlags(access_flags); setType(return_type); setArgumentTypes(arg_types); setArgumentNames(arg_names); setName(method_name); setClassName(class_name); setInstructionList(il); setConstantPool(cp); boolean abstract_ = isAbstract() || isNative(); InstructionHandle start = null; InstructionHandle end = null; if(!abstract_) { start = il.getStart(); end = il.getEnd(); /* Add local variables, namely the implicit `this' and the arguments */ // if(!isStatic() && (class_name != null)) { // Instance method -> `this' is local var 0 // addLocalVariable("this", new ObjectType(class_name), start, end); // } } if(arg_types != null) { int size = arg_types.length; for(int i=0; i < size; i++) { if(Type.VOID == arg_types[i]) { throw new ClassGenException("'void' is an illegal argument type for a method"); } } if(arg_names != null) { // Names for variables provided? if(size != arg_names.length) throw new ClassGenException("Mismatch in argument array lengths: " + size + " vs. " + arg_names.length); } else { // Give them dummy names // arg_names = new String[size]; // // for(int i=0; i < size; i++) // arg_names[i] = "arg" + i; // // setArgumentNames(arg_names); } if(!abstract_) { for(int i=0; i < size; i++) { // addLocalVariable(arg_names[i], arg_types[i], start, end); } } } } /** * Instantiate from existing method. * * @param m method * @param class_name class name containing this method * @param cp constant pool */ public MethodGen(Method m, String class_name, ConstantPoolGen cp) { this(m.getAccessFlags(), Type.getReturnType(m.getSignature()), Type.getArgumentTypes(m.getSignature()), null /* may be overridden anyway */, m.getName(), class_name, ((m.getAccessFlags() & (Constants.ACC_ABSTRACT | Constants.ACC_NATIVE)) == 0)? new InstructionList(m.getCode().getCode()) : null, cp); Attribute[] attributes = m.getAttributes(); for(int i=0; i < attributes.length; i++) { Attribute a = attributes[i]; if(a instanceof Code) { Code c = (Code)a; setMaxStack(c.getMaxStack()); setMaxLocals(c.getMaxLocals()); CodeException[] ces = c.getExceptionTable(); if(ces != null) { for(int j=0; j < ces.length; j++) { CodeException ce = ces[j]; int type = ce.getCatchType(); ObjectType c_type = null; if(type > 0) { String cen = m.getConstantPool().getConstantString(type, Constants.CONSTANT_Class); c_type = new ObjectType(cen); } int end_pc = ce.getEndPC(); int length = m.getCode().getCode().length; InstructionHandle end; if(length == end_pc) { // May happen, because end_pc is exclusive end = il.getEnd(); } else { end = il.findHandle(end_pc); end = end.getPrev(); // Make it inclusive } addExceptionHandler(il.findHandle(ce.getStartPC()), end, il.findHandle(ce.getHandlerPC()), c_type); } } Attribute[] c_attributes = c.getAttributes(); for(int j=0; j < c_attributes.length; j++) { a = c_attributes[j]; if(a instanceof LineNumberTable) { LineNumber[] ln = ((LineNumberTable)a).getLineNumberTable(); for(int k=0; k < ln.length; k++) { LineNumber l = ln[k]; addLineNumber(il.findHandle(l.getStartPC()), l.getLineNumber()); } } else if(a instanceof LocalVariableTable) { LocalVariable[] lv = ((LocalVariableTable)a).getLocalVariableTable(); removeLocalVariables(); for(int k=0; k < lv.length; k++) { LocalVariable l = lv[k]; InstructionHandle start = il.findHandle(l.getStartPC()); InstructionHandle end = il.findHandle(l.getStartPC() + l.getLength()); // Repair malformed handles if(null == start) { start = il.getStart(); } if(null == end) { end = il.getEnd(); } addLocalVariable(l.getName(), Type.getType(l.getSignature()), l.getIndex(), start, end); } } else addCodeAttribute(a); } } else if(a instanceof ExceptionTable) { String[] names = ((ExceptionTable)a).getExceptionNames(); for(int j=0; j < names.length; j++) addException(names[j]); } else if (a instanceof RuntimeAnnotations) { RuntimeAnnotations runtimeAnnotations = (RuntimeAnnotations)a; List l = runtimeAnnotations.getAnnotations(); for (Iterator it = l.iterator(); it.hasNext();) { Annotation element = (Annotation) it.next(); addAnnotation(new AnnotationGen(element,cp,false)); } } else { addAttribute(a); } } } /** * Adds a local variable to this method. * * @param name variable name * @param type variable type * @param slot the index of the local variable, if type is long or double, the next available * index is slot+2 * @param start from where the variable is valid * @param end until where the variable is valid * @return new local variable object * @see LocalVariable */ public LocalVariableGen addLocalVariable(String name, Type type, int slot, InstructionHandle start, InstructionHandle end) { byte t = type.getType(); if(t != Constants.T_ADDRESS) { int add = type.getSize(); if(slot + add > max_locals) max_locals = slot + add; LocalVariableGen l = new LocalVariableGen(slot, name, type, start, end); int i; if((i = variable_vec.indexOf(l)) >= 0) // Overwrite if necessary variable_vec.set(i, l); else variable_vec.add(l); return l; } else { throw new IllegalArgumentException("Can not use " + type + " as type for local variable"); } } /** * Adds a local variable to this method and assigns an index automatically. * * @param name variable name * @param type variable type * @param start from where the variable is valid, if this is null, * it is valid from the start * @param end until where the variable is valid, if this is null, * it is valid to the end * @return new local variable object * @see LocalVariable */ public LocalVariableGen addLocalVariable(String name, Type type, InstructionHandle start, InstructionHandle end) { return addLocalVariable(name, type, max_locals, start, end); } /** * Remove a local variable, its slot will not be reused, if you do not use addLocalVariable * with an explicit index argument. */ public void removeLocalVariable(LocalVariableGen l) { variable_vec.remove(l); } /** * Remove all local variables. */ public void removeLocalVariables() { variable_vec.clear(); } /** * Sort local variables by index */ private static final void sort(LocalVariableGen[] vars, int l, int r) { int i = l, j = r; int m = vars[(l + r) / 2].getIndex(); LocalVariableGen h; do { while(vars[i].getIndex() < m) i++; while(m < vars[j].getIndex()) j--; if(i <= j) { h=vars[i]; vars[i]=vars[j]; vars[j]=h; // Swap elements i++; j--; } } while(i <= j); if(l < j) sort(vars, l, j); if(i < r) sort(vars, i, r); } /* * If the range of the variable has not been set yet, it will be set to be valid from * the start to the end of the instruction list. * * @return array of declared local variables sorted by index */ public LocalVariableGen[] getLocalVariables() { int size = variable_vec.size(); LocalVariableGen[] lg = new LocalVariableGen[size]; variable_vec.toArray(lg); for(int i=0; i < size; i++) { if(lg[i].getStart() == null) lg[i].setStart(il.getStart()); if(lg[i].getEnd() == null) lg[i].setEnd(il.getEnd()); } if(size > 1) sort(lg, 0, size - 1); return lg; } /** * @return `LocalVariableTable' attribute of all the local variables of this method. */ public LocalVariableTable getLocalVariableTable(ConstantPoolGen cp) { LocalVariableGen[] lg = getLocalVariables(); int size = lg.length; LocalVariable[] lv = new LocalVariable[size]; for(int i=0; i < size; i++) lv[i] = lg[i].getLocalVariable(cp); return new LocalVariableTable(cp.addUtf8("LocalVariableTable"), 2 + lv.length * 10, lv, cp.getConstantPool()); } /** * Give an instruction a line number corresponding to the source code line. * * @param ih instruction to tag * @return new line number object * @see LineNumber */ public LineNumberGen addLineNumber(InstructionHandle ih, int src_line) { LineNumberGen l = new LineNumberGen(ih, src_line); line_number_vec.add(l); return l; } /** * Remove a line number. */ public void removeLineNumber(LineNumberGen l) { line_number_vec.remove(l); } /** * Remove all line numbers. */ public void removeLineNumbers() { line_number_vec.clear(); } /* * @return array of line numbers */ public LineNumberGen[] getLineNumbers() { LineNumberGen[] lg = new LineNumberGen[line_number_vec.size()]; line_number_vec.toArray(lg); return lg; } /** * @return `LineNumberTable' attribute of all the local variables of this method. */ public LineNumberTable getLineNumberTable(ConstantPoolGen cp) { int size = line_number_vec.size(); LineNumber[] ln = new LineNumber[size]; try { for(int i=0; i < size; i++) ln[i] = ((LineNumberGen)line_number_vec.get(i)).getLineNumber(); } catch(ArrayIndexOutOfBoundsException e) {} // Never occurs return new LineNumberTable(cp.addUtf8("LineNumberTable"), 2 + ln.length * 4, ln, cp.getConstantPool()); } /** * Add an exception handler, i.e., specify region where a handler is active and an * instruction where the actual handling is done. * * @param start_pc Start of region (inclusive) * @param end_pc End of region (inclusive) * @param handler_pc Where handling is done * @param catch_type class type of handled exception or null if any * exception is handled * @return new exception handler object */ public CodeExceptionGen addExceptionHandler(InstructionHandle start_pc, InstructionHandle end_pc, InstructionHandle handler_pc, ObjectType catch_type) { if((start_pc == null) || (end_pc == null) || (handler_pc == null)) throw new ClassGenException("Exception handler target is null instruction"); CodeExceptionGen c = new CodeExceptionGen(start_pc, end_pc, handler_pc, catch_type); exception_vec.add(c); return c; } /** * Remove an exception handler. */ public void removeExceptionHandler(CodeExceptionGen c) { exception_vec.remove(c); } /** * Remove all line numbers. */ public void removeExceptionHandlers() { exception_vec.clear(); } /* * @return array of declared exception handlers */ public CodeExceptionGen[] getExceptionHandlers() { CodeExceptionGen[] cg = new CodeExceptionGen[exception_vec.size()]; exception_vec.toArray(cg); return cg; } /** * @return code exceptions for `Code' attribute */ private CodeException[] getCodeExceptions() { int size = exception_vec.size(); CodeException[] c_exc = new CodeException[size]; try { for(int i=0; i < size; i++) { CodeExceptionGen c = (CodeExceptionGen)exception_vec.get(i); c_exc[i] = c.getCodeException(cp); } } catch(ArrayIndexOutOfBoundsException e) {} return c_exc; } /** * Add an exception possibly thrown by this method. * * @param class_name (fully qualified) name of exception */ public void addException(String class_name) { throws_vec.add(class_name); } /** * Remove an exception. */ public void removeException(String c) { throws_vec.remove(c); } /** * Remove all exceptions. */ public void removeExceptions() { throws_vec.clear(); } /* * @return array of thrown exceptions */ public String[] getExceptions() { String[] e = new String[throws_vec.size()]; throws_vec.toArray(e); return e; } /** * @return `Exceptions' attribute of all the exceptions thrown by this method. */ private ExceptionTable getExceptionTable(ConstantPoolGen cp) { int size = throws_vec.size(); int[] ex = new int[size]; try { for(int i=0; i < size; i++) ex[i] = cp.addClass((String)throws_vec.get(i)); } catch(ArrayIndexOutOfBoundsException e) {} return new ExceptionTable(cp.addUtf8("Exceptions"), 2 + 2 * size, ex, cp.getConstantPool()); } /** * Add an attribute to the code. Currently, the JVM knows about the * LineNumberTable, LocalVariableTable and StackMap attributes, * where the former two will be generated automatically and the * latter is used for the MIDP only. Other attributes will be * ignored by the JVM but do no harm. * * @param a attribute to be added */ public void addCodeAttribute(Attribute a) { code_attrs_vec.add(a); } public void addAnnotationsAsAttribute(ConstantPoolGen cp) { Attribute[] attrs = Utility.getAnnotationAttributes(cp,annotation_vec); if (attrs!=null) { for (int i = 0; i < attrs.length; i++) { addAttribute(attrs[i]); } } } public void addParameterAnnotationsAsAttribute(ConstantPoolGen cp) { if (!hasParameterAnnotations) return; Attribute[] attrs = Utility.getParameterAnnotationAttributes(cp,param_annotations); if (attrs!=null) { for (int i = 0; i < attrs.length; i++) { addAttribute(attrs[i]); } } } /** * Remove a code attribute. */ public void removeCodeAttribute(Attribute a) { code_attrs_vec.remove(a); } /** * Remove all code attributes. */ public void removeCodeAttributes() { code_attrs_vec.clear(); } /** * @return all attributes of this method. */ public Attribute[] getCodeAttributes() { Attribute[] attributes = new Attribute[code_attrs_vec.size()]; code_attrs_vec.toArray(attributes); return attributes; } /** * Get method object. Never forget to call setMaxStack() or setMaxStack(max), respectively, * before calling this method (the same applies for max locals). * * @return method object */ public Method getMethod() { String signature = getSignature(); int name_index = cp.addUtf8(name); int signature_index = cp.addUtf8(signature); /* Also updates positions of instructions, i.e., their indices */ byte[] byte_code = null; if(il != null) byte_code = il.getByteCode(); LineNumberTable lnt = null; LocalVariableTable lvt = null; //J5TODO: LocalVariableTypeTable support! /* Create LocalVariableTable and LineNumberTable attributes (for debuggers, e.g.) */ if((variable_vec.size() > 0) && !strip_attributes) addCodeAttribute(lvt = getLocalVariableTable(cp)); if((line_number_vec.size() > 0) && !strip_attributes) addCodeAttribute(lnt = getLineNumberTable(cp)); Attribute[] code_attrs = getCodeAttributes(); /* Each attribute causes 6 additional header bytes */ int attrs_len = 0; for(int i=0; i < code_attrs.length; i++) attrs_len += (code_attrs[i].getLength() + 6); CodeException[] c_exc = getCodeExceptions(); int exc_len = c_exc.length * 8; // Every entry takes 8 bytes Code code = null; if((il != null) && !isAbstract()) { // Remove any stale code attribute Attribute[] attributes = getAttributes(); for(int i=0; i < attributes.length; i++) { Attribute a = attributes[i]; if(a instanceof Code) removeAttribute(a); } code = new Code(cp.addUtf8("Code"), 8 + byte_code.length + // prologue byte code 2 + exc_len + // exceptions 2 + attrs_len, // attributes max_stack, max_locals, byte_code, c_exc, code_attrs, cp.getConstantPool()); addAttribute(code); } addAnnotationsAsAttribute(cp); addParameterAnnotationsAsAttribute(cp); ExceptionTable et = null; if(throws_vec.size() > 0) addAttribute(et = getExceptionTable(cp)); // Add `Exceptions' if there are "throws" clauses Method m = new Method(access_flags, name_index, signature_index, getAttributes(), cp.getConstantPool()); // Undo effects of adding attributes if(lvt != null) removeCodeAttribute(lvt); if(lnt != null) removeCodeAttribute(lnt); if(code != null) removeAttribute(code); if(et != null) removeAttribute(et); //J5TODO: Remove the annotation attributes that may have been added return m; } /** * Remove all NOPs from the instruction list (if possible) and update every * object refering to them, i.e., branch instructions, local variables and * exception handlers. */ public void removeNOPs() { if(il != null) { InstructionHandle next; /* Check branch instructions. */ for(InstructionHandle ih = il.getStart(); ih != null; ih = next) { next = ih.next; if((next != null) && (ih.getInstruction() instanceof NOP)) { try { il.delete(ih); } catch(TargetLostException e) { InstructionHandle[] targets = e.getTargets(); for(int i=0; i < targets.length; i++) { InstructionTargeter[] targeters = targets[i].getTargeters(); for(int j=0; j < targeters.length; j++) targeters[j].updateTarget(targets[i], next); } } } } } } /** * Set maximum number of local variables. */ public void setMaxLocals(int m) { max_locals = m; } public int getMaxLocals() { return max_locals; } /** * Set maximum stack size for this method. */ public void setMaxStack(int m) { max_stack = m; } public int getMaxStack() { return max_stack; } /** @return class that contains this method */ public String getClassName() { return class_name; } public void setClassName(String class_name) { this.class_name = class_name; } public void setReturnType(Type return_type) { setType(return_type); } public Type getReturnType() { return getType(); } public void setArgumentTypes(Type[] arg_types) { this.arg_types = arg_types; } public Type[] getArgumentTypes() { return (Type[])arg_types.clone(); } public void setArgumentType(int i, Type type) { arg_types[i] = type; } public Type getArgumentType(int i) { return arg_types[i]; } public void setArgumentNames(String[] arg_names) { this.arg_names = arg_names; } public String[] getArgumentNames() { if (arg_names!=null) return (String[])arg_names.clone(); else return new String[0]; } public void setArgumentName(int i, String name) { arg_names[i] = name; } public String getArgumentName(int i) { return arg_names[i]; } public InstructionList getInstructionList() { return il; } public void setInstructionList(InstructionList il) { this.il = il; } public String getSignature() { return Type.getMethodSignature(type, arg_types); } /** * Computes max. stack size by performing control flow analysis. */ public void setMaxStack() { if(il != null) max_stack = getMaxStack(cp, il, getExceptionHandlers()); else max_stack = 0; } /** * Compute maximum number of local variables. */ public void setMaxLocals() { if(il != null) { int max = isStatic()? 0 : 1; if(arg_types != null) for(int i=0; i < arg_types.length; i++) max += arg_types[i].getSize(); for(InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { Instruction ins = ih.getInstruction(); if((ins instanceof LocalVariableInstruction) || (ins instanceof RET) || (ins instanceof IINC)) { int index = ((IndexedInstruction)ins).getIndex() + ((TypedInstruction)ins).getType(cp).getSize(); if(index > max) max = index; } } max_locals = max; } else max_locals = 0; } /** Do not/Do produce attributes code attributesLineNumberTable and * LocalVariableTable, like javac -O */ public void stripAttributes(boolean flag) { strip_attributes = flag; } static final class BranchTarget { InstructionHandle target; int stackDepth; BranchTarget(InstructionHandle target, int stackDepth) { this.target = target; this.stackDepth = stackDepth; } } static final class BranchStack { Stack branchTargets = new Stack(); Hashtable visitedTargets = new Hashtable(); public void push(InstructionHandle target, int stackDepth) { if(visited(target)) return; branchTargets.push(visit(target, stackDepth)); } public BranchTarget pop() { if(!branchTargets.empty()) { BranchTarget bt = (BranchTarget) branchTargets.pop(); return bt; } return null; } private final BranchTarget visit(InstructionHandle target, int stackDepth) { BranchTarget bt = new BranchTarget(target, stackDepth); visitedTargets.put(target, bt); return bt; } private final boolean visited(InstructionHandle target) { return (visitedTargets.get(target) != null); } } /** * Computes stack usage of an instruction list by performing control flow analysis. * * @return maximum stack depth used by method */ public static int getMaxStack(ConstantPoolGen cp, InstructionList il, CodeExceptionGen[] et) { BranchStack branchTargets = new BranchStack(); /* Initially, populate the branch stack with the exception * handlers, because these aren't (necessarily) branched to * explicitly. in each case, the stack will have depth 1, * containing the exception object. */ for (int i = 0; i < et.length; i++) { InstructionHandle handler_pc = et[i].getHandlerPC(); if (handler_pc != null) branchTargets.push(handler_pc, 1); } int stackDepth = 0, maxStackDepth = 0; InstructionHandle ih = il.getStart(); while(ih != null) { Instruction instruction = ih.getInstruction(); short opcode = instruction.getOpcode(); int delta = instruction.produceStack(cp) - instruction.consumeStack(cp); stackDepth += delta; if(stackDepth > maxStackDepth) maxStackDepth = stackDepth; // choose the next instruction based on whether current is a branch. if(instruction instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction) instruction; if(instruction instanceof Select) { // explore all of the select's targets. the default target is handled below. Select select = (Select) branch; InstructionHandle[] targets = select.getTargets(); for (int i = 0; i < targets.length; i++) branchTargets.push(targets[i], stackDepth); // nothing to fall through to. ih = null; } else if(!(branch instanceof IfInstruction)) { // if an instruction that comes back to following PC, // push next instruction, with stack depth reduced by 1. if(opcode == Constants.JSR || opcode == Constants.JSR_W) branchTargets.push(ih.getNext(), stackDepth - 1); ih = null; } // for all branches, the target of the branch is pushed on the branch stack. // conditional branches have a fall through case, selects don't, and // jsr/jsr_w return to the next instruction. branchTargets.push(branch.getTarget(), stackDepth); } else { // check for instructions that terminate the method. if(opcode == Constants.ATHROW || opcode == Constants.RET || (opcode >= Constants.IRETURN && opcode <= Constants.RETURN)) ih = null; } // normal case, go to the next instruction. if(ih != null) ih = ih.getNext(); // if we have no more instructions, see if there are any deferred branches to explore. if(ih == null) { BranchTarget bt = branchTargets.pop(); if (bt != null) { ih = bt.target; stackDepth = bt.stackDepth; } } } return maxStackDepth; } private ArrayList observers; /** Add observer for this object. */ public void addObserver(MethodObserver o) { if(observers == null) observers = new ArrayList(); observers.add(o); } /** Remove observer for this object. */ public void removeObserver(MethodObserver o) { if(observers != null) observers.remove(o); } /** Call notify() method on all observers. This method is not called * automatically whenever the state has changed, but has to be * called by the user after he has finished editing the object. */ public void update() { if(observers != null) for(Iterator e = observers.iterator(); e.hasNext(); ) ((MethodObserver)e.next()).notify(this); } /** * Return string representation close to declaration format, * `public static void main(String[]) throws IOException', e.g. * * @return String representation of the method. */ public final String toString() { String access = Utility.accessToString(access_flags); String signature = Type.getMethodSignature(type, arg_types); signature = Utility.methodSignatureToString(signature, name, access, true, getLocalVariableTable(cp)); StringBuffer buf = new StringBuffer(signature); if(throws_vec.size() > 0) { for(Iterator e = throws_vec.iterator(); e.hasNext(); ) buf.append("\n\t\tthrows " + e.next()); } return buf.toString(); } /** @return deep copy of this method */ public MethodGen copy(String class_name, ConstantPoolGen cp) { Method m = ((MethodGen)clone()).getMethod(); MethodGen mg = new MethodGen(m, class_name, this.cp); if(this.cp != cp) { mg.setConstantPool(cp); mg.getInstructionList().replaceConstantPool(this.cp, cp); } return mg; } //J5TODO: Should param_annotations be an array of arrays? Rather than an array of lists, this // is more likely to suggest to the caller it is readonly (which a List does not). /** * Return a list of AnnotationGen objects representing parameter annotations */ public List getAnnotationsOnParameter(int i) { ensureExistingParameterAnnotationsUnpacked(); if (!hasParameterAnnotations || i>arg_types.length) return null; return param_annotations[i]; } /** * Goes through the attributes on the method and identifies any that are RuntimeParameterAnnotations, * extracting their contents and storing them as parameter annotations. There are two kinds of * parameter annotation - visible and invisible. Once they have been unpacked, these attributes are * deleted. (The annotations will be rebuilt as attributes when someone builds a Method object out * of this MethodGen object). */ private void ensureExistingParameterAnnotationsUnpacked() { if (haveUnpackedParameterAnnotations) return; // Find attributes that contain parameter annotation data Attribute[] attrs = getAttributes(); RuntimeParameterAnnotations paramAnnVisAttr = null; RuntimeParameterAnnotations paramAnnInvisAttr=null; List accumulatedAnnotations = new ArrayList(); for (int i = 0; i < attrs.length; i++) { Attribute attribute = attrs[i]; if (attribute instanceof RuntimeParameterAnnotations) { // Initialize param_annotations if (!hasParameterAnnotations) { param_annotations = new List[arg_types.length]; for (int j=0;j<arg_types.length;j++) param_annotations[j]=new ArrayList(); } hasParameterAnnotations = true; RuntimeParameterAnnotations rpa = (RuntimeParameterAnnotations)attribute; if (rpa.areVisible()) paramAnnVisAttr = rpa; else paramAnnInvisAttr=rpa; for (int j=0; j<arg_types.length; j++) { // This returns Annotation[] ... Annotation[] immutableArray = rpa.getAnnotationsOnParameter(j); // ... which needs transforming into an AnnotationGen[] ... List mutable = makeMutableVersion(immutableArray); // ... then add these to any we already know about param_annotations[j].addAll(mutable); } } } if (paramAnnVisAttr != null) removeAttribute(paramAnnVisAttr); if (paramAnnInvisAttr!=null) removeAttribute(paramAnnInvisAttr); haveUnpackedParameterAnnotations = true; } private List /*AnnotationGen*/ makeMutableVersion(Annotation[] mutableArray) { List result = new ArrayList(); for (int i = 0; i < mutableArray.length; i++) { result.add(new AnnotationGen(mutableArray[i],getConstantPool(),false)); } return result; } public void addParameterAnnotation(int parameterIndex, AnnotationGen annotation) { ensureExistingParameterAnnotationsUnpacked(); if (!hasParameterAnnotations) { param_annotations = new List[arg_types.length]; hasParameterAnnotations = true; } List existingAnnotations = param_annotations[parameterIndex]; if (existingAnnotations != null) { existingAnnotations.add(annotation); } else { List l = new ArrayList(); l.add(annotation); param_annotations[parameterIndex] = l; } } }
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
tests/src/org/aspectj/systemtest/ajc150/SuppressedWarnings.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.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; public class SuppressedWarnings extends XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(SuppressedWarnings.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } // Check basic suppression public void testSuppression1() { runTest("suppressing non-matching advice warnings"); } // Checks source contexts aren't put out incorrectly // NOTE: Source contexts only come out if the primary source location in a message // matches the file currently being dealt with. Because advice not matching // messages come out at the last stage of compilation, you currently only // get sourcecontext for advice not matching messages that point to places in // the last file being processed. You do get source locations in all cases - // you just don't always get context, we could revisit this sometime... // (see bug 62073 reference in WeaverMessageHandler.handleMessage()) public void testSuppression2() { runTest("suppressing non-matching advice warnings when multiple source files involved"); } public void testSuppressionWithCflow_pr93345() { runTest("XLint warning for advice not applied with cflow(execution)"); } }