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
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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 * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Member; import java.util.ArrayList; import java.util.Collections; import java.util.List; 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.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.WeaverMessages; 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; 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; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } public boolean alwaysFalse() { return false; } public boolean alwaysTrue() { return false; } /* (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); testMethod.write(s); s.writeByte(extraParameterFlags); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { IfPointcut ret = new IfPointcut(ResolvedMember.readResolvedMember(s, context), 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() { return "if(" + testMethod + ")"; } //??? 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; protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (findingResidue) return Literal.TRUE; findingResidue = true; try { ExposedState myState = new ExposedState(baseArgsCount); //System.out.println(residueSource); //??? we throw out the test that comes from this walk. All we want here // is bindings for the arguments residueSource.findResidue(shadow, myState); //System.out.println(myState); Test ret = Literal.TRUE; List args = new ArrayList(); 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()); } ret = Test.makeAnd(ret, Test.makeCall(testMethod, (Expr[])args.toArray(new Expr[args.size()]))); 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(ResolvedTypeX inAspect, IntMap bindings) { // return this.concretize1(inAspect, bindings); // } protected boolean shouldCopyLocationForConcretize() { return false; } private IfPointcut partiallyConcretized = null; public Pointcut concretize1(ResolvedTypeX inAspect, 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; } IfPointcut 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, 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; IntMap newBindings = IntMap.idMap(ret.baseArgsCount); newBindings.copyContext(bindings); ret.residueSource = def.getPointcut().concretize(inAspect, newBindings); } return ret; } // 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; } private static class IfFalsePointcut extends IfPointcut { public IfFalsePointcut() { super(null,0); } 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(ResolvedTypeX enclosingType) { } public Pointcut concretize1( ResolvedTypeX inAspect, 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; } private static class IfTruePointcut extends IfPointcut { public IfTruePointcut() { super(null,0); } 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(ResolvedTypeX enclosingType) { } public Pointcut concretize1( ResolvedTypeX inAspect, 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)"; } } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.aspectj.bridge.ISourceLocation; 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.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; 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; 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; } /* (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; } protected FuzzyBoolean matchInternal(Shadow shadow) { if (shadow.getKind() != kind) return FuzzyBoolean.NO; if (!signature.matches(shadow.getSignature(), shadow.getIWorld())){ 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 = shadow.getSignature().getModifiers(shadow.getIWorld()); if (ResolvedTypeX.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 TypeX exactDeclaringType = signature.getDeclaringType().getExactType(); ResolvedTypeX shadowDeclaringType = shadow.getSignature().getDeclaringType().resolve(world); if (signature.getDeclaringType().isStar() || exactDeclaringType== ResolvedTypeX.MISSING) return; // warning not needed if match type couldn't ever be the declaring type if (!shadowDeclaringType.isAssignableFrom(exactDeclaringType)) { return; } // if the method in the declaring type is *not* visible to the // exact declaring type then warning not needed. int shadowModifiers = shadow.getSignature().getModifiers(world); if (!ResolvedTypeX .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.isInterface(world) && 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())) { 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(ResolvedTypeX 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(DataInputStream 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(); TypeX exactType = signature.getDeclaringType().getExactType(); if (signature.getKind() == Member.CONSTRUCTOR && !exactType.equals(ResolvedTypeX.MISSING) && exactType.isInterface(world) && !signature.getDeclaringType().isIncludeSubtypes()) { world.getLint().noInterfaceCtorJoinpoint.signal(exactType.toString(), 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(ResolvedTypeX inAspect, IntMap bindings) { Pointcut ret = new KindedPointcut(kind, signature, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } public Shadow.Kind getKind() { return kind; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/ModifiersPattern.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.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; public class ModifiersPattern extends PatternNode { private int requiredModifiers; private int forbiddenModifiers; public static final ModifiersPattern ANY = new ModifiersPattern(0, 0); public ModifiersPattern(int requiredModifiers, int forbiddenModifiers) { this.requiredModifiers = requiredModifiers; this.forbiddenModifiers = forbiddenModifiers; } public String toString() { if (this == ANY) return ""; String ret = Modifier.toString(requiredModifiers); if (forbiddenModifiers == 0) return ret; else return ret + " !" + Modifier.toString(forbiddenModifiers); } public boolean equals(Object other) { if (!(other instanceof ModifiersPattern)) return false; ModifiersPattern o = (ModifiersPattern)other; return o.requiredModifiers == this.requiredModifiers && o.forbiddenModifiers == this.forbiddenModifiers; } public int hashCode() { int result = 17; result = 37*result + requiredModifiers; result = 37*result + forbiddenModifiers; return result; } public boolean matches(int modifiers) { return ((modifiers & requiredModifiers) == requiredModifiers) && ((modifiers & forbiddenModifiers) == 0); } public static ModifiersPattern read(DataInputStream s) throws IOException { int requiredModifiers = s.readShort(); int forbiddenModifiers = s.readShort(); if (requiredModifiers == 0 && forbiddenModifiers == 0) return ANY; return new ModifiersPattern(requiredModifiers, forbiddenModifiers); } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { //s.writeByte(MODIFIERS_PATTERN); s.writeShort(requiredModifiers); s.writeShort(forbiddenModifiers); } private static Map modifierFlags = null; public static int getModifierFlag(String name) { if (modifierFlags == null) { modifierFlags = new HashMap(); int flag = 1; while (flag <= Modifier.STRICT) { String flagName = Modifier.toString(flag); modifierFlags.put(flagName, new Integer(flag)); flag = flag << 1; } } Integer flag = (Integer)modifierFlags.get(name); if (flag == null) return -1; return flag.intValue(); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/NamePattern.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; public class NamePattern extends PatternNode { char[] pattern; int starCount = 0; public static final NamePattern ELLIPSIS = new NamePattern(""); public static final NamePattern ANY = new NamePattern("*"); public NamePattern(String name) { this(name.toCharArray()); } public NamePattern(char[] pattern) { this.pattern = pattern; for (int i=0, len=pattern.length; i<len; i++) { if (pattern[i] == '*') starCount++; } } public boolean matches(char[] a2) { char[] a1 = pattern; int len1 = a1.length; int len2 = a2.length; if (starCount == 0) { if (len1 != len2) return false; for (int i=0; i<len1; i++) { if (a1[i] != a2[i]) return false; } return true; } else if (starCount == 1) { // just '*' matches anything if (len1 == 1) return true; if (len1 > len2+1) return false; int i2=0; for (int i1=0; i1<len1; i1++) { char c1 = a1[i1]; if (c1 == '*') { i2 = len2 - (len1-(i1+1)); } else if (c1 != a2[i2++]) { return false; } } return true; } else { // String pattern = new String(a1); // String target = new String(a2); // System.err.print("match(\"" + pattern + "\", \"" + target + "\") -> "); boolean b = outOfStar(a1, a2, 0, 0, len1 - starCount, len2, starCount); // System.err.println(b); return b; } } private static boolean outOfStar(final char[] 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] == '*') { return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1); } if (target[ti] != pattern[pi]) { return false; } pi++; ti++; pLeft--; tLeft--; } } private static boolean inStar(final char[] 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 char patternChar = pattern[pi]; while (patternChar == '*') { starsLeft--; patternChar = pattern[++pi]; } while (true) { // invariant: if (tLeft > 0) then (ti < target.length) if (pLeft > tLeft) return false; if (target[ti] == patternChar) { if (outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft)) return true; } ti++; tLeft--; } } public boolean matches(String other) { return matches(other.toCharArray()); } public String toString() { return new String(pattern); } public boolean equals(Object other) { if (other instanceof NamePattern) { NamePattern otherPat = (NamePattern)other; return otherPat.starCount == this.starCount && new String(otherPat.pattern).equals(new String(this.pattern)); } return false; } public int hashCode() { return new String(pattern).hashCode(); } public void write(DataOutputStream out) throws IOException { out.writeUTF(new String(pattern)); } public static NamePattern read(DataInputStream in) throws IOException { String s = in.readUTF(); if (s.length() == 0) return ELLIPSIS; return new NamePattern(s); } /** * Method maybeGetSimpleName. * @return String */ public String maybeGetSimpleName() { if (starCount == 0 && pattern.length > 0) return new String(pattern); return null; } /** * Method isAny. * @return boolean */ public boolean isAny() { return starCount == 1 && pattern.length == 1; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/NotAnnotationTypePattern.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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.World; public class NotAnnotationTypePattern extends AnnotationTypePattern { private AnnotationTypePattern negatedPattern; public NotAnnotationTypePattern(AnnotationTypePattern pattern) { this.negatedPattern = pattern; setLocation(pattern.getSourceContext(), pattern.getStart(), pattern.getEnd()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#matches(org.aspectj.weaver.AnnotatedElement) */ public FuzzyBoolean matches(AnnotatedElement annotated) { return negatedPattern.matches(annotated).not(); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolve(org.aspectj.weaver.World) */ public void resolve(World world) { negatedPattern.resolve(world); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { negatedPattern = negatedPattern.resolveBindings(scope,bindings,allowBinding); return this; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.NOT); negatedPattern.write(s); writeLocation(s); } public static AnnotationTypePattern read(DataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern ret = new NotAnnotationTypePattern(AnnotationTypePattern.read(s,context)); ret.readLocation(context,s); return ret; } public boolean equals(Object obj) { if (!(obj instanceof NotAnnotationTypePattern)) return false; NotAnnotationTypePattern other = (NotAnnotationTypePattern) obj; return other.negatedPattern.equals(negatedPattern); } public int hashCode() { int result = 17 + 37*negatedPattern.hashCode(); return result; } public String toString() { return "!" + negatedPattern.toString(); } public AnnotationTypePattern getNegatedPattern() { return negatedPattern; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Member; 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.ResolvedTypeX; import org.aspectj.weaver.Shadow; 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(); } 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(DataInputStream 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(ResolvedTypeX inAspect, IntMap bindings) { Pointcut ret = new NotPointcut(body.concretize(inAspect, bindings)); ret.copyLocationFrom(this); return ret; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; /** * !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 pattern; public NotTypePattern(TypePattern pattern) { super(false,false); //??? we override all methods that care about includeSubtypes this.pattern = pattern; setLocation(pattern.getSourceContext(), pattern.getStart(), pattern.getEnd()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } public FuzzyBoolean matchesInstanceof(ResolvedTypeX type) { return pattern.matchesInstanceof(type).not(); } protected boolean matchesExactly(ResolvedTypeX type) { return !pattern.matchesExactly(type); } public boolean matchesStatically(Class type) { return !pattern.matchesStatically(type); } public FuzzyBoolean matchesInstanceof(Class type) { return pattern.matchesInstanceof(type).not(); } protected boolean matchesExactly(Class type) { return !pattern.matchesExactly(type); } public boolean matchesStatically(ResolvedTypeX type) { return !pattern.matchesStatically(type); } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.NOT); pattern.write(s); writeLocation(s); } public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException { TypePattern ret = new NotTypePattern(TypePattern.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); pattern = pattern.resolveBindings(scope, bindings, false, false); return this; } public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) { if (requireExactType) return TypePattern.NO; pattern = pattern.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(pattern); 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 (pattern.equals(((NotTypePattern)obj).pattern)); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37 * pattern.hashCode(); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/OrAnnotationTypePattern.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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.World; public class OrAnnotationTypePattern extends AnnotationTypePattern { private AnnotationTypePattern left; private AnnotationTypePattern right; public OrAnnotationTypePattern(AnnotationTypePattern left, AnnotationTypePattern right) { this.left = left; this.right = right; setLocation(left.getSourceContext(), left.getStart(), right.getEnd()); } public FuzzyBoolean matches(AnnotatedElement annotated) { return left.matches(annotated).or(right.matches(annotated)); } public void resolve(World world) { left.resolve(world); right.resolve(world); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings, boolean) */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { left = left.resolveBindings(scope,bindings,allowBinding); right =right.resolveBindings(scope,bindings,allowBinding); return this; } public static AnnotationTypePattern read(DataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern p = new OrAnnotationTypePattern( AnnotationTypePattern.read(s,context), AnnotationTypePattern.read(s,context)); p.readLocation(context,s); return p; } public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.OR); left.write(s); right.write(s); writeLocation(s); } public boolean equals(Object obj) { if (!(obj instanceof OrAnnotationTypePattern)) return false; OrAnnotationTypePattern other = (OrAnnotationTypePattern) obj; return (left.equals(other.left) && right.equals(other.right)); } public int hashCode() { int result = 17; result = result*37 + left.hashCode(); result = result*37 + right.hashCode(); return result; } public String toString() { return "(" + left.toString() + " || " + right.toString() + ")"; } public AnnotationTypePattern getLeft() { return left; } public AnnotationTypePattern getRight() { return right; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Member; import java.util.HashSet; 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.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ast.Test; public class OrPointcut extends Pointcut { private 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)); } 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(DataInputStream 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(ResolvedTypeX inAspect, IntMap bindings) { Pointcut ret = new OrPointcut(left.concretize(inAspect, bindings), right.concretize(inAspect, bindings)); ret.copyLocationFrom(this); return ret; } public Pointcut getLeft() { return left; } public Pointcut getRight() { return right; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; /** * 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()); } /* (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(ResolvedTypeX type) { return left.matchesInstanceof(type).or(right.matchesInstanceof(type)); } protected boolean matchesExactly(ResolvedTypeX type) { //??? if these had side-effects, this sort-circuit could be a mistake return left.matchesExactly(type) || right.matchesExactly(type); } public boolean matchesStatically(ResolvedTypeX 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 write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.OR); left.write(s); right.write(s); writeLocation(s); } public static TypePattern read(DataInputStream s, ISourceContext context) throws IOException { TypePattern ret = new OrTypePattern(TypePattern.read(s, context), TypePattern.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); left = left.resolveBindings(scope, bindings, false, false); right = right.resolveBindings(scope, bindings, false, false); return this; } 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; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; 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.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; 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 Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.YES; } public void resolveBindings(IScope scope, Bindings bindings) { // assert bindings == null; entry.resolve(scope); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { Expr myInstance = Expr.makeCallExpr(AjcMemberMaker.perCflowAspectOfMethod(inAspect), Expr.NONE, inAspect); state.setAspectInstance(myInstance); return Test.makeCall(AjcMemberMaker.perCflowHasAspectMethod(inAspect), Expr.NONE); } public PerClause concretize(ResolvedTypeX inAspect) { PerCflow ret = new PerCflow(entry, isBelow); ret.inAspect = inAspect; if (inAspect.isAbstract()) return ret; Member cflowStackField = new ResolvedMember( Member.FIELD, inAspect, Modifier.STATIC|Modifier.PUBLIC|Modifier.FINAL, TypeX.forName(NameMangler.CFLOW_STACK_TYPE), NameMangler.PERCFLOW_FIELD_NAME, TypeX.NONE); World world = inAspect.getWorld(); CrosscuttingMembers xcut = inAspect.crosscuttingMembers; Collection previousCflowEntries = xcut.getCflowEntries(); Pointcut concreteEntry = entry.concretize(inAspect, 0, null); //IntMap.EMPTY); List innerCflowEntries = new ArrayList(xcut.getCflowEntries()); innerCflowEntries.removeAll(previousCflowEntries); xcut.addConcreteShadowMunger( Advice.makePerCflowEntry(world, concreteEntry, isBelow, cflowStackField, inAspect, innerCflowEntries)); return ret; } public void write(DataOutputStream s) throws IOException { PERCFLOW.write(s); entry.write(s); s.writeBoolean(isBelow); writeLocation(s); } public static PerClause readPerClause(DataInputStream 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 + ")"; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.IOException; import org.aspectj.util.TypeSafeEnum; import org.aspectj.weaver.*; public abstract class PerClause extends Pointcut { protected ResolvedTypeX inAspect; public static PerClause readPerClause(DataInputStream 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); throw new BCException("unknown kind: " + kind); } public final Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { throw new RuntimeException("unimplemented: wrong concretize"); } public abstract PerClause concretize(ResolvedTypeX inAspect); public abstract PerClause.Kind getKind(); 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 SINGLETON; case 2: return PERCFLOW; case 3: return PEROBJECT; case 4: return FROMSUPER; } 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); }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; 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.ResolvedTypeX; import org.aspectj.weaver.Shadow; 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 Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { throw new RuntimeException("unimplemented"); } protected FuzzyBoolean matchInternal(Shadow shadow) { throw new RuntimeException("unimplemented"); } public void resolveBindings(IScope scope, Bindings bindings) { // this method intentionally left blank } protected Test findResidueInternal(Shadow shadow, ExposedState state) { throw new RuntimeException("unimplemented"); } public PerClause concretize(ResolvedTypeX inAspect) { PerClause p = lookupConcretePerClause(inAspect.getSuperclass()); if (p == null) { inAspect.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.MISSING_PER_CLAUSE,inAspect.getSuperclass()), getSourceLocation()) ); } if (p.getKind() != kind) { inAspect.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WRONG_PER_CLAUSE,kind,p.getKind()), getSourceLocation()) ); } return p.concretize(inAspect); } private PerClause lookupConcretePerClause(ResolvedTypeX 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(DataInputStream 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 PerClause.Kind getKind() { return kind; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; 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.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.World; 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 Set couldMatchKinds() { return isThis ? thisKindSet : targetKindSet; } // ----- public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //System.err.println("matches " + this + " ? " + shadow + ", " + shadow.hasTarget()); //??? could probably optimize this better by testing could match if (isThis) return FuzzyBoolean.fromBoolean(shadow.hasThis()); else return FuzzyBoolean.fromBoolean(shadow.hasTarget()); } public void resolveBindings(IScope scope, Bindings bindings) { // assert bindings == null; entry.resolve(scope); } private Var getVar(Shadow shadow) { return isThis ? shadow.getThisVar() : shadow.getTargetVar(); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { Expr myInstance = Expr.makeCallExpr(AjcMemberMaker.perObjectAspectOfMethod(inAspect), new Expr[] {getVar(shadow)}, inAspect); state.setAspectInstance(myInstance); return Test.makeCall(AjcMemberMaker.perObjectHasAspectMethod(inAspect), new Expr[] { getVar(shadow) }); } public PerClause concretize(ResolvedTypeX inAspect) { PerObject ret = new PerObject(entry, isThis); ret.inAspect = inAspect; if (inAspect.isAbstract()) return ret; World world = inAspect.getWorld(); Pointcut concreteEntry = entry.concretize(inAspect, 0, null); //concreteEntry = new AndPointcut(this, concreteEntry); //concreteEntry.state = Pointcut.CONCRETE; inAspect.crosscuttingMembers.addConcreteShadowMunger( Advice.makePerObjectEntry(world, concreteEntry, isThis, inAspect)); ResolvedTypeMunger munger = new PerObjectInterfaceTypeMunger(inAspect, concreteEntry); inAspect.crosscuttingMembers.addTypeMunger(world.concreteTypeMunger(munger, 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(DataInputStream 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 String toString() { return "per" + (isThis ? "this" : "target") + "(" + entry + ")"; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; 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.ResolvedTypeX; import org.aspectj.weaver.Shadow; 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 Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.YES; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.YES; } public void resolveBindings(IScope scope, Bindings bindings) { // this method intentionally left blank } protected Test findResidueInternal(Shadow shadow, ExposedState state) { 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; } public PerClause concretize(ResolvedTypeX inAspect) { PerSingleton ret = new PerSingleton(); ret.inAspect = inAspect; return ret; } public void write(DataOutputStream s) throws IOException { SINGLETON.write(s); writeLocation(s); } public static PerClause readPerClause(DataInputStream 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 + ")"; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Member; import java.util.Collections; 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.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; 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); } } 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; /** * Constructor for Pattern. */ public Pointcut() { super(); this.state = SYMBOLIC; } /** * Could I match any shadows in the code defined within this type? */ public abstract FuzzyBoolean fastMatch(FastMatchInfo info); /** * The set of ShadowKinds that this Pointcut could possibly match */ public abstract /*Enum*/Set/*<Shadow.Kind>*/ couldMatchKinds(); /** * 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 ATARGS = 20; public static final byte NONE = 40; 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()); this.resolveBindings(scope, bindingTable); bindingTable.checkAllBound(scope); 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(ResolvedTypeX inAspect, int arity) { return concretize(inAspect, IntMap.idMap(arity)); } //XXX this is the signature we're moving to public final Pointcut concretize(ResolvedTypeX inAspect, int arity, ShadowMunger advice) { //if (state == CONCRETE) return this; //??? IntMap map = IntMap.idMap(arity); map.setEnclosingAdvice(advice); map.setConcreteAspect(inAspect); return concretize(inAspect, 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(ResolvedTypeX inAspect, IntMap bindings) { //!!! add this test -- assertState(RESOLVED); Pointcut ret = this.concretize1(inAspect, bindings); if (shouldCopyLocationForConcretize()) ret.copyLocationFrom(this); ret.state = CONCRETE; 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(ResolvedTypeX inAspect, 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(ResolvedTypeX enclosingType) {} public static Pointcut read(DataInputStream 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(); } private static class MatchesNothingPointcut extends Pointcut { protected Test findResidueInternal(Shadow shadow, ExposedState state) { return Literal.FALSE; // can only get here if an earlier error occurred } public Set couldMatchKinds() { return Collections.EMPTY_SET; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.NO; } protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public 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(ResolvedTypeX enclosingType) { } public Pointcut concretize1( ResolvedTypeX inAspect, IntMap bindings) { return makeMatchesNothing(state); } public void write(DataOutputStream s) throws IOException { s.writeByte(NONE); } public String toString() { return ""; } } //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); } } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; 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.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; 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 TypeX onType; public TypePattern onTypeSymbolic; public String name; public TypePatternList arguments; //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(TypeX onType, String name, TypePatternList arguments) { this.onType = onType; this.name = name; this.arguments = arguments; this.pointcutKind = REFERENCE; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } //??? do either of these match methods make any sense??? public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } /** * Do I really match this shadow? */ protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public String toString() { StringBuffer buf = new StringBuffer(); if (onType != null) { buf.append(onType); buf.append("."); // for (int i=0, len=fromType.length; i < len; i++) { // buf.append(fromType[i]); // buf.append("."); // } } buf.append(name); buf.append(arguments.toString()); return buf.toString(); } public void write(DataOutputStream s) throws IOException { //XXX ignores onType s.writeByte(Pointcut.REFERENCE); if (onType != null) { s.writeBoolean(true); onType.write(s); } else { s.writeBoolean(false); } s.writeUTF(name); arguments.write(s); writeLocation(s); } public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException { TypeX onType = null; if (s.readBoolean()) { onType = TypeX.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 == ResolvedTypeX.MISSING) return; } ResolvedTypeX 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) { TypeX 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"); 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; } } ResolvedTypeX[] 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(TypeX.OBJECT)) { scope.message(IMessage.ERROR, p, "incompatible type, expected " + parameterTypes[i].getName() + " found " + p); return; } } } public void resolveBindingsFromRTTI() { throw new UnsupportedOperationException("Referenced pointcuts are not supported in runtime evaluation"); } public void postRead(ResolvedTypeX 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; public Pointcut concretize1(ResolvedTypeX searchStart, 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 == ResolvedTypeX.MISSING) { return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } } 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); ResolvedTypeX[] 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); //we are allowed to bind to pointcuts which use subtypes as this is type safe if (!p.matchesSubtypes(parameterTypes[i]) && !p.getExactType().equals(TypeX.OBJECT)) { throw new BCException("illegal change to pointcut declaration: " + this); } if (p instanceof BindingTypePattern) { newBindings.put(i, ((BindingTypePattern)p).getFormalIndex()); } } newBindings.copyContext(bindings); newBindings.pushEnclosingDefinition(pointcutDec); try { return pointcutDec.getPointcut().concretize(searchStart, newBindings); } finally { newBindings.popEnclosingDefinitition(); } } finally { concretizing = false; } } // 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; 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; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; 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 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.Constants; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; 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(ResolvedTypeX enclosingType) { if (returnType != null) { returnType.postRead(enclosingType); } if (declaringType != null) { declaringType.postRead(enclosingType); } if (parameterTypes != null) { parameterTypes.postRead(enclosingType); } } public boolean matches(Member member, World world) { return (matchesIgnoringAnnotations(member,world) && matchesAnnotations(member,world)); } public boolean matchesAnnotations(Member member,World world) { ResolvedMember rMember = member.resolve(world); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return false; } world.getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return false; } annotationPattern.resolve(world); return annotationPattern.matches(rMember).alwaysTrue(); } public boolean matchesIgnoringAnnotations(Member member, World world) { //XXX performance gains would come from matching on name before resolving // to fail fast. ASC 30th Nov 04 => Not necessarily, it didn't make it faster for me. // Here is the code I used: // String n1 = member.getName(); // String n2 = this.getName().maybeGetSimpleName(); // if (n2!=null && !n1.equals(n2)) return false; ResolvedMember sig = member.resolve(world); if (sig == null) { //XXX if (member.getName().startsWith(NameMangler.PREFIX)) { return false; } world.getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return false; } // Java5 introduces bridge methods, we don't want to match on them at all... if (sig.isBridgeMethod()) { return false; } // This check should only matter when used from WithincodePointcut as KindedPointcut // has already effectively checked this with the shadows kind. if (kind != member.getKind()) { 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().resolve(world)); } else if (kind == Member.FIELD) { if (!returnType.matchesStatically(sig.getReturnType().resolve(world))) return false; if (!name.matches(sig.getName())) return false; boolean ret = declaringTypeMatch(member.getDeclaringType(), member, world); //System.out.println(" ret: " + ret); return ret; } else if (kind == Member.METHOD) { // Change all this in the face of covariance... // Check the name if (!name.matches(sig.getName())) return false; // Check the parameters if (!parameterTypes.matches(world.resolve(sig.getParameterTypes()), TypePattern.STATIC).alwaysTrue()) { return false; } // If we have matched on parameters, let's just check it isn't because the last parameter in the pattern // is an array type and the method is declared with varargs // XXX - Ideally the shadow would be included in the msg but we don't know it... if (isNotMatchBecauseOfVarargsIssue(parameterTypes,sig.getModifiers())) { world.getLint().cantMatchArrayTypeOnVarargs.signal(sig.toString(),getSourceLocation()); return false; } if (parameterTypes.size()>0 && (sig.isVarargsMethod()^parameterTypes.get(parameterTypes.size()-1).isVarArgs)) return false; // Check the throws pattern if (!throwsPattern.matches(sig.getExceptions(), world)) return false; return declaringTypeMatchAllowingForCovariance(member,world,returnType,sig.getReturnType().resolve(world)); } else if (kind == Member.CONSTRUCTOR) { if (!parameterTypes.matches(world.resolve(sig.getParameterTypes()), TypePattern.STATIC).alwaysTrue()) { return false; } // If we have matched on parameters, let's just check it isn't because the last parameter in the pattern // is an array type and the method is declared with varargs // XXX - Ideally the shadow would be included in the msg but we don't know it... if (isNotMatchBecauseOfVarargsIssue(parameterTypes,sig.getModifiers())) { world.getLint().cantMatchArrayTypeOnVarargs.signal(sig.toString(),getSourceLocation()); return false; } if (!throwsPattern.matches(sig.getExceptions(), world)) return false; return declaringType.matchesStatically(member.getDeclaringType().resolve(world)); //return declaringTypeMatch(member.getDeclaringType(), member, world); } return false; } public boolean declaringTypeMatchAllowingForCovariance(Member member,World world,TypePattern returnTypePattern,ResolvedTypeX sigReturn) { TypeX onTypeUnresolved = member.getDeclaringType(); ResolvedTypeX onType = onTypeUnresolved.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(); ) { ResolvedTypeX type = (ResolvedTypeX)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 TypeX returnTypeX = rm.getReturnType(); ResolvedTypeX 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 (isNotMatchBecauseOfVarargsIssue(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 (isNotMatchBecauseOfVarargsIssue(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 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 (isNotMatchBecauseOfVarargsIssue(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 (isNotMatchBecauseOfVarargsIssue(parameterTypes,member.getModifiers())) { return false; } if (!throwsPattern.matches(exceptionTypes)) return false; return declaringType.matchesStatically(declaringClass); } return false; } // For methods, the above covariant aware version (declaringTypeMatchAllowingForCovariance) is used - this version is still here for fields private boolean declaringTypeMatch(TypeX onTypeUnresolved, Member member, World world) { ResolvedTypeX onType = onTypeUnresolved.resolve(world); // fastmatch if (declaringType.matchesStatically(onType)) return true; Collection declaringTypes = member.getDeclaringTypes(world); for (Iterator i = declaringTypes.iterator(); i.hasNext(); ) { ResolvedTypeX type = (ResolvedTypeX)i.next(); if (declaringType.matchesStatically(type)) return true; } 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 { Method m = (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>()"); } 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()); } } 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(DataInputStream 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.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 isNotMatchBecauseOfVarargsIssue(TypePatternList params,int modifiers) { if (params.size()>0 && (modifiers & Constants.ACC_VARARGS)!=0 && // XXX Promote this to an isVarargs() on MethodSignature? !params.get(params.size()-1).isVarArgs) { return true; } return false; } public AnnotationTypePattern getAnnotationPattern() { return annotationPattern; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; 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.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; 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 Set couldMatchKinds() { return isThis ? thisKindSet : targetKindSet; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { if (!couldMatch(shadow)) return FuzzyBoolean.NO; ResolvedTypeX toMatchAgainst = (isThis ? shadow.getThisType() : shadow.getTargetType() ).resolve(shadow.getIWorld()); annotationTypePattern.resolve(shadow.getIWorld()); if (annotationTypePattern.matches(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; } ResolvedTypeX rAnnotationType = (ResolvedTypeX) 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.ResolvedTypeX, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedTypeX inAspect, 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) */ 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; TypeX 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) return Literal.TRUE; // should be exception when we implement properly // 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)) { return Literal.TRUE; } else { if (annVar != null) { // TODO - need to bind it, next line is a placeholder return Literal.FALSE; } else { ResolvedTypeX 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(DataInputStream 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("); buf.append(annotationTypePattern.toString()); buf.append(")"); return buf.toString(); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; 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.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeX; 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 boolean isThis() { return isThis; } public Set couldMatchKinds() { return isThis ? thisKindSet : targetKindSet; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } private boolean couldMatch(Shadow shadow) { return isThis ? shadow.hasThis() : shadow.hasTarget(); } protected FuzzyBoolean matchInternal(Shadow shadow) { if (!couldMatch(shadow)) return FuzzyBoolean.NO; TypeX typeToMatch = isThis ? shadow.getThisType() : shadow.getTargetType(); //if (typeToMatch == ResolvedTypeX.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(DataInputStream 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); // ??? handle non-formal } public void resolveBindingsFromRTTI() { type = type.resolveBindingsFromRTTI(true,true); } public void postRead(ResolvedTypeX 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(ResolvedTypeX inAspect, 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; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; 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 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 boolean matches(TypeX[] tys, World world) { if (this == ANY) return true; //System.out.println("matching: " + this + " with " + Arrays.asList(tys)); ResolvedTypeX[] 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, ResolvedTypeX[] 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(DataInputStream 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); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Iterator; 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.ResolvedTypeX; import org.aspectj.weaver.TypeX; 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 TypePattern(boolean includeSubtypes,boolean isVarArgs) { this.includeSubtypes = includeSubtypes; this.isVarArgs = isVarArgs; } protected TypePattern(boolean includeSubtypes) { this(includeSubtypes,false); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { this.annotationPattern = annPatt; } // 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(ResolvedTypeX type) { if (includeSubtypes) { return matchesSubtypes(type); } else { return matchesExactly(type); } } public abstract FuzzyBoolean matchesInstanceof(ResolvedTypeX type); public final FuzzyBoolean matches(ResolvedTypeX type, MatchKind kind) { FuzzyBoolean typeMatch = null; //??? This is part of gracefully handling missing references if (type == ResolvedTypeX.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(ResolvedTypeX type); protected boolean matchesSubtypes(ResolvedTypeX 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(); ) { ResolvedTypeX superType = (ResolvedTypeX)i.next(); if (matchesSubtypes(superType)) return true; } return false; } public TypeX resolveExactType(IScope scope, Bindings bindings) { TypePattern p = resolveBindings(scope, bindings, false, true); if (p == NO) return ResolvedTypeX.MISSING; return ((ExactTypePattern)p).getType(); } public TypeX getExactType() { if (this instanceof ExactTypePattern) return ((ExactTypePattern)this).getType(); else return ResolvedTypeX.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); } public void postRead(ResolvedTypeX 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 TypePattern read(DataInputStream 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); } 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); } /* (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(ResolvedTypeX type) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedTypeX 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; } } class AnyTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public AnyTypePattern() { super(false,false); } /* (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(ResolvedTypeX type) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedTypeX 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(ResolvedTypeX 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; } } class NoTypePattern extends TypePattern { public NoTypePattern() { super(false,false); } /* (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(ResolvedTypeX type) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedTypeX 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(ResolvedTypeX type) { return false; } public boolean isStar() { return false; } public String toString() { return "<nothing>"; } /* (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; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; 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[] {TypePattern.ELLIPSIS}); 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 { // 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(ResolvedTypeX[] 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 ResolvedTypeX[] 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 ResolvedTypeX[] 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--; } } 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(ResolvedTypeX 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(DataInputStream 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++) { TypeX t = typePatterns[i].getExactType(); if (t != ResolvedTypeX.MISSING) ret.add(t); } return ret; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/src/org/aspectj/weaver/patterns/WildAnnotationTypePattern.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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class WildAnnotationTypePattern extends AnnotationTypePattern { private TypePattern typePattern; private boolean resolved = false; /** * */ public WildAnnotationTypePattern(TypePattern typePattern) { super(); this.typePattern = typePattern; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#matches(org.aspectj.weaver.AnnotatedElement) */ public FuzzyBoolean matches(AnnotatedElement annotated) { if (!resolved) { throw new IllegalStateException("Can't match on an unresolved annotation type pattern"); } // matches if the type of any of the annotations on the AnnotatedElement is // matched by the typePattern. ResolvedTypeX[] annTypes = annotated.getAnnotationTypes(); for (int i = 0; i < annTypes.length; i++) { if (typePattern.matches(annTypes[i],TypePattern.STATIC).alwaysTrue()) { return FuzzyBoolean.YES; } } return FuzzyBoolean.NO; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolve(org.aspectj.weaver.World) */ public void resolve(World world) { // nothing to do... } /** * This can modify in place, or return a new TypePattern if the type changes. */ public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) { this.typePattern = typePattern.resolveBindings(scope,bindings,false,false); resolved = true; if (typePattern instanceof ExactTypePattern) { ExactTypePattern et = (ExactTypePattern)typePattern; if (!et.getExactType().isAnnotation(scope.getWorld())) { IMessage m = MessageUtil.error( WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE,et.getExactType().getName()), getSourceLocation()); scope.getWorld().getMessageHandler().handleMessage(m); resolved = false; } return new ExactAnnotationTypePattern(et.getExactType().resolve(scope.getWorld())); } else { return this; } } private static final byte VERSION = 1; // rev if ser. form changes /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(AnnotationTypePattern.WILD); s.writeByte(VERSION); typePattern.write(s); writeLocation(s); } public static AnnotationTypePattern read(DataInputStream s,ISourceContext context) throws IOException { AnnotationTypePattern ret; byte version = s.readByte(); if (version > VERSION) { throw new BCException("ExactAnnotationTypePattern was written by a newer version of AspectJ"); } TypePattern t = TypePattern.read(s,context); ret = new WildAnnotationTypePattern(t); ret.readLocation(context,s); return ret; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (!(obj instanceof WildAnnotationTypePattern)) return false; WildAnnotationTypePattern other = (WildAnnotationTypePattern) obj; return other.typePattern.equals(typePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 + 37*typePattern.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return "@(" + typePattern.toString() + ")"; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; 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.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverMessages; //XXX need to use dim in matching public class WildTypePattern extends TypePattern { NamePattern[] namePatterns; int ellipsisCount; String[] importedPrefixes; String[] knownMatches; int dim; WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim, boolean isVarArgs) { super(includeSubtypes,isVarArgs); 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); } 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; } /* (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 TypeX otherType = other.getExactType(); if (otherType != ResolvedTypeX.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(ResolvedTypeX type) { String targetTypeName = type.getName(); //System.err.println("match: " + targetTypeName + ", " + knownMatches); //Arrays.asList(importedPrefixes)); return matchesExactlyByName(targetTypeName) && annotationPattern.matches(type).alwaysTrue(); } /** * Used in conjunction with checks on 'isStar()' to tell you if this pattern represents '*' or '*[]' which are * different ! */ public int getDimensions() { return dim; } /** * @param targetTypeName * @return */ private boolean matchesExactlyByName(String targetTypeName) { //XXX hack if (knownMatches == null && importedPrefixes == null) { return innerMatchesExactly(targetTypeName); } if (isStar()) { // 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(ResolvedTypeX 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() { //System.err.println("extract from : " + Arrays.asList(namePatterns)); int len = namePatterns.length; 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(); } /** * 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 (isStar() && (annotationPattern == AnnotationTypePattern.ANY)) { if (dim == 0) { // pr72531 return TypePattern.ANY; //??? loses source location } } annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); 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; } } String cleanName = maybeGetCleanName(); String originalName = cleanName; // if we discover it is 'MISSING' when searching via the scope, this next local var will // tell us if it is really missing or if it does exist in the world and we just can't // see it from the current scope. ResolvedTypeX resolvedTypeInTheWorld = null; if (cleanName != null) { TypeX type; //System.out.println("resolve: " + cleanName); //??? this loop has too many inefficiencies to count resolvedTypeInTheWorld = scope.getWorld().resolve(TypeX.forName(cleanName),true); while ((type = scope.lookupType(cleanName, this)) == ResolvedTypeX.MISSING) { int lastDot = cleanName.lastIndexOf('.'); if (lastDot == -1) break; cleanName = cleanName.substring(0, lastDot) + '$' + cleanName.substring(lastDot+1); if (resolvedTypeInTheWorld == ResolvedTypeX.MISSING) resolvedTypeInTheWorld = scope.getWorld().resolve(TypeX.forName(cleanName),true); } if (type == ResolvedTypeX.MISSING) { if (requireExactType) { if (!allowBinding) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE,originalName), getSourceLocation())); } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, 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 (resolvedTypeInTheWorld == ResolvedTypeX.MISSING) scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, getSourceLocation()); } } else { if (dim != 0) type = TypeX.makeArray(type, dim); TypePattern ret = new ExactTypePattern(type, includeSubtypes,isVarArgs); ret.copyLocationFrom(this); return ret; } } else { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } //XXX need to implement behavior for Lint.invalidWildcardTypeName } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } 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 { TypeX type = TypeX.forName(clazz.getName()); if (dim != 0) type = TypeX.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() { 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(ResolvedTypeX 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 (includeSubtypes) 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; 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(); 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); //??? 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); } public static TypePattern read(DataInputStream 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(); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim,varArg); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); return ret; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; 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 Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return annotationTypePattern.fastMatches(info.getType()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedTypeX enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true); if (enclosingType == ResolvedTypeX.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.ResolvedTypeX, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedTypeX inAspect, 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; TypeX annotationType = btp.annotationType; Var var = shadow.getWithinAnnotationVar(annotationType); if (var == null) return Literal.FALSE; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId == shadow.shadowId)) { // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use @pointcut to match at this location and bind a formal to type '"+var.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic binding.", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } state.set(btp.getFormalIndex(),var); } 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(DataInputStream 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("); buf.append(annotationTypePattern.toString()); buf.append(")"); return buf.toString(); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; 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.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.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; 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 Set couldMatchKinds() { return matchedShadowKinds; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { AnnotatedElement toMatchAgainst = null; Member member = shadow.getEnclosingCodeSignature(); ResolvedMember rMember = member.resolve(shadow.getIWorld()); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(rMember); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindingsFromRTTI() */ protected void resolveBindingsFromRTTI() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedTypeX, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedTypeX inAspect, 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; TypeX annotationType = btp.annotationType; Var var = shadow.getWithinCodeAnnotationVar(annotationType); if (var == null) return Literal.FALSE; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId == shadow.shadowId)) { // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use @pointcut to match at this location and bind a formal to type '"+var.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic binding.", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } state.set(btp.getFormalIndex(),var); } 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(DataInputStream 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("); buf.append(annotationTypePattern.toString()); buf.append(")"); return buf.toString(); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; 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.lang.JoinPoint; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class WithinPointcut extends Pointcut { TypePattern typePattern; public WithinPointcut(TypePattern type) { this.typePattern = type; this.pointcutKind = WITHIN; } private FuzzyBoolean isWithinType(ResolvedTypeX type) { while (type != null) { if (typePattern.matchesStatically(type)) { return FuzzyBoolean.YES; } type = type.getDeclaringType(); } return FuzzyBoolean.NO; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo info) { if (typePattern.annotationPattern instanceof AnyAnnotationTypePattern) { return isWithinType(info.getType()); } return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedTypeX enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true); if (enclosingType == ResolvedTypeX.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(DataInputStream 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); } public void resolveBindingsFromRTTI() { typePattern = typePattern.resolveBindingsFromRTTI(false,false); } public void postRead(ResolvedTypeX 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(ResolvedTypeX inAspect, IntMap bindings) { Pointcut ret = new WithinPointcut(typePattern); ret.copyLocationFrom(this); return ret; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Member; import java.util.HashSet; import java.util.Set; 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.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; public class WithincodePointcut extends Pointcut { 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 Set couldMatchKinds() { return matchedShadowKinds; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //This will not match code in local or anonymous classes as if //they were withincode of the outer signature return FuzzyBoolean.fromBoolean( signature.matches(shadow.getEnclosingCodeSignature(), shadow.getIWorld())); } 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(DataInputStream 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); } public void resolveBindingsFromRTTI() { signature = signature.resolveBindingsFromRTTI(); } public void postRead(ResolvedTypeX 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(ResolvedTypeX inAspect, IntMap bindings) { Pointcut ret = new WithincodePointcut(signature); ret.copyLocationFrom(this); return ret; } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/testsrc/org/aspectj/weaver/bcel/PatternWeaveTestCase.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.*; import java.util.*; import org.aspectj.weaver.*; import org.aspectj.weaver.patterns.*; public class PatternWeaveTestCase extends WeaveTestCase { { regenerate = false; } public PatternWeaveTestCase(String name) { super(name); } String[] none = new String[0]; //XXX this test is incompatible with optimizations made to weaver public void testPublic() throws IOException { String[] publicHello = new String[] { "method-execution(void HelloWorld.main(java.lang.String[]))", }; String[] publicFancyHello = new String[] { "method-execution(void FancyHelloWorld.main(java.lang.String[]))", "method-execution(java.lang.String FancyHelloWorld.getName())", }; checkPointcut("execution(public * *(..))", publicHello, publicFancyHello); } // // public void testPrintln() throws IOException { // String[] callPrintlnHello = new String[] { // "method-call(void java.io.PrintStream.println(java.lang.String))", // }; // String[] callPrintlnFancyHello = new String[] { // "method-call(void java.io.PrintStream.println(java.lang.String))", // "method-call(void java.io.PrintStream.println(java.lang.String))", // "method-call(void java.io.PrintStream.println(java.lang.Object))", // }; // checkPointcut("call(* println(*))", callPrintlnHello, callPrintlnFancyHello); // } // // public void testMumble() throws IOException { // checkPointcut("call(* mumble(*))", none, none); // } // // public void testFooBar() throws IOException { // checkPointcut("call(FooBar *(..))", none, none); // } // // public void testGetOut() throws IOException { // String[] getOutHello = new String[] { // "field-get(java.io.PrintStream java.lang.System.out)", // }; // // checkPointcut("get(* java.lang.System.out)", getOutHello, getOutHello); // } // //// private Pointcut makePointcut(String s) { //// return new PatternParser(s).parsePointcut(); //// } // private void checkPointcut(String pointcutSource, String[] expectedHelloShadows, String[] expectedFancyShadows) throws IOException { Pointcut sp = Pointcut.fromString(pointcutSource); Pointcut rp = sp.resolve(new SimpleScope(world, FormalBinding.NONE)); Pointcut cp = rp.concretize(ResolvedTypeX.MISSING, 0); final List l = new ArrayList(); BcelAdvice p = new BcelAdvice(null, cp, null, 0, -1, -1, null, null) { public void implementOn(Shadow shadow) { l.add(shadow); } }; weaveTest(new String[] {"HelloWorld"}, "PatternWeave", p); checkShadowSet(l, expectedHelloShadows); l.clear(); weaveTest(new String[] {"FancyHelloWorld"}, "PatternWeave", p); checkShadowSet(l, expectedFancyShadows); checkSerialize(rp); } public void checkSerialize(Pointcut p) throws IOException { 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); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/testsrc/org/aspectj/weaver/bcel/PointcutResidueTestCase.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.*; import java.lang.reflect.Modifier; import java.util.*; import org.aspectj.weaver.*; import org.aspectj.weaver.patterns.*; import org.aspectj.weaver.patterns.SimpleScope; public class PointcutResidueTestCase extends WeaveTestCase { { regenerate = false; } public PointcutResidueTestCase(String name) { super(name); } String[] none = new String[0]; // ----- // ---- public void testArgResidue1() throws IOException { checkMultiArgWeave( "StringResidue1", "call(* *(java.lang.Object, java.lang.Object)) && args(java.lang.String, java.lang.String)"); } public void testArgResidue2() throws IOException { checkMultiArgWeave( "StringResidue2", "call(* *(java.lang.Object, java.lang.Object)) && args(.., java.lang.String)"); } public void testArgResidue3() throws IOException { checkMultiArgWeave( "StringResidue3", "call(* *(java.lang.Object, java.lang.Object)) && args(java.lang.String, ..)"); } // BETAX this is a beta feature. // public void testArgResidue4() throws IOException { // checkMultiArgWeave( // "StringResidue4", // "call(* *(java.lang.Object, java.lang.Object)) && args(.., java.lang.String, ..)"); // } public void testMultiArgState() throws IOException { checkWeave( "StateResidue", "MultiArgHelloWorld", "call(* *(java.lang.Object, java.lang.Object)) && args(s, ..)", new String[] { "java.lang.String" }, new String[] { "s" }); checkWeave( "StateResidue", "MultiArgHelloWorld", "call(* *(java.lang.Object, java.lang.Object)) && args(s, *)", new String[] { "java.lang.String" }, new String[] { "s" }); } public void testAdd() throws IOException { checkDynamicWeave("AddResidue", "call(public * add(..)) && target(java.util.ArrayList)"); checkDynamicWeave("AddResidue", "call(public * add(..)) && (target(java.util.ArrayList) || target(java.lang.String))"); checkDynamicWeave("AddResidue", "call(public * add(..)) && this(java.io.Serializable) && target(java.util.ArrayList) && !this(java.lang.Integer)"); } public void testNot() throws IOException { checkDynamicWeave("AddNotResidue", "call(public * add(..)) && !target(java.util.ArrayList)"); checkDynamicWeave("AddNotResidue", "call(public * add(..)) && !(target(java.util.ArrayList) || target(java.lang.String)) "); checkDynamicWeave("AddNotResidue", "call(public * add(..)) && target(java.lang.Object) && !target(java.util.ArrayList)"); } public void testState() throws IOException { checkWeave( "AddStateResidue", "DynamicHelloWorld", "call(public * add(..)) && target(list)", new String[] { "java.util.ArrayList" }, new String[] { "list" }); checkWeave( "AddStateResidue", "DynamicHelloWorld", "target(foo) && !target(java.lang.Integer) && call(public * add(..))", new String[] { "java.util.ArrayList" }, new String[] { "foo" }); checkDynamicWeave( "AddResidue", "call(public * add(..)) && (target(java.util.ArrayList) || target(java.lang.String))"); checkDynamicWeave( "AddResidue", "call(public * add(..)) && this(java.io.Serializable) && target(java.util.ArrayList) && !this(java.lang.Integer)"); } public void testNoResidueArgs() throws IOException { checkDynamicWeave("NoResidue", "call(public * add(..)) && args(java.lang.Object)"); checkDynamicWeave("NoResidue", "call(public * add(..)) && args(*)"); checkDynamicWeave("NoResidue", "call(public * add(..))"); } // ---- cflow tests public void testCflowState() throws IOException { checkWeave( "CflowStateResidue", "DynamicHelloWorld", "cflow(call(public * add(..)) && target(list)) && execution(public void main(..))", new String[] { "java.util.ArrayList" }, new String[] { "list" }); // checkWeave( // "CflowStateResidue", // "DynamicHelloWorld", // "cflow(call(public * add(..)) && target(list)) && this(obj) && execution(public void doit(..))", // new String[] { "java.lang.Object", "java.util.ArrayList" }, // new String[] { "obj", "list" }); // checkWeave( // "AddStateResidue", // "DynamicHelloWorld", // "target(foo) && !target(java.lang.Integer) && call(public * add(..))", // new String[] { "java.util.ArrayList" }, // new String[] { "foo" }); // checkDynamicWeave( // "AddResidue", // "call(public * add(..)) && (target(java.util.ArrayList) || target(java.lang.String))"); // checkDynamicWeave( // "AddResidue", // "call(public * add(..)) && this(java.io.Serializable) && target(java.util.ArrayList) && !this(java.lang.Integer)"); } // ---- private void checkDynamicWeave(String label, String pointcutSource) throws IOException { checkWeave(label, "DynamicHelloWorld", pointcutSource, new String[0], new String[0]); } private void checkMultiArgWeave(String label, String pointcutSource) throws IOException { checkWeave(label, "MultiArgHelloWorld", pointcutSource, new String[0], new String[0]); } private void checkWeave( String label, String filename, String pointcutSource, String[] formalTypes, String[] formalNames) throws IOException { final Pointcut sp = Pointcut.fromString(pointcutSource); final Pointcut rp = sp.resolve( new SimpleScope( world, SimpleScope.makeFormalBindings(TypeX.forNames(formalTypes), formalNames) )); ShadowMunger pp = new BcelAdvice( AdviceKind.Before, rp, Member.method( TypeX.forName("Aspect"), Modifier.STATIC, "ajc_before_0", Member.typesToSignature( ResolvedTypeX.VOID, TypeX.forNames(formalTypes))), 0, -1, -1, null, null); ResolvedTypeX inAspect = world.resolve("Aspect"); CrosscuttingMembers xcut = new CrosscuttingMembers(inAspect); inAspect.crosscuttingMembers = xcut; ShadowMunger cp = pp.concretize(inAspect, world, null); xcut.addConcreteShadowMunger(cp); //System.out.println("extras: " + inAspect.getExtraConcreteShadowMungers()); // List advice = new ArrayList(); // advice.add(cp); // advice.addAll(inAspect.getExtraConcreteShadowMungers()); weaveTest(new String[] { filename }, label, xcut.getShadowMungers()); checkSerialize(rp); } public void weaveTest(String name, String outName, ShadowMunger planner) throws IOException { List l = new ArrayList(1); l.add(planner); weaveTest(name, outName, l); } public void checkSerialize(Pointcut p) throws IOException { 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); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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()); DataInputStream in = new DataInputStream(bi); Pointcut newP = Pointcut.read(in, null); assertEquals("write/read", p, newP); } private static class Foo{}; private static class Bar{}; private static class C{}; }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/testsrc/org/aspectj/weaver/patterns/DeclareErrorOrWarningTestCase.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; public class DeclareErrorOrWarningTestCase extends TestCase { public DeclareErrorOrWarningTestCase(String name) { super(name); } public void testParse() throws IOException { DeclareErrorOrWarning d = parse("declare error: call(void foo()): \"that is bad\";"); assertTrue(d.isError()); assertEquals(d.getPointcut(), new PatternParser("call(void foo())").parsePointcut()); assertEquals("that is bad", d.getMessage()); checkSerialization(d); d = parse("declare warning: bar() && baz(): \"boo!\";"); assertTrue(!d.isError()); assertEquals(d.getPointcut(), new PatternParser("bar() && baz()").parsePointcut()); assertEquals("boo!", d.getMessage()); checkSerialization(d); } private DeclareErrorOrWarning parse(String string) { return (DeclareErrorOrWarning)new PatternParser(string).parseDeclare(); } private void checkSerialization(Declare declare) throws IOException { ByteArrayOutputStream bo = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bo); declare.write(out); out.close(); ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); DataInputStream in = new DataInputStream(bi); Declare newDeclare = Declare.read(in, null); assertEquals("write/read", declare, newDeclare); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/testsrc/org/aspectj/weaver/patterns/ModifiersPatternTestCase.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 java.lang.reflect.*; import org.aspectj.weaver.bcel.*; import junit.framework.TestCase; import org.aspectj.weaver.*; public class ModifiersPatternTestCase extends TestCase { /** * Constructor for PatternTestCase. * @param name */ public ModifiersPatternTestCase(String name) { super(name); } World world; public void testMatch() { world = new BcelWorld(); int[] publicMatches = new int[] { Modifier.PUBLIC, Modifier.PUBLIC | Modifier.STATIC, Modifier.PUBLIC | Modifier.STATIC | Modifier.STRICT | Modifier.FINAL, }; int[] publicFailures = new int[] { Modifier.PRIVATE, 0, Modifier.STATIC | Modifier.STRICT | Modifier.FINAL, }; int[] publicStaticMatches = new int[] { Modifier.PUBLIC | Modifier.STATIC, Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL | Modifier.STRICT, }; int[] publicStaticFailures = new int[] { 0, Modifier.PUBLIC, Modifier.STATIC, }; int[] trickMatches = new int[] { Modifier.PRIVATE, Modifier.PRIVATE | Modifier.ABSTRACT, Modifier.PRIVATE | Modifier.FINAL, }; int[] trickFailures = new int[] { Modifier.PUBLIC, Modifier.PRIVATE | Modifier.STATIC, Modifier.PRIVATE | Modifier.STRICT, }; int[] none = new int[0]; checkMatch("", publicMatches, none); checkMatch("", publicFailures, none); checkMatch("!public", publicFailures, publicMatches); checkMatch("public", publicMatches, publicFailures); checkMatch("public static", none, publicFailures); checkMatch("public static", publicStaticMatches, publicStaticFailures); checkMatch("private !static !strictfp", trickMatches, trickFailures); checkMatch("private !static !strictfp", none, publicMatches); checkMatch("private !static !strictfp", none, publicStaticMatches); } private ModifiersPattern makeModifiersPattern(String pattern) { return new PatternParser(pattern).parseModifiersPattern(); } private void checkMatch(String pattern, int[] shouldMatch, int[] shouldFail) { ModifiersPattern p = makeModifiersPattern(pattern); checkMatch(p, shouldMatch, true); checkMatch(p, shouldFail, false); } private void checkMatch(ModifiersPattern p, int[] matches, boolean shouldMatch) { for (int i=0; i<matches.length; i++) { boolean result = p.matches(matches[i]); String msg = "matches " + p + " to " + Modifier.toString(matches[i]) + " expected "; if (shouldMatch) { assertTrue(msg + shouldMatch, result); } else { assertTrue(msg + shouldMatch, !result); } } } public void testSerialization() throws IOException { String[] patterns = new String[] { "", "!public", "public", "public static", "private !static !strictfp", }; for (int i=0, len=patterns.length; i < len; i++) { checkSerialization(patterns[i]); } } /** * Method checkSerialization. * @param string */ private void checkSerialization(String string) throws IOException { ModifiersPattern p = makeModifiersPattern(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); ModifiersPattern newP = ModifiersPattern.read(in); assertEquals("write/read", p, newP); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/testsrc/org/aspectj/weaver/patterns/NamePatternTestCase.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.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import junit.framework.TestCase; /** * @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 NamePatternTestCase extends TestCase { static String[] matchAll = new String[] { "*****", "*" }; static String[] match1 = new String[] { "abcde", "abc*", "abcd*", "abcde*", "*e", "*cde", "*abcde", "a*e", "ab*e", "abc*de", "*a*b*c*d*e*", "a*c*e", "a***bcde", "*d*", }; static String[] match2 = new String[] { "abababab", "aba*", "abab*", "abababab*", "*b", "*ab", "*ababab", "*abababab", "a*b", "ab*b", "abab*abab", "*a*b*a*b*a*b*a*b*", "a*****b", "a**b", "ab*b*b", }; /** * Constructor for PatternTestCase. * @param name */ public NamePatternTestCase(String name) { super(name); } public void testMatch() { checkMatch("abcde", matchAll, true); checkMatch("abcde", match1, true); checkMatch("abcde", match2, false); checkMatch("abababab", matchAll, true); checkMatch("abababab", match1, false); checkMatch("abababab", match2, true); } /** * Method checkMatch. * @param string * @param matchAll * @param b */ private void checkMatch(String string, String[] patterns, boolean shouldMatch) { for (int i=0, len=patterns.length; i < len; i++) { NamePattern p = new NamePattern(patterns[i]); checkMatch(string, p, shouldMatch); } } private void checkMatch(String string, NamePattern p, boolean shouldMatch) { String msg = "matching " + string + " to " + p; assertEquals(msg, shouldMatch, p.matches(string)); } public void testSerialization() throws IOException { checkSerialization(matchAll); checkSerialization(match1); checkSerialization(match2); } private void checkSerialization(String[] patterns) throws IOException { for (int i=0, len=patterns.length; i < len; i++) { NamePattern p = new NamePattern(patterns[i]); checkSerialization(p); } } private void checkSerialization(NamePattern p) throws IOException { 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); NamePattern newP = NamePattern.read(in); assertEquals("write/read", p, newP); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/testsrc/org/aspectj/weaver/patterns/SignaturePatternTestCase.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.*; import org.aspectj.weaver.*; import org.aspectj.weaver.bcel.*; public class SignaturePatternTestCase extends TestCase { /** * Constructor for PatternTestCase. * @param name */ public SignaturePatternTestCase(String name) { super(name); } BcelWorld world = new BcelWorld(); public void testThrowsMatch() throws IOException { Member onlyDerivedOnDerived = Member.methodFromString("static void fluffy.Derived.onlyDerived()"); Member mOnBase = Member.methodFromString("void fluffy.Base.m()"); Member mOnDerived = Member.methodFromString("void fluffy.Derived.m()"); checkMatch(makeMethodPat("* fluffy.Base.*(..) throws java.lang.CloneNotSupportedException"), new Member[] { mOnBase }, new Member[] { mOnDerived }); checkMatch(makeMethodPat("* fluffy.Derived.*(..) throws java.lang.CloneNotSupportedException"), new Member[] { }, new Member[] { mOnBase, mOnDerived }); //XXX need pattern checks Member[] NONE = new Member[] {}; Member[] M = new Member[] { onlyDerivedOnDerived }; Member[] NO_EXCEPTIONS = new Member[] { mOnDerived }; Member[] BOTH = new Member[] {mOnDerived, onlyDerivedOnDerived}; checkMatch(makeMethodPat("* *(..)"), M, NONE); checkMatch(makeMethodPat("* *(..) throws !*"), NO_EXCEPTIONS, M); checkMatch(makeMethodPat("* *(..) throws *"), M, NO_EXCEPTIONS); checkMatch(makeMethodPat("* *(..) throws *, !*"), NONE, BOTH); checkMatch(makeMethodPat("* *(..) throws (!*)"), NONE, BOTH); checkMatch(makeMethodPat("* *(..) throws !(!*)"), BOTH, NONE); checkMatch(makeMethodPat("* *(..) throws *..IOException"), M, NO_EXCEPTIONS); checkMatch(makeMethodPat("* *(..) throws *..IOException, *..Clone*"), M, NO_EXCEPTIONS); checkMatch(makeMethodPat("* *(..) throws *..IOException, !*..Clone*"), NONE, BOTH); checkMatch(makeMethodPat("* *(..) throws !*..IOException"), NO_EXCEPTIONS, M); } public void testInstanceMethodMatch() throws IOException { Member objectToString = Member.methodFromString("java.lang.String java.lang.Object.toString()"); Member integerToString = Member.methodFromString("java.lang.String java.lang.Integer.toString()"); Member integerIntValue = Member.methodFromString("int java.lang.Integer.intValue()"); //Member objectToString = Member.methodFromString("java.lang.String java.lang.Object.toString()"); checkMatch(makeMethodPat("* java.lang.Object.*(..)"), new Member[] { objectToString, integerToString }, new Member[] { integerIntValue }); checkMatch(makeMethodPat("* java.lang.Integer.*(..)"), new Member[] { integerIntValue, integerToString }, new Member[] { objectToString }); } public void testStaticMethodMatch() throws IOException { Member onlyBaseOnBase = Member.methodFromString("static void fluffy.Base.onlyBase()"); Member onlyBaseOnDerived = Member.methodFromString("static void fluffy.Derived.onlyBase()"); Member onlyDerivedOnDerived = Member.methodFromString("static void fluffy.Derived.onlyDerived()"); Member bothOnBase = Member.methodFromString("static void fluffy.Base.both()"); Member bothOnDerived = Member.methodFromString("static void fluffy.Derived.both()"); checkMatch(makeMethodPat("* fluffy.Base.*(..)"), new Member[] { onlyBaseOnBase, onlyBaseOnDerived, bothOnBase }, new Member[] { onlyDerivedOnDerived, bothOnDerived }); checkMatch(makeMethodPat("* fluffy.Derived.*(..)"), new Member[] { onlyBaseOnDerived, bothOnDerived, onlyDerivedOnDerived }, new Member[] { onlyBaseOnBase, bothOnBase }); } public void testFieldMatch() throws IOException { Member onlyBaseOnBase = Member.fieldFromString("int fluffy.Base.onlyBase"); Member onlyBaseOnDerived = Member.fieldFromString("int fluffy.Derived.onlyBase"); Member onlyDerivedOnDerived = Member.fieldFromString("int fluffy.Derived.onlyDerived"); Member bothOnBase = Member.fieldFromString("int fluffy.Base.both"); Member bothOnDerived = Member.fieldFromString("int fluffy.Derived.both"); checkMatch(makeFieldPat("* fluffy.Base.*"), new Member[] { onlyBaseOnBase, onlyBaseOnDerived, bothOnBase }, new Member[] { onlyDerivedOnDerived, bothOnDerived }); checkMatch(makeFieldPat("* fluffy.Derived.*"), new Member[] { onlyBaseOnDerived, bothOnDerived, onlyDerivedOnDerived }, new Member[] { onlyBaseOnBase, bothOnBase }); } public void testConstructorMatch() throws IOException { Member onBase = Member.methodFromString("void fluffy.Base.<init>()"); Member onDerived = Member.methodFromString("void fluffy.Derived.<init>()"); Member onBaseWithInt = Member.methodFromString("void fluffy.Base.<init>(int)"); checkMatch(makeMethodPat("fluffy.Base.new(..)"), new Member[] { onBase, onBaseWithInt }, new Member[] { onDerived }); checkMatch(makeMethodPat("fluffy.Derived.new(..)"), new Member[] { onDerived}, new Member[] { onBase, onBaseWithInt }); } public void checkMatch(SignaturePattern p, Member[] yes, Member[] no) throws IOException { p = p.resolveBindings(new TestScope(world, new FormalBinding[0]), new Bindings(0)); for (int i=0; i < yes.length; i++) { checkMatch(p, yes[i], true); } for (int i=0; i < no.length; i++) { checkMatch(p, no[i], false); } checkSerialization(p); } private void checkMatch(SignaturePattern p, Member member, boolean b) { boolean matches = p.matches(member, world); assertEquals(p.toString() + " matches " + member.toString(), b, matches); } private SignaturePattern makeMethodPat(String pattern) { return new PatternParser(pattern).parseMethodOrConstructorSignaturePattern(); } private SignaturePattern makeFieldPat(String pattern) { return new PatternParser(pattern).parseFieldSignaturePattern(); } private void checkSerialization(SignaturePattern p) throws IOException { 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); SignaturePattern newP = SignaturePattern.read(in, null); assertEquals("write/read", p, newP); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/testsrc/org/aspectj/weaver/patterns/TypePatternListTestCase.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 java.util.Arrays; import org.aspectj.weaver.bcel.*; import org.aspectj.util.*; 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 TypePatternListTestCase extends TestCase { /** * Constructor for PatternTestCase. * @param name */ public TypePatternListTestCase(String name) { super(name); } World world; //XXX when instanceof matching works add tests for that here public void testMatch() { world = new BcelWorld(); checkStaticMatch("()", new String[] {}, FuzzyBoolean.YES); checkStaticMatch("()", new String[] {"java.lang.Object"}, FuzzyBoolean.NO); checkStaticMatch("(java.lang.Object)", new String[] {"java.lang.Object"}, FuzzyBoolean.YES); checkStaticMatch("(java.lang.String)", new String[] {"java.lang.Object"}, FuzzyBoolean.NO); checkStaticMatch("(java.lang.Object)", new String[] {"java.lang.String"}, FuzzyBoolean.NO); checkStaticMatch("()", new String[] {"java.lang.Object"}, FuzzyBoolean.NO); checkStaticMatch("(..)", new String[] {}, FuzzyBoolean.YES); checkStaticMatch("(..)", new String[] {"int", "char"}, FuzzyBoolean.YES); checkStaticMatch("(int,..,int)", new String[] {"int", "int"}, FuzzyBoolean.YES); checkStaticMatch("(int,..)", new String[] {}, FuzzyBoolean.NO); checkStaticMatch("(int,..)", new String[] {"int"}, FuzzyBoolean.YES); checkStaticMatch("(..,int,..)", new String[] {"int"}, FuzzyBoolean.YES); // these checks are taken from new/ExpandedDotPattern.java stupidCheck("( .., .., ..)", new boolean[] { true, true, true, true, true }); stupidCheck("( .., .., int)", new boolean[] { false, true, true, true, true }); stupidCheck("( .., int, ..)", new boolean[] { false, true, true, true, true }); stupidCheck("( .., int, int)", new boolean[] { false, false, true, true, true }); stupidCheck("(int, .., ..)", new boolean[] { false, true, true, true, true }); stupidCheck("(int, .., int)", new boolean[] { false, false, true, true, true }); stupidCheck("(int, int, ..)", new boolean[] { false, false, true, true, true }); stupidCheck("(int, int, int)", new boolean[] { false, false, false, true, false }); stupidCheck("( .., .., .., ..)", new boolean[] { true, true, true, true, true }); stupidCheck("( .., .., .., int)", new boolean[] { false, true, true, true, true }); stupidCheck("( .., .., int, ..)", new boolean[] { false, true, true, true, true }); stupidCheck("( .., .., int, int)", new boolean[] { false, false, true, true, true }); stupidCheck("( .., int, .., ..)", new boolean[] { false, true, true, true, true }); stupidCheck("( .., int, .., int)", new boolean[] { false, false, true, true, true }); stupidCheck("( .., int, int, ..)", new boolean[] { false, false, true, true, true }); stupidCheck("( .., int, int, int)", new boolean[] { false, false, false, true, true }); stupidCheck("(int, .., .., ..)", new boolean[] { false, true, true, true, true }); stupidCheck("(int, .., .., int)", new boolean[] { false, false, true, true, true }); stupidCheck("(int, .., int, ..)", new boolean[] { false, false, true, true, true }); stupidCheck("(int, .., int, int)", new boolean[] { false, false, false, true, true }); stupidCheck("(int, int, .., ..)", new boolean[] { false, false, true, true, true }); stupidCheck("(int, int, .., int)", new boolean[] { false, false, false, true, true }); stupidCheck("(int, int, int, ..)", new boolean[] { false, false, false, true, true }); stupidCheck("(int, int, int, int)", new boolean[] { false, false, false, false, true }); } private TypePatternList makeArgumentsPattern(String pattern) { return new PatternParser(pattern).parseArgumentsPattern(); } private void checkStaticMatch(String pattern, String[] names, FuzzyBoolean shouldMatchStatically) { // We're only doing TypePattern.STATIC matching here because my intent was // to test the wildcarding, and we don't do DYNAMIC matching on wildcarded things. TypePatternList p = makeArgumentsPattern(pattern); ResolvedTypeX[] types = new ResolvedTypeX[names.length]; for (int i = 0; i < names.length; i++) { types[i] = world.resolve(names[i]); } p.resolveBindings(makeTestScope(), Bindings.NONE, false, false); //System.out.println("type: " + type); FuzzyBoolean result = p.matches(types, TypePattern.STATIC); String msg = "matches statically " + pattern + " to " + Arrays.asList(types); assertEquals(msg, shouldMatchStatically, result); } private TestScope makeTestScope() { TestScope scope = new TestScope(CollectionUtil.NO_STRINGS, CollectionUtil.NO_STRINGS, world); return scope; } public void stupidCheck(String pattern, boolean[] matches) { TypePatternList p = makeArgumentsPattern(pattern); p.resolveBindings(makeTestScope(), Bindings.NONE, false, false); int len = matches.length; for (int j = 0; j < len; j++) { ResolvedTypeX[] types = new ResolvedTypeX[j]; for (int i = 0; i < j; i++) { types[i] = world.resolve("int"); } FuzzyBoolean result = p.matches(types, TypePattern.STATIC); String msg = "matches statically " + pattern + " to " + Arrays.asList(types); assertEquals(msg, FuzzyBoolean.fromBoolean(matches[j]), result); } } public void testSerialization() throws IOException { String[] patterns = new String[] { "( .., .., .., int)", "( .., .., int, ..)", "( .., .., int, int)", "( .., int, .., ..)", "( .., int, .., int)", "( .., int, int, ..)", "( .., int, int, int)", "(int, .., .., ..)", "(int, .., .., int)", "(int, .., int, ..)", "(int, .., int, int)", "(int, int, .., ..)", "(int, int, .., int)", "(int, int, int, ..)", "(int, int, int, int)" }; for (int i=0, len=patterns.length; i < len; i++) { checkSerialization(patterns[i]); } } /** * Method checkSerialization. * @param string */ private void checkSerialization(String string) throws IOException { TypePatternList p = makeArgumentsPattern(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); TypePatternList newP = TypePatternList.read(in, null); assertEquals("write/read", p, newP); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46:40Z
weaver/testsrc/org/aspectj/weaver/patterns/TypePatternTestCase.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.weaver.bcel.*; import org.aspectj.bridge.AbortException; import org.aspectj.util.FuzzyBoolean; import junit.framework.TestCase; import org.aspectj.weaver.*; public class TypePatternTestCase extends TestCase { /** * Constructor for PatternTestCase. * @param name */ public TypePatternTestCase(String name) { super(name); } World world; public void testStaticMatch() { world = new BcelWorld(); checkMatch("java.lang.Object", "java.lang.Object", true); checkMatch("java.lang.Object+", "java.lang.Object", true); checkMatch("java.lang.Object+", "java.lang.String", true); checkMatch("java.lang.String+", "java.lang.Object", false); checkMatch("java.lang.Integer", "java.lang.String", false); checkMatch("java.lang.Integer", "int", false); checkMatch("java.lang.Number+", "java.lang.Integer", true); checkMatch("java..*", "java.lang.Integer", true); checkMatch("java..*", "java.lang.reflect.Modifier", true); checkMatch("java..*", "int", false); checkMatch("java..*", "javax.swing.Action", false); checkMatch("java..*+", "javax.swing.Action", true); checkMatch("*.*.Object", "java.lang.Object", true); checkMatch("*.Object", "java.lang.Object", false); checkMatch("*..*", "java.lang.Object", true); checkMatch("*..*", "int", false); checkMatch("java..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java.lang.reflect.Mod..ifier", "java.lang.reflect.Modifier", false); checkMatch("java..reflect..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java..lang..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java..*..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java..*..*..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java..*..*..*..Modifier", "java.lang.reflect.Modifier", false); //checkMatch("java..reflect..Modifier", "java.lang.reflect.Modxifier", false); checkMatch("ja*va..Modifier", "java.lang.reflect.Modifier", true); checkMatch("java..*..Mod*ifier", "java.lang.reflect.Modifier", true); } // three levels: // 0. defined in current compilation unit, or imported by name // 1. defined in current package/type/whatever // 2. defined in package imported by * /** * We've decided not to test this here, but rather in any compilers */ public void testImportResolve() { world = new BcelWorld(); // checkIllegalImportResolution("List", new String[] { "java.util", "java.awt", }, // ZERO_STRINGS); } // Assumption for bcweaver: Already resolved type patterns with no *s or ..'s into exact type // patterns. Exact type patterns don't have import lists. non-exact-type pattens don't // care about precedence, so the current package can be included with all the other packages, // and we don't care about compilation units, and we don't care about ordering. // only giving this wild-type patterns public void testImportMatch() { world = new BcelWorld(); checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.util.List", false); checkImportMatch("*List", new String[] { "java.util.", }, ZERO_STRINGS, "java.awt.List", false); checkImportMatch("*List", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.List", true); checkImportMatch("*List", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", true); checkImportMatch("awt.*List", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", false); checkImportMatch("*Foo", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", false); checkImportMatch("*List", new String[] { "java.util.", "java.awt.", }, ZERO_STRINGS, "java.util.List", true); checkImportMatch("*List", new String[] { "java.util.", "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); checkImportMatch("*..List", new String[] { "java.util." }, ZERO_STRINGS, "java.util.List", true); checkImportMatch("*..List", new String[] { "java.util." }, ZERO_STRINGS, "java.awt.List", true); } public void testImportMatchWithInners() { world = new BcelWorld(); checkImportMatch("*Entry", new String[] { "java.util.", "java.util.Map$"}, ZERO_STRINGS, "java.util.Map$Entry", true); checkImportMatch("java.util.Map.*Entry", ZERO_STRINGS, ZERO_STRINGS, "java.util.Map$Entry", true); checkImportMatch("*Entry", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", false); checkImportMatch("*.Entry", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", true); checkImportMatch("Map.*", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", true); checkImportMatch("Map.*", ZERO_STRINGS, new String[] { "java.util.Map" }, "java.util.Map$Entry", true); } private void checkImportMatch( String wildPattern, String[] importedPackages, String[] importedNames, String matchName, boolean shouldMatch) { WildTypePattern p = makeResolvedWildTypePattern(wildPattern, importedPackages, importedNames); checkPatternMatch(p, matchName, shouldMatch); } private WildTypePattern makeResolvedWildTypePattern( String wildPattern, String[] importedPackages, String[] importedNames) { WildTypePattern unresolved = (WildTypePattern) new PatternParser(wildPattern).parseTypePattern(); WildTypePattern resolved = resolve(unresolved, importedPackages, importedNames); return resolved; } private WildTypePattern resolve( WildTypePattern unresolved, String[] importedPrefixes, String[] importedNames) { TestScope scope = makeTestScope(); scope.setImportedPrefixes(importedPrefixes); scope.setImportedNames(importedNames); return (WildTypePattern) unresolved.resolveBindings(scope, Bindings.NONE, false, false); } public static final String[] ZERO_STRINGS = new String[0]; public void testInstanceofMatch() { world = new BcelWorld(); checkInstanceofMatch("java.lang.Object", "java.lang.Object", FuzzyBoolean.YES); checkIllegalInstanceofMatch("java.lang.Object+", "java.lang.Object"); checkIllegalInstanceofMatch("java.lang.Object+", "java.lang.String"); checkIllegalInstanceofMatch("java.lang.String+", "java.lang.Object"); checkIllegalInstanceofMatch("java.lang.*", "java.lang.Object"); checkInstanceofMatch("java.lang.Integer", "java.lang.String", FuzzyBoolean.NO); checkInstanceofMatch("java.lang.Number", "java.lang.Integer", FuzzyBoolean.YES); checkInstanceofMatch("java.lang.Integer", "java.lang.Number", FuzzyBoolean.MAYBE); checkIllegalInstanceofMatch("java..Integer", "java.lang.Integer"); checkInstanceofMatch("*", "java.lang.Integer", FuzzyBoolean.YES); } public void testArrayMatch() { world = new BcelWorld(); checkMatch("*[][]","java.lang.Object",false); checkMatch("*[]","java.lang.Object[]",true); checkMatch("*[][]","java.lang.Object[][]",true); checkMatch("java.lang.Object[]","java.lang.Object",false); checkMatch("java.lang.Object[]","java.lang.Object[]",true); checkMatch("java.lang.Object[][]","java.lang.Object[][]",true); checkMatch("java.lang.String[]","java.lang.Object",false); checkMatch("java.lang.String[]","java.lang.Object[]",false); checkMatch("java.lang.String[][]","java.lang.Object[][]",false); checkMatch("java.lang.Object+[]","java.lang.String[]",true); } private void checkIllegalInstanceofMatch(String pattern, String name) { try { TypePattern p = makeTypePattern(pattern); ResolvedTypeX type = world.resolve(name); /*FuzzyBoolean result = */p.matchesInstanceof(type); } catch (AbortException e) { return; } assertTrue("matching " + pattern + " with " + name + " should fail", false); } private void checkInstanceofMatch(String pattern, String name, FuzzyBoolean shouldMatch) { TypePattern p = makeTypePattern(pattern); ResolvedTypeX type = world.resolve(name); p = p.resolveBindings(makeTestScope(), null, false, false); //System.out.println("type: " + p); FuzzyBoolean result = p.matchesInstanceof(type); String msg = "matches " + pattern + " to " + type; assertEquals(msg, shouldMatch, result); } private TestScope makeTestScope() { TestScope scope = new TestScope(ZERO_STRINGS, ZERO_STRINGS, world); return scope; } private TypePattern makeTypePattern(String pattern) { return new PatternParser(pattern).parseSingleTypePattern(); } private void checkMatch(String pattern, String name, boolean shouldMatch) { TypePattern p = makeTypePattern(pattern); p = p.resolveBindings(makeTestScope(), null, false, false); checkPatternMatch(p, name, shouldMatch); } private void checkPatternMatch( TypePattern p, String name, boolean shouldMatch) { ResolvedTypeX type = world.resolve(name); //System.out.println("type: " + type); boolean result = p.matchesStatically(type); String msg = "matches " + p + " to " + type + " expected "; if (shouldMatch) { assertTrue(msg + shouldMatch, result); } else { assertTrue(msg + shouldMatch, !result); } } public void testSerialization() throws IOException { String[] patterns = new String[] { "java.lang.Object", "java.lang.Object+", "java.lang.Integer", "int", "java..*", "java..util..*", "*.*.Object", "*", }; for (int i=0, len=patterns.length; i < len; i++) { checkSerialization(patterns[i]); } } /** * Method checkSerialization. * @param string */ private void checkSerialization(String string) throws IOException { TypePattern p = makeTypePattern(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); TypePattern newP = TypePattern.read(in, null); assertEquals("write/read", p, newP); } }
82,134
Bug 82134 AspectJ 5 M2 should implement backwards compatibility for binary aspect form
null
resolved fixed
797b6a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-07T14:14:45Z
2005-01-04T14:46: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, Member.fieldFromString("java.io.PrintStream java.lang.System.out"), TypeX.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, Member.fieldFromString("java.io.PrintStream java.lang.System.out"), TypeX.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, 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()); DataInputStream in = new DataInputStream(bi); Pointcut newP = Pointcut.read(in, null); assertEquals("write/read", p, newP); } }
78,021
Bug 78021 Injecting exception into while loop with break statement causes catch block to be ignored
In order to test exception scenarios in an existing framework, I have created an aspect to inject an exception. The exception is injected into some code running within a try/catch/finally block. After the exception is thrown, I am expecting control to pass to the catch block. However, what is happening is that the catch block code is not executed, control passes through the finally block and the (undeclared) exception is thrown to the calling method. Here is a distilled test case: public class MainClass { protected Integer counter; private int j; public static void main(String[] args) { MainClass mh = new MainClass(); try { mh.doSomething(); } catch (Exception e) { System.out.println("Exception thrown by doSomething!!!!!"); e.printStackTrace(); } } public void doSomething() { int i = 0; while (i++ < 1) { counter=null; try { counter = getCounter(); if (counter == null) { break; } commit(); } catch (Throwable e) { System.out.println("Caught exception " + e); } finally { System.out.println("In finally block"); } } } protected Integer getCounter() { return new Integer(j++); } protected void commit() throws SQLException { System.out.println("Main.commit"); } } The following aspect injects the exception: public aspect SimpleExceptionThrowingAspect { pointcut commitOperation() : call (* MainClass+.commit(..)); before() throws SQLException : commitOperation() { throw new SQLException("Dummy SQL Exception", "55102"); } } Expected output is: Caught exception java.sql.SQLException: Dummy SQL Exception In finally block Actual output is: In finally block Exception thrown by doSomething!!!!! java.sql.SQLException: Dummy SQL Exception at nz.govt.moh.test.SimpleExceptionThrowingAspect.ajc$before$nz_govt_moh_test_SimpleExceptionThrowingAspect$1$292c82f1(SimpleExceptionThrowingAspect.aj:10) at nz.govt.moh.test.MainClass.doSomething(MainClass.java:32) at nz.govt.moh.test.MainClass.main(MainClass.java:14) Removing the "break;" statement from MainClass.java causes the expected output to be produced.
resolved fixed
603b063
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-11T11:22:15Z
2004-11-06T19:40:00Z
tests/bugs150/PR78021.java
78,021
Bug 78021 Injecting exception into while loop with break statement causes catch block to be ignored
In order to test exception scenarios in an existing framework, I have created an aspect to inject an exception. The exception is injected into some code running within a try/catch/finally block. After the exception is thrown, I am expecting control to pass to the catch block. However, what is happening is that the catch block code is not executed, control passes through the finally block and the (undeclared) exception is thrown to the calling method. Here is a distilled test case: public class MainClass { protected Integer counter; private int j; public static void main(String[] args) { MainClass mh = new MainClass(); try { mh.doSomething(); } catch (Exception e) { System.out.println("Exception thrown by doSomething!!!!!"); e.printStackTrace(); } } public void doSomething() { int i = 0; while (i++ < 1) { counter=null; try { counter = getCounter(); if (counter == null) { break; } commit(); } catch (Throwable e) { System.out.println("Caught exception " + e); } finally { System.out.println("In finally block"); } } } protected Integer getCounter() { return new Integer(j++); } protected void commit() throws SQLException { System.out.println("Main.commit"); } } The following aspect injects the exception: public aspect SimpleExceptionThrowingAspect { pointcut commitOperation() : call (* MainClass+.commit(..)); before() throws SQLException : commitOperation() { throw new SQLException("Dummy SQL Exception", "55102"); } } Expected output is: Caught exception java.sql.SQLException: Dummy SQL Exception In finally block Actual output is: In finally block Exception thrown by doSomething!!!!! java.sql.SQLException: Dummy SQL Exception at nz.govt.moh.test.SimpleExceptionThrowingAspect.ajc$before$nz_govt_moh_test_SimpleExceptionThrowingAspect$1$292c82f1(SimpleExceptionThrowingAspect.aj:10) at nz.govt.moh.test.MainClass.doSomething(MainClass.java:32) at nz.govt.moh.test.MainClass.main(MainClass.java:14) Removing the "break;" statement from MainClass.java causes the expected output to be produced.
resolved fixed
603b063
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-11T11:22:15Z
2004-11-06T19:40:00Z
tests/bugs150/PR79554.java
78,021
Bug 78021 Injecting exception into while loop with break statement causes catch block to be ignored
In order to test exception scenarios in an existing framework, I have created an aspect to inject an exception. The exception is injected into some code running within a try/catch/finally block. After the exception is thrown, I am expecting control to pass to the catch block. However, what is happening is that the catch block code is not executed, control passes through the finally block and the (undeclared) exception is thrown to the calling method. Here is a distilled test case: public class MainClass { protected Integer counter; private int j; public static void main(String[] args) { MainClass mh = new MainClass(); try { mh.doSomething(); } catch (Exception e) { System.out.println("Exception thrown by doSomething!!!!!"); e.printStackTrace(); } } public void doSomething() { int i = 0; while (i++ < 1) { counter=null; try { counter = getCounter(); if (counter == null) { break; } commit(); } catch (Throwable e) { System.out.println("Caught exception " + e); } finally { System.out.println("In finally block"); } } } protected Integer getCounter() { return new Integer(j++); } protected void commit() throws SQLException { System.out.println("Main.commit"); } } The following aspect injects the exception: public aspect SimpleExceptionThrowingAspect { pointcut commitOperation() : call (* MainClass+.commit(..)); before() throws SQLException : commitOperation() { throw new SQLException("Dummy SQL Exception", "55102"); } } Expected output is: Caught exception java.sql.SQLException: Dummy SQL Exception In finally block Actual output is: In finally block Exception thrown by doSomething!!!!! java.sql.SQLException: Dummy SQL Exception at nz.govt.moh.test.SimpleExceptionThrowingAspect.ajc$before$nz_govt_moh_test_SimpleExceptionThrowingAspect$1$292c82f1(SimpleExceptionThrowingAspect.aj:10) at nz.govt.moh.test.MainClass.doSomething(MainClass.java:32) at nz.govt.moh.test.MainClass.main(MainClass.java:14) Removing the "break;" statement from MainClass.java causes the expected output to be produced.
resolved fixed
603b063
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-11T11:22:15Z
2004-11-06T19:40:00Z
tests/src/org/aspectj/systemtest/AllTests.java
/* * Created on 03-Aug-2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package org.aspectj.systemtest; import junit.framework.Test; import junit.framework.TestSuite; import org.aspectj.systemtest.ajc10x.Ajc10xTests; import org.aspectj.systemtest.ajc11.Ajc11Tests; import org.aspectj.systemtest.ajc120.Ajc120Tests; import org.aspectj.systemtest.ajc121.Ajc121Tests; import org.aspectj.systemtest.ajc150.AllTestsJava5_binaryWeaving; import org.aspectj.systemtest.aspectpath.AspectPathTests; import org.aspectj.systemtest.base.BaseTests; import org.aspectj.systemtest.design.DesignTests; import org.aspectj.systemtest.incremental.IncrementalTests; import org.aspectj.systemtest.incremental.model.IncrementalModelTests; import org.aspectj.systemtest.inpath.InPathTests; import org.aspectj.systemtest.options.OptionsTests; import org.aspectj.systemtest.pre10x.AjcPre10xTests; import org.aspectj.systemtest.serialVerUID.SUIDTests; import org.aspectj.systemtest.xlint.XLintTests; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class AllTests { public static Test suite() { TestSuite suite = new TestSuite("AspectJ System Test Suite - JDK 1.3"); //$JUnit-BEGIN$ suite.addTest(AllTestsJava5_binaryWeaving.suite()); suite.addTest(Ajc121Tests.suite()); suite.addTest(Ajc120Tests.suite()); suite.addTest(Ajc11Tests.suite()); suite.addTest(Ajc10xTests.suite()); suite.addTest(AspectPathTests.suite()); suite.addTest(InPathTests.suite()); suite.addTest(BaseTests.suite()); suite.addTest(DesignTests.suite()); suite.addTest(IncrementalTests.suite()); suite.addTest(IncrementalModelTests.suite()); //suite.addTest(KnownLimitationsTests.class); suite.addTest(OptionsTests.suite()); suite.addTest(AjcPre10xTests.suite()); //suite.addTest(PureJavaTests.class); suite.addTest(SUIDTests.suite()); suite.addTest(XLintTests.suite()); //$JUnit-END$ return suite; } }
78,021
Bug 78021 Injecting exception into while loop with break statement causes catch block to be ignored
In order to test exception scenarios in an existing framework, I have created an aspect to inject an exception. The exception is injected into some code running within a try/catch/finally block. After the exception is thrown, I am expecting control to pass to the catch block. However, what is happening is that the catch block code is not executed, control passes through the finally block and the (undeclared) exception is thrown to the calling method. Here is a distilled test case: public class MainClass { protected Integer counter; private int j; public static void main(String[] args) { MainClass mh = new MainClass(); try { mh.doSomething(); } catch (Exception e) { System.out.println("Exception thrown by doSomething!!!!!"); e.printStackTrace(); } } public void doSomething() { int i = 0; while (i++ < 1) { counter=null; try { counter = getCounter(); if (counter == null) { break; } commit(); } catch (Throwable e) { System.out.println("Caught exception " + e); } finally { System.out.println("In finally block"); } } } protected Integer getCounter() { return new Integer(j++); } protected void commit() throws SQLException { System.out.println("Main.commit"); } } The following aspect injects the exception: public aspect SimpleExceptionThrowingAspect { pointcut commitOperation() : call (* MainClass+.commit(..)); before() throws SQLException : commitOperation() { throw new SQLException("Dummy SQL Exception", "55102"); } } Expected output is: Caught exception java.sql.SQLException: Dummy SQL Exception In finally block Actual output is: In finally block Exception thrown by doSomething!!!!! java.sql.SQLException: Dummy SQL Exception at nz.govt.moh.test.SimpleExceptionThrowingAspect.ajc$before$nz_govt_moh_test_SimpleExceptionThrowingAspect$1$292c82f1(SimpleExceptionThrowingAspect.aj:10) at nz.govt.moh.test.MainClass.doSomething(MainClass.java:32) at nz.govt.moh.test.MainClass.main(MainClass.java:14) Removing the "break;" statement from MainClass.java causes the expected output to be produced.
resolved fixed
603b063
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-11T11:22:15Z
2004-11-06T19:40:00Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150TestsNoHarness.java
78,021
Bug 78021 Injecting exception into while loop with break statement causes catch block to be ignored
In order to test exception scenarios in an existing framework, I have created an aspect to inject an exception. The exception is injected into some code running within a try/catch/finally block. After the exception is thrown, I am expecting control to pass to the catch block. However, what is happening is that the catch block code is not executed, control passes through the finally block and the (undeclared) exception is thrown to the calling method. Here is a distilled test case: public class MainClass { protected Integer counter; private int j; public static void main(String[] args) { MainClass mh = new MainClass(); try { mh.doSomething(); } catch (Exception e) { System.out.println("Exception thrown by doSomething!!!!!"); e.printStackTrace(); } } public void doSomething() { int i = 0; while (i++ < 1) { counter=null; try { counter = getCounter(); if (counter == null) { break; } commit(); } catch (Throwable e) { System.out.println("Caught exception " + e); } finally { System.out.println("In finally block"); } } } protected Integer getCounter() { return new Integer(j++); } protected void commit() throws SQLException { System.out.println("Main.commit"); } } The following aspect injects the exception: public aspect SimpleExceptionThrowingAspect { pointcut commitOperation() : call (* MainClass+.commit(..)); before() throws SQLException : commitOperation() { throw new SQLException("Dummy SQL Exception", "55102"); } } Expected output is: Caught exception java.sql.SQLException: Dummy SQL Exception In finally block Actual output is: In finally block Exception thrown by doSomething!!!!! java.sql.SQLException: Dummy SQL Exception at nz.govt.moh.test.SimpleExceptionThrowingAspect.ajc$before$nz_govt_moh_test_SimpleExceptionThrowingAspect$1$292c82f1(SimpleExceptionThrowingAspect.aj:10) at nz.govt.moh.test.MainClass.doSomething(MainClass.java:32) at nz.govt.moh.test.MainClass.main(MainClass.java:14) Removing the "break;" statement from MainClass.java causes the expected output to be produced.
resolved fixed
603b063
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-11T11:22:15Z
2004-11-06T19:40:00Z
tests/src/org/aspectj/systemtest/ajc150/AllTestsAspectJ150.java
78,021
Bug 78021 Injecting exception into while loop with break statement causes catch block to be ignored
In order to test exception scenarios in an existing framework, I have created an aspect to inject an exception. The exception is injected into some code running within a try/catch/finally block. After the exception is thrown, I am expecting control to pass to the catch block. However, what is happening is that the catch block code is not executed, control passes through the finally block and the (undeclared) exception is thrown to the calling method. Here is a distilled test case: public class MainClass { protected Integer counter; private int j; public static void main(String[] args) { MainClass mh = new MainClass(); try { mh.doSomething(); } catch (Exception e) { System.out.println("Exception thrown by doSomething!!!!!"); e.printStackTrace(); } } public void doSomething() { int i = 0; while (i++ < 1) { counter=null; try { counter = getCounter(); if (counter == null) { break; } commit(); } catch (Throwable e) { System.out.println("Caught exception " + e); } finally { System.out.println("In finally block"); } } } protected Integer getCounter() { return new Integer(j++); } protected void commit() throws SQLException { System.out.println("Main.commit"); } } The following aspect injects the exception: public aspect SimpleExceptionThrowingAspect { pointcut commitOperation() : call (* MainClass+.commit(..)); before() throws SQLException : commitOperation() { throw new SQLException("Dummy SQL Exception", "55102"); } } Expected output is: Caught exception java.sql.SQLException: Dummy SQL Exception In finally block Actual output is: In finally block Exception thrown by doSomething!!!!! java.sql.SQLException: Dummy SQL Exception at nz.govt.moh.test.SimpleExceptionThrowingAspect.ajc$before$nz_govt_moh_test_SimpleExceptionThrowingAspect$1$292c82f1(SimpleExceptionThrowingAspect.aj:10) at nz.govt.moh.test.MainClass.doSomething(MainClass.java:32) at nz.govt.moh.test.MainClass.main(MainClass.java:14) Removing the "break;" statement from MainClass.java causes the expected output to be produced.
resolved fixed
603b063
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-11T11:22:15Z
2004-11-06T19:40:00Z
tests/src/org/aspectj/systemtest/ajc150/AllTestsJava5_binaryWeaving.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 junit.framework.Test; import junit.framework.TestSuite; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class AllTestsJava5_binaryWeaving { public static Test suite() { TestSuite suite = new TestSuite("Java5 - binary weaving"); //$JUnit-BEGIN$ suite.addTestSuite(MigrationTests.class); suite.addTest(Ajc150Tests.suite()); suite.addTest(AccBridgeMethods.suite()); suite.addTestSuite(CovarianceTests.class); suite.addTestSuite(Enums.class); suite.addTestSuite(Annotations.class); suite.addTestSuite(AnnotationPointcutsTests.class); suite.addTestSuite(VarargsTests.class); suite.addTestSuite(AnnotationRuntimeTests.class); //$JUnit-END$ return suite; } }
78,021
Bug 78021 Injecting exception into while loop with break statement causes catch block to be ignored
In order to test exception scenarios in an existing framework, I have created an aspect to inject an exception. The exception is injected into some code running within a try/catch/finally block. After the exception is thrown, I am expecting control to pass to the catch block. However, what is happening is that the catch block code is not executed, control passes through the finally block and the (undeclared) exception is thrown to the calling method. Here is a distilled test case: public class MainClass { protected Integer counter; private int j; public static void main(String[] args) { MainClass mh = new MainClass(); try { mh.doSomething(); } catch (Exception e) { System.out.println("Exception thrown by doSomething!!!!!"); e.printStackTrace(); } } public void doSomething() { int i = 0; while (i++ < 1) { counter=null; try { counter = getCounter(); if (counter == null) { break; } commit(); } catch (Throwable e) { System.out.println("Caught exception " + e); } finally { System.out.println("In finally block"); } } } protected Integer getCounter() { return new Integer(j++); } protected void commit() throws SQLException { System.out.println("Main.commit"); } } The following aspect injects the exception: public aspect SimpleExceptionThrowingAspect { pointcut commitOperation() : call (* MainClass+.commit(..)); before() throws SQLException : commitOperation() { throw new SQLException("Dummy SQL Exception", "55102"); } } Expected output is: Caught exception java.sql.SQLException: Dummy SQL Exception In finally block Actual output is: In finally block Exception thrown by doSomething!!!!! java.sql.SQLException: Dummy SQL Exception at nz.govt.moh.test.SimpleExceptionThrowingAspect.ajc$before$nz_govt_moh_test_SimpleExceptionThrowingAspect$1$292c82f1(SimpleExceptionThrowingAspect.aj:10) at nz.govt.moh.test.MainClass.doSomething(MainClass.java:32) at nz.govt.moh.test.MainClass.main(MainClass.java:14) Removing the "break;" statement from MainClass.java causes the expected output to be produced.
resolved fixed
603b063
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-11T11:22:15Z
2004-11-06T19:40:00Z
tests/src/org/aspectj/systemtest/ajc150/TestUtils.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: * Andy Clement - initial implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.tools.ajc.AjcTestCase; import org.aspectj.tools.ajc.CompilationResult; public abstract class TestUtils extends AjcTestCase { private static final boolean verbose = false; protected File baseDir; protected CompilationResult binaryWeave(String inpath,String insource,int expErrors,int expWarnings) { return binaryWeave(inpath,insource,expErrors,expWarnings,false); } protected CompilationResult binaryWeave(String inpath, String insource,int expErrors,int expWarnings,boolean xlinterror) { return binaryWeave(inpath,insource,expErrors,expWarnings,xlinterror,""); } protected CompilationResult binaryWeave(String inpath, String insource,int expErrors,int expWarnings,String extraOption) { return binaryWeave(inpath,insource,expErrors,expWarnings,false,extraOption); } protected CompilationResult binaryWeave(String inpath, String insource,int expErrors,int expWarnings,boolean xlinterror,String extraOption) { String[] args = null; if (xlinterror) { if (extraOption!=null && extraOption.length()>0) args = new String[] {"-inpath",inpath,insource,"-showWeaveInfo","-proceedOnError","-Xlint:warning",extraOption}; else args = new String[] {"-inpath",inpath,insource,"-showWeaveInfo","-proceedOnError","-Xlint:warning"}; } else { if (extraOption!=null && extraOption.length()>0) args = new String[] {"-inpath",inpath,insource,"-showWeaveInfo","-proceedOnError",extraOption}; else args = new String[] {"-inpath",inpath,insource,"-showWeaveInfo","-proceedOnError"}; } CompilationResult result = ajc(baseDir,args); if (verbose || result.hasErrorMessages()) System.out.println(result); assertTrue("Expected "+expErrors+" errors but got "+result.getErrorMessages().size()+":\n"+ formatCollection(result.getErrorMessages()),result.getErrorMessages().size()==expErrors); assertTrue("Expected "+expWarnings+" warnings but got "+result.getWarningMessages().size()+":\n"+ formatCollection(result.getWarningMessages()),result.getWarningMessages().size()==expWarnings); return result; } private String formatCollection(Collection s) { StringBuffer sb = new StringBuffer(); for (Iterator iter = s.iterator(); iter.hasNext();) { Object element = (Object) iter.next(); sb.append(element).append("\n"); } return sb.toString(); } protected List getWeavingMessages(List msgs) { List result = new ArrayList(); for (Iterator iter = msgs.iterator(); iter.hasNext();) { IMessage element = (IMessage) iter.next(); if (element.getKind()==IMessage.WEAVEINFO) { result.add(element.toString()); } } return result; } protected void verifyWeavingMessagesOutput(CompilationResult cR,String[] expected) { List weavingmessages = getWeavingMessages(cR.getInfoMessages()); dump(weavingmessages); for (int i = 0; i < expected.length; i++) { boolean found = weavingmessages.contains(expected[i]); if (found) { weavingmessages.remove(expected[i]); } else { System.err.println(dump(getWeavingMessages(cR.getInfoMessages()))); fail("Expected message not found.\nExpected:\n"+expected[i]+"\nObtained:\n"+dump(getWeavingMessages(cR.getInfoMessages()))); } } if (weavingmessages.size()!=0) { fail("Unexpected messages obtained from program:\n"+dump(weavingmessages)); } } private String dump(List l) { StringBuffer sb = new StringBuffer(); int i =0; sb.append("--- Weaving Messages ---\n"); for (Iterator iter = l.iterator(); iter.hasNext();) { sb.append(i+") "+iter.next()+"\n"); } sb.append("------------------------\n"); return sb.toString(); } }
78,021
Bug 78021 Injecting exception into while loop with break statement causes catch block to be ignored
In order to test exception scenarios in an existing framework, I have created an aspect to inject an exception. The exception is injected into some code running within a try/catch/finally block. After the exception is thrown, I am expecting control to pass to the catch block. However, what is happening is that the catch block code is not executed, control passes through the finally block and the (undeclared) exception is thrown to the calling method. Here is a distilled test case: public class MainClass { protected Integer counter; private int j; public static void main(String[] args) { MainClass mh = new MainClass(); try { mh.doSomething(); } catch (Exception e) { System.out.println("Exception thrown by doSomething!!!!!"); e.printStackTrace(); } } public void doSomething() { int i = 0; while (i++ < 1) { counter=null; try { counter = getCounter(); if (counter == null) { break; } commit(); } catch (Throwable e) { System.out.println("Caught exception " + e); } finally { System.out.println("In finally block"); } } } protected Integer getCounter() { return new Integer(j++); } protected void commit() throws SQLException { System.out.println("Main.commit"); } } The following aspect injects the exception: public aspect SimpleExceptionThrowingAspect { pointcut commitOperation() : call (* MainClass+.commit(..)); before() throws SQLException : commitOperation() { throw new SQLException("Dummy SQL Exception", "55102"); } } Expected output is: Caught exception java.sql.SQLException: Dummy SQL Exception In finally block Actual output is: In finally block Exception thrown by doSomething!!!!! java.sql.SQLException: Dummy SQL Exception at nz.govt.moh.test.SimpleExceptionThrowingAspect.ajc$before$nz_govt_moh_test_SimpleExceptionThrowingAspect$1$292c82f1(SimpleExceptionThrowingAspect.aj:10) at nz.govt.moh.test.MainClass.doSomething(MainClass.java:32) at nz.govt.moh.test.MainClass.main(MainClass.java:14) Removing the "break;" statement from MainClass.java causes the expected output to be produced.
resolved fixed
603b063
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-11T11:22:15Z
2004-11-06T19:40: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.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.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.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.WeaverMessages; /** * 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 */ final LazyClassGen enclosingClass; private final BcelMethod memberView; 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 ResolvedTypeX 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(); } 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(); } public boolean hasDeclaredLineNumberInfo() { return (memberView != null && memberView.hasDeclarationLineNumberInfo()); } public int getDeclarationLineNumber() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationLineNumber(); } else { return -1; } } 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.maxLocals = gen.getMaxLocals(); // this.returnType = BcelWorld.makeBcelType(memberView.getReturnType()); // this.argumentTypes = BcelWorld.makeBcelTypes(memberView.getParameterTypes()); // // this.declaredExceptions = TypeX.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() { return toLongString(); } 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() { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s)); return new String(s.toByteArray()); } public void print() { print(System.out); } public void print(PrintStream out) { out.print(" " + toShortString()); printAspectAttributes(out); InstructionList body = getBody(); if (body == null) { out.println(";"); return; } out.println(":"); new BodyPrinter(out).run(); out.println(" end " + toShortString()); } private void printAspectAttributes(PrintStream out) { ISourceContext context = null; if (enclosingClass != null && enclosingClass.getType() != null) { context = enclosingClass.getType().getSourceContext(); } List as = BcelAttributes.readAjAttributes(getClassName(),attributes, context,null); 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 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 (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)); } } /** This proedure 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; } } } // 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) { // for (ListIterator iter = l.listIterator(); iter.hasNext();) { // ExceptionRange r = (ExceptionRange) iter.next(); // if (fresh.getPriority() >= r.getPriority()) { // iter.previous(); // iter.add(fresh); // return; // } // } l.add(0, 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; return memberView.getEffectiveSignature(); } public String getSignature() { if (memberView!=null) return memberView.getSignature(); return Member.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes())); } public String getParameterSignature() { if (memberView!=null) return memberView.getParameterSignature(); return Member.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; } }
82,218
Bug 82218 fails to doc spacewar using AJDT 1.2.0M2
Using AJDT 1.2.0M2 {with Java 5 JRE on XP SP2}, install Spacewar example and generate to Spacewar/docs. Result: output has no cross-references (and displays special AJDT tags), and stderr lists this exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:980) at java.lang.StringBuffer.insert(StringBuffer.java:447) at org.aspectj.tools.ajdoc.HtmlDecorator.insertDeclarationsDetails(HtmlDecorator.java:350) at org.aspectj.tools.ajdoc.HtmlDecorator.addAspectDocumentation(HtmlDecorator.java:234) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFile(HtmlDecorator.java:188) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecl(HtmlDecorator.java:116) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecls(HtmlDecorator.java:54) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromInputFiles(HtmlDecorator.java:43) at org.aspectj.tools.ajdoc.Main.main(Main.java:210)
resolved fixed
f70b383
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T04:22:51Z
2005-01-05T10:13:20Z
ajdoc/src/org/aspectj/tools/ajdoc/HtmlDecorator.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.*; import java.util.*; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; /** * @author Mik Kersten */ class HtmlDecorator { static List visibleFileList = new ArrayList(); static Hashtable declIDTable = null; static SymbolManager symbolManager = null; static File rootDir = null; static void decorateHTMLFromInputFiles(Hashtable table, File newRootDir, SymbolManager sm, File[] inputFiles, String docModifier ) throws IOException { rootDir = newRootDir; declIDTable = table; symbolManager = sm; for (int i = 0; i < inputFiles.length; i++) { decorateHTMLFromDecls(symbolManager.getDeclarations(inputFiles[i].getCanonicalPath()), rootDir.getCanonicalPath() + Config.DIR_SEP_CHAR, docModifier, false); } } static void decorateHTMLFromDecls(Declaration[] decls, String base, String docModifier, boolean exceededNestingLevel) throws IOException { if ( decls != null ) { for (int i = 0; i < decls.length; i++) { Declaration decl = decls[i]; decorateHTMLFromDecl(decl, base, docModifier, exceededNestingLevel); } } } /** * Before attempting to decorate the HTML file we have to verify that it exists, * which depends on the documentation visibility specified to c. * * Depending on docModifier, can document * - public: only public * - protected: protected and public (default) * - package: package protected and public * - private: everything */ static void decorateHTMLFromDecl(Declaration decl, String base, String docModifier, boolean exceededNestingLevel ) throws IOException { boolean nestedClass = false; if ( decl.isType() ) { boolean decorateFile = true; if ( (docModifier.equals("private")) || // everything (docModifier.equals("package") && decl.getModifiers().indexOf( "private" ) == -1) || // package (docModifier.equals("protected") && (decl.getModifiers().indexOf( "protected" ) != -1 || decl.getModifiers().indexOf( "public" ) != -1 )) || (docModifier.equals("public") && decl.getModifiers().indexOf( "public" ) != -1) ) { visibleFileList.add(decl.getSignature()); String packageName = decl.getPackageName(); String filename = ""; if ( packageName != null ) { int index1 = base.lastIndexOf(Config.DIR_SEP_CHAR); int index2 = base.lastIndexOf("."); String currFileClass = ""; if (index1 > -1 && index2 > 0 && index1 < index2) { currFileClass = base.substring(index1+1, index2); } // XXX only one level of nexting if (currFileClass.equals(decl.getDeclaringType())) { nestedClass = true; packageName = packageName.replace( '.','/' ); String newBase = ""; if ( base.lastIndexOf(Config.DIR_SEP_CHAR) > 0 ) { newBase = base.substring(0, base.lastIndexOf(Config.DIR_SEP_CHAR)); } String signature = constructNestedTypeName(decl.getNode()); filename = newBase + Config.DIR_SEP_CHAR + packageName + Config.DIR_SEP_CHAR + currFileClass + //"." + signature + ".html"; } else { packageName = packageName.replace( '.','/' ); filename = base + packageName + Config.DIR_SEP_CHAR + decl.getSignature() + ".html"; } } else { filename = base + decl.getSignature() + ".html"; } if (!exceededNestingLevel) { decorateHTMLFile(new File(filename)); decorateHTMLFromDecls(decl.getDeclarations(), base + decl.getSignature() + ".", docModifier, nestedClass); } else { System.out.println("Warning: can not generate documentation for nested " + "inner class: " + decl.getSignature() ); } } } } private static String constructNestedTypeName(IProgramElement node) { if (node.getParent().getKind().isSourceFile()) { return node.getName(); } else { String nodeName = ""; if (node.getKind().isType()) nodeName += '.' + node.getName(); return constructNestedTypeName(node.getParent()) + nodeName; } } /** * Skips files that are public in the model but not public in the source, * e.g. nested aspects. */ static void decorateHTMLFile(File file) throws IOException { if (!file.exists()) return; System.out.println( "> Decorating " + file.getCanonicalPath() + "..." ); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuffer fileContents = new StringBuffer(); String line = reader.readLine(); while( line != null ) { fileContents.append(line + "\n"); line = reader.readLine(); } boolean isSecond = false; int index = 0; IProgramElement decl; while ( true ) { //---this next part is an inlined procedure that returns two values--- //---the next declaration and the index at which that declaration's--- //---DeclID sits in the .html file --- String contents = fileContents.toString(); int start = contents.indexOf( Config.DECL_ID_STRING, index); int end = contents.indexOf( Config.DECL_ID_TERMINATOR, index ); if ( start == -1 ) decl = null; else if ( end == -1 ) throw new Error("Malformed DeclID."); else { String tid = contents.substring(start + Config.DECL_ID_STRING.length(), end); decl = (IProgramElement)declIDTable.get(tid); index = start; } //--- --- //--- --- if ( decl == null ) break; fileContents.delete(start, end + Config.DECL_ID_TERMINATOR.length()); if ( decl.getKind().isType() ) { isSecond = true; // addIntroductionDocumentation(decl, fileContents, index); // addAdviceDocumentation(decl, fileContents, index); // addPointcutDocumentation(decl, fileContents, index); addAspectDocumentation(decl, fileContents, index); } else { decorateMemberDocumentation(decl, fileContents, index); } } // Change "Class" to "Aspect", HACK: depends on "affects:" int classStartIndex = fileContents.toString().indexOf("<BR>\nClass"); if (classStartIndex != -1 && fileContents.toString().indexOf("Advises:") != -1) { int classEndIndex = fileContents.toString().indexOf("</H2>", classStartIndex); if (classStartIndex != -1 && classEndIndex != -1) { String classLine = fileContents.toString().substring(classStartIndex, classEndIndex); String aspectLine = "<BR>\n" + "Aspect " + classLine.substring(11, classLine.length()); fileContents.delete(classStartIndex, classEndIndex); fileContents.insert(classStartIndex, aspectLine); } } file.delete(); FileOutputStream fos = new FileOutputStream( file ); fos.write( fileContents.toString().getBytes() ); } static void addAspectDocumentation(IProgramElement node, StringBuffer fileBuffer, int index ) { // List relations = AsmManager.getDefault().getRelationshipMap().get(node); // System.err.println("> node: " + node + ", " + "relations: " + relations); List pointcuts = new ArrayList(); List advice = new ArrayList(); for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { IProgramElement member = (IProgramElement)it.next(); if (member.getKind().equals(IProgramElement.Kind.POINTCUT)) { pointcuts.add(member); } else if (member.getKind().equals(IProgramElement.Kind.ADVICE)) { advice.add(member); } } if (pointcuts.size() > 0) { insertDeclarationsSummary(fileBuffer, pointcuts, "Pointcut Summary", index); insertDeclarationsDetails(fileBuffer, pointcuts, "Pointcut Detail", index); } if (advice.size() > 0) { insertDeclarationsSummary(fileBuffer, advice, "Advice Summary", index); insertDeclarationsDetails(fileBuffer, advice, "Advice Detail", index); } } // static void addIntroductionDocumentation(IProgramElement decl, // StringBuffer fileBuffer, // int index ) { // Declaration[] introductions = decl.getIntroductionDeclarations(); // if ( introductions.length > 0 ) { // insertDeclarationsSummary(fileBuffer, // introductions, // "Introduction Summary", // index); // insertDeclarationsDetails(fileBuffer, // introductions, // "Introduction Detail", // index); // } // } static void insertDeclarationsSummary(StringBuffer fileBuffer, List decls, String kind, int index) { int insertIndex = findSummaryIndex(fileBuffer, index); // insert the head of the table String tableHead = "<!-- ======== " + kind.toUpperCase() + " ======= -->\n\n" + "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"1\"" + "CELLSPACING=\"0\"><TR><TD COLSPAN=2 BGCOLOR=\"#CCCCFF\">" + "<FONT SIZE=\"+2\"><B>" + kind + "</B></FONT></TD></TR>\n"; fileBuffer.insert(insertIndex, tableHead); insertIndex += tableHead.length(); // insert the body of the table for ( int i = 0; i < decls.size(); i++ ) { IProgramElement decl = (IProgramElement)decls.get(i); // insert the table row accordingly String comment = generateSummaryComment(decl); String entry = ""; if ( kind.equals( "Advice Summary" ) ) { entry += "<TR><TD>" + "<A HREF=\"#" + generateHREFName(decl) + "\">" + "<TT>" + generateAdviceSignatures(decl) + "</TT></A><BR>&nbsp;"; if (!comment.equals("")) { entry += comment + "<P>"; } entry += generateAffects(decl, false) + "</TD>" + "</TR><TD>\n"; } else if ( kind.equals( "Pointcut Summary" ) ) { entry += "<TR><TD WIDTH=\"1%\">" + "<FONT SIZE=-1><TT>" + genAccessibility(decl) + "</TT></FONT>" + "</TD>\n" + "<TD>" + "<TT><A HREF=\"#" + generateHREFName(decl) + "\">" + decl.toLabelString() + "</A></TT><BR>&nbsp;"; if (!comment.equals("")) { entry += comment + "<P>"; } entry += "</TR></TD>\n"; } else if ( kind.equals( "Introduction Summary" ) ) { entry += "<TR><TD WIDTH=\"1%\">" + "<FONT SIZE=-1><TT>" + decl.getModifiers() + "</TT></FONT>" + "</TD>" + "<TD>" + "<A HREF=\"#" + generateHREFName(decl) + "\">" + "<TT>introduction " + decl.toLabelString() + "</TT></A><P>" + generateIntroductionSignatures(decl, false) + generateAffects(decl, true); } // insert the entry fileBuffer.insert(insertIndex, entry); insertIndex += entry.length(); } // insert the end of the table String tableTail = "</TABLE><P>&nbsp;\n"; fileBuffer.insert(insertIndex, tableTail); insertIndex += tableTail.length(); } private static String genAccessibility(IProgramElement decl) { if (decl.getAccessibility().equals(IProgramElement.Accessibility.PACKAGE)) { return "(package private)"; } else { return decl.getAccessibility().toString(); } } static void insertDeclarationsDetails(StringBuffer fileBuffer, List decls, String kind, int index) { int insertIndex = findDetailsIndex(fileBuffer, index); // insert the table heading String detailsHeading = "<P>&nbsp;\n" + "<!-- ======== " + kind.toUpperCase() + " SUMMARY ======= -->\n\n" + "<TABLE BORDER=\"1\" CELLPADDING=\"3\" CELLSPACING=\"0\" WIDTH=\"100%\">\n" + "<TR BGCOLOR=\"#CCCCFF\" CLASS=\"TableHeadingColor\">\n" + "<TD COLSPAN=1><FONT SIZE=\"+2\">\n" + "<B>" + kind + "</B></FONT></TD>\n" + "</TR>\n" + "</TABLE>"; fileBuffer.insert(insertIndex, detailsHeading); insertIndex += detailsHeading.length(); // insert the details for ( int i = 0; i < decls.size(); i++ ) { IProgramElement decl = (IProgramElement)decls.get(i); String entry = ""; // insert the table row accordingly entry += "<A NAME=\"" + generateHREFName(decl) + "\"><!-- --></A>\n"; if ( kind.equals( "Advice Detail" ) ) { entry += "<H3>" + decl.getName() + "</H3><P>"; entry += "<TT>" + generateAdviceSignatures(decl) + "</TT>\n" + "<P>" + generateDetailsComment(decl) + "<P>" + generateAffects(decl, false); } else if (kind.equals("Pointcut Detail")) { entry += "<H3>" + decl.toLabelString() + "</H3><P>" + generateDetailsComment(decl); } else if (kind.equals("Introduction Detail")) { entry += "<H3>introduction " + decl.toLabelString() + "</H3><P>"; entry += generateIntroductionSignatures(decl, true) + generateAffects(decl, true) + generateDetailsComment(decl); } // insert the entry if (i != decls.size()-1) { entry += "<P><HR>\n"; } else { entry += "<P>"; } fileBuffer.insert(insertIndex, entry); insertIndex += entry.length(); } } /** * TODO: don't place the summary first. */ static int findSummaryIndex(StringBuffer fileBuffer, int index) { String fbs = fileBuffer.toString(); String MARKER_1 = "<!-- =========== FIELD SUMMARY =========== -->"; String MARKER_2 = "<!-- ======== CONSTRUCTOR SUMMARY ======== -->"; int index1 = fbs.indexOf(MARKER_1, index); int index2 = fbs.indexOf(MARKER_2, index); if (index1 < index2) { return index1; } else { return index2; } } static int findDetailsIndex(StringBuffer fileBuffer, int index) { String fbs = fileBuffer.toString(); String MARKER_1 = "<!-- ========= CONSTRUCTOR DETAIL ======== -->"; String MARKER_2 = "<!-- ============ FIELD DETAIL =========== -->"; String MARKER_3 = "<!-- ============ METHOD DETAIL ========== -->"; int index1 = fbs.indexOf(MARKER_1, index); int index2 = fbs.indexOf(MARKER_2, index); int index3 = fbs.indexOf(MARKER_3, index); if (index1 < index2 && index1 < index3) { return index1; } else if (index2 < index1 && index2 < index3) { return index2; } else { return index3; } } static void decorateMemberDocumentation(IProgramElement node, StringBuffer fileContentsBuffer, int index ) { List targets = StructureUtil.getTargets(node, IRelationship.Kind.ADVICE); if (targets != null && !targets.isEmpty()) { String prevName = ""; String adviceDoc = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>" + "<TD width=\"15%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>&nbsp;Advised&nbsp;by:</font></b></td><td>"; String relativePackagePath = getRelativePathFromHere( node.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR); List addedNames = new ArrayList(); for (Iterator it = targets.iterator(); it.hasNext(); ) { String currHandle = (String)it.next(); IProgramElement currDecl = AsmManager.getDefault().getHierarchy().findElementForHandle(currHandle); String packagePath = ""; if (currDecl.getPackageName() != null && !currDecl.getPackageName().equals("")) { packagePath = currDecl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR; } String hrefName = ""; String hrefLink = ""; // Start the hRefLink with the relative path based on where // *this* type (i.e. the advised) is in the package structure. hrefLink = relativePackagePath + packagePath; if (currDecl.getPackageName() != null ) { hrefName = currDecl.getPackageName().replace('.', '/'); // hrefLink = "";//+ currDecl.getPackageName() + Config.DIR_SEP_CHAR; } hrefName += Config.DIR_SEP_CHAR + currDecl.getParent().toLinkLabelString() + "." + currDecl.getName(); hrefLink += currDecl.getParent().toLinkLabelString() + ".html" + "#" + currDecl.toLabelString(); if (!addedNames.contains(hrefName)) { adviceDoc = adviceDoc + "<A HREF=\"" + hrefLink + "\"><tt>" + hrefName.replace('/', '.') + "</tt></A>"; if (it.hasNext()) adviceDoc += ", "; addedNames.add(hrefName); } } adviceDoc += "</TR></TD></TABLE>\n"; fileContentsBuffer.insert( index, adviceDoc ); } } /** * TODO: probably want to make this the same for intros and advice. */ static String generateAffects(IProgramElement decl, boolean isIntroduction) { List targets = StructureUtil.getTargets(decl, IRelationship.Kind.ADVICE); if (targets == null) return null; List packageList = new ArrayList(); String entry = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>" + "<TD width=\"10%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>&nbsp;Advises:</b></font></td><td>"; String relativePackagePath = getRelativePathFromHere( decl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR); List addedNames = new ArrayList(); // for ensuring that we don't add duplciates for (Iterator it = targets.iterator(); it.hasNext(); ) { String currHandle = (String)it.next(); IProgramElement currDecl = AsmManager.getDefault().getHierarchy().findElementForHandle(currHandle); if (currDecl.getKind().equals(IProgramElement.Kind.CODE)) { currDecl = currDecl.getParent(); // promote to enclosing } if (currDecl != null && !StructureUtil.isAnonymous(currDecl.getParent())) { String packagePath = ""; if (currDecl.getPackageName() != null && !currDecl.getPackageName().equals("")) { packagePath = currDecl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR; } String typeSignature = constructNestedTypeName(currDecl); String hrefName = packagePath + typeSignature; // Start the hRefLink with the relative path based on where // *this* type (i.e. the advisor) is in the package structure. String hrefLink = relativePackagePath + packagePath + typeSignature + ".html"; if (!currDecl.getKind().isType()) { hrefName += '.' + currDecl.getName(); hrefLink += "#" + currDecl.toLabelString(); } if (!addedNames.contains(hrefName)) { entry += "<A HREF=\"" + hrefLink + "\"><tt>" + hrefName.replace('/', '.') + "</tt></A>"; // !!! don't replace if (it.hasNext()) entry += ", "; addedNames.add(hrefName); } } } entry += "</B></FONT></TD></TR></TABLE>\n</TR></TD>\n"; return entry; } /** * Generates a relative directory path fragment that can be * used to navigate "upwards" from the directory location * implied by the argument. * @param packagePath * @return String consisting of multiple "../" parts, one for * each component part of the input <code>packagePath</code>. */ private static String getRelativePathFromHere(String packagePath) { StringBuffer result = new StringBuffer(""); if (packagePath != null && (packagePath.indexOf("/") != -1)) { StringTokenizer sTok = new StringTokenizer(packagePath, "/", false); while (sTok.hasMoreTokens()) { sTok.nextToken(); // don't care about the token value result.append(".." + Config.DIR_SEP_CHAR); }// end while }// end if return result.toString(); } static String generateIntroductionSignatures(IProgramElement decl, boolean isDetails) { return "<not implemented>"; // Declaration[] decls = decl.getDeclarations(); // String entry = ""; // for ( int j = 0; j < decls.length; j++ ) { // Declaration currDecl = decls[j]; // if ( currDecl != null ) { // entry += // "<TT><B>" + // currDecl.getSignature() + // "</B></TT><BR>"; // } // if (isDetails) { // entry += generateDetailsComment(currDecl) + "<P>"; // } // else { // entry += generateSummaryComment(currDecl) + "<P>"; // } // } // return entry; } static String generateAdviceSignatures(IProgramElement decl ) { return "<B>" + decl.toLabelString() + "</B>"; } static String generateSummaryComment(IProgramElement decl) { String COMMENT_INDENT = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; // !!! String formattedComment = getFormattedComment(decl); int periodIndex = formattedComment.indexOf( '.' ); if (formattedComment.equals("")) { return ""; } else if ( periodIndex != -1 ) { return COMMENT_INDENT + formattedComment.substring( 0, periodIndex+1 ) ; } else { return COMMENT_INDENT + formattedComment; } } static String generateDetailsComment(IProgramElement decl) { return getFormattedComment(decl); } static String generateHREFName(IProgramElement decl) { String hrefLink = decl.toLabelString(); // !!! return hrefLink; } /** * Figure out the link relative to the package. */ static String generateAffectsHREFLink(String declaringType) { String link = rootDir.getAbsolutePath() + "/" + declaringType + ".html"; return link; } /** * This formats a comment according to the rules in the Java Langauge Spec: * <I>The text of a docuemntation comment consists of the characters between * the /** that begins the comment and the 'star-slash' that ends it. The text is * devided into one or more lines. On each of these lines, the leading * * characters are ignored; for lines other than the first, blanks and * tabs preceding the initial * characters are also discarded.</I> * * TODO: implement formatting or linking for tags. */ static String getFormattedComment(IProgramElement decl) { String comment = decl.getFormalComment(); if (comment == null) return ""; String formattedComment = ""; // strip the comment markers int startIndex = comment.indexOf("/**"); int endIndex = comment.indexOf("*/"); if ( startIndex == -1 ) { startIndex = 0; } else { startIndex += 3; } if ( endIndex == -1 ) { endIndex = comment.length(); } comment = comment.substring( startIndex, endIndex ); // string the leading whitespace and '*' characters at the beginning of each line BufferedReader reader = new BufferedReader( new StringReader( comment ) ); try { for (String line = reader.readLine(); line != null; line = reader.readLine()) { line = line.trim(); for (int i = 0; i < line.length(); i++ ) { if ( line.charAt(0) == '*' ) { line = line.substring(1, line.length()); } else { break; } } // !!! remove any @see and @link tags from the line //int seeIndex = line.indexOf("@see"); //int linkIndex = line.indexOf("@link"); //if ( seeIndex != -1 ) { // line = line.substring(0, seeIndex) + line.substring(seeIndex); //} //if ( linkIndex != -1 ) { // line = line.substring(0, linkIndex) + line.substring(linkIndex); //} formattedComment += line; } } catch ( IOException ioe ) { throw new Error( "Couldn't format comment for declaration: " + decl.getName() ); } return formattedComment; } }
82,218
Bug 82218 fails to doc spacewar using AJDT 1.2.0M2
Using AJDT 1.2.0M2 {with Java 5 JRE on XP SP2}, install Spacewar example and generate to Spacewar/docs. Result: output has no cross-references (and displays special AJDT tags), and stderr lists this exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:980) at java.lang.StringBuffer.insert(StringBuffer.java:447) at org.aspectj.tools.ajdoc.HtmlDecorator.insertDeclarationsDetails(HtmlDecorator.java:350) at org.aspectj.tools.ajdoc.HtmlDecorator.addAspectDocumentation(HtmlDecorator.java:234) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFile(HtmlDecorator.java:188) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecl(HtmlDecorator.java:116) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecls(HtmlDecorator.java:54) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromInputFiles(HtmlDecorator.java:43) at org.aspectj.tools.ajdoc.Main.main(Main.java:210)
resolved fixed
f70b383
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T04:22:51Z
2005-01-05T10:13:20Z
ajdoc/src/org/aspectj/tools/ajdoc/Util.java
82,218
Bug 82218 fails to doc spacewar using AJDT 1.2.0M2
Using AJDT 1.2.0M2 {with Java 5 JRE on XP SP2}, install Spacewar example and generate to Spacewar/docs. Result: output has no cross-references (and displays special AJDT tags), and stderr lists this exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:980) at java.lang.StringBuffer.insert(StringBuffer.java:447) at org.aspectj.tools.ajdoc.HtmlDecorator.insertDeclarationsDetails(HtmlDecorator.java:350) at org.aspectj.tools.ajdoc.HtmlDecorator.addAspectDocumentation(HtmlDecorator.java:234) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFile(HtmlDecorator.java:188) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecl(HtmlDecorator.java:116) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecls(HtmlDecorator.java:54) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromInputFiles(HtmlDecorator.java:43) at org.aspectj.tools.ajdoc.Main.main(Main.java:210)
resolved fixed
f70b383
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T04:22:51Z
2005-01-05T10:13:20Z
ajdoc/testdata/coverage/foo/ModelCoverage.java
package foo; import java.io.*; import java.util.List; interface I { } class Point { int x; static int sx; { System.out.println(""); } { x = 0; } static { sx = 1; } public Point() { } public int getX() { return x; } public void setX(int x) { this.x = x; } public int changeX(int x) { this.x = x; return x; } void doIt() { try { File f = new File("."); f.getCanonicalPath(); } catch (IOException ioe) { System.err.println("!"); } // setX(10); new Point(); } } class SubPoint extends Point { } class Line { } aspect AdvisesRelationshipCoverage { pointcut methodExecutionP(): execution(void Point.setX(int)); before(): methodExecutionP() { } pointcut constructorExecutionP(): execution(Point.new()); before(): constructorExecutionP() { } pointcut callMethodP(): call(* Point.setX(int)); before(): callMethodP() { } pointcut callConstructorP(): call(Point.new()); before(): callConstructorP() { } pointcut getP(): get(int *.*); before(): getP() { } pointcut setP(): set(int *.*) && !set(int *.xxx); before(): setP() { } pointcut initializationP(): initialization(Point.new(..)); before(): initializationP() { } pointcut staticinitializationP(): staticinitialization(Point); before(): staticinitializationP() { } pointcut handlerP(): handler(IOException); before(): handlerP() { } // before(): within(*) && execution(* Point.setX(..)) { } // before(): within(*) && execution(Point.new()) { } } aspect AdviceNamingCoverage { pointcut named(): call(* *.mumble()); pointcut namedWithOneArg(int i): call(int Point.changeX(int)) && args(i); pointcut namedWithArgs(int i, int j): set(int Point.x) && args(i, j); after(): named() { } after(int i, int j) returning: namedWithArgs(i, j) { } after() throwing: named() { } after(): named() { } before(): named() { } int around(int i): namedWithOneArg(i) { return i;} int around(int i) throws SizeException: namedWithOneArg(i) { return proceed(i); } before(): named() { } before(int i): call(* *.mumble()) && named() && namedWithOneArg(i) { } before(int i): named() && call(* *.mumble()) && namedWithOneArg(i) { } before(): call(* *.mumble()) { } } abstract aspect AbstractAspect { abstract pointcut abPtct(); } aspect InterTypeDecCoverage { public int Point.xxx = 0; public int Point.check(int i, Line l) { return 1 + i; } } aspect DeclareCoverage { pointcut illegalNewFigElt(): call(Point.new(..)) && !withincode(* *.doIt(..)); declare error: illegalNewFigElt(): "Illegal constructor call."; declare warning: call(* Point.setX(..)): "Illegal call."; declare parents: Point extends java.io.Serializable; declare parents: Point+ implements java.util.Observable; declare parents: Point && Line implements java.util.Observable; declare soft: SizeException : call(* Point.getX()); declare precedence: AdviceCoverage, InterTypeDecCoverage, *; // public Line.new(String s) { } } class SizeException extends Exception { } aspect AdviceCoverage { } abstract class ModifiersCoverage { private int a; protected int b; public int c; int d; static int staticA; final int finalA = 0; abstract void abstractM(); }
82,218
Bug 82218 fails to doc spacewar using AJDT 1.2.0M2
Using AJDT 1.2.0M2 {with Java 5 JRE on XP SP2}, install Spacewar example and generate to Spacewar/docs. Result: output has no cross-references (and displays special AJDT tags), and stderr lists this exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:980) at java.lang.StringBuffer.insert(StringBuffer.java:447) at org.aspectj.tools.ajdoc.HtmlDecorator.insertDeclarationsDetails(HtmlDecorator.java:350) at org.aspectj.tools.ajdoc.HtmlDecorator.addAspectDocumentation(HtmlDecorator.java:234) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFile(HtmlDecorator.java:188) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecl(HtmlDecorator.java:116) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecls(HtmlDecorator.java:54) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromInputFiles(HtmlDecorator.java:43) at org.aspectj.tools.ajdoc.Main.main(Main.java:210)
resolved fixed
f70b383
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T04:22:51Z
2005-01-05T10:13:20Z
ajdoc/testdata/coverage/foo/NoMembers.java
82,218
Bug 82218 fails to doc spacewar using AJDT 1.2.0M2
Using AJDT 1.2.0M2 {with Java 5 JRE on XP SP2}, install Spacewar example and generate to Spacewar/docs. Result: output has no cross-references (and displays special AJDT tags), and stderr lists this exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:980) at java.lang.StringBuffer.insert(StringBuffer.java:447) at org.aspectj.tools.ajdoc.HtmlDecorator.insertDeclarationsDetails(HtmlDecorator.java:350) at org.aspectj.tools.ajdoc.HtmlDecorator.addAspectDocumentation(HtmlDecorator.java:234) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFile(HtmlDecorator.java:188) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecl(HtmlDecorator.java:116) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecls(HtmlDecorator.java:54) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromInputFiles(HtmlDecorator.java:43) at org.aspectj.tools.ajdoc.Main.main(Main.java:210)
resolved fixed
f70b383
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T04:22:51Z
2005-01-05T10:13:20Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/CoverageTestCase.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; /** * A long way to go until full coverage, but this is the place to add more. * * @author Mik Kersten */ public class CoverageTestCase extends TestCase { File file0 = new File("testdata/coverage/InDefaultPackage.java"); File file1 = new File("testdata/coverage/foo/ClassA.java"); File aspect1 = new File("testdata/coverage/foo/UseThisAspectForLinkCheck.aj"); File file2 = new File("testdata/coverage/foo/InterfaceI.java"); File file3 = new File("testdata/coverage/foo/PlainJava.java"); File file4 = new File("testdata/coverage/foo/ModelCoverage.java"); File file5 = new File("testdata/coverage/fluffy/Fluffy.java"); File file6 = new File("testdata/coverage/fluffy/bunny/Bunny.java"); File file7 = new File("testdata/coverage/fluffy/bunny/rocks/Rocks.java"); File file8 = new File("testdata/coverage/fluffy/bunny/rocks/UseThisAspectForLinkCheckToo.java"); File file9 = new File("testdata/coverage/foo/PkgVisibleClass.java"); File outdir = new File("testdata/coverage/doc"); public void testOptions() { outdir.delete(); String[] args = { "-private", "-encoding", "EUCJIS", "-docencoding", "EUCJIS", "-charset", "UTF-8", "-d", outdir.getAbsolutePath(), file0.getAbsolutePath(), }; org.aspectj.tools.ajdoc.Main.main(args); assertTrue(true); } public void testCoverage() { outdir.delete(); String[] args = { // "-XajdocDebug", "-source", "1.4", "-private", "-d", outdir.getAbsolutePath(), aspect1.getAbsolutePath(), file0.getAbsolutePath(), file1.getAbsolutePath(), file2.getAbsolutePath(), file3.getAbsolutePath(), file4.getAbsolutePath(), file5.getAbsolutePath(), file6.getAbsolutePath(), file7.getAbsolutePath(), file8.getAbsolutePath(), file9.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); } public void testCoveragePublicMode() { outdir.delete(); String[] args = { "-public", "-source", "1.4", "-d", outdir.getAbsolutePath(), file3.getAbsolutePath(), file9.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); } // public void testPlainJava() { // outdir.delete(); // String[] args = { "-d", // outdir.getAbsolutePath(), // file3.getAbsolutePath() }; // org.aspectj.tools.ajdoc.Main.main(args); // } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
82,218
Bug 82218 fails to doc spacewar using AJDT 1.2.0M2
Using AJDT 1.2.0M2 {with Java 5 JRE on XP SP2}, install Spacewar example and generate to Spacewar/docs. Result: output has no cross-references (and displays special AJDT tags), and stderr lists this exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:980) at java.lang.StringBuffer.insert(StringBuffer.java:447) at org.aspectj.tools.ajdoc.HtmlDecorator.insertDeclarationsDetails(HtmlDecorator.java:350) at org.aspectj.tools.ajdoc.HtmlDecorator.addAspectDocumentation(HtmlDecorator.java:234) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFile(HtmlDecorator.java:188) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecl(HtmlDecorator.java:116) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromDecls(HtmlDecorator.java:54) at org.aspectj.tools.ajdoc.HtmlDecorator.decorateHTMLFromInputFiles(HtmlDecorator.java:43) at org.aspectj.tools.ajdoc.Main.main(Main.java:210)
resolved fixed
f70b383
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T04:22:51Z
2005-01-05T10:13:20Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/JDKVersionTest.java
82,340
Bug 82340 Visibility selector ignored for pointcuts
Using ajdoc under AJDT 1.1.12 or AspectJ 1.2.1 at the commandline has the following aspect has problems. public abstract aspect Aspect { private pointcut privatePointcut (); protected pointcut protectedPointcut (); public pointcut publicPointcut (); private void privateMethod () { } public void protectedMethod () { } public void publicMethod () { } } 1. Asking for "protected" gives all pointcuts (public, protected _and_ private) 2. The Aspect entry is wrong: "public abstract class Aspect" 3. The "Methods inherited ..." section has a leading comma: ", clone, equals, finalize, ..."
resolved fixed
b460597
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T15:53:01Z
2005-01-06T16:46:40Z
ajdoc/src/org/aspectj/tools/ajdoc/HtmlDecorator.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.*; import java.util.*; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; /** * @author Mik Kersten */ class HtmlDecorator { static List visibleFileList = new ArrayList(); static Hashtable declIDTable = null; static SymbolManager symbolManager = null; static File rootDir = null; static void decorateHTMLFromInputFiles(Hashtable table, File newRootDir, SymbolManager sm, File[] inputFiles, String docModifier ) throws IOException { rootDir = newRootDir; declIDTable = table; symbolManager = sm; for (int i = 0; i < inputFiles.length; i++) { decorateHTMLFromDecls(symbolManager.getDeclarations(inputFiles[i].getCanonicalPath()), rootDir.getCanonicalPath() + Config.DIR_SEP_CHAR, docModifier, false); } } static void decorateHTMLFromDecls(Declaration[] decls, String base, String docModifier, boolean exceededNestingLevel) throws IOException { if ( decls != null ) { for (int i = 0; i < decls.length; i++) { Declaration decl = decls[i]; decorateHTMLFromDecl(decl, base, docModifier, exceededNestingLevel); } } } /** * Before attempting to decorate the HTML file we have to verify that it exists, * which depends on the documentation visibility specified to c. * * Depending on docModifier, can document * - public: only public * - protected: protected and public (default) * - package: package protected and public * - private: everything */ static void decorateHTMLFromDecl(Declaration decl, String base, String docModifier, boolean exceededNestingLevel ) throws IOException { boolean nestedClass = false; if ( decl.isType() ) { boolean decorateFile = true; if ( (docModifier.equals("private")) || // everything (docModifier.equals("package") && decl.getModifiers().indexOf( "private" ) == -1) || // package (docModifier.equals("protected") && (decl.getModifiers().indexOf( "protected" ) != -1 || decl.getModifiers().indexOf( "public" ) != -1 )) || (docModifier.equals("public") && decl.getModifiers().indexOf( "public" ) != -1) ) { visibleFileList.add(decl.getSignature()); String packageName = decl.getPackageName(); String filename = ""; if ( packageName != null ) { int index1 = base.lastIndexOf(Config.DIR_SEP_CHAR); int index2 = base.lastIndexOf("."); String currFileClass = ""; if (index1 > -1 && index2 > 0 && index1 < index2) { currFileClass = base.substring(index1+1, index2); } // XXX only one level of nexting if (currFileClass.equals(decl.getDeclaringType())) { nestedClass = true; packageName = packageName.replace( '.','/' ); String newBase = ""; if ( base.lastIndexOf(Config.DIR_SEP_CHAR) > 0 ) { newBase = base.substring(0, base.lastIndexOf(Config.DIR_SEP_CHAR)); } String signature = constructNestedTypeName(decl.getNode()); filename = newBase + Config.DIR_SEP_CHAR + packageName + Config.DIR_SEP_CHAR + currFileClass + //"." + signature + ".html"; } else { packageName = packageName.replace( '.','/' ); filename = base + packageName + Config.DIR_SEP_CHAR + decl.getSignature() + ".html"; } } else { filename = base + decl.getSignature() + ".html"; } if (!exceededNestingLevel) { decorateHTMLFile(new File(filename)); decorateHTMLFromDecls(decl.getDeclarations(), base + decl.getSignature() + ".", docModifier, nestedClass); } else { System.out.println("Warning: can not generate documentation for nested " + "inner class: " + decl.getSignature() ); } } } } private static String constructNestedTypeName(IProgramElement node) { if (node.getParent().getKind().isSourceFile()) { return node.getName(); } else { String nodeName = ""; if (node.getKind().isType()) nodeName += '.' + node.getName(); return constructNestedTypeName(node.getParent()) + nodeName; } } /** * Skips files that are public in the model but not public in the source, * e.g. nested aspects. */ static void decorateHTMLFile(File file) throws IOException { if (!file.exists()) return; System.out.println( "> Decorating " + file.getCanonicalPath() + "..." ); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuffer fileContents = new StringBuffer(); String line = reader.readLine(); while( line != null ) { fileContents.append(line + "\n"); line = reader.readLine(); } boolean isSecond = false; int index = 0; IProgramElement decl; while ( true ) { //---this next part is an inlined procedure that returns two values--- //---the next declaration and the index at which that declaration's--- //---DeclID sits in the .html file --- String contents = fileContents.toString(); int start = contents.indexOf( Config.DECL_ID_STRING, index); int end = contents.indexOf( Config.DECL_ID_TERMINATOR, index ); if ( start == -1 ) decl = null; else if ( end == -1 ) throw new Error("Malformed DeclID."); else { String tid = contents.substring(start + Config.DECL_ID_STRING.length(), end); decl = (IProgramElement)declIDTable.get(tid); index = start; } //--- --- //--- --- if ( decl == null ) break; fileContents.delete(start, end + Config.DECL_ID_TERMINATOR.length()); if ( decl.getKind().isType() ) { isSecond = true; // addIntroductionDocumentation(decl, fileContents, index); // addAdviceDocumentation(decl, fileContents, index); // addPointcutDocumentation(decl, fileContents, index); addAspectDocumentation(decl, fileContents, index); } else { decorateMemberDocumentation(decl, fileContents, index); } } // Change "Class" to "Aspect", HACK: depends on "affects:" int classStartIndex = fileContents.toString().indexOf("<BR>\nClass"); if (classStartIndex != -1 && fileContents.toString().indexOf("Advises:") != -1) { int classEndIndex = fileContents.toString().indexOf("</H2>", classStartIndex); if (classStartIndex != -1 && classEndIndex != -1) { String classLine = fileContents.toString().substring(classStartIndex, classEndIndex); String aspectLine = "<BR>\n" + "Aspect " + classLine.substring(11, classLine.length()); fileContents.delete(classStartIndex, classEndIndex); fileContents.insert(classStartIndex, aspectLine); } } file.delete(); FileOutputStream fos = new FileOutputStream( file ); fos.write( fileContents.toString().getBytes() ); } static void addAspectDocumentation(IProgramElement node, StringBuffer fileBuffer, int index ) { // List relations = AsmManager.getDefault().getRelationshipMap().get(node); // System.err.println("> node: " + node + ", " + "relations: " + relations); List pointcuts = new ArrayList(); List advice = new ArrayList(); for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { IProgramElement member = (IProgramElement)it.next(); if (member.getKind().equals(IProgramElement.Kind.POINTCUT)) { pointcuts.add(member); } else if (member.getKind().equals(IProgramElement.Kind.ADVICE)) { advice.add(member); } } if (pointcuts.size() > 0) { insertDeclarationsSummary(fileBuffer, pointcuts, "Pointcut Summary", index); insertDeclarationsDetails(fileBuffer, pointcuts, "Pointcut Detail", index); } if (advice.size() > 0) { insertDeclarationsSummary(fileBuffer, advice, "Advice Summary", index); insertDeclarationsDetails(fileBuffer, advice, "Advice Detail", index); } } // static void addIntroductionDocumentation(IProgramElement decl, // StringBuffer fileBuffer, // int index ) { // Declaration[] introductions = decl.getIntroductionDeclarations(); // if ( introductions.length > 0 ) { // insertDeclarationsSummary(fileBuffer, // introductions, // "Introduction Summary", // index); // insertDeclarationsDetails(fileBuffer, // introductions, // "Introduction Detail", // index); // } // } static void insertDeclarationsSummary(StringBuffer fileBuffer, List decls, String kind, int index) { int insertIndex = findSummaryIndex(fileBuffer, index); // insert the head of the table String tableHead = "<!-- ======== " + kind.toUpperCase() + " ======= -->\n\n" + "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"1\"" + "CELLSPACING=\"0\"><TR><TD COLSPAN=2 BGCOLOR=\"#CCCCFF\">" + "<FONT SIZE=\"+2\"><B>" + kind + "</B></FONT></TD></TR>\n"; fileBuffer.insert(insertIndex, tableHead); insertIndex += tableHead.length(); // insert the body of the table for ( int i = 0; i < decls.size(); i++ ) { IProgramElement decl = (IProgramElement)decls.get(i); // insert the table row accordingly String comment = generateSummaryComment(decl); String entry = ""; if ( kind.equals( "Advice Summary" ) ) { entry += "<TR><TD>" + "<A HREF=\"#" + generateHREFName(decl) + "\">" + "<TT>" + generateAdviceSignatures(decl) + "</TT></A><BR>&nbsp;"; if (!comment.equals("")) { entry += comment + "<P>"; } entry += generateAffects(decl, false) + "</TD>" + "</TR><TD>\n"; } else if ( kind.equals( "Pointcut Summary" ) ) { entry += "<TR><TD WIDTH=\"1%\">" + "<FONT SIZE=-1><TT>" + genAccessibility(decl) + "</TT></FONT>" + "</TD>\n" + "<TD>" + "<TT><A HREF=\"#" + generateHREFName(decl) + "\">" + decl.toLabelString() + "</A></TT><BR>&nbsp;"; if (!comment.equals("")) { entry += comment + "<P>"; } entry += "</TR></TD>\n"; } else if ( kind.equals( "Introduction Summary" ) ) { entry += "<TR><TD WIDTH=\"1%\">" + "<FONT SIZE=-1><TT>" + decl.getModifiers() + "</TT></FONT>" + "</TD>" + "<TD>" + "<A HREF=\"#" + generateHREFName(decl) + "\">" + "<TT>introduction " + decl.toLabelString() + "</TT></A><P>" + generateIntroductionSignatures(decl, false) + generateAffects(decl, true); } // insert the entry fileBuffer.insert(insertIndex, entry); insertIndex += entry.length(); } // insert the end of the table String tableTail = "</TABLE><P>&nbsp;\n"; fileBuffer.insert(insertIndex, tableTail); insertIndex += tableTail.length(); } private static String genAccessibility(IProgramElement decl) { if (decl.getAccessibility().equals(IProgramElement.Accessibility.PACKAGE)) { return "(package private)"; } else { return decl.getAccessibility().toString(); } } static void insertDeclarationsDetails(StringBuffer fileBuffer, List decls, String kind, int index) { int insertIndex = findDetailsIndex(fileBuffer, index); // insert the table heading String detailsHeading = "<P>&nbsp;\n" + "<!-- ======== " + kind.toUpperCase() + " SUMMARY ======= -->\n\n" + "<TABLE BORDER=\"1\" CELLPADDING=\"3\" CELLSPACING=\"0\" WIDTH=\"100%\">\n" + "<TR BGCOLOR=\"#CCCCFF\" CLASS=\"TableHeadingColor\">\n" + "<TD COLSPAN=1><FONT SIZE=\"+2\">\n" + "<B>" + kind + "</B></FONT></TD>\n" + "</TR>\n" + "</TABLE>"; fileBuffer.insert(insertIndex, detailsHeading); insertIndex += detailsHeading.length(); // insert the details for ( int i = 0; i < decls.size(); i++ ) { IProgramElement decl = (IProgramElement)decls.get(i); String entry = ""; // insert the table row accordingly entry += "<A NAME=\"" + generateHREFName(decl) + "\"><!-- --></A>\n"; if ( kind.equals( "Advice Detail" ) ) { entry += "<H3>" + decl.getName() + "</H3><P>"; entry += "<TT>" + generateAdviceSignatures(decl) + "</TT>\n" + "<P>" + generateDetailsComment(decl) + "<P>" + generateAffects(decl, false); } else if (kind.equals("Pointcut Detail")) { entry += "<H3>" + decl.toLabelString() + "</H3><P>" + generateDetailsComment(decl); } else if (kind.equals("Introduction Detail")) { entry += "<H3>introduction " + decl.toLabelString() + "</H3><P>"; entry += generateIntroductionSignatures(decl, true) + generateAffects(decl, true) + generateDetailsComment(decl); } // insert the entry if (i != decls.size()-1) { entry += "<P><HR>\n"; } else { entry += "<P>"; } fileBuffer.insert(insertIndex, entry); insertIndex += entry.length(); } } /** * TODO: don't place the summary first. */ static int findSummaryIndex(StringBuffer fileBuffer, int index) { String fbs = fileBuffer.toString(); String MARKER_1 = "<!-- =========== FIELD SUMMARY =========== -->"; String MARKER_2 = "<!-- ======== CONSTRUCTOR SUMMARY ======== -->"; int index1 = fbs.indexOf(MARKER_1, index); int index2 = fbs.indexOf(MARKER_2, index); if (index1 < index2 && index1 != -1) { return index1; } else if (index2 != -1){ return index2; } else { return index; } } static int findDetailsIndex(StringBuffer fileBuffer, int index) { String fbs = fileBuffer.toString(); String MARKER_1 = "<!-- ========= CONSTRUCTOR DETAIL ======== -->"; String MARKER_2 = "<!-- ============ FIELD DETAIL =========== -->"; String MARKER_3 = "<!-- ============ METHOD DETAIL ========== -->"; int index1 = fbs.indexOf(MARKER_1, index); int index2 = fbs.indexOf(MARKER_2, index); int index3 = fbs.indexOf(MARKER_3, index); if (index1 != -1 && index1 < index2 && index1 < index3) { return index1; } else if (index2 != -1 && index2 < index1 && index2 < index3) { return index2; } else if (index3 != -1) { return index3; } else { return index; } } static void decorateMemberDocumentation(IProgramElement node, StringBuffer fileContentsBuffer, int index ) { List targets = StructureUtil.getTargets(node, IRelationship.Kind.ADVICE); if (targets != null && !targets.isEmpty()) { String prevName = ""; String adviceDoc = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>" + "<TD width=\"15%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>&nbsp;Advised&nbsp;by:</font></b></td><td>"; String relativePackagePath = getRelativePathFromHere( node.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR); List addedNames = new ArrayList(); for (Iterator it = targets.iterator(); it.hasNext(); ) { String currHandle = (String)it.next(); IProgramElement currDecl = AsmManager.getDefault().getHierarchy().findElementForHandle(currHandle); String packagePath = ""; if (currDecl.getPackageName() != null && !currDecl.getPackageName().equals("")) { packagePath = currDecl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR; } String hrefName = ""; String hrefLink = ""; // Start the hRefLink with the relative path based on where // *this* type (i.e. the advised) is in the package structure. hrefLink = relativePackagePath + packagePath; if (currDecl.getPackageName() != null ) { hrefName = currDecl.getPackageName().replace('.', '/'); // hrefLink = "";//+ currDecl.getPackageName() + Config.DIR_SEP_CHAR; } hrefName += Config.DIR_SEP_CHAR + currDecl.getParent().toLinkLabelString() + "." + currDecl.getName(); hrefLink += currDecl.getParent().toLinkLabelString() + ".html" + "#" + currDecl.toLabelString(); if (!addedNames.contains(hrefName)) { adviceDoc = adviceDoc + "<A HREF=\"" + hrefLink + "\"><tt>" + hrefName.replace('/', '.') + "</tt></A>"; if (it.hasNext()) adviceDoc += ", "; addedNames.add(hrefName); } } adviceDoc += "</TR></TD></TABLE>\n"; fileContentsBuffer.insert( index, adviceDoc ); } } /** * TODO: probably want to make this the same for intros and advice. */ static String generateAffects(IProgramElement decl, boolean isIntroduction) { List targets = StructureUtil.getTargets(decl, IRelationship.Kind.ADVICE); if (targets == null) return null; List packageList = new ArrayList(); String entry = "<TABLE WIDTH=\"100%\" BGCOLOR=#FFFFFF><TR>" + "<TD width=\"10%\" bgcolor=\"#FFD8B0\"><B><FONT COLOR=000000>&nbsp;Advises:</b></font></td><td>"; String relativePackagePath = getRelativePathFromHere( decl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR); List addedNames = new ArrayList(); // for ensuring that we don't add duplciates for (Iterator it = targets.iterator(); it.hasNext(); ) { String currHandle = (String)it.next(); IProgramElement currDecl = AsmManager.getDefault().getHierarchy().findElementForHandle(currHandle); if (currDecl.getKind().equals(IProgramElement.Kind.CODE)) { currDecl = currDecl.getParent(); // promote to enclosing } if (currDecl != null && !StructureUtil.isAnonymous(currDecl.getParent())) { String packagePath = ""; if (currDecl.getPackageName() != null && !currDecl.getPackageName().equals("")) { packagePath = currDecl.getPackageName().replace('.', '/') + Config.DIR_SEP_CHAR; } String typeSignature = constructNestedTypeName(currDecl); String hrefName = packagePath + typeSignature; // Start the hRefLink with the relative path based on where // *this* type (i.e. the advisor) is in the package structure. String hrefLink = relativePackagePath + packagePath + typeSignature + ".html"; if (!currDecl.getKind().isType()) { hrefName += '.' + currDecl.getName(); hrefLink += "#" + currDecl.toLabelString(); } if (!addedNames.contains(hrefName)) { entry += "<A HREF=\"" + hrefLink + "\"><tt>" + hrefName.replace('/', '.') + "</tt></A>"; // !!! don't replace if (it.hasNext()) entry += ", "; addedNames.add(hrefName); } } } entry += "</B></FONT></TD></TR></TABLE>\n</TR></TD>\n"; return entry; } /** * Generates a relative directory path fragment that can be * used to navigate "upwards" from the directory location * implied by the argument. * @param packagePath * @return String consisting of multiple "../" parts, one for * each component part of the input <code>packagePath</code>. */ private static String getRelativePathFromHere(String packagePath) { StringBuffer result = new StringBuffer(""); if (packagePath != null && (packagePath.indexOf("/") != -1)) { StringTokenizer sTok = new StringTokenizer(packagePath, "/", false); while (sTok.hasMoreTokens()) { sTok.nextToken(); // don't care about the token value result.append(".." + Config.DIR_SEP_CHAR); }// end while }// end if return result.toString(); } static String generateIntroductionSignatures(IProgramElement decl, boolean isDetails) { return "<not implemented>"; // Declaration[] decls = decl.getDeclarations(); // String entry = ""; // for ( int j = 0; j < decls.length; j++ ) { // Declaration currDecl = decls[j]; // if ( currDecl != null ) { // entry += // "<TT><B>" + // currDecl.getSignature() + // "</B></TT><BR>"; // } // if (isDetails) { // entry += generateDetailsComment(currDecl) + "<P>"; // } // else { // entry += generateSummaryComment(currDecl) + "<P>"; // } // } // return entry; } static String generateAdviceSignatures(IProgramElement decl ) { return "<B>" + decl.toLabelString() + "</B>"; } static String generateSummaryComment(IProgramElement decl) { String COMMENT_INDENT = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; // !!! String formattedComment = getFormattedComment(decl); int periodIndex = formattedComment.indexOf( '.' ); if (formattedComment.equals("")) { return ""; } else if ( periodIndex != -1 ) { return COMMENT_INDENT + formattedComment.substring( 0, periodIndex+1 ) ; } else { return COMMENT_INDENT + formattedComment; } } static String generateDetailsComment(IProgramElement decl) { return getFormattedComment(decl); } static String generateHREFName(IProgramElement decl) { String hrefLink = decl.toLabelString(); // !!! return hrefLink; } /** * Figure out the link relative to the package. */ static String generateAffectsHREFLink(String declaringType) { String link = rootDir.getAbsolutePath() + "/" + declaringType + ".html"; return link; } /** * This formats a comment according to the rules in the Java Langauge Spec: * <I>The text of a docuemntation comment consists of the characters between * the /** that begins the comment and the 'star-slash' that ends it. The text is * devided into one or more lines. On each of these lines, the leading * * characters are ignored; for lines other than the first, blanks and * tabs preceding the initial * characters are also discarded.</I> * * TODO: implement formatting or linking for tags. */ static String getFormattedComment(IProgramElement decl) { String comment = decl.getFormalComment(); if (comment == null) return ""; String formattedComment = ""; // strip the comment markers int startIndex = comment.indexOf("/**"); int endIndex = comment.indexOf("*/"); if ( startIndex == -1 ) { startIndex = 0; } else { startIndex += 3; } if ( endIndex == -1 ) { endIndex = comment.length(); } comment = comment.substring( startIndex, endIndex ); // string the leading whitespace and '*' characters at the beginning of each line BufferedReader reader = new BufferedReader( new StringReader( comment ) ); try { for (String line = reader.readLine(); line != null; line = reader.readLine()) { line = line.trim(); for (int i = 0; i < line.length(); i++ ) { if ( line.charAt(0) == '*' ) { line = line.substring(1, line.length()); } else { break; } } // !!! remove any @see and @link tags from the line //int seeIndex = line.indexOf("@see"); //int linkIndex = line.indexOf("@link"); //if ( seeIndex != -1 ) { // line = line.substring(0, seeIndex) + line.substring(seeIndex); //} //if ( linkIndex != -1 ) { // line = line.substring(0, linkIndex) + line.substring(linkIndex); //} formattedComment += line; } } catch ( IOException ioe ) { throw new Error( "Couldn't format comment for declaration: " + decl.getName() ); } return formattedComment; } }
82,340
Bug 82340 Visibility selector ignored for pointcuts
Using ajdoc under AJDT 1.1.12 or AspectJ 1.2.1 at the commandline has the following aspect has problems. public abstract aspect Aspect { private pointcut privatePointcut (); protected pointcut protectedPointcut (); public pointcut publicPointcut (); private void privateMethod () { } public void protectedMethod () { } public void publicMethod () { } } 1. Asking for "protected" gives all pointcuts (public, protected _and_ private) 2. The Aspect entry is wrong: "public abstract class Aspect" 3. The "Methods inherited ..." section has a leading comma: ", clone, equals, finalize, ..."
resolved fixed
b460597
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T15:53:01Z
2005-01-06T16:46:40Z
ajdoc/src/org/aspectj/tools/ajdoc/StubFileGenerator.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Mik Kersten port to AspectJ 1.1+ code base * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.*; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; /** * @author Mik Kersten */ class StubFileGenerator { static Hashtable declIDTable = null; static void doFiles(Hashtable table, SymbolManager symbolManager, File[] inputFiles, File[] signatureFiles) { declIDTable = table; for (int i = 0; i < inputFiles.length; i++) { processFile(symbolManager, inputFiles[i], signatureFiles[i]); } } static void processFile(SymbolManager symbolManager, File inputFile, File signatureFile) { try { String path = StructureUtil.translateAjPathName(signatureFile.getCanonicalPath()); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(path))); String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile); if (packageName != null && packageName != "") { writer.println( "package " + packageName + ";" ); } IProgramElement fileNode = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(inputFile.getAbsolutePath()); for (Iterator it = fileNode.getChildren().iterator(); it.hasNext(); ) { IProgramElement node = (IProgramElement)it.next(); if (node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) { processImportDeclaration(node, writer); } else { processTypeDeclaration(node, writer); } } // if we got an error we don't want the contents of the file writer.close(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } private static void processImportDeclaration(IProgramElement node, PrintWriter writer) throws IOException { List imports = node.getChildren(); for (Iterator i = imports.iterator(); i.hasNext();) { IProgramElement importNode = (IProgramElement) i.next(); writer.print("import "); writer.print(importNode.getName()); writer.println(';'); } } private static void processTypeDeclaration(IProgramElement classNode, PrintWriter writer) throws IOException { String formalComment = addDeclID(classNode, classNode.getFormalComment()); writer.println(formalComment); String signature = genSourceSignature(classNode);// StructureUtil.genSignature(classNode); // System.err.println("######" + signature + ", " + classNode.getName()); if (!StructureUtil.isAnonymous(classNode) && !classNode.getName().equals("<undefined>")) { writer.println(signature + " {" ); processMembers(classNode.getChildren(), writer, classNode.getKind().equals(IProgramElement.Kind.INTERFACE)); writer.println(); writer.println("}"); } } private static void processMembers(List/*IProgramElement*/ members, PrintWriter writer, boolean declaringTypeIsInterface) throws IOException { for (Iterator it = members.iterator(); it.hasNext();) { IProgramElement member = (IProgramElement) it.next(); if (member.getKind().isType()) { if (!member.getParent().getKind().equals(IProgramElement.Kind.METHOD) && !StructureUtil.isAnonymous(member)) {// don't print anonymous types // System.err.println(">>>>>>>>>>>>>" + member.getName() + "<<<<" + member.getParent()); processTypeDeclaration(member, writer); } } else { String formalComment = addDeclID(member, member.getFormalComment());; writer.println(formalComment); String signature = ""; if (!member.getKind().equals(IProgramElement.Kind.POINTCUT) && !member.getKind().equals(IProgramElement.Kind.ADVICE)) { signature = member.getSourceSignature();//StructureUtil.genSignature(member); } if (member.getKind().isDeclare()) { System.err.println("> Skipping declare (ajdoc limitation): " + member.toLabelString()); } else if (signature != null && signature != "" && !member.getKind().isInterTypeMember() && !member.getKind().equals(IProgramElement.Kind.INITIALIZER) && !StructureUtil.isAnonymous(member)) { writer.print(signature); } else { // System.err.println(">> skipping: " + member.getKind()); } if (member.getKind().equals(IProgramElement.Kind.METHOD) || member.getKind().equals(IProgramElement.Kind.CONSTRUCTOR)) { if (member.getParent().getKind().equals(IProgramElement.Kind.INTERFACE) || signature.indexOf("abstract ") != -1) { writer.println(";"); } else { writer.println(" { }"); } } else if (member.getKind().equals(IProgramElement.Kind.FIELD)) { // writer.println(";"); } } } } /** * Translates "aspect" to "class", as long as its not ".aspect" */ private static String genSourceSignature(IProgramElement classNode) { String signature = classNode.getSourceSignature(); int index = signature.indexOf("aspect"); if (index != -1 && signature.charAt(index-1) != '.') { signature = signature.substring(0, index) + "class " + signature.substring(index + 6, signature.length()); } return signature; } static int nextDeclID = 0; static String addDeclID(IProgramElement decl, String formalComment) { String declID = "" + ++nextDeclID; declIDTable.put(declID, decl); return addToFormal(formalComment, Config.DECL_ID_STRING + declID + Config.DECL_ID_TERMINATOR); } /** * We want to go: * just before the first period * just before the first @ * just before the end of the comment * * Adds a place holder for the period ('#') if one will need to be * replaced. */ static String addToFormal(String formalComment, String string) { boolean appendPeriod = true; if ( (formalComment == null) || formalComment.equals("")) { //formalComment = "/**\n * . \n */\n"; formalComment = "/**\n * \n */\n"; appendPeriod = false; } formalComment = formalComment.trim(); int atsignPos = formalComment.indexOf('@'); int endPos = formalComment.indexOf("*/"); int periodPos = formalComment.indexOf("/**")+2; int position = 0; String periodPlaceHolder = ""; if ( periodPos != -1 ) { position = periodPos+1; } else if ( atsignPos != -1 ) { string = string + "\n * "; position = atsignPos; } else if ( endPos != -1 ) { string = "* " + string + "\n"; position = endPos; } else { // !!! perhaps this error should not be silent throw new Error("Failed to append to formal comment for comment: " + formalComment ); } return formalComment.substring(0, position) + periodPlaceHolder + string + formalComment.substring(position); } }
82,340
Bug 82340 Visibility selector ignored for pointcuts
Using ajdoc under AJDT 1.1.12 or AspectJ 1.2.1 at the commandline has the following aspect has problems. public abstract aspect Aspect { private pointcut privatePointcut (); protected pointcut protectedPointcut (); public pointcut publicPointcut (); private void privateMethod () { } public void protectedMethod () { } public void publicMethod () { } } 1. Asking for "protected" gives all pointcuts (public, protected _and_ private) 2. The Aspect entry is wrong: "public abstract class Aspect" 3. The "Methods inherited ..." section has a leading comma: ", clone, equals, finalize, ..."
resolved fixed
b460597
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T15:53:01Z
2005-01-06T16:46:40Z
ajdoc/testdata/bug82340/Pointcuts.java
82,340
Bug 82340 Visibility selector ignored for pointcuts
Using ajdoc under AJDT 1.1.12 or AspectJ 1.2.1 at the commandline has the following aspect has problems. public abstract aspect Aspect { private pointcut privatePointcut (); protected pointcut protectedPointcut (); public pointcut publicPointcut (); private void privateMethod () { } public void protectedMethod () { } public void publicMethod () { } } 1. Asking for "protected" gives all pointcuts (public, protected _and_ private) 2. The Aspect entry is wrong: "public abstract class Aspect" 3. The "Methods inherited ..." section has a leading comma: ", clone, equals, finalize, ..."
resolved fixed
b460597
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T15:53:01Z
2005-01-06T16:46:40Z
ajdoc/testdata/coverage/foo/NoMembers.java
/* * Created on Jan 12, 2005 */ /** * @author Mik Kersten */ public class NoMembers { }
82,340
Bug 82340 Visibility selector ignored for pointcuts
Using ajdoc under AJDT 1.1.12 or AspectJ 1.2.1 at the commandline has the following aspect has problems. public abstract aspect Aspect { private pointcut privatePointcut (); protected pointcut protectedPointcut (); public pointcut publicPointcut (); private void privateMethod () { } public void protectedMethod () { } public void publicMethod () { } } 1. Asking for "protected" gives all pointcuts (public, protected _and_ private) 2. The Aspect entry is wrong: "public abstract class Aspect" 3. The "Methods inherited ..." section has a leading comma: ", clone, equals, finalize, ..."
resolved fixed
b460597
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T15:53:01Z
2005-01-06T16:46:40Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/CoverageTestCase.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.tools.ajdoc; import java.io.File; import junit.framework.TestCase; /** * A long way to go until full coverage, but this is the place to add more. * * @author Mik Kersten */ public class CoverageTestCase extends TestCase { File file0 = new File("testdata/coverage/InDefaultPackage.java"); File file1 = new File("testdata/coverage/foo/ClassA.java"); File aspect1 = new File("testdata/coverage/foo/UseThisAspectForLinkCheck.aj"); File file2 = new File("testdata/coverage/foo/InterfaceI.java"); File file3 = new File("testdata/coverage/foo/PlainJava.java"); File file4 = new File("testdata/coverage/foo/ModelCoverage.java"); File file5 = new File("testdata/coverage/fluffy/Fluffy.java"); File file6 = new File("testdata/coverage/fluffy/bunny/Bunny.java"); File file7 = new File("testdata/coverage/fluffy/bunny/rocks/Rocks.java"); File file8 = new File("testdata/coverage/fluffy/bunny/rocks/UseThisAspectForLinkCheckToo.java"); File file9 = new File("testdata/coverage/foo/PkgVisibleClass.java"); File file10 = new File("testdata/coverage/foo/NoMembers.java"); File outdir = new File("testdata/coverage/doc"); public void testOptions() { outdir.delete(); String[] args = { "-private", "-encoding", "EUCJIS", "-docencoding", "EUCJIS", "-charset", "UTF-8", "-d", outdir.getAbsolutePath(), file0.getAbsolutePath(), }; org.aspectj.tools.ajdoc.Main.main(args); assertTrue(true); } public void testCoveragePublicMode() { outdir.delete(); String[] args = { "-public", "-source", "1.4", "-d", outdir.getAbsolutePath(), file3.getAbsolutePath(), file9.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); } public void testCoverage() { outdir.delete(); String[] args = { // "-XajdocDebug", "-source", "1.4", "-private", "-d", outdir.getAbsolutePath(), aspect1.getAbsolutePath(), file0.getAbsolutePath(), file1.getAbsolutePath(), file2.getAbsolutePath(), file3.getAbsolutePath(), file4.getAbsolutePath(), file5.getAbsolutePath(), file6.getAbsolutePath(), file7.getAbsolutePath(), file8.getAbsolutePath(), file9.getAbsolutePath(), file10.getAbsolutePath() }; org.aspectj.tools.ajdoc.Main.main(args); } // public void testPlainJava() { // outdir.delete(); // String[] args = { "-d", // outdir.getAbsolutePath(), // file3.getAbsolutePath() }; // org.aspectj.tools.ajdoc.Main.main(args); // } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
82,340
Bug 82340 Visibility selector ignored for pointcuts
Using ajdoc under AJDT 1.1.12 or AspectJ 1.2.1 at the commandline has the following aspect has problems. public abstract aspect Aspect { private pointcut privatePointcut (); protected pointcut protectedPointcut (); public pointcut publicPointcut (); private void privateMethod () { } public void protectedMethod () { } public void publicMethod () { } } 1. Asking for "protected" gives all pointcuts (public, protected _and_ private) 2. The Aspect entry is wrong: "public abstract class Aspect" 3. The "Methods inherited ..." section has a leading comma: ", clone, equals, finalize, ..."
resolved fixed
b460597
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-13T15:53:01Z
2005-01-06T16:46:40Z
ajdoc/testsrc/org/aspectj/tools/ajdoc/PointcutVisibilityTest.java
83,303
Bug 83303 complier error when mixing inheritance, overriding and polymorphism
Given this scenario: - class A define method m1 (with proteceted visibility) - class B extends class A and implements interface I and override method m1 (but with public visibility) - interface I define method m1 (with public visibility) The code is correct and compile using java 1.4 Let's modify the scenario: move the method B.m1 into a method introduction on aspect C, such that - class B extends class A - apsect C intosuces method m1 into B (with public visibility) and makes B implemts I (declare parents) - A and I as before The compiler reports this error: B.java:1 [error] The inherited method A.m1() cannot hide the public abstract method in I class B extends A {
resolved fixed
5d281fd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-20T14:44:39Z
2005-01-20T14:06:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.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.problem; import java.lang.reflect.Modifier; import java.util.Iterator; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.ast.Proceed; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; 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.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; 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.ExplicitConstructorCall; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; 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.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.patterns.DeclareSoft; /** * Extends problem reporter to support compiler-side implementation of declare soft. * Also overrides error reporting for the need to implement abstract methods to * account for inter-type declarations and pointcut declarations. This second * job might be better done directly in the SourceTypeBinding/ClassScope classes. * * @author Jim Hugunin */ public class AjProblemReporter extends ProblemReporter { private static final boolean DUMP_STACK = false; public EclipseFactory factory; public AjProblemReporter( IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) { super(policy, options, problemFactory); } public void unhandledException( TypeBinding exceptionType, ASTNode location) { if (!factory.getWorld().getDeclareSoft().isEmpty()) { Shadow callSite = factory.makeShadow(location, referenceContext); Shadow enclosingExec = factory.makeShadow(referenceContext); // PR 72157 - calls to super / this within a constructor are not part of the cons join point. if ((callSite == null) && (enclosingExec.getKind() == Shadow.ConstructorExecution) && (location instanceof ExplicitConstructorCall)) { super.unhandledException(exceptionType, location); return; } // System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) + // " at " + location + " in " + referenceContext); for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext(); ) { DeclareSoft d = (DeclareSoft)i.next(); // We need the exceptionType to match the type in the declare soft statement // This means it must either be the same type or a subtype ResolvedTypeX throwException = factory.fromEclipse((ReferenceBinding)exceptionType); FuzzyBoolean isExceptionTypeOrSubtype = d.getException().matchesInstanceof(throwException); if (!isExceptionTypeOrSubtype.alwaysTrue() ) continue; if (callSite != null) { FuzzyBoolean match = d.getPointcut().match(callSite); if (match.alwaysTrue()) { //System.err.println("matched callSite: " + callSite + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } if (enclosingExec != null) { FuzzyBoolean match = d.getPointcut().match(enclosingExec); if (match.alwaysTrue()) { //System.err.println("matched enclosingExec: " + enclosingExec + " with " + d); return; } else if (!match.alwaysFalse()) { //!!! need this check to happen much sooner //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here"); } } } } //??? is this always correct if (location instanceof Proceed) { return; } super.unhandledException(exceptionType, location); } private boolean isPointcutDeclaration(MethodBinding binding) { return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector); } public void abstractMethodCannotBeOverridden( SourceTypeBinding type, MethodBinding concreteMethod) { if (isPointcutDeclaration(concreteMethod)) { return; } super.abstractMethodCannotBeOverridden(type, concreteMethod); } public void abstractMethodMustBeImplemented( SourceTypeBinding type, MethodBinding abstractMethod) { // if this is a PointcutDeclaration then there is no error if (isPointcutDeclaration(abstractMethod)) { return; } if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) { //??? think through how this could go wrong return; } // if we implemented this method by an inter-type declaration, then there is no error //??? be sure this is always right ResolvedTypeX onTypeX = null; // If the type is anonymous, look at its supertype if (!type.isAnonymousType()) { onTypeX = factory.fromEclipse(type); } else { // Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type, // we sort it out elsewhere and don't come into this method - // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); //abstractMethod.declaringClass); } for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedTypeX .matches( AjcMemberMaker.interMethod( sig, m.getAspectType(), sig.getDeclaringType().isInterface( factory.getWorld())), EclipseFactory.makeResolvedMember(abstractMethod))) { return; } } } super.abstractMethodMustBeImplemented(type, abstractMethod); } public void handle( int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) { if (severity != Ignore && DUMP_STACK) { Thread.dumpStack(); } super.handle( problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition, referenceContext, unitResult); } // PR71076 public void javadocMissingParamTag(char[] name, int sourceStart, int sourceEnd, int modifiers) { boolean reportIt = true; String sName = new String(name); if (sName.startsWith("ajc$")) reportIt = false; if (sName.equals("thisJoinPoint")) reportIt = false; if (sName.equals("thisJoinPointStaticPart")) reportIt = false; if (sName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false; if (sName.equals("ajc_aroundClosure")) reportIt = false; if (reportIt) super.javadocMissingParamTag(name,sourceStart,sourceEnd,modifiers); } public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) { String abstractMethodName = new String(methodDecl.selector); if (abstractMethodName.startsWith("ajc$pointcut")) { // This will already have been reported, see: PointcutDeclaration.postParse() return; } String[] arguments = new String[] {new String(type.sourceName()), abstractMethodName}; super.handle( IProblem.AbstractMethodInAbstractClass, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd,this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult()); } }
83,303
Bug 83303 complier error when mixing inheritance, overriding and polymorphism
Given this scenario: - class A define method m1 (with proteceted visibility) - class B extends class A and implements interface I and override method m1 (but with public visibility) - interface I define method m1 (with public visibility) The code is correct and compile using java 1.4 Let's modify the scenario: move the method B.m1 into a method introduction on aspect C, such that - class B extends class A - apsect C intosuces method m1 into B (with public visibility) and makes B implemts I (declare parents) - A and I as before The compiler reports this error: B.java:1 [error] The inherited method A.m1() cannot hide the public abstract method in I class B extends A {
resolved fixed
5d281fd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-20T14:44:39Z
2005-01-20T14:06:40Z
tests/bugs150/PR83303.java
83,303
Bug 83303 complier error when mixing inheritance, overriding and polymorphism
Given this scenario: - class A define method m1 (with proteceted visibility) - class B extends class A and implements interface I and override method m1 (but with public visibility) - interface I define method m1 (with public visibility) The code is correct and compile using java 1.4 Let's modify the scenario: move the method B.m1 into a method introduction on aspect C, such that - class B extends class A - apsect C intosuces method m1 into B (with public visibility) and makes B implemts I (declare parents) - A and I as before The compiler reports this error: B.java:1 [error] The inherited method A.m1() cannot hide the public abstract method in I class B extends A {
resolved fixed
5d281fd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-20T14:44:39Z
2005-01-20T14:06:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150TestsNoHarness.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 API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.File; 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.tools.ajc.CompilationResult; /** * These are tests that run on Java 1.4 and use the new ajctestcase format. * If you have a test that *needs* to run on Java 1.5 then look in Ajc150TestsRequireJava15.java */ public class Ajc150TestsNoHarness extends TestUtils { protected void setUp() throws Exception { super.setUp(); baseDir = new File("../tests/bugs150"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { CompilationResult cR=ajc(baseDir,new String[]{"PR78021.java"}); if (verbose) { System.err.println(cR); System.err.println(cR.getStandardError());} RunResult rR = run("PR78021"); if (verbose) {System.err.println(rR.getStdErr());} } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { CompilationResult cR=ajc(baseDir,new String[]{"PR79554.java"}); if (verbose) { System.err.println(cR); System.err.println(cR.getStandardError());} RunResult rR = run("PR79554"); if (verbose) {System.err.println(rR.getStdErr());} } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { boolean f = false; CompilationResult cR = ajc(baseDir,new String[]{"PR82570_1.java"}); System.err.println(cR.getStandardError()); assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); 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); // } } ///////////////////////////////////////// TESTCASE HELPER METHODS BELOW HERE ////////////////////////// // Some util methods for accessing .class contents as BCEL objects public SyntheticRepository createRepos(File cpentry) { ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path")); return SyntheticRepository.getInstance(cp); } private JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException { SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } }
83,563
Bug 83563 pertypewithin() handing of inner classes
null
resolved fixed
1b01255
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-25T20:18:42Z
2005-01-24T20:53:20Z
tests/bugs150/PR83563_1.java
83,563
Bug 83563 pertypewithin() handing of inner classes
null
resolved fixed
1b01255
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-25T20:18:42Z
2005-01-24T20:53:20Z
tests/bugs150/PR83563_2.java
83,563
Bug 83563 pertypewithin() handing of inner classes
null
resolved fixed
1b01255
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-25T20:18:42Z
2005-01-24T20:53:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150TestsNoHarness.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 API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.File; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.tools.ajc.CompilationResult; /** * These are tests that run on Java 1.4 and use the new ajctestcase format. * If you have a test that *needs* to run on Java 1.5 then look in Ajc150TestsRequireJava15.java */ public class Ajc150TestsNoHarness extends TestUtils { protected void setUp() throws Exception { super.setUp(); baseDir = new File("../tests/bugs150"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { CompilationResult cR=ajc(baseDir,new String[]{"PR78021.java"}); if (verbose) { System.err.println(cR); System.err.println(cR.getStandardError());} RunResult rR = run("PR78021"); if (verbose) {System.err.println(rR.getStdErr());} } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { CompilationResult cR=ajc(baseDir,new String[]{"PR79554.java"}); if (verbose) { System.err.println(cR); System.err.println(cR.getStandardError());} RunResult rR = run("PR79554"); if (verbose) {System.err.println(rR.getStdErr());} } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { boolean f = false; CompilationResult cR = ajc(baseDir,new String[]{"PR82570_1.java"}); System.err.println(cR.getStandardError()); assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); 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() { CompilationResult cR = ajc(baseDir,new String[]{"PR83303.java"}); assertTrue("Should be no errors:"+cR,!cR.hasErrorMessages()); } }
83,563
Bug 83563 pertypewithin() handing of inner classes
null
resolved fixed
1b01255
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-25T20:18:42Z
2005-01-24T20:53:20Z
weaver/src/org/aspectj/weaver/PerTypeWithinTargetTypeMunger.java
/* ******************************************************************* * Copyright (c) 2005 * 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; import java.io.DataOutputStream; import java.io.IOException; import org.aspectj.weaver.patterns.PerTypeWithin; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.TypePattern; // PTWIMPL Target type munger adds the localAspectOf() method public class PerTypeWithinTargetTypeMunger extends ResolvedTypeMunger { private ResolvedMember localAspectOfMethod; private TypeX aspectType; private PerTypeWithin testPointcut; public PerTypeWithinTargetTypeMunger(TypeX aspectType, PerTypeWithin testPointcut) { super(PerTypeWithinInterface, null); this.aspectType = aspectType; this.testPointcut = testPointcut; } public void write(DataOutputStream s) throws IOException { throw new RuntimeException("shouldn't be serialized"); } public TypeX getAspectType() { return aspectType; } public Pointcut getTestPointcut() { return testPointcut; } public boolean matches(ResolvedTypeX matchType, ResolvedTypeX aspectType) { return testPointcut.getTypePattern().matches(matchType,TypePattern.STATIC).alwaysTrue(); } }
83,563
Bug 83563 pertypewithin() handing of inner classes
null
resolved fixed
1b01255
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-25T20:18:42Z
2005-01-24T20:53:20Z
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.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; 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 Set couldMatchKinds() { return kindSet; } // ----- public FuzzyBoolean fastMatch(FastMatchInfo info) { if (typePattern.annotationPattern instanceof AnyAnnotationTypePattern) { return isWithinType(info.getType()); } return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { ResolvedTypeX enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true); if (enclosingType == ResolvedTypeX.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); } 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(ResolvedTypeX 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, NamePattern.ANY, TypePatternList.ANY, ThrowsPattern.ANY, AnnotationTypePattern.ANY ); Pointcut testPc = new KindedPointcut(Shadow.StaticInitialization,sigpat); Pointcut testPc2= new WithinPointcut(typePattern); // This munger will initialize the aspect instance field in the matched type inAspect.crosscuttingMembers.addConcreteShadowMunger(Advice.makePerTypeWithinEntry(world, testPc, inAspect)); ResolvedTypeMunger munger = new PerTypeWithinTargetTypeMunger(inAspect, ret); inAspect.crosscuttingMembers.addTypeMunger(world.concreteTypeMunger(munger, 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+")"; } private FuzzyBoolean isWithinType(ResolvedTypeX type) { while (type != null) { if (typePattern.matchesStatically(type)) { return FuzzyBoolean.YES; } type = type.getDeclaringType(); } return FuzzyBoolean.NO; } }
83,626
Bug 83626 @AJ
Andy wants a patch format + a bugzilla for @AJ work due to some funny license issue. Here it is as drafted
resolved fixed
7b4c7d7
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-26T14:01:30Z
2005-01-25T16: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.2 2004/11/19 16:45:19 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)); } } 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() { return (String[])arg_names.clone(); } 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())); } 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; } } }
83,565
Bug 83565 BCException "bad type name" thrown when compiling
I just downloaded AJDT version 1.2.0.20050124144759 and I am running Eclipse 3.1M4. I tried to use aspectJ on an existing Java 5 project. There are no aspects in it yet, just straight Java 5. The project runs just fine as a standard Java project. When add the AspectJ nature and I try to compile the project, no class files are generated and I get this error generated on a type that is parameterized: Internal compiler error org.aspectj.weaver.BCException: Bad type name: at org.aspectj.weaver.TypeX.nameToSignature(TypeX.java:634) at org.aspectj.weaver.TypeX.forName(TypeX.java:87) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:155) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBindings(EclipseFactory.java:163) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:229) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:224) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.visit(AsmHierarchyBuilder.java:675) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration.traverse(ConstructorDeclaration.java:447) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1133) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:314) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.internalBuild(AsmHierarchyBuilder.java:171) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.buildStructureForCompilationUnit(AsmHierarchyBuilder.java:111) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.finishedCompilationUnit(EclipseFactory.java:354) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:138) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:373) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:682) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:165) The source code of the file that generates this error is: package mj.compiler.ast; import java.util.Vector; import mj.compiler.Driver; import mj.compiler.Visitor; public class Sequence<T extends AST> extends AST { private Vector<T> elements = new Vector<T>(); public Sequence() { super(0, 0); } public Sequence(T element) { super(element); elements.add(element); } public int length() { return elements.size(); } public T elementAt(int i) { return elements.elementAt(i); } public Sequence add(T element) { elements.add(element); return this; } public Sequence add(int pos, T element) { elements.add(pos, element); return this; } public Sequence addAll(Sequence<T> others) { if( others == null ) return this; elements.addAll(others.elements); return this; } public void visitChildren(Visitor v) { for( AST element : elements ) { element.visit(v); } } public void replaceChild(AST old, AST gnu) { T NEW = (T)gnu; for(int i = 0; i < elements.size(); i++ ) { if( elements.get(i) == old ) { elements.set(i, NEW); return; } } throw new Driver.CompileError("Can't find child in replaceChild."); } /*** START GENERATED VISITOR PROTOCOL ***///TODO public void visit(mj.compiler.Visitor v) { v.visitSequence(this); } /*** END GENERATED VISITOR PROTOCOL ***/ } Hope this helps something. ps- I am able to create and run a very simple AspectJ project with an aspect, advice, and some Java 5 syntax.
resolved fixed
5765d53
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-27T17:21:17Z
2005-01-24T20:53:20Z
ajde/testdata/bug-83565/Bug.java
83,565
Bug 83565 BCException "bad type name" thrown when compiling
I just downloaded AJDT version 1.2.0.20050124144759 and I am running Eclipse 3.1M4. I tried to use aspectJ on an existing Java 5 project. There are no aspects in it yet, just straight Java 5. The project runs just fine as a standard Java project. When add the AspectJ nature and I try to compile the project, no class files are generated and I get this error generated on a type that is parameterized: Internal compiler error org.aspectj.weaver.BCException: Bad type name: at org.aspectj.weaver.TypeX.nameToSignature(TypeX.java:634) at org.aspectj.weaver.TypeX.forName(TypeX.java:87) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:155) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBindings(EclipseFactory.java:163) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:229) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:224) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.visit(AsmHierarchyBuilder.java:675) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration.traverse(ConstructorDeclaration.java:447) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1133) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:314) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.internalBuild(AsmHierarchyBuilder.java:171) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.buildStructureForCompilationUnit(AsmHierarchyBuilder.java:111) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.finishedCompilationUnit(EclipseFactory.java:354) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:138) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:373) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:682) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:165) The source code of the file that generates this error is: package mj.compiler.ast; import java.util.Vector; import mj.compiler.Driver; import mj.compiler.Visitor; public class Sequence<T extends AST> extends AST { private Vector<T> elements = new Vector<T>(); public Sequence() { super(0, 0); } public Sequence(T element) { super(element); elements.add(element); } public int length() { return elements.size(); } public T elementAt(int i) { return elements.elementAt(i); } public Sequence add(T element) { elements.add(element); return this; } public Sequence add(int pos, T element) { elements.add(pos, element); return this; } public Sequence addAll(Sequence<T> others) { if( others == null ) return this; elements.addAll(others.elements); return this; } public void visitChildren(Visitor v) { for( AST element : elements ) { element.visit(v); } } public void replaceChild(AST old, AST gnu) { T NEW = (T)gnu; for(int i = 0; i < elements.size(); i++ ) { if( elements.get(i) == old ) { elements.set(i, NEW); return; } } throw new Driver.CompileError("Can't find child in replaceChild."); } /*** START GENERATED VISITOR PROTOCOL ***///TODO public void visit(mj.compiler.Visitor v) { v.visitSequence(this); } /*** END GENERATED VISITOR PROTOCOL ***/ } Hope this helps something. ps- I am able to create and run a very simple AspectJ project with an aspect, advice, and some Java 5 syntax.
resolved fixed
5765d53
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-27T17:21:17Z
2005-01-24T20:53:20Z
ajde/testsrc/org/aspectj/ajde/AjdeTests.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde; import junit.framework.*; public class AjdeTests extends TestCase { public static String TESTDATA_PATH = "../ajde/testdata"; public static Test suite() { TestSuite suite = new TestSuite(AjdeTests.class.getName()); //$JUnit-BEGIN$ suite.addTestSuite(ShowWeaveMessagesTestCase.class); suite.addTestSuite(DuplicateManifestTest.class); suite.addTestSuite(BuildOptionsTest.class); suite.addTestSuite(BuildConfigurationTests.class); suite.addTestSuite(StructureModelRegressionTest.class); suite.addTestSuite(StructureModelTest.class); suite.addTestSuite(VersionTest.class); suite.addTestSuite(CompilerMessagesTest.class); suite.addTestSuite(AsmDeclarationsTest.class); suite.addTestSuite(AsmRelationshipsTest.class); suite.addTestSuite(InpathTestcase.class); suite.addTestSuite(ReweavableTestCase.class); suite.addTestSuite(ResourceCopyTestCase.class); suite.addTestSuite(ModelPerformanceTest.class); suite.addTestSuite(SavedModelConsistencyTest. class); suite.addTestSuite(BuildCancellingTest.class); suite.addTestSuite(JarManifestTest.class); suite.addTestSuite(ExtensionTests.class); //$JUnit-END$ return suite; } public AjdeTests(String name) { super(name); } }
83,565
Bug 83565 BCException "bad type name" thrown when compiling
I just downloaded AJDT version 1.2.0.20050124144759 and I am running Eclipse 3.1M4. I tried to use aspectJ on an existing Java 5 project. There are no aspects in it yet, just straight Java 5. The project runs just fine as a standard Java project. When add the AspectJ nature and I try to compile the project, no class files are generated and I get this error generated on a type that is parameterized: Internal compiler error org.aspectj.weaver.BCException: Bad type name: at org.aspectj.weaver.TypeX.nameToSignature(TypeX.java:634) at org.aspectj.weaver.TypeX.forName(TypeX.java:87) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:155) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBindings(EclipseFactory.java:163) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:229) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:224) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.visit(AsmHierarchyBuilder.java:675) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration.traverse(ConstructorDeclaration.java:447) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1133) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:314) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.internalBuild(AsmHierarchyBuilder.java:171) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.buildStructureForCompilationUnit(AsmHierarchyBuilder.java:111) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.finishedCompilationUnit(EclipseFactory.java:354) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:138) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:373) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:682) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:165) The source code of the file that generates this error is: package mj.compiler.ast; import java.util.Vector; import mj.compiler.Driver; import mj.compiler.Visitor; public class Sequence<T extends AST> extends AST { private Vector<T> elements = new Vector<T>(); public Sequence() { super(0, 0); } public Sequence(T element) { super(element); elements.add(element); } public int length() { return elements.size(); } public T elementAt(int i) { return elements.elementAt(i); } public Sequence add(T element) { elements.add(element); return this; } public Sequence add(int pos, T element) { elements.add(pos, element); return this; } public Sequence addAll(Sequence<T> others) { if( others == null ) return this; elements.addAll(others.elements); return this; } public void visitChildren(Visitor v) { for( AST element : elements ) { element.visit(v); } } public void replaceChild(AST old, AST gnu) { T NEW = (T)gnu; for(int i = 0; i < elements.size(); i++ ) { if( elements.get(i) == old ) { elements.set(i, NEW); return; } } throw new Driver.CompileError("Can't find child in replaceChild."); } /*** START GENERATED VISITOR PROTOCOL ***///TODO public void visit(mj.compiler.Visitor v) { v.visitSequence(this); } /*** END GENERATED VISITOR PROTOCOL ***/ } Hope this helps something. ps- I am able to create and run a very simple AspectJ project with an aspect, advice, and some Java 5 syntax.
resolved fixed
5765d53
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-27T17:21:17Z
2005-01-24T20:53:20Z
ajde/testsrc/org/aspectj/ajde/GenericsTest.java
83,565
Bug 83565 BCException "bad type name" thrown when compiling
I just downloaded AJDT version 1.2.0.20050124144759 and I am running Eclipse 3.1M4. I tried to use aspectJ on an existing Java 5 project. There are no aspects in it yet, just straight Java 5. The project runs just fine as a standard Java project. When add the AspectJ nature and I try to compile the project, no class files are generated and I get this error generated on a type that is parameterized: Internal compiler error org.aspectj.weaver.BCException: Bad type name: at org.aspectj.weaver.TypeX.nameToSignature(TypeX.java:634) at org.aspectj.weaver.TypeX.forName(TypeX.java:87) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:155) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBindings(EclipseFactory.java:163) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:229) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:224) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.visit(AsmHierarchyBuilder.java:675) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration.traverse(ConstructorDeclaration.java:447) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1133) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:314) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.internalBuild(AsmHierarchyBuilder.java:171) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.buildStructureForCompilationUnit(AsmHierarchyBuilder.java:111) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.finishedCompilationUnit(EclipseFactory.java:354) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:138) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:373) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:682) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:165) The source code of the file that generates this error is: package mj.compiler.ast; import java.util.Vector; import mj.compiler.Driver; import mj.compiler.Visitor; public class Sequence<T extends AST> extends AST { private Vector<T> elements = new Vector<T>(); public Sequence() { super(0, 0); } public Sequence(T element) { super(element); elements.add(element); } public int length() { return elements.size(); } public T elementAt(int i) { return elements.elementAt(i); } public Sequence add(T element) { elements.add(element); return this; } public Sequence add(int pos, T element) { elements.add(pos, element); return this; } public Sequence addAll(Sequence<T> others) { if( others == null ) return this; elements.addAll(others.elements); return this; } public void visitChildren(Visitor v) { for( AST element : elements ) { element.visit(v); } } public void replaceChild(AST old, AST gnu) { T NEW = (T)gnu; for(int i = 0; i < elements.size(); i++ ) { if( elements.get(i) == old ) { elements.set(i, NEW); return; } } throw new Driver.CompileError("Can't find child in replaceChild."); } /*** START GENERATED VISITOR PROTOCOL ***///TODO public void visit(mj.compiler.Visitor v) { v.visitSequence(this); } /*** END GENERATED VISITOR PROTOCOL ***/ } Hope this helps something. ps- I am able to create and run a very simple AspectJ project with an aspect, advice, and some Java 5 syntax.
resolved fixed
5765d53
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-01-27T17:21:17Z
2005-01-24T20:53:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Mik Kersten revisions, added additional relationships * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Stack; import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration; import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ExtendedStringLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ImportReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Initializer; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodScope; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemHandler; import org.aspectj.util.LangUtil; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.ReferencePointcut; /** * At each iteration of <CODE>processCompilationUnit</CODE> the declarations for a * particular compilation unit are added to the hierarchy passed as a a parameter. * <p> * Clients who extend this class need to ensure that they do not override any of the existing * behavior. If they do, the structure model will not be built properly and tools such as IDE * structure views and ajdoc will fail. * <p> * <b>Note:</b> this class is not considered public API and the overridable * methods are subject to change. * * @author Mik Kersten */ public class AsmHierarchyBuilder extends ASTVisitor { protected AsmElementFormatter formatter = new AsmElementFormatter(); /** * Reset for every compilation unit. */ protected AjBuildConfig buildConfig; /** * Reset for every compilation unit. */ protected Stack stack; /** * Reset for every compilation unit. */ private CompilationResult currCompilationResult; /** * * @param cuDeclaration * @param buildConfig * @param structureModel hiearchy to add this unit's declarations to */ public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) { currCompilationResult = cuDeclaration.compilationResult(); LangUtil.throwIaxIfNull(currCompilationResult, "result"); stack = new Stack(); this.buildConfig = buildConfig; internalBuild(cuDeclaration, structureModel); // throw new RuntimeException("not implemented"); } private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) { LangUtil.throwIaxIfNull(structureModel, "structureModel"); if (!currCompilationResult.equals(unit.compilationResult())) { throw new IllegalArgumentException("invalid unit: " + unit); } // ---- summary // add unit to package (or root if no package), // first removing any duplicate (XXX? removes children if 3 classes in same file?) // push the node on the stack // and traverse // -- create node to add final File file = new File(new String(unit.getFileName())); final IProgramElement cuNode; { // AMC - use the source start and end from the compilation unit decl int startLine = getStartLine(unit); int endLine = getEndLine(unit); SourceLocation sourceLocation = new SourceLocation(file, startLine, endLine); sourceLocation.setOffset(unit.sourceStart); cuNode = new ProgramElement( new String(file.getName()), IProgramElement.Kind.FILE_JAVA, sourceLocation, 0, "", new ArrayList()); } cuNode.addChild(new ProgramElement( "import declarations", IProgramElement.Kind.IMPORT_REFERENCE, null, 0, "", new ArrayList())); final IProgramElement addToNode = genAddToNode(unit, structureModel); // -- remove duplicates before adding (XXX use them instead?) if (addToNode!=null && addToNode.getChildren()!=null) { for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) { IProgramElement child = (IProgramElement)itt.next(); ISourceLocation childLoc = child.getSourceLocation(); if (null == childLoc) { // XXX ok, packages have null source locations // signal others? } else if (childLoc.getSourceFile().equals(file)) { itt.remove(); } } } // -- add and traverse addToNode.addChild(cuNode); stack.push(cuNode); unit.traverse(this, unit.scope); // -- update file map (XXX do this before traversal?) try { structureModel.addToFileMap(file.getCanonicalPath(), cuNode); } catch (IOException e) { System.err.println("IOException " + e.getMessage() + " creating path for " + file ); // XXX signal IOException when canonicalizing file path } } /** * Get/create the node (package or root) to add to. */ private IProgramElement genAddToNode( CompilationUnitDeclaration unit, IHierarchy structureModel) { final IProgramElement addToNode; { ImportReference currentPackage = unit.currentPackage; if (null == currentPackage) { addToNode = structureModel.getRoot(); } else { String pkgName; { StringBuffer nameBuffer = new StringBuffer(); final char[][] importName = currentPackage.getImportName(); final int last = importName.length-1; for (int i = 0; i < importName.length; i++) { nameBuffer.append(new String(importName[i])); if (i < last) { nameBuffer.append('.'); } } pkgName = nameBuffer.toString(); } IProgramElement pkgNode = null; if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) { for (Iterator it = structureModel.getRoot().getChildren().iterator(); it.hasNext(); ) { IProgramElement currNode = (IProgramElement)it.next(); if (pkgName.equals(currNode.getName())) { pkgNode = currNode; break; } } } if (pkgNode == null) { // note packages themselves have no source location pkgNode = new ProgramElement( pkgName, IProgramElement.Kind.PACKAGE, new ArrayList() ); structureModel.getRoot().addChild(pkgNode); } addToNode = pkgNode; } } return addToNode; } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { String name = new String(typeDeclaration.name); IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT; else if (typeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE; else if (typeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM; else if (typeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION; IProgramElement peNode = new ProgramElement( name, kind, makeLocation(typeDeclaration), typeDeclaration.modifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(typeDeclaration)); peNode.setFormalComment(generateJavadocComment(typeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { stack.pop(); } // ??? share impl with visit(TypeDeclaration, ..) ? public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { String name = new String(memberTypeDeclaration.name); IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT; else if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE; else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM; else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION; IProgramElement peNode = new ProgramElement( name, kind, makeLocation(memberTypeDeclaration), memberTypeDeclaration.modifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration)); peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { stack.pop(); } public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) { String fullName = "<undefined>"; if (memberTypeDeclaration.allocation != null && memberTypeDeclaration.allocation.type != null) { // Create a name something like 'new Runnable() {..}' fullName = "new "+memberTypeDeclaration.allocation.type.toString()+"() {..}"; } else if (memberTypeDeclaration.binding != null && memberTypeDeclaration.binding.constantPoolName() != null) { // If we couldn't find a nice name like 'new Runnable() {..}' then use the number after the $ fullName = new String(memberTypeDeclaration.binding.constantPoolName()); int dollar = fullName.indexOf('$'); fullName = fullName.substring(dollar+1); } IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE; else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM; else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION; IProgramElement peNode = new ProgramElement( fullName, kind, makeLocation(memberTypeDeclaration), memberTypeDeclaration.modifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration)); peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration memberTypeDeclaration, BlockScope scope) { stack.pop(); } private String genSourceSignature(TypeDeclaration typeDeclaration) { StringBuffer output = new StringBuffer(); typeDeclaration.printHeader(0, output); return output.toString(); } private IProgramElement findEnclosingClass(Stack stack) { for (int i = stack.size()-1; i >= 0; i--) { IProgramElement pe = (IProgramElement)stack.get(i); if (pe.getKind() == IProgramElement.Kind.CLASS) { return pe; } } return (IProgramElement)stack.peek(); } public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { IProgramElement peNode = null; // For intertype decls, use the modifiers from the original signature, not the generated method if (methodDeclaration instanceof InterTypeDeclaration) { InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration; ResolvedMember sig = itd.getSignature(); peNode = new ProgramElement( "", IProgramElement.Kind.ERROR, makeLocation(methodDeclaration), (sig!=null?sig.getModifiers():0), "", new ArrayList()); } else { peNode = new ProgramElement( "", IProgramElement.Kind.ERROR, makeLocation(methodDeclaration), methodDeclaration.modifiers, "", new ArrayList()); } formatter.genLabelAndKind(methodDeclaration, peNode); genBytecodeInfo(methodDeclaration, peNode); List namedPointcuts = genNamedPointcuts(methodDeclaration); addUsesPointcutRelationsForNode(peNode, namedPointcuts, methodDeclaration); if (methodDeclaration.returnType!=null) { peNode.setCorrespondingType(methodDeclaration.returnType.toString()); } else { peNode.setCorrespondingType(null); } peNode.setSourceSignature(genSourceSignature(methodDeclaration)); peNode.setFormalComment(generateJavadocComment(methodDeclaration)); // TODO: add return type test if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) { if (peNode.toLabelString().equals("main(String[])") && peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC) && peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) { ((IProgramElement)stack.peek()).setRunnable(true); } } stack.push(peNode); return true; } private void addUsesPointcutRelationsForNode(IProgramElement peNode, List namedPointcuts, MethodDeclaration declaration) { for (Iterator it = namedPointcuts.iterator(); it.hasNext();) { ReferencePointcut rp = (ReferencePointcut) it.next(); ResolvedMember member = getPointcutDeclaration(rp, declaration); if (member != null) { IRelationship foreward = AsmManager.getDefault().getRelationshipMap().get(peNode.getHandleIdentifier(), IRelationship.Kind.USES_POINTCUT, "uses pointcut", false, true); foreward.addTarget(ProgramElement.genHandleIdentifier(member.getSourceLocation())); IRelationship back = AsmManager.getDefault().getRelationshipMap().get(ProgramElement.genHandleIdentifier(member.getSourceLocation()), IRelationship.Kind.USES_POINTCUT, "pointcut used by", false, true); back.addTarget(peNode.getHandleIdentifier()); } } } private ResolvedMember getPointcutDeclaration(ReferencePointcut rp, MethodDeclaration declaration) { World world = ((AjLookupEnvironment)declaration.scope.environment()).factory.getWorld(); TypeX onType = rp.onType; if (onType == null) { Member member = EclipseFactory.makeResolvedMember(declaration.binding); onType = member.getDeclaringType(); } ResolvedMember[] members = onType.getDeclaredPointcuts(world); if (members != null) { for (int i = 0; i < members.length; i++) { if (members[i].getName().equals(rp.name)) { return members[i]; } } } return null; } /** * @param methodDeclaration * @return all of the named pointcuts referenced by the PCD of this declaration */ private List genNamedPointcuts(MethodDeclaration methodDeclaration) { List pointcuts = new ArrayList(); if (methodDeclaration instanceof AdviceDeclaration) { if (((AdviceDeclaration)methodDeclaration).pointcutDesignator != null) addAllNamed(((AdviceDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts); } else if (methodDeclaration instanceof PointcutDeclaration) { if (((PointcutDeclaration)methodDeclaration).pointcutDesignator != null) addAllNamed(((PointcutDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts); } return pointcuts; } /** * @param left * @param pointcuts accumulator for named pointcuts */ private void addAllNamed(Pointcut pointcut, List pointcuts) { if (pointcut == null) return; if (pointcut instanceof ReferencePointcut) { ReferencePointcut rp = (ReferencePointcut)pointcut; pointcuts.add(rp); } else if (pointcut instanceof AndPointcut) { AndPointcut ap = (AndPointcut)pointcut; addAllNamed(ap.getLeft(), pointcuts); addAllNamed(ap.getRight(), pointcuts); } else if (pointcut instanceof OrPointcut) { OrPointcut op = (OrPointcut)pointcut; addAllNamed(op.getLeft(), pointcuts); addAllNamed(op.getRight(), pointcuts); } } private String genSourceSignature(MethodDeclaration methodDeclaration) { StringBuffer output = new StringBuffer(); ASTNode.printModifiers(methodDeclaration.modifiers, output); methodDeclaration.printReturnType(0, output).append(methodDeclaration.selector).append('('); if (methodDeclaration.arguments != null) { for (int i = 0; i < methodDeclaration.arguments.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ methodDeclaration.arguments[i].print(0, output); } } output.append(')'); if (methodDeclaration.thrownExceptions != null) { output.append(" throws "); //$NON-NLS-1$ for (int i = 0; i < methodDeclaration.thrownExceptions.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ methodDeclaration.thrownExceptions[i].print(0, output); } } return output.toString(); } protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) { if (methodDeclaration.binding != null) { String memberName = ""; String memberBytecodeSignature = ""; try { Member member = EclipseFactory.makeResolvedMember(methodDeclaration.binding); memberName = member.getName(); memberBytecodeSignature = member.getSignature(); } catch (NullPointerException npe) { memberName = "<undefined>"; } peNode.setBytecodeName(memberName); peNode.setBytecodeSignature(memberBytecodeSignature); } ((IProgramElement)stack.peek()).addChild(peNode); } public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) { stack.pop(); } public boolean visit(ImportReference importRef, CompilationUnitScope scope) { int dotIndex = importRef.toString().lastIndexOf('.'); String currPackageImport = ""; if (dotIndex != -1) { currPackageImport = importRef.toString().substring(0, dotIndex); } if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) { IProgramElement peNode = new ProgramElement( new String(importRef.toString()), IProgramElement.Kind.IMPORT_REFERENCE, makeLocation(importRef), 0, "", new ArrayList()); ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0); imports.addChild(0, peNode); stack.push(peNode); } return true; } public void endVisit(ImportReference importRef, CompilationUnitScope scope) { int dotIndex = importRef.toString().lastIndexOf('.'); String currPackageImport = ""; if (dotIndex != -1) { currPackageImport = importRef.toString().substring(0, dotIndex); } if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) { stack.pop(); } } public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { IProgramElement peNode = null; if (fieldDeclaration.type == null) { // The field represents an enum value peNode = new ProgramElement( new String(fieldDeclaration.name),IProgramElement.Kind.ENUM_VALUE, makeLocation(fieldDeclaration), fieldDeclaration.modifiers, "", new ArrayList()); peNode.setCorrespondingType(fieldDeclaration.binding.type.debugName()); } else { peNode = new ProgramElement( new String(fieldDeclaration.name),IProgramElement.Kind.FIELD, makeLocation(fieldDeclaration), fieldDeclaration.modifiers, "", new ArrayList()); peNode.setCorrespondingType(fieldDeclaration.type.toString()); } peNode.setSourceSignature(genSourceSignature(fieldDeclaration)); peNode.setFormalComment(generateJavadocComment(fieldDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) { stack.pop(); } /** * Checks if comments should be added to the model before generating. */ protected String generateJavadocComment(ASTNode astNode) { if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null; StringBuffer sb = new StringBuffer(); // !!! specify length? boolean completed = false; int startIndex = -1; if (astNode instanceof MethodDeclaration) { startIndex = ((MethodDeclaration)astNode).declarationSourceStart; } else if (astNode instanceof FieldDeclaration) { startIndex = ((FieldDeclaration)astNode).declarationSourceStart; } else if (astNode instanceof TypeDeclaration) { startIndex = ((TypeDeclaration)astNode).declarationSourceStart; } if (startIndex == -1) { return null; } else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /** && currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*' && currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') { for (int i = startIndex; i < astNode.sourceStart && !completed; i++) { char curr = currCompilationResult.compilationUnit.getContents()[i]; if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */ sb.append(currCompilationResult.compilationUnit.getContents()[i]); } return sb.toString(); } else { return null; } } /** * Doesn't print qualified allocation expressions. */ protected String genSourceSignature(FieldDeclaration fieldDeclaration) { StringBuffer output = new StringBuffer(); FieldDeclaration.printModifiers(fieldDeclaration.modifiers, output); if (fieldDeclaration.type == null) { // This is an enum value output.append(fieldDeclaration.binding.type.debugName()).append(" ").append(fieldDeclaration.name); } else { fieldDeclaration.type.print(0, output).append(' ').append(fieldDeclaration.name); } if (fieldDeclaration.initialization != null && !(fieldDeclaration.initialization instanceof QualifiedAllocationExpression)) { output.append(" = "); //$NON-NLS-1$ if (fieldDeclaration.initialization instanceof ExtendedStringLiteral) { output.append("\"<extended string literal>\""); } else { fieldDeclaration.initialization.printExpression(0, output); } } output.append(';'); return output.toString(); } // public boolean visit(ImportReference importRef, CompilationUnitScope scope) { // ProgramElementNode peNode = new ProgramElementNode( // new String(importRef.toString()), // ProgramElementNode.Kind., // makeLocation(importRef), // 0, // "", // new ArrayList()); // ((IProgramElement)stack.peek()).addChild(0, peNode); // stack.push(peNode); // return true; // } // public void endVisit(ImportReference importRef,CompilationUnitScope scope) { // stack.pop(); // } public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { if (constructorDeclaration.isDefaultConstructor) { stack.push(null); // a little wierd but does the job return true; } StringBuffer argumentsSignature = new StringBuffer(); argumentsSignature.append("("); if (constructorDeclaration.arguments!=null) { for (int i = 0;i<constructorDeclaration.arguments.length;i++) { argumentsSignature.append(constructorDeclaration.arguments[i]); if (i+1<constructorDeclaration.arguments.length) argumentsSignature.append(","); } } argumentsSignature.append(")"); IProgramElement peNode = new ProgramElement( new String(constructorDeclaration.selector)+argumentsSignature, IProgramElement.Kind.CONSTRUCTOR, makeLocation(constructorDeclaration), constructorDeclaration.modifiers, "", new ArrayList()); peNode.setModifiers(constructorDeclaration.modifiers); peNode.setSourceSignature(genSourceSignature(constructorDeclaration)); // Fix to enable us to anchor things from ctor nodes if (constructorDeclaration.binding != null) { String memberName = ""; String memberBytecodeSignature = ""; try { Member member = EclipseFactory.makeResolvedMember(constructorDeclaration.binding); memberName = member.getName(); memberBytecodeSignature = member.getSignature(); } catch (NullPointerException npe) { memberName = "<undefined>"; } peNode.setBytecodeName(memberName); peNode.setBytecodeSignature(memberBytecodeSignature); } ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { stack.pop(); } private String genSourceSignature(ConstructorDeclaration constructorDeclaration) { StringBuffer output = new StringBuffer(); ASTNode.printModifiers(constructorDeclaration.modifiers, output); output.append(constructorDeclaration.selector).append('('); if (constructorDeclaration.arguments != null) { for (int i = 0; i < constructorDeclaration.arguments.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ constructorDeclaration.arguments[i].print(0, output); } } output.append(')'); if (constructorDeclaration.thrownExceptions != null) { output.append(" throws "); //$NON-NLS-1$ for (int i = 0; i < constructorDeclaration.thrownExceptions.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ constructorDeclaration.thrownExceptions[i].print(0, output); } } return output.toString(); } // public boolean visit(Clinit clinit, ClassScope scope) { // ProgramElementNode peNode = new ProgramElementNode( // "<clinit>", // ProgramElementNode.Kind.INITIALIZER, // makeLocation(clinit), // clinit.modifiers, // "", // new ArrayList()); // ((IProgramElement)stack.peek()).addChild(peNode); // stack.push(peNode); // return false; // } // public void endVisit(Clinit clinit, ClassScope scope) { // stack.pop(); // } /** This method works-around an odd traverse implementation on Initializer */ private Initializer inInitializer = null; public boolean visit(Initializer initializer, MethodScope scope) { if (initializer == inInitializer) return false; inInitializer = initializer; IProgramElement peNode = new ProgramElement( "...", IProgramElement.Kind.INITIALIZER, makeLocation(initializer), initializer.modifiers, "", new ArrayList()); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); initializer.block.traverse(this, scope); stack.pop(); return false; } // ??? handle non-existant files protected ISourceLocation makeLocation(ASTNode node) { String fileName = ""; if (currCompilationResult.getFileName() != null) { fileName = new String(currCompilationResult.getFileName()); } // AMC - different strategies based on node kind int startLine = getStartLine(node); int endLine = getEndLine(node); SourceLocation loc = null; if ( startLine <= endLine ) { // found a valid end line for this node... loc = new SourceLocation(new File(fileName), startLine, endLine); loc.setOffset(node.sourceStart); } else { loc = new SourceLocation(new File(fileName), startLine); loc.setOffset(node.sourceStart); } return loc; } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! protected int getStartLine( ASTNode n){ // if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n); // if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n); // if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n); return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, n.sourceStart); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! protected int getEndLine( ASTNode n){ if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n); if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n); if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n); return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, n.sourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( AbstractVariableDeclaration avd ) { // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // avd.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( AbstractVariableDeclaration avd ){ return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, avd.declarationSourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( AbstractMethodDeclaration amd ){ // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // amd.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( AbstractMethodDeclaration amd) { return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, amd.declarationSourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( TypeDeclaration td ){ // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // td.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( TypeDeclaration td){ return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, td.declarationSourceEnd); } }
86,789
Bug 86789 annotations and "circularity in declare precedence"
null
resolved fixed
f90186c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-09T14:13:14Z
2005-02-27T21:33:20Z
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 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.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; //XXX need to use dim in matching public class WildTypePattern extends TypePattern { NamePattern[] namePatterns; int ellipsisCount; String[] importedPrefixes; String[] knownMatches; int dim; WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim, boolean isVarArgs) { super(includeSubtypes,isVarArgs); 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); } 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; } /* (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 TypeX otherType = other.getExactType(); if (otherType != ResolvedTypeX.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(ResolvedTypeX type) { 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) && annotationPattern.matches(type).alwaysTrue(); } /** * Used in conjunction with checks on 'isStar()' to tell you if this pattern represents '*' or '*[]' which are * different ! */ public int getDimensions() { return dim; } /** * @param targetTypeName * @return */ private boolean matchesExactlyByName(String targetTypeName) { //XXX hack if (knownMatches == null && importedPrefixes == null) { return innerMatchesExactly(targetTypeName); } if (isStar()) { // 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(ResolvedTypeX 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() { //System.err.println("extract from : " + Arrays.asList(namePatterns)); int len = namePatterns.length; 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(); } /** * 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 (isStar()) { // 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) { // 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; } } annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); 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; } } String cleanName = maybeGetCleanName(); String originalName = cleanName; // if we discover it is 'MISSING' when searching via the scope, this next local var will // tell us if it is really missing or if it does exist in the world and we just can't // see it from the current scope. ResolvedTypeX resolvedTypeInTheWorld = null; if (cleanName != null) { TypeX type; //System.out.println("resolve: " + cleanName); //??? this loop has too many inefficiencies to count resolvedTypeInTheWorld = scope.getWorld().resolve(TypeX.forName(cleanName),true); while ((type = scope.lookupType(cleanName, this)) == ResolvedTypeX.MISSING) { int lastDot = cleanName.lastIndexOf('.'); if (lastDot == -1) break; cleanName = cleanName.substring(0, lastDot) + '$' + cleanName.substring(lastDot+1); if (resolvedTypeInTheWorld == ResolvedTypeX.MISSING) resolvedTypeInTheWorld = scope.getWorld().resolve(TypeX.forName(cleanName),true); } if (type == ResolvedTypeX.MISSING) { if (requireExactType) { if (!allowBinding) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE,originalName), getSourceLocation())); } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, 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 (resolvedTypeInTheWorld == ResolvedTypeX.MISSING) scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, getSourceLocation()); } } else { if (dim != 0) type = TypeX.makeArray(type, dim); TypePattern ret = new ExactTypePattern(type, includeSubtypes,isVarArgs); ret.copyLocationFrom(this); return ret; } } else { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } //XXX need to implement behavior for Lint.invalidWildcardTypeName } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } 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 { TypeX type = TypeX.forName(clazz.getName()); if (dim != 0) type = TypeX.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() { 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(ResolvedTypeX 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 (includeSubtypes) 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; 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(); 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); //??? 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); } 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(); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, varArg); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); ret.setAnnotationTypePattern(AnnotationTypePattern.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); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); return ret; } }
87,376
Bug 87376 NPE when unresolved type of a bound var in a pointcut expression (EclipseFactory.java:224)
see attached mini-project to reproduce
resolved fixed
85aa152
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-10T13:34:55Z
2005-03-08T13:53:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Mik Kersten revisions, added additional relationships * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.IOException; import java.util.*; import org.aspectj.ajdt.internal.compiler.ast.*; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.asm.*; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.*; import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.*; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemHandler; import org.aspectj.util.LangUtil; import org.aspectj.weaver.*; import org.aspectj.weaver.patterns.*; /** * At each iteration of <CODE>processCompilationUnit</CODE> the declarations for a * particular compilation unit are added to the hierarchy passed as a a parameter. * <p> * Clients who extend this class need to ensure that they do not override any of the existing * behavior. If they do, the structure model will not be built properly and tools such as IDE * structure views and ajdoc will fail. * <p> * <b>Note:</b> this class is not considered public API and the overridable * methods are subject to change. * * @author Mik Kersten */ public class AsmHierarchyBuilder extends ASTVisitor { protected AsmElementFormatter formatter = new AsmElementFormatter(); /** * Reset for every compilation unit. */ protected AjBuildConfig buildConfig; /** * Reset for every compilation unit. */ protected Stack stack; /** * Reset for every compilation unit. */ private CompilationResult currCompilationResult; /** * * @param cuDeclaration * @param buildConfig * @param structureModel hiearchy to add this unit's declarations to */ public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) { currCompilationResult = cuDeclaration.compilationResult(); LangUtil.throwIaxIfNull(currCompilationResult, "result"); stack = new Stack(); this.buildConfig = buildConfig; internalBuild(cuDeclaration, structureModel); // throw new RuntimeException("not implemented"); } private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) { LangUtil.throwIaxIfNull(structureModel, "structureModel"); if (!currCompilationResult.equals(unit.compilationResult())) { throw new IllegalArgumentException("invalid unit: " + unit); } // ---- summary // add unit to package (or root if no package), // first removing any duplicate (XXX? removes children if 3 classes in same file?) // push the node on the stack // and traverse // -- create node to add final File file = new File(new String(unit.getFileName())); final IProgramElement cuNode; { // AMC - use the source start and end from the compilation unit decl int startLine = getStartLine(unit); int endLine = getEndLine(unit); SourceLocation sourceLocation = new SourceLocation(file, startLine, endLine); sourceLocation.setOffset(unit.sourceStart); cuNode = new ProgramElement( new String(file.getName()), IProgramElement.Kind.FILE_JAVA, sourceLocation, 0, "", new ArrayList()); } cuNode.addChild(new ProgramElement( "import declarations", IProgramElement.Kind.IMPORT_REFERENCE, null, 0, "", new ArrayList())); final IProgramElement addToNode = genAddToNode(unit, structureModel); // -- remove duplicates before adding (XXX use them instead?) if (addToNode!=null && addToNode.getChildren()!=null) { for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) { IProgramElement child = (IProgramElement)itt.next(); ISourceLocation childLoc = child.getSourceLocation(); if (null == childLoc) { // XXX ok, packages have null source locations // signal others? } else if (childLoc.getSourceFile().equals(file)) { itt.remove(); } } } // -- add and traverse addToNode.addChild(cuNode); stack.push(cuNode); unit.traverse(this, unit.scope); // -- update file map (XXX do this before traversal?) try { structureModel.addToFileMap(file.getCanonicalPath(), cuNode); } catch (IOException e) { System.err.println("IOException " + e.getMessage() + " creating path for " + file ); // XXX signal IOException when canonicalizing file path } } /** * Get/create the node (package or root) to add to. */ private IProgramElement genAddToNode( CompilationUnitDeclaration unit, IHierarchy structureModel) { final IProgramElement addToNode; { ImportReference currentPackage = unit.currentPackage; if (null == currentPackage) { addToNode = structureModel.getRoot(); } else { String pkgName; { StringBuffer nameBuffer = new StringBuffer(); final char[][] importName = currentPackage.getImportName(); final int last = importName.length-1; for (int i = 0; i < importName.length; i++) { nameBuffer.append(new String(importName[i])); if (i < last) { nameBuffer.append('.'); } } pkgName = nameBuffer.toString(); } IProgramElement pkgNode = null; if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) { for (Iterator it = structureModel.getRoot().getChildren().iterator(); it.hasNext(); ) { IProgramElement currNode = (IProgramElement)it.next(); if (pkgName.equals(currNode.getName())) { pkgNode = currNode; break; } } } if (pkgNode == null) { // note packages themselves have no source location pkgNode = new ProgramElement( pkgName, IProgramElement.Kind.PACKAGE, new ArrayList() ); structureModel.getRoot().addChild(pkgNode); } addToNode = pkgNode; } } return addToNode; } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { String name = new String(typeDeclaration.name); IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT; else if (typeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE; else if (typeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM; else if (typeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION; IProgramElement peNode = new ProgramElement( name, kind, makeLocation(typeDeclaration), typeDeclaration.modifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(typeDeclaration)); peNode.setFormalComment(generateJavadocComment(typeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { stack.pop(); } // ??? share impl with visit(TypeDeclaration, ..) ? public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { String name = new String(memberTypeDeclaration.name); IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT; else if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE; else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM; else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION; IProgramElement peNode = new ProgramElement( name, kind, makeLocation(memberTypeDeclaration), memberTypeDeclaration.modifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration)); peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { stack.pop(); } public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) { String fullName = "<undefined>"; if (memberTypeDeclaration.allocation != null && memberTypeDeclaration.allocation.type != null) { // Create a name something like 'new Runnable() {..}' fullName = "new "+memberTypeDeclaration.allocation.type.toString()+"() {..}"; } else if (memberTypeDeclaration.binding != null && memberTypeDeclaration.binding.constantPoolName() != null) { // If we couldn't find a nice name like 'new Runnable() {..}' then use the number after the $ fullName = new String(memberTypeDeclaration.binding.constantPoolName()); int dollar = fullName.indexOf('$'); fullName = fullName.substring(dollar+1); } IProgramElement.Kind kind = IProgramElement.Kind.CLASS; if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE; else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM; else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION; IProgramElement peNode = new ProgramElement( fullName, kind, makeLocation(memberTypeDeclaration), memberTypeDeclaration.modifiers, "", new ArrayList()); peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration)); peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration memberTypeDeclaration, BlockScope scope) { stack.pop(); } private String genSourceSignature(TypeDeclaration typeDeclaration) { StringBuffer output = new StringBuffer(); typeDeclaration.printHeader(0, output); return output.toString(); } private IProgramElement findEnclosingClass(Stack stack) { for (int i = stack.size()-1; i >= 0; i--) { IProgramElement pe = (IProgramElement)stack.get(i); if (pe.getKind() == IProgramElement.Kind.CLASS) { return pe; } } return (IProgramElement)stack.peek(); } public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { IProgramElement peNode = null; // For intertype decls, use the modifiers from the original signature, not the generated method if (methodDeclaration instanceof InterTypeDeclaration) { InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration; ResolvedMember sig = itd.getSignature(); peNode = new ProgramElement( "", IProgramElement.Kind.ERROR, makeLocation(methodDeclaration), (sig!=null?sig.getModifiers():0), "", new ArrayList()); } else { peNode = new ProgramElement( "", IProgramElement.Kind.ERROR, makeLocation(methodDeclaration), methodDeclaration.modifiers, "", new ArrayList()); } formatter.genLabelAndKind(methodDeclaration, peNode); genBytecodeInfo(methodDeclaration, peNode); List namedPointcuts = genNamedPointcuts(methodDeclaration); addUsesPointcutRelationsForNode(peNode, namedPointcuts, methodDeclaration); if (methodDeclaration.returnType!=null) { peNode.setCorrespondingType(methodDeclaration.returnType.toString()); } else { peNode.setCorrespondingType(null); } peNode.setSourceSignature(genSourceSignature(methodDeclaration)); peNode.setFormalComment(generateJavadocComment(methodDeclaration)); // TODO: add return type test if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) { if (peNode.toLabelString().equals("main(String[])") && peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC) && peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) { ((IProgramElement)stack.peek()).setRunnable(true); } } stack.push(peNode); return true; } private void addUsesPointcutRelationsForNode(IProgramElement peNode, List namedPointcuts, MethodDeclaration declaration) { for (Iterator it = namedPointcuts.iterator(); it.hasNext();) { ReferencePointcut rp = (ReferencePointcut) it.next(); ResolvedMember member = getPointcutDeclaration(rp, declaration); if (member != null) { IRelationship foreward = AsmManager.getDefault().getRelationshipMap().get(peNode.getHandleIdentifier(), IRelationship.Kind.USES_POINTCUT, "uses pointcut", false, true); foreward.addTarget(ProgramElement.genHandleIdentifier(member.getSourceLocation())); IRelationship back = AsmManager.getDefault().getRelationshipMap().get(ProgramElement.genHandleIdentifier(member.getSourceLocation()), IRelationship.Kind.USES_POINTCUT, "pointcut used by", false, true); back.addTarget(peNode.getHandleIdentifier()); } } } private ResolvedMember getPointcutDeclaration(ReferencePointcut rp, MethodDeclaration declaration) { World world = ((AjLookupEnvironment)declaration.scope.environment()).factory.getWorld(); TypeX onType = rp.onType; if (onType == null) { Member member = EclipseFactory.makeResolvedMember(declaration.binding); onType = member.getDeclaringType(); } ResolvedMember[] members = onType.getDeclaredPointcuts(world); if (members != null) { for (int i = 0; i < members.length; i++) { if (members[i].getName().equals(rp.name)) { return members[i]; } } } return null; } /** * @param methodDeclaration * @return all of the named pointcuts referenced by the PCD of this declaration */ private List genNamedPointcuts(MethodDeclaration methodDeclaration) { List pointcuts = new ArrayList(); if (methodDeclaration instanceof AdviceDeclaration) { if (((AdviceDeclaration)methodDeclaration).pointcutDesignator != null) addAllNamed(((AdviceDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts); } else if (methodDeclaration instanceof PointcutDeclaration) { if (((PointcutDeclaration)methodDeclaration).pointcutDesignator != null) addAllNamed(((PointcutDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts); } return pointcuts; } /** * @param left * @param pointcuts accumulator for named pointcuts */ private void addAllNamed(Pointcut pointcut, List pointcuts) { if (pointcut == null) return; if (pointcut instanceof ReferencePointcut) { ReferencePointcut rp = (ReferencePointcut)pointcut; pointcuts.add(rp); } else if (pointcut instanceof AndPointcut) { AndPointcut ap = (AndPointcut)pointcut; addAllNamed(ap.getLeft(), pointcuts); addAllNamed(ap.getRight(), pointcuts); } else if (pointcut instanceof OrPointcut) { OrPointcut op = (OrPointcut)pointcut; addAllNamed(op.getLeft(), pointcuts); addAllNamed(op.getRight(), pointcuts); } } private String genSourceSignature(MethodDeclaration methodDeclaration) { StringBuffer output = new StringBuffer(); ASTNode.printModifiers(methodDeclaration.modifiers, output); methodDeclaration.printReturnType(0, output).append(methodDeclaration.selector).append('('); if (methodDeclaration.arguments != null) { for (int i = 0; i < methodDeclaration.arguments.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ methodDeclaration.arguments[i].print(0, output); } } output.append(')'); if (methodDeclaration.thrownExceptions != null) { output.append(" throws "); //$NON-NLS-1$ for (int i = 0; i < methodDeclaration.thrownExceptions.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ methodDeclaration.thrownExceptions[i].print(0, output); } } return output.toString(); } protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) { if (methodDeclaration.binding != null) { String memberName = ""; String memberBytecodeSignature = ""; try { Member member = EclipseFactory.makeResolvedMember(methodDeclaration.binding); memberName = member.getName(); memberBytecodeSignature = member.getSignature(); } catch (BCException bce) { // bad type name memberName = "<undefined>"; } catch (NullPointerException npe) { memberName = "<undefined>"; } peNode.setBytecodeName(memberName); peNode.setBytecodeSignature(memberBytecodeSignature); } ((IProgramElement)stack.peek()).addChild(peNode); } public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) { stack.pop(); } public boolean visit(ImportReference importRef, CompilationUnitScope scope) { int dotIndex = importRef.toString().lastIndexOf('.'); String currPackageImport = ""; if (dotIndex != -1) { currPackageImport = importRef.toString().substring(0, dotIndex); } if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) { IProgramElement peNode = new ProgramElement( new String(importRef.toString()), IProgramElement.Kind.IMPORT_REFERENCE, makeLocation(importRef), 0, "", new ArrayList()); ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0); imports.addChild(0, peNode); stack.push(peNode); } return true; } public void endVisit(ImportReference importRef, CompilationUnitScope scope) { int dotIndex = importRef.toString().lastIndexOf('.'); String currPackageImport = ""; if (dotIndex != -1) { currPackageImport = importRef.toString().substring(0, dotIndex); } if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) { stack.pop(); } } public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { IProgramElement peNode = null; if (fieldDeclaration.type == null) { // The field represents an enum value peNode = new ProgramElement( new String(fieldDeclaration.name),IProgramElement.Kind.ENUM_VALUE, makeLocation(fieldDeclaration), fieldDeclaration.modifiers, "", new ArrayList()); peNode.setCorrespondingType(fieldDeclaration.binding.type.debugName()); } else { peNode = new ProgramElement( new String(fieldDeclaration.name),IProgramElement.Kind.FIELD, makeLocation(fieldDeclaration), fieldDeclaration.modifiers, "", new ArrayList()); peNode.setCorrespondingType(fieldDeclaration.type.toString()); } peNode.setSourceSignature(genSourceSignature(fieldDeclaration)); peNode.setFormalComment(generateJavadocComment(fieldDeclaration)); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) { stack.pop(); } /** * Checks if comments should be added to the model before generating. */ protected String generateJavadocComment(ASTNode astNode) { if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null; StringBuffer sb = new StringBuffer(); // !!! specify length? boolean completed = false; int startIndex = -1; if (astNode instanceof MethodDeclaration) { startIndex = ((MethodDeclaration)astNode).declarationSourceStart; } else if (astNode instanceof FieldDeclaration) { startIndex = ((FieldDeclaration)astNode).declarationSourceStart; } else if (astNode instanceof TypeDeclaration) { startIndex = ((TypeDeclaration)astNode).declarationSourceStart; } if (startIndex == -1) { return null; } else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /** && currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*' && currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') { for (int i = startIndex; i < astNode.sourceStart && !completed; i++) { char curr = currCompilationResult.compilationUnit.getContents()[i]; if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */ sb.append(currCompilationResult.compilationUnit.getContents()[i]); } return sb.toString(); } else { return null; } } /** * Doesn't print qualified allocation expressions. */ protected String genSourceSignature(FieldDeclaration fieldDeclaration) { StringBuffer output = new StringBuffer(); FieldDeclaration.printModifiers(fieldDeclaration.modifiers, output); if (fieldDeclaration.type == null) { // This is an enum value output.append(fieldDeclaration.binding.type.debugName()).append(" ").append(fieldDeclaration.name); } else { fieldDeclaration.type.print(0, output).append(' ').append(fieldDeclaration.name); } if (fieldDeclaration.initialization != null && !(fieldDeclaration.initialization instanceof QualifiedAllocationExpression)) { output.append(" = "); //$NON-NLS-1$ if (fieldDeclaration.initialization instanceof ExtendedStringLiteral) { output.append("\"<extended string literal>\""); } else { fieldDeclaration.initialization.printExpression(0, output); } } output.append(';'); return output.toString(); } // public boolean visit(ImportReference importRef, CompilationUnitScope scope) { // ProgramElementNode peNode = new ProgramElementNode( // new String(importRef.toString()), // ProgramElementNode.Kind., // makeLocation(importRef), // 0, // "", // new ArrayList()); // ((IProgramElement)stack.peek()).addChild(0, peNode); // stack.push(peNode); // return true; // } // public void endVisit(ImportReference importRef,CompilationUnitScope scope) { // stack.pop(); // } public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { if (constructorDeclaration.isDefaultConstructor) { stack.push(null); // a little wierd but does the job return true; } StringBuffer argumentsSignature = new StringBuffer(); argumentsSignature.append("("); if (constructorDeclaration.arguments!=null) { for (int i = 0;i<constructorDeclaration.arguments.length;i++) { argumentsSignature.append(constructorDeclaration.arguments[i]); if (i+1<constructorDeclaration.arguments.length) argumentsSignature.append(","); } } argumentsSignature.append(")"); IProgramElement peNode = new ProgramElement( new String(constructorDeclaration.selector)+argumentsSignature, IProgramElement.Kind.CONSTRUCTOR, makeLocation(constructorDeclaration), constructorDeclaration.modifiers, "", new ArrayList()); peNode.setModifiers(constructorDeclaration.modifiers); peNode.setSourceSignature(genSourceSignature(constructorDeclaration)); // Fix to enable us to anchor things from ctor nodes if (constructorDeclaration.binding != null) { String memberName = ""; String memberBytecodeSignature = ""; try { Member member = EclipseFactory.makeResolvedMember(constructorDeclaration.binding); memberName = member.getName(); memberBytecodeSignature = member.getSignature(); } catch (BCException bce) { // bad type name memberName = "<undefined>"; } catch (NullPointerException npe) { memberName = "<undefined>"; } peNode.setBytecodeName(memberName); peNode.setBytecodeSignature(memberBytecodeSignature); } ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { stack.pop(); } private String genSourceSignature(ConstructorDeclaration constructorDeclaration) { StringBuffer output = new StringBuffer(); ASTNode.printModifiers(constructorDeclaration.modifiers, output); output.append(constructorDeclaration.selector).append('('); if (constructorDeclaration.arguments != null) { for (int i = 0; i < constructorDeclaration.arguments.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ constructorDeclaration.arguments[i].print(0, output); } } output.append(')'); if (constructorDeclaration.thrownExceptions != null) { output.append(" throws "); //$NON-NLS-1$ for (int i = 0; i < constructorDeclaration.thrownExceptions.length; i++) { if (i > 0) output.append(", "); //$NON-NLS-1$ constructorDeclaration.thrownExceptions[i].print(0, output); } } return output.toString(); } // public boolean visit(Clinit clinit, ClassScope scope) { // ProgramElementNode peNode = new ProgramElementNode( // "<clinit>", // ProgramElementNode.Kind.INITIALIZER, // makeLocation(clinit), // clinit.modifiers, // "", // new ArrayList()); // ((IProgramElement)stack.peek()).addChild(peNode); // stack.push(peNode); // return false; // } // public void endVisit(Clinit clinit, ClassScope scope) { // stack.pop(); // } /** This method works-around an odd traverse implementation on Initializer */ private Initializer inInitializer = null; public boolean visit(Initializer initializer, MethodScope scope) { if (initializer == inInitializer) return false; inInitializer = initializer; IProgramElement peNode = new ProgramElement( "...", IProgramElement.Kind.INITIALIZER, makeLocation(initializer), initializer.modifiers, "", new ArrayList()); ((IProgramElement)stack.peek()).addChild(peNode); stack.push(peNode); initializer.block.traverse(this, scope); stack.pop(); return false; } // ??? handle non-existant files protected ISourceLocation makeLocation(ASTNode node) { String fileName = ""; if (currCompilationResult.getFileName() != null) { fileName = new String(currCompilationResult.getFileName()); } // AMC - different strategies based on node kind int startLine = getStartLine(node); int endLine = getEndLine(node); SourceLocation loc = null; if ( startLine <= endLine ) { // found a valid end line for this node... loc = new SourceLocation(new File(fileName), startLine, endLine); loc.setOffset(node.sourceStart); } else { loc = new SourceLocation(new File(fileName), startLine); loc.setOffset(node.sourceStart); } return loc; } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! protected int getStartLine( ASTNode n){ // if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n); // if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n); // if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n); return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, n.sourceStart); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! protected int getEndLine( ASTNode n){ if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n); if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n); if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n); return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, n.sourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( AbstractVariableDeclaration avd ) { // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // avd.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( AbstractVariableDeclaration avd ){ return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, avd.declarationSourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( AbstractMethodDeclaration amd ){ // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // amd.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( AbstractMethodDeclaration amd) { return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, amd.declarationSourceEnd); } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! // private int getStartLine( TypeDeclaration td ){ // return ProblemHandler.searchLineNumber( // currCompilationResult.lineSeparatorPositions, // td.declarationSourceStart); // } // AMC - overloaded set of methods to get start and end lines for // various ASTNode types. They have no common ancestor in the // hierarchy!! private int getEndLine( TypeDeclaration td){ return ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, td.declarationSourceEnd); } }
87,376
Bug 87376 NPE when unresolved type of a bound var in a pointcut expression (EclipseFactory.java:224)
see attached mini-project to reproduce
resolved fixed
85aa152
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-10T13:34:55Z
2005-03-08T13:53:20Z
tests/bugs150/pr87376/I.java
87,376
Bug 87376 NPE when unresolved type of a bound var in a pointcut expression (EclipseFactory.java:224)
see attached mini-project to reproduce
resolved fixed
85aa152
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-10T13:34:55Z
2005-03-08T13:53:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import 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; /** * 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 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 (System.getProperty("java.vm.version").startsWith("1.5")) { 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); } } // 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,652
Bug 88652 an array type as the last parameter in a signature does not match on the varargs declared method
I get this warning in my code, though I actually do not specify an array type. The signature I want to match is the following constructor signature: public Touple(Object formulaHandle, Object... propositions) {...} Touple implements IRelation The pointcut I use is the following: pointcut p(): call(Touple.new(..)); This should actually match the signature, shouldn't it? AspectJ however complains with this warning: an array type as the last parameter in a signature does not match on the varargs declared method: void ltlrv.Touple.<init>(java.lang.Object, java.lang.Object[]) [Xlint:cantMatchArrayTypeOnVarargs] Also, even if I *had* stated an array type, it should match even then IMHO, since arrays and varargs are actually the same in the Java implementation.
resolved fixed
b5f4d09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-22T13:14:44Z
2005-03-21T15: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; /** * 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 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 (System.getProperty("java.vm.version").startsWith("1.5")) { 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"); } // 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,652
Bug 88652 an array type as the last parameter in a signature does not match on the varargs declared method
I get this warning in my code, though I actually do not specify an array type. The signature I want to match is the following constructor signature: public Touple(Object formulaHandle, Object... propositions) {...} Touple implements IRelation The pointcut I use is the following: pointcut p(): call(Touple.new(..)); This should actually match the signature, shouldn't it? AspectJ however complains with this warning: an array type as the last parameter in a signature does not match on the varargs declared method: void ltlrv.Touple.<init>(java.lang.Object, java.lang.Object[]) [Xlint:cantMatchArrayTypeOnVarargs] Also, even if I *had* stated an array type, it should match even then IMHO, since arrays and varargs are actually the same in the Java implementation.
resolved fixed
b5f4d09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-22T13:14:44Z
2005-03-21T15:46: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.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.VersionedDataInputStream; public class ExactTypePattern extends TypePattern { protected TypeX 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(TypeX type, boolean includeSubtypes,boolean isVarArgs) { super(includeSubtypes,isVarArgs); this.type = type; } /* (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 TypeX otherType = other.getExactType(); if (otherType != ResolvedTypeX.MISSING) { return type.equals(otherType); } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String yourSimpleNamePrefix = owtp.namePatterns[0].maybeGetSimpleName(); if (yourSimpleNamePrefix != null) { return (type.getName().startsWith(yourSimpleNamePrefix)); } } return true; } protected boolean matchesExactly(ResolvedTypeX matchType) { boolean typeMatch = this.type.equals(matchType); annotationPattern.resolve(matchType.getWorld()); boolean annMatch = this.annotationPattern.matches(matchType).alwaysTrue(); return (typeMatch && annMatch); } protected boolean matchesExactly(ResolvedTypeX matchType, ResolvedTypeX annotatedType) { boolean typeMatch = this.type.equals(matchType); annotationPattern.resolve(matchType.getWorld()); boolean annMatch = this.annotationPattern.matches(annotatedType).alwaysTrue(); return (typeMatch && annMatch); } public TypeX getType() { return type; } public FuzzyBoolean matchesInstanceof(ResolvedTypeX matchType) { // in our world, Object is assignable from anything if (type.equals(ResolvedTypeX.OBJECT)) return FuzzyBoolean.YES.and(annotationPattern.matches(matchType)); if (type.isAssignableFrom(matchType, matchType.getWorld())) { return FuzzyBoolean.YES.and(annotationPattern.matches(matchType)); } // fix for PR 64262 - shouldn't try to coerce primitives if (type.isPrimitive()) { return FuzzyBoolean.NO; } else { return matchType.isCoerceableFrom(type) ? 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; 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); 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(TypeX.read(s), s.readBoolean(), s.readBoolean()); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); ret.readLocation(context, s); return ret; } public static TypePattern readTypePatternOldStyle(DataInputStream s, ISourceContext context) throws IOException { TypePattern ret = new ExactTypePattern(TypeX.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"); } }
88,652
Bug 88652 an array type as the last parameter in a signature does not match on the varargs declared method
I get this warning in my code, though I actually do not specify an array type. The signature I want to match is the following constructor signature: public Touple(Object formulaHandle, Object... propositions) {...} Touple implements IRelation The pointcut I use is the following: pointcut p(): call(Touple.new(..)); This should actually match the signature, shouldn't it? AspectJ however complains with this warning: an array type as the last parameter in a signature does not match on the varargs declared method: void ltlrv.Touple.<init>(java.lang.Object, java.lang.Object[]) [Xlint:cantMatchArrayTypeOnVarargs] Also, even if I *had* stated an array type, it should match even then IMHO, since arrays and varargs are actually the same in the Java implementation.
resolved fixed
b5f4d09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-22T13:14:44Z
2005-03-21T15:46: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 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.Constants; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.World; 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(ResolvedTypeX enclosingType) { if (returnType != null) { returnType.postRead(enclosingType); } if (declaringType != null) { declaringType.postRead(enclosingType); } if (parameterTypes != null) { parameterTypes.postRead(enclosingType); } } public boolean matches(Member member, World world) { return (matchesIgnoringAnnotations(member,world) && matchesAnnotations(member,world)); } public boolean matchesAnnotations(Member member,World world) { ResolvedMember rMember = member.resolve(world); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return false; } world.getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return false; } annotationPattern.resolve(world); return annotationPattern.matches(rMember).alwaysTrue(); } public boolean matchesIgnoringAnnotations(Member member, World world) { //XXX performance gains would come from matching on name before resolving // to fail fast. ASC 30th Nov 04 => Not necessarily, it didn't make it faster for me. // Here is the code I used: // String n1 = member.getName(); // String n2 = this.getName().maybeGetSimpleName(); // if (n2!=null && !n1.equals(n2)) return false; // FIXME ASC : if (member == null) return false; ResolvedMember sig = member.resolve(world); if (sig == null) { //XXX if (member.getName().startsWith(NameMangler.PREFIX)) { return false; } world.getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return false; } // Java5 introduces bridge methods, we don't want to match on them at all... if (sig.isBridgeMethod()) { return false; } // This check should only matter when used from WithincodePointcut as KindedPointcut // has already effectively checked this with the shadows kind. if (kind != member.getKind()) { 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().resolve(world)); } else if (kind == Member.FIELD) { if (!returnType.matchesStatically(sig.getReturnType().resolve(world))) return false; if (!name.matches(sig.getName())) return false; boolean ret = declaringTypeMatch(member.getDeclaringType(), member, world); //System.out.println(" ret: " + ret); return ret; } else if (kind == Member.METHOD) { // Change all this in the face of covariance... // Check the name if (!name.matches(sig.getName())) return false; // Check the parameters if (!parameterTypes.matches(world.resolve(sig.getParameterTypes()), TypePattern.STATIC).alwaysTrue()) { return false; } // If we have matched on parameters, let's just check it isn't because the last parameter in the pattern // is an array type and the method is declared with varargs // XXX - Ideally the shadow would be included in the msg but we don't know it... if (isNotMatchBecauseOfVarargsIssue(parameterTypes,sig.getModifiers())) { world.getLint().cantMatchArrayTypeOnVarargs.signal(sig.toString(),getSourceLocation()); return false; } if (parameterTypes.size()>0 && (sig.isVarargsMethod()^parameterTypes.get(parameterTypes.size()-1).isVarArgs)) return false; // Check the throws pattern if (!throwsPattern.matches(sig.getExceptions(), world)) return false; return declaringTypeMatchAllowingForCovariance(member,world,returnType,sig.getReturnType().resolve(world)); } else if (kind == Member.CONSTRUCTOR) { if (!parameterTypes.matches(world.resolve(sig.getParameterTypes()), TypePattern.STATIC).alwaysTrue()) { return false; } // If we have matched on parameters, let's just check it isn't because the last parameter in the pattern // is an array type and the method is declared with varargs // XXX - Ideally the shadow would be included in the msg but we don't know it... if (isNotMatchBecauseOfVarargsIssue(parameterTypes,sig.getModifiers())) { world.getLint().cantMatchArrayTypeOnVarargs.signal(sig.toString(),getSourceLocation()); return false; } if (!throwsPattern.matches(sig.getExceptions(), world)) return false; return declaringType.matchesStatically(member.getDeclaringType().resolve(world)); //return declaringTypeMatch(member.getDeclaringType(), member, world); } return false; } public boolean declaringTypeMatchAllowingForCovariance(Member member,World world,TypePattern returnTypePattern,ResolvedTypeX sigReturn) { TypeX onTypeUnresolved = member.getDeclaringType(); ResolvedTypeX onType = onTypeUnresolved.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(); ) { ResolvedTypeX type = (ResolvedTypeX)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 TypeX returnTypeX = rm.getReturnType(); ResolvedTypeX 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 (isNotMatchBecauseOfVarargsIssue(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 (isNotMatchBecauseOfVarargsIssue(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 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 (isNotMatchBecauseOfVarargsIssue(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 (isNotMatchBecauseOfVarargsIssue(parameterTypes,member.getModifiers())) { return false; } if (!throwsPattern.matches(exceptionTypes)) return false; return declaringType.matchesStatically(declaringClass); } return false; } // For methods, the above covariant aware version (declaringTypeMatchAllowingForCovariance) is used - this version is still here for fields private boolean declaringTypeMatch(TypeX onTypeUnresolved, Member member, World world) { ResolvedTypeX onType = onTypeUnresolved.resolve(world); // fastmatch if (declaringType.matchesStatically(onType)) return true; Collection declaringTypes = member.getDeclaringTypes(world); for (Iterator i = declaringTypes.iterator(); i.hasNext(); ) { ResolvedTypeX type = (ResolvedTypeX)i.next(); if (declaringType.matchesStatically(type)) return true; } 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 { Method m = (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>()"); } 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()); } } 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 isNotMatchBecauseOfVarargsIssue(TypePatternList params,int modifiers) { if (params.size()>0 && (modifiers & Constants.ACC_VARARGS)!=0 && // XXX Promote this to an isVarargs() on MethodSignature? !params.get(params.size()-1).isVarArgs) { return true; } return false; } public AnnotationTypePattern getAnnotationPattern() { return annotationPattern; } public boolean isStarAnnotation() { return annotationPattern == AnnotationTypePattern.ANY; } }
88,652
Bug 88652 an array type as the last parameter in a signature does not match on the varargs declared method
I get this warning in my code, though I actually do not specify an array type. The signature I want to match is the following constructor signature: public Touple(Object formulaHandle, Object... propositions) {...} Touple implements IRelation The pointcut I use is the following: pointcut p(): call(Touple.new(..)); This should actually match the signature, shouldn't it? AspectJ however complains with this warning: an array type as the last parameter in a signature does not match on the varargs declared method: void ltlrv.Touple.<init>(java.lang.Object, java.lang.Object[]) [Xlint:cantMatchArrayTypeOnVarargs] Also, even if I *had* stated an array type, it should match even then IMHO, since arrays and varargs are actually the same in the Java implementation.
resolved fixed
b5f4d09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-22T13:14:44Z
2005-03-21T15:46: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.util.Iterator; 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.ResolvedTypeX; import org.aspectj.weaver.TypeX; 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 TypePattern(boolean includeSubtypes,boolean isVarArgs) { this.includeSubtypes = includeSubtypes; this.isVarArgs = isVarArgs; } public boolean isStarAnnotation() { return annotationPattern == AnnotationTypePattern.ANY; } protected TypePattern(boolean includeSubtypes) { this(includeSubtypes,false); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { this.annotationPattern = annPatt; } 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(ResolvedTypeX type) { if (includeSubtypes) { return matchesSubtypes(type); } else { return matchesExactly(type); } } public abstract FuzzyBoolean matchesInstanceof(ResolvedTypeX type); public final FuzzyBoolean matches(ResolvedTypeX type, MatchKind kind) { FuzzyBoolean typeMatch = null; //??? This is part of gracefully handling missing references if (type == ResolvedTypeX.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(ResolvedTypeX type); protected abstract boolean matchesExactly(ResolvedTypeX type, ResolvedTypeX annotatedType); protected boolean matchesSubtypes(ResolvedTypeX 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(); ) { ResolvedTypeX superType = (ResolvedTypeX)i.next(); if (matchesSubtypes(superType,type)) return true; } return false; } protected boolean matchesSubtypes(ResolvedTypeX superType, ResolvedTypeX 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(); ) { ResolvedTypeX superSuperType = (ResolvedTypeX)i.next(); if (matchesSubtypes(superSuperType,annotatedType)) return true; } return false; } public TypeX resolveExactType(IScope scope, Bindings bindings) { TypePattern p = resolveBindings(scope, bindings, false, true); if (p == NO) return ResolvedTypeX.MISSING; return ((ExactTypePattern)p).getType(); } public TypeX getExactType() { if (this instanceof ExactTypePattern) return ((ExactTypePattern)this).getType(); else return ResolvedTypeX.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); } public void postRead(ResolvedTypeX 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 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); } 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); } /* (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(ResolvedTypeX type) { return false; } protected boolean matchesExactly(ResolvedTypeX type, ResolvedTypeX annotatedType) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedTypeX 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; } } class AnyTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public AnyTypePattern() { super(false,false); } /* (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(ResolvedTypeX type) { return true; } protected boolean matchesExactly(ResolvedTypeX type, ResolvedTypeX annotatedType) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedTypeX 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(ResolvedTypeX 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; } } /** * 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; } protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } protected boolean matchesExactly(ResolvedTypeX type) { annotationPattern.resolve(type.getWorld()); return annotationPattern.matches(type).alwaysTrue(); } protected boolean matchesExactly(ResolvedTypeX type, ResolvedTypeX annotatedType) { annotationPattern.resolve(type.getWorld()); return annotationPattern.matches(annotatedType).alwaysTrue(); } public FuzzyBoolean matchesInstanceof(ResolvedTypeX type) { return FuzzyBoolean.YES; } protected boolean matchesExactly(Class type) { return true; } public FuzzyBoolean matchesInstanceof(Class type) { return FuzzyBoolean.YES; } 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(ResolvedTypeX 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)); } public int hashCode() { return annotationPattern.hashCode(); } } class NoTypePattern extends TypePattern { public NoTypePattern() { super(false,false); } /* (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(ResolvedTypeX type) { return false; } protected boolean matchesExactly(ResolvedTypeX type, ResolvedTypeX annotatedType) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedTypeX 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(ResolvedTypeX type) { return false; } public boolean isStar() { return false; } public String toString() { return "<nothing>"; } /* (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; } }
88,652
Bug 88652 an array type as the last parameter in a signature does not match on the varargs declared method
I get this warning in my code, though I actually do not specify an array type. The signature I want to match is the following constructor signature: public Touple(Object formulaHandle, Object... propositions) {...} Touple implements IRelation The pointcut I use is the following: pointcut p(): call(Touple.new(..)); This should actually match the signature, shouldn't it? AspectJ however complains with this warning: an array type as the last parameter in a signature does not match on the varargs declared method: void ltlrv.Touple.<init>(java.lang.Object, java.lang.Object[]) [Xlint:cantMatchArrayTypeOnVarargs] Also, even if I *had* stated an array type, it should match even then IMHO, since arrays and varargs are actually the same in the Java implementation.
resolved fixed
b5f4d09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-22T13:14:44Z
2005-03-21T15:46: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 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.ISourceContext; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; //XXX need to use dim in matching public class WildTypePattern extends TypePattern { NamePattern[] namePatterns; int ellipsisCount; String[] importedPrefixes; String[] knownMatches; int dim; WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim, boolean isVarArgs) { super(includeSubtypes,isVarArgs); 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); } 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; } // 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 TypeX otherType = other.getExactType(); if (otherType != ResolvedTypeX.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(ResolvedTypeX type) { return matchesExactly(type,type); } protected boolean matchesExactly(ResolvedTypeX type, ResolvedTypeX 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) && annotationPattern.matches(annotatedType).alwaysTrue(); } /** * Used in conjunction with checks on 'isStar()' to tell you if this pattern represents '*' or '*[]' which are * different ! */ public int getDimensions() { return dim; } /** * @param targetTypeName * @return */ private boolean matchesExactlyByName(String targetTypeName) { //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(ResolvedTypeX 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() { //System.err.println("extract from : " + Arrays.asList(namePatterns)); int len = namePatterns.length; 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(); } /** * 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()) { // 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) { // 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; } } annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); 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; } } String cleanName = maybeGetCleanName(); String originalName = cleanName; // if we discover it is 'MISSING' when searching via the scope, this next local var will // tell us if it is really missing or if it does exist in the world and we just can't // see it from the current scope. ResolvedTypeX resolvedTypeInTheWorld = null; if (cleanName != null) { TypeX type; //System.out.println("resolve: " + cleanName); //??? this loop has too many inefficiencies to count resolvedTypeInTheWorld = scope.getWorld().resolve(TypeX.forName(cleanName),true); while ((type = scope.lookupType(cleanName, this)) == ResolvedTypeX.MISSING) { int lastDot = cleanName.lastIndexOf('.'); if (lastDot == -1) break; cleanName = cleanName.substring(0, lastDot) + '$' + cleanName.substring(lastDot+1); if (resolvedTypeInTheWorld == ResolvedTypeX.MISSING) resolvedTypeInTheWorld = scope.getWorld().resolve(TypeX.forName(cleanName),true); } if (type == ResolvedTypeX.MISSING) { if (requireExactType) { if (!allowBinding) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE,originalName), getSourceLocation())); } else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) { scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, 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 (resolvedTypeInTheWorld == ResolvedTypeX.MISSING) scope.getWorld().getLint().invalidAbsoluteTypeName.signal(originalName, getSourceLocation()); } } else { if (dim != 0) type = TypeX.makeArray(type, dim); TypePattern ret = new ExactTypePattern(type, includeSubtypes,isVarArgs); ret.setAnnotationTypePattern(annotationPattern); ret.copyLocationFrom(this); return ret; } } else { if (requireExactType) { scope.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED), getSourceLocation())); return NO; } //XXX need to implement behavior for Lint.invalidWildcardTypeName } importedPrefixes = scope.getImportedPrefixes(); knownMatches = preMatch(scope.getImportedNames()); return this; } 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 { TypeX type = TypeX.forName(clazz.getName()); if (dim != 0) type = TypeX.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(ResolvedTypeX 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 (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; 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(); 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); //??? 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); } 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(); WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, varArg); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); ret.setAnnotationTypePattern(AnnotationTypePattern.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); ret.knownMatches = FileUtil.readStringArray(s); ret.importedPrefixes = FileUtil.readStringArray(s); ret.readLocation(context, s); return ret; } }
76,055
Bug 76055 Some Pointcut PatternNodes are missing getters to traverse syntax tree
In order to find out which other pointcuts are referenced by a pointcut definition i need to access the private members of the CflowPointcut, IfPointcut and NotPointcut PatternNodes found in the weaver module. Unlike the OrPointcut and AndPointcut classes, they are missing the appropriate getter methods.
resolved fixed
b0f270e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T13:45:09Z
2004-10-12T08:33:20Z
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.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeX; 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 private 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, TypeX.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; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } /* (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(ResolvedTypeX inAspect, 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; ResolvedTypeX 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, 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 ResolvedMember(Member.FIELD,concreteAspect,Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL, NameMangler.cflowCounter(xcut),TypeX.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); ResolvedTypeX 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 ResolvedMember( Member.FIELD, concreteAspect, Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL, NameMangler.cflowStack(xcut), TypeX.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); } } }
76,055
Bug 76055 Some Pointcut PatternNodes are missing getters to traverse syntax tree
In order to find out which other pointcuts are referenced by a pointcut definition i need to access the private members of the CflowPointcut, IfPointcut and NotPointcut PatternNodes found in the weaver module. Unlike the OrPointcut and AndPointcut classes, they are missing the appropriate getter methods.
resolved fixed
b0f270e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T13:45:09Z
2004-10-12T08:33:20Z
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 * ******************************************************************/ 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.List; 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.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; 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; 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; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } protected FuzzyBoolean matchInternal(Shadow shadow) { //??? this is not maximally efficient return FuzzyBoolean.MAYBE; } public boolean alwaysFalse() { return false; } public boolean alwaysTrue() { return false; } /* (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); testMethod.write(s); s.writeByte(extraParameterFlags); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { IfPointcut ret = new IfPointcut(ResolvedMember.readResolvedMember(s, context), 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() { return "if(" + testMethod + ")"; } //??? 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; protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (findingResidue) return Literal.TRUE; findingResidue = true; try { ExposedState myState = new ExposedState(baseArgsCount); //System.out.println(residueSource); //??? we throw out the test that comes from this walk. All we want here // is bindings for the arguments residueSource.findResidue(shadow, myState); //System.out.println(myState); Test ret = Literal.TRUE; List args = new ArrayList(); 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()); } ret = Test.makeAnd(ret, Test.makeCall(testMethod, (Expr[])args.toArray(new Expr[args.size()]))); 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(ResolvedTypeX inAspect, IntMap bindings) { // return this.concretize1(inAspect, bindings); // } protected boolean shouldCopyLocationForConcretize() { return false; } private IfPointcut partiallyConcretized = null; public Pointcut concretize1(ResolvedTypeX inAspect, 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; } IfPointcut 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, 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; IntMap newBindings = IntMap.idMap(ret.baseArgsCount); newBindings.copyContext(bindings); ret.residueSource = def.getPointcut().concretize(inAspect, newBindings); } return ret; } // 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; } private static class IfFalsePointcut extends IfPointcut { public IfFalsePointcut() { super(null,0); } 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(ResolvedTypeX enclosingType) { } public Pointcut concretize1( ResolvedTypeX inAspect, 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; } private static class IfTruePointcut extends IfPointcut { public IfTruePointcut() { super(null,0); } 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(ResolvedTypeX enclosingType) { } public Pointcut concretize1( ResolvedTypeX inAspect, 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)"; } } }
84,122
Bug 84122 Allow aspectPath to contain directories
The -aspectpath option to the compiler only allows jar/zip files, not directories. But inpath and classpath allow directories. This capability would improve the handling of aspects spanning multiple projects in Eclipse. AJDT can currently only support jar/zip files on the aspect path, which requires one of the projects to create an outjar instead of writing to the bin directory as usual. The iajc ant task could then also be enhanced to support aspectpath directories.
resolved fixed
68f6350
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T16:47:55Z
2005-02-01T09:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.ajc; import java.io.*; import java.util.*; import org.aspectj.ajdt.internal.core.builder.*; import org.aspectj.bridge.*; import org.aspectj.util.*; import org.aspectj.weaver.Dump; import org.aspectj.weaver.WeaverMessages; import org.aspectj.org.eclipse.jdt.core.compiler.InvalidInputException; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.Main; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; public class BuildArgParser extends Main { private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages"; private static boolean LOADED_BUNDLE = false; static { bundle = ResourceBundle.getBundle(BUNDLE_NAME); if (!LOADED_BUNDLE) { LOADED_BUNDLE = true; } } /** to initialize super's PrintWriter but refer to underlying StringWriter */ private static class StringPrintWriter extends PrintWriter { public final StringWriter stringWriter; StringPrintWriter(StringWriter sw) { super(sw); this.stringWriter = sw; } } /** @return multi-line String usage for the compiler */ public static String getUsage() { return Main.bind("misc.usage"); } public static String getXOptionUsage() { return Main.bind("xoption.usage"); } /** * StringWriter sink for some errors. * This only captures errors not handled by any IMessageHandler parameter * and only when no PrintWriter is set in the constructor. * XXX This relies on (Sun's) implementation of StringWriter, * which returns the actual (not copy) internal StringBuffer. */ private final StringBuffer errorSink; private IMessageHandler handler; /** * Overrides super's bundle. */ public BuildArgParser(PrintWriter writer, IMessageHandler handler) { super(writer, writer, false); if (writer instanceof StringPrintWriter) { errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer(); } else { errorSink = null; } this.handler = handler; } /** Set up to capture messages using getOtherMessages(boolean) */ public BuildArgParser(IMessageHandler handler) { this(new StringPrintWriter(new StringWriter()),handler); } /** * Generate build configuration for the input args, * passing to handler any error messages. * @param args the String[] arguments for the build configuration * @return AjBuildConfig per args, * which will be invalid unless there are no handler errors. */ public AjBuildConfig genBuildConfig(String[] args) { AjBuildConfig config = new AjBuildConfig(); populateBuildConfig(config, args, true, null); return config; } /** * Generate build configuration for the input args, * passing to handler any error messages. * @param args the String[] arguments for the build configuration * @param setClasspath determines if the classpath should be parsed and set on the build configuration * @param configFile can be null * @return AjBuildConfig per args, * which will be invalid unless there are no handler errors. */ public AjBuildConfig populateBuildConfig(AjBuildConfig buildConfig, String[] args, boolean setClasspath, File configFile) { Dump.saveCommandLine(args); buildConfig.setConfigFile(configFile); try { // sets filenames to be non-null in order to make sure that file paramters are ignored super.filenames = new String[] { "" }; AjcConfigParser parser = new AjcConfigParser(buildConfig, handler); parser.parseCommandLine(args); boolean swi = buildConfig.getShowWeavingInformation(); // Now jump through firey hoops to turn them on/off if (handler instanceof CountingMessageHandler) { IMessageHandler delegate = ((CountingMessageHandler)handler).delegate; // Without dontIgnore() on the IMessageHandler interface, we have to do this *blurgh* if (delegate instanceof MessageHandler) { if (swi) ((MessageHandler)delegate).dontIgnore(IMessage.WEAVEINFO); else ((MessageHandler)delegate).ignore(IMessage.WEAVEINFO); } } boolean incrementalMode = buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode(); List fileList = new ArrayList(); List files = parser.getFiles(); if (!LangUtil.isEmpty(files)) { if (incrementalMode) { MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots"); } else { fileList.addAll(files); } } List javaArgList = new ArrayList(); // disable all special eclipse warnings by default - why??? //??? might want to instead override getDefaultOptions() javaArgList.add("-warn:none"); // these next four lines are some nonsense to fool the eclipse batch compiler // without these it will go searching for reasonable values from properties //TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed javaArgList.add("-classpath"); javaArgList.add(System.getProperty("user.dir")); javaArgList.add("-bootclasspath"); javaArgList.add(System.getProperty("user.dir")); javaArgList.addAll(parser.getUnparsedArgs()); super.configure((String[])javaArgList.toArray(new String[javaArgList.size()])); if (!proceed) { buildConfig.doNotProceed(); return buildConfig; } if (buildConfig.getSourceRoots() != null) { for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) { fileList.addAll(collectSourceRootFiles((File)i.next())); } } buildConfig.setFiles(fileList); if (destinationPath != null) { // XXX ?? unparsed but set? buildConfig.setOutputDir(new File(destinationPath)); } if (setClasspath) { buildConfig.setClasspath(getClasspath(parser)); buildConfig.setBootclasspath(getBootclasspath(parser)); } if (incrementalMode && (0 == buildConfig.getSourceRoots().size())) { MessageUtil.error(handler, "specify a source root when in incremental mode"); } /* * Ensure we don't overwrite injars, inpath or aspectpath with outjar * bug-71339 */ File outjar = buildConfig.getOutputJar(); if (outjar != null) { /* Search injars */ for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File injar = (File)i.next(); if (injar.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } /* Search inpath */ for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory() && inPathElement.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } /* Search aspectpath */ for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext(); ) { File pathElement = (File)i.next(); if (!pathElement.isDirectory() && pathElement.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } } setDebugOptions(); buildConfig.getOptions().set(options); } catch (InvalidInputException iie) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location); handler.handleMessage(m); } return buildConfig; } // from super... public void printVersion() { System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$ System.err.flush(); } public void printUsage() { System.out.println(bind("misc.usage")); //$NON-NLS-1$ System.out.flush(); } /** * Get messages not dumped to handler or any PrintWriter. * @param flush if true, empty errors * @return null if none, String otherwise * @see BuildArgParser() */ public String getOtherMessages(boolean flush) { if (null == errorSink) { return null; } String result = errorSink.toString().trim(); if (0 == result.length()) { result = null; } if (flush) { errorSink.setLength(0); } return result; } private void setDebugOptions() { options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); } private Collection collectSourceRootFiles(File dir) { return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter)); } public List getBootclasspath(AjcConfigParser parser) { List ret = new ArrayList(); if (parser.bootclasspath == null) { addClasspath(System.getProperty("sun.boot.class.path", ""), ret); } else { addClasspath(parser.bootclasspath, ret); } return ret; } /** * If the classpath is not set, we use the environment's java.class.path, but remove * the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues * (refer to bug#39959). */ public List getClasspath(AjcConfigParser parser) { List ret = new ArrayList(); // if (parser.bootclasspath == null) { // addClasspath(System.getProperty("sun.boot.class.path", ""), ret); // } else { // addClasspath(parser.bootclasspath, ret); // } String extdirs = parser.extdirs; if (extdirs == null) { extdirs = System.getProperty("java.ext.dirs", ""); } addExtDirs(extdirs, ret); if (parser.classpath == null) { addClasspath(System.getProperty("java.class.path", ""), ret); List fixedList = new ArrayList(); for (Iterator it = ret.iterator(); it.hasNext(); ) { String entry = (String)it.next(); if (!entry.endsWith("aspectjtools.jar")) { fixedList.add(entry); } } ret = fixedList; } else { addClasspath(parser.classpath, ret); } //??? eclipse seems to put outdir on the classpath //??? we're brave and believe we don't need it return ret; } private void addExtDirs(String extdirs, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator); while (tokenizer.hasMoreTokens()) { // classpathCollector.add(tokenizer.nextToken()); File dirFile = new File((String)tokenizer.nextToken()); if (dirFile.canRead() && dirFile.isDirectory()) { File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER); for (int i = 0; i < files.length; i++) { classpathCollector.add(files[i].getAbsolutePath()); } } else { // XXX alert on invalid -extdirs entries } } } private void addClasspath(String classpath, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { classpathCollector.add(tokenizer.nextToken()); } } private class AjcConfigParser extends ConfigParser { private String bootclasspath = null; private String classpath = null; private String extdirs = null; private List unparsedArgs = new ArrayList(); private AjBuildConfig buildConfig; private IMessageHandler handler; public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) { this.buildConfig = buildConfig; this.handler = handler; } public List getUnparsedArgs() { return unparsedArgs; } /** * Extract AspectJ-specific options (except for argfiles). * Caller should warn when sourceroots is empty but in * incremental mode. * Signals warnings or errors through handler set in constructor. */ public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove() int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique // trim arg? if (LangUtil.isEmpty(arg)) { showWarning("empty arg found"); } else if (arg.equals("-inpath")) {; if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE); List inPath = buildConfig.getInpath(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File file = makeFile(filename); if (file.exists() && FileUtil.hasZipSuffix(filename)) { inPath.add(file); } else { if (file.isDirectory()) { inPath.add(file); } else showError("bad inpath component: " + filename); } } buildConfig.setInPath(inPath); args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-injars")) {; if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) { buildConfig.getInJars().add(jarFile); } else { File dirFile = makeFile(filename); if (dirFile.isDirectory()) { buildConfig.getInJars().add(dirFile); } else showError("bad injar: " + filename); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-aspectpath")) {; if (args.size() > nextArgIndex) { StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) { buildConfig.getAspectpath().add(jarFile); } else { showError("bad aspectpath: " + filename); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-sourceroots")) { if (args.size() > nextArgIndex) { List sourceRoots = new ArrayList(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { File f = makeFile(st.nextToken()); if (f.isDirectory() && f.canRead()) { sourceRoots.add(f); } else { showError("bad sourceroot: " + f); } } if (0 < sourceRoots.size()) { buildConfig.setSourceRoots(sourceRoots); } args.remove(args.get(nextArgIndex)); } else { showError("-sourceroots requires list of directories"); } } else if (arg.equals("-outjar")) { if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE); File jarFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); if (FileUtil.hasZipSuffix(jarFile)) { try { if (!jarFile.exists()) { jarFile.createNewFile(); } buildConfig.setOutputJar(jarFile); } catch (IOException ioe) { showError("unable to create outjar file: " + jarFile); } } else { showError("invalid -outjar file: " + jarFile); } args.remove(args.get(nextArgIndex)); } else { showError("-outjar requires jar path argument"); } } else if (arg.equals("-incremental")) { buildConfig.setIncrementalMode(true); } else if (arg.equals("-XincrementalFile")) { if (args.size() > nextArgIndex) { File file = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); buildConfig.setIncrementalFile(file); if (!file.canRead()) { showError("bad -XincrementalFile : " + file); // if not created before recompile test, stop after first compile } args.remove(args.get(nextArgIndex)); } else { showError("-XincrementalFile requires file argument"); } } else if (arg.equals("-emacssym")) { buildConfig.setEmacsSymMode(true); buildConfig.setGenerateModelMode(true); } else if (arg.equals("-XjavadocsInModel")) { buildConfig.setGenerateModelMode(true); buildConfig.setGenerateJavadocsInModelMode(true); } else if (arg.equals("-noweave") || arg.equals( "-XnoWeave")) { buildConfig.setNoWeave(true); } else if (arg.equals("-XserializableAspects")) { buildConfig.setXserializableAspects(true); } else if (arg.equals("-XlazyTjp")) { buildConfig.setXlazyTjp(true); } else if (arg.startsWith("-Xreweavable")) { buildConfig.setXreweavable(true); if (arg.endsWith(":compress")) { buildConfig.setXreweavableCompressClasses(true); } } else if (arg.equals("-XnoInline")) { buildConfig.setXnoInline(true); } else if (arg.startsWith("-showWeaveInfo")) { buildConfig.setShowWeavingInformation(true); } else if (arg.equals("-Xlintfile")) { if (args.size() > nextArgIndex) { File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); // XXX relax restriction on props file suffix? if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) { buildConfig.setLintSpecFile(lintSpecFile); } else { showError("bad -Xlintfile file: " + lintSpecFile); buildConfig.setLintSpecFile(null); } args.remove(args.get(nextArgIndex)); } else { showError("-Xlintfile requires .properties file argument"); } } else if (arg.equals("-Xlint")) { // buildConfig.getAjOptions().put( // AjCompilerOptions.OPTION_Xlint, // CompilerOptions.GENERATE); buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT); } else if (arg.startsWith("-Xlint:")) { if (7 < arg.length()) { buildConfig.setLintMode(arg.substring(7)); } else { showError("invalid lint option " + arg); } } else if (arg.equals("-bootclasspath")) { if (args.size() > nextArgIndex) { String bcpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer bcp = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator); while (strTok.hasMoreTokens()) { bcp.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { bcp.append(File.pathSeparator); } } bootclasspath = bcp.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-bootclasspath requires classpath entries"); } } else if (arg.equals("-classpath") || arg.equals("-cp")) { if (args.size() > nextArgIndex) { String cpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer cp = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator); while (strTok.hasMoreTokens()) { cp.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { cp.append(File.pathSeparator); } } classpath = cp.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-classpath requires classpath entries"); } } else if (arg.equals("-extdirs")) { if (args.size() > nextArgIndex) { String extdirsArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer ed = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator); while (strTok.hasMoreTokens()) { ed.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { ed.append(File.pathSeparator); } } extdirs = ed.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-extdirs requires list of external directories"); } // error on directory unless -d, -{boot}classpath, or -extdirs } else if (arg.equals("-d")) { dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-classpath")) { // dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-bootclasspath")) { // dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-extdirs")) { // dirLookahead(arg, args, nextArgIndex); } else if (arg.equals("-proceedOnError")) { buildConfig.setProceedOnError(true); } else if (new File(arg).isDirectory()) { showError("dir arg not permitted: " + arg); } else if (arg.equals("-1.5")) { buildConfig.setBehaveInJava5Way(true); unparsedArgs.add("-1.5"); // this would enable the '-source 1.5' to do the same as '-1.5' but doesnt sound quite right as // as an option right now as it doesnt mean we support 1.5 source code - people will get confused... } else if (arg.equals("-source")) { if (args.size() > nextArgIndex) { String level = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); if (level.equals("1.5")){ buildConfig.setBehaveInJava5Way(true); } unparsedArgs.add("-source"); unparsedArgs.add(level); args.remove(args.get(nextArgIndex)); } } else { // argfile, @file parsed by superclass // no eclipse options parsed: // -d args, -help (handled), // -classpath, -target, -1.3, -1.4, -source [1.3|1.4] // -nowarn, -warn:[...], -deprecation, -noImportError, // -g:[...], -preserveAllLocals, // -referenceInfo, -encoding, -verbose, -log, -time // -noExit, -repeat // (Actually, -noExit grabbed by Main) unparsedArgs.add(arg); } } protected void dirLookahead(String arg, LinkedList argList, int nextArgIndex) { unparsedArgs.add(arg); ConfigParser.Arg next = (ConfigParser.Arg) argList.get(nextArgIndex); String value = next.getValue(); if (!LangUtil.isEmpty(value)) { if (new File(value).isDirectory()) { unparsedArgs.add(value); argList.remove(next); return; } } } public void showError(String message) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.ERROR, null, location); handler.handleMessage(errorMessage); // MessageUtil.error(handler, CONFIG_MSG + message); } protected void showWarning(String message) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location); handler.handleMessage(errorMessage); // MessageUtil.warn(handler, message); } protected File makeFile(File dir, String name) { name = name.replace('/', File.separatorChar); File ret = new File(name); if (dir == null || ret.isAbsolute()) return ret; try { dir = dir.getCanonicalFile(); } catch (IOException ioe) { } return new File(dir, name); } } }
84,122
Bug 84122 Allow aspectPath to contain directories
The -aspectpath option to the compiler only allows jar/zip files, not directories. But inpath and classpath allow directories. This capability would improve the handling of aspects spanning multiple projects in Eclipse. AJDT can currently only support jar/zip files on the aspect path, which requires one of the projects to create an outjar instead of writing to the bin directory as usual. The iajc ant task could then also be enhanced to support aspectpath directories.
resolved fixed
68f6350
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T16:47:55Z
2005-02-01T09:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.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.File; import java.io.FileFilter; import java.io.IOException; 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.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.FileUtil; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; import org.aspectj.org.eclipse.jdt.internal.core.builder.ReferenceCollection; import org.aspectj.org.eclipse.jdt.internal.core.builder.StringSet; /** * Holds state needed for incremental compilation */ public class AjState { AjBuildManager buildManager; long lastSuccessfulBuildTime = -1; long currentBuildTime = -1; AjBuildConfig buildConfig; AjBuildConfig newBuildConfig; // Map/*<File, List<UnwovenClassFile>*/ classesFromFile = new HashMap(); Map/*<File, CompilationResult*/ resultsFromFile = new HashMap(); Map/*<File, ReferenceCollection>*/ references = new HashMap(); Map/*File, List<UnwovenClassFile>*/ binarySourceFiles = new HashMap(); Map/*<String, UnwovenClassFile>*/ classesFromName = new HashMap(); List/*File*/ compiledSourceFiles = new ArrayList(); List/*String*/ resources = new ArrayList(); ArrayList/*<String>*/ qualifiedStrings; ArrayList/*<String>*/ simpleStrings; Set addedFiles; Set deletedFiles; Set /*BinarySourceFile*/addedBinaryFiles; Set /*BinarySourceFile*/deletedBinaryFiles; List addedClassFiles; public AjState(AjBuildManager buildManager) { this.buildManager = buildManager; } void successfulCompile(AjBuildConfig config) { buildConfig = config; lastSuccessfulBuildTime = currentBuildTime; } /** * Returns false if a batch build is needed. */ boolean prepareForNextBuild(AjBuildConfig newBuildConfig) { currentBuildTime = System.currentTimeMillis(); addedClassFiles = new ArrayList(); if (lastSuccessfulBuildTime == -1 || buildConfig == null) { return false; } // we don't support incremental with an outjar yet if (newBuildConfig.getOutputJar() != null) return false; // we can't do an incremental build if one of our paths // has changed, or a jar on a path has been modified if (pathChange(buildConfig,newBuildConfig)) { // last time we built, .class files and resource files from jars on the // inpath will have been copied to the output directory. // these all need to be deleted in preparation for the clean build that is // coming - otherwise a file that has been deleted from an inpath jar // since the last build will not be deleted from the output directory. removeAllResultsOfLastBuild(); return false; } simpleStrings = new ArrayList(); qualifiedStrings = new ArrayList(); Set oldFiles = new HashSet(buildConfig.getFiles()); Set newFiles = new HashSet(newBuildConfig.getFiles()); addedFiles = new HashSet(newFiles); addedFiles.removeAll(oldFiles); deletedFiles = new HashSet(oldFiles); deletedFiles.removeAll(newFiles); Set oldBinaryFiles = new HashSet(buildConfig.getBinaryFiles()); Set newBinaryFiles = new HashSet(newBuildConfig.getBinaryFiles()); addedBinaryFiles = new HashSet(newBinaryFiles); addedBinaryFiles.removeAll(oldBinaryFiles); deletedBinaryFiles = new HashSet(oldBinaryFiles); deletedBinaryFiles.removeAll(newBinaryFiles); this.newBuildConfig = newBuildConfig; return true; } private Collection getModifiedFiles() { return getModifiedFiles(lastSuccessfulBuildTime); } Collection getModifiedFiles(long lastBuildTime) { List ret = new ArrayList(); //not our job to account for new and deleted files for (Iterator i = buildConfig.getFiles().iterator(); i.hasNext(); ) { File file = (File)i.next(); if (!file.exists()) continue; long modTime = file.lastModified(); //System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime); // need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms if (modTime + 1000 >= lastBuildTime) { ret.add(file); } } return ret; } private Collection getModifiedBinaryFiles() { return getModifiedBinaryFiles(lastSuccessfulBuildTime); } Collection getModifiedBinaryFiles(long lastBuildTime) { List ret = new ArrayList(); //not our job to account for new and deleted files for (Iterator i = buildConfig.getBinaryFiles().iterator(); i.hasNext(); ) { AjBuildConfig.BinarySourceFile bsfile = (AjBuildConfig.BinarySourceFile)i.next(); File file = bsfile.binSrc; if (!file.exists()) continue; long modTime = file.lastModified(); //System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime); // need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms if (modTime + 1000 >= lastBuildTime) { ret.add(bsfile); } } return ret; } private boolean pathChange(AjBuildConfig oldConfig, AjBuildConfig newConfig) { boolean changed = false; List oldClasspath = oldConfig.getClasspath(); List newClasspath = newConfig.getClasspath(); if (changed(oldClasspath,newClasspath)) return true; List oldAspectpath = oldConfig.getAspectpath(); List newAspectpath = newConfig.getAspectpath(); if (changed(oldAspectpath,newAspectpath)) return true; List oldInJars = oldConfig.getInJars(); List newInJars = newConfig.getInJars(); if (changed(oldInJars,newInJars)) return true; List oldInPath = oldConfig.getInpath(); List newInPath = newConfig.getInpath(); if (changed(oldInPath, newInPath)) return true; return changed; } private boolean changed(List oldPath, List newPath) { if (oldPath == null) oldPath = new ArrayList(); if (newPath == null) newPath = new ArrayList(); if (oldPath.size() != newPath.size()) { return true; } for (int i = 0; i < oldPath.size(); i++) { if (!oldPath.get(i).equals(newPath.get(i))) { return true; } Object o = oldPath.get(i); // String on classpath, File on other paths File f = null; if (o instanceof String) { f = new File((String)o); } else { f = (File) o; } if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) { return true; } } return false; } public List getFilesToCompile(boolean firstPass) { List thisTime = new ArrayList(); if (firstPass) { compiledSourceFiles = new ArrayList(); Collection modifiedFiles = getModifiedFiles(); //System.out.println("modified: " + modifiedFiles); thisTime.addAll(modifiedFiles); //??? eclipse IncrementalImageBuilder appears to do this // for (Iterator i = modifiedFiles.iterator(); i.hasNext();) { // File file = (File) i.next(); // addDependentsOf(file); // } thisTime.addAll(addedFiles); deleteClassFiles(); deleteResources(); addAffectedSourceFiles(thisTime,thisTime); } else { addAffectedSourceFiles(thisTime,compiledSourceFiles); } compiledSourceFiles = thisTime; return thisTime; } public Map /* String -> List<ucf> */ getBinaryFilesToCompile(boolean firstTime) { if (lastSuccessfulBuildTime == -1 || buildConfig == null) { return binarySourceFiles; } // else incremental... Map toWeave = new HashMap(); if (firstTime) { List addedOrModified = new ArrayList(); addedOrModified.addAll(addedBinaryFiles); addedOrModified.addAll(getModifiedBinaryFiles()); for (Iterator iter = addedOrModified.iterator(); iter.hasNext();) { AjBuildConfig.BinarySourceFile bsf = (AjBuildConfig.BinarySourceFile) iter.next(); UnwovenClassFile ucf = createUnwovenClassFile(bsf); if (ucf == null) continue; List ucfs = new ArrayList(); ucfs.add(ucf); addDependentsOf(ucf.getClassName()); binarySourceFiles.put(bsf.binSrc.getPath(),ucfs); toWeave.put(bsf.binSrc.getPath(),ucfs); } deleteBinaryClassFiles(); } else { // return empty set... we've already done our bit. } return toWeave; } /** * Called when a path change is about to trigger a full build, but * we haven't cleaned up from the last incremental build... */ private void removeAllResultsOfLastBuild() { // remove all binarySourceFiles, and all classesFromName... for (Iterator iter = binarySourceFiles.values().iterator(); iter.hasNext();) { List ucfs = (List) iter.next(); for (Iterator iterator = ucfs.iterator(); iterator.hasNext();) { UnwovenClassFile ucf = (UnwovenClassFile) iterator.next(); try { ucf.deleteRealFile(); } catch (IOException ex) { /* we did our best here */ } } } for (Iterator iterator = classesFromName.values().iterator(); iterator.hasNext();) { UnwovenClassFile ucf = (UnwovenClassFile) iterator.next(); try { ucf.deleteRealFile(); } catch (IOException ex) { /* we did our best here */ } } for (Iterator iter = resources.iterator(); iter.hasNext();) { String resource = (String) iter.next(); new File(buildConfig.getOutputDir(),resource).delete(); } } private void deleteClassFiles() { for (Iterator i = deletedFiles.iterator(); i.hasNext(); ) { File deletedFile = (File)i.next(); //System.out.println("deleting: " + deletedFile); addDependentsOf(deletedFile); InterimCompilationResult intRes = (InterimCompilationResult) resultsFromFile.get(deletedFile); resultsFromFile.remove(deletedFile); //System.out.println("deleting: " + unwovenClassFiles); if (intRes == null) continue; for (int j=0; j<intRes.unwovenClassFiles().length; j++ ) { deleteClassFile(intRes.unwovenClassFiles()[j]); } } } private void deleteBinaryClassFiles() { // range of bsf is ucfs, domain is files (.class and jars) in inpath/jars for (Iterator iter = deletedBinaryFiles.iterator(); iter.hasNext();) { AjBuildConfig.BinarySourceFile deletedFile = (AjBuildConfig.BinarySourceFile) iter.next(); List ucfs = (List) binarySourceFiles.get(deletedFile.binSrc.getPath()); binarySourceFiles.remove(deletedFile.binSrc.getPath()); deleteClassFile((UnwovenClassFile)ucfs.get(0)); } } private void deleteResources() { List oldResources = new ArrayList(); oldResources.addAll(resources); // note - this deliberately ignores resources in jars as we don't yet handle jar changes // with incremental compilation for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (inPathElement.isDirectory() && AjBuildManager.COPY_INPATH_DIR_RESOURCES) { deleteResourcesFromDirectory(inPathElement,oldResources); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) { String resource = (String)i.next(); maybeDeleteResource(resource, oldResources); } } // oldResources need to be deleted... for (Iterator iter = oldResources.iterator(); iter.hasNext();) { String victim = (String) iter.next(); File f = new File(buildConfig.getOutputDir(),victim); if (f.exists()) { f.delete(); } resources.remove(victim); } } private void maybeDeleteResource(String resName, List oldResources) { if (resources.contains(resName)) { oldResources.remove(resName); File source = new File(buildConfig.getOutputDir(),resName); if ((source != null) && (source.exists()) && (source.lastModified() >= lastSuccessfulBuildTime)) { resources.remove(resName); // will ensure it is re-copied } } } private void deleteResourcesFromDirectory(File dir, List oldResources) { 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); maybeDeleteResource(filename, oldResources); } } private void deleteClassFile(UnwovenClassFile classFile) { classesFromName.remove(classFile.getClassName()); buildManager.bcelWeaver.deleteClassFile(classFile.getClassName()); try { classFile.deleteRealFile(); } catch (IOException e) { //!!! might be okay to ignore } } private UnwovenClassFile createUnwovenClassFile(AjBuildConfig.BinarySourceFile bsf) { UnwovenClassFile ucf = null; try { ucf = buildManager.bcelWeaver.addClassFile(bsf.binSrc, bsf.fromInPathDirectory, buildConfig.getOutputDir()); } catch(IOException ex) { IMessage msg = new Message("can't read class file " + bsf.binSrc.getPath(), new SourceLocation(bsf.binSrc,0),false); buildManager.handler.handleMessage(msg); } return ucf; } public void noteResult(InterimCompilationResult result) { File sourceFile = new File(result.fileName()); CompilationResult cr = result.result(); if (result != null) { references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences)); } InterimCompilationResult previous = (InterimCompilationResult) resultsFromFile.get(sourceFile); UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles(); for (int i = 0; i < unwovenClassFiles.length; i++) { UnwovenClassFile lastTimeRound = removeFromPreviousIfPresent(unwovenClassFiles[i],previous); recordClassFile(unwovenClassFiles[i],lastTimeRound); classesFromName.put(unwovenClassFiles[i].getClassName(),unwovenClassFiles[i]); } if (previous != null) { for (int i = 0; i < previous.unwovenClassFiles().length; i++) { if (previous.unwovenClassFiles()[i] != null) { deleteClassFile(previous.unwovenClassFiles()[i]); } } } resultsFromFile.put(sourceFile, result); } private UnwovenClassFile removeFromPreviousIfPresent(UnwovenClassFile cf, InterimCompilationResult previous) { if (previous == null) return null; UnwovenClassFile[] unwovenClassFiles = previous.unwovenClassFiles(); for (int i = 0; i < unwovenClassFiles.length; i++) { UnwovenClassFile candidate = unwovenClassFiles[i]; if ((candidate != null) && candidate.getFilename().equals(cf.getFilename())) { unwovenClassFiles[i] = null; return candidate; } } return null; } private void recordClassFile(UnwovenClassFile thisTime, UnwovenClassFile lastTime) { if (simpleStrings == null) return; // batch build if (lastTime == null) { addDependentsOf(thisTime.getClassName()); return; } byte[] newBytes = thisTime.getBytes(); byte[] oldBytes = lastTime.getBytes(); boolean bytesEqual = (newBytes.length == oldBytes.length); for (int i = 0; (i < oldBytes.length) && bytesEqual; i++) { if (newBytes[i] != oldBytes[i]) bytesEqual = false; } if (!bytesEqual) { try { ClassFileReader reader = new ClassFileReader(oldBytes, lastTime.getFilename().toCharArray()); // ignore local types since they're only visible inside a single method if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) { addDependentsOf(lastTime.getClassName()); } } catch (ClassFormatException e) { addDependentsOf(lastTime.getClassName()); } } } // public void noteClassesFromFile(CompilationResult result, String sourceFileName, List unwovenClassFiles) { // File sourceFile = new File(sourceFileName); // // if (result != null) { // references.put(sourceFile, new ReferenceCollection(result.qualifiedReferences, result.simpleNameReferences)); // } // // List previous = (List)classesFromFile.get(sourceFile); // List newClassFiles = new ArrayList(); // for (Iterator i = unwovenClassFiles.iterator(); i.hasNext();) { // UnwovenClassFile cf = (UnwovenClassFile) i.next(); // cf = writeClassFile(cf, findAndRemoveClassFile(cf.getClassName(), previous)); // newClassFiles.add(cf); // classesFromName.put(cf.getClassName(), cf); // } // // if (previous != null && !previous.isEmpty()) { // for (Iterator i = previous.iterator(); i.hasNext();) { // UnwovenClassFile cf = (UnwovenClassFile) i.next(); // deleteClassFile(cf); // } // } // // classesFromFile.put(sourceFile, newClassFiles); // resultsFromFile.put(sourceFile, result); // } // // private UnwovenClassFile findAndRemoveClassFile(String name, List previous) { // if (previous == null) return null; // for (Iterator i = previous.iterator(); i.hasNext();) { // UnwovenClassFile cf = (UnwovenClassFile) i.next(); // if (cf.getClassName().equals(name)) { // i.remove(); // return cf; // } // } // return null; // } // // private UnwovenClassFile writeClassFile(UnwovenClassFile cf, UnwovenClassFile previous) { // if (simpleStrings == null) { // batch build // addedClassFiles.add(cf); // return cf; // } // // try { // if (previous == null) { // addedClassFiles.add(cf); // addDependentsOf(cf.getClassName()); // return cf; // } // // byte[] oldBytes = previous.getBytes(); // byte[] newBytes = cf.getBytes(); // //if (this.compileLoop > 1) { // only optimize files which were recompiled during the dependent pass, see 33990 // notEqual : if (newBytes.length == oldBytes.length) { // for (int i = newBytes.length; --i >= 0;) { // if (newBytes[i] != oldBytes[i]) break notEqual; // } // //addedClassFiles.add(previous); //!!! performance wasting // buildManager.bcelWorld.addSourceObjectType(previous.getJavaClass()); // return previous; // bytes are identical so skip them // } // //} // ClassFileReader reader = new ClassFileReader(oldBytes, previous.getFilename().toCharArray()); // // ignore local types since they're only visible inside a single method // if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) { // addDependentsOf(cf.getClassName()); // } // } catch (ClassFormatException e) { // addDependentsOf(cf.getClassName()); // } // addedClassFiles.add(cf); // return cf; // } private static StringSet makeStringSet(List strings) { StringSet ret = new StringSet(strings.size()); for (Iterator iter = strings.iterator(); iter.hasNext();) { String element = (String) iter.next(); ret.add(element); } return ret; } protected void addAffectedSourceFiles(List addTo, List lastTimeSources) { if (qualifiedStrings.isEmpty() && simpleStrings.isEmpty()) return; // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X' char[][][] qualifiedNames = ReferenceCollection.internQualifiedNames(makeStringSet(qualifiedStrings)); // if a well known qualified name was found then we can skip over these if (qualifiedNames.length < qualifiedStrings.size()) qualifiedNames = null; char[][] simpleNames = ReferenceCollection.internSimpleNames(makeStringSet(simpleStrings)); // if a well known name was found then we can skip over these if (simpleNames.length < simpleStrings.size()) simpleNames = null; //System.err.println("simple: " + simpleStrings); //System.err.println("qualif: " + qualifiedStrings); for (Iterator i = references.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ReferenceCollection refs = (ReferenceCollection)entry.getValue(); if (refs != null && refs.includes(qualifiedNames, simpleNames)) { File file = (File)entry.getKey(); if (file.exists()) { if (!lastTimeSources.contains(file)) { //??? O(n**2) addTo.add(file); } } } } qualifiedStrings.clear(); simpleStrings.clear(); } protected void addDependentsOf(String qualifiedTypeName) { int lastDot = qualifiedTypeName.lastIndexOf('.'); String typeName; if (lastDot != -1) { String packageName = qualifiedTypeName.substring(0,lastDot).replace('.', '/'); if (!qualifiedStrings.contains(packageName)) { //??? O(n**2) qualifiedStrings.add(packageName); } typeName = qualifiedTypeName.substring(lastDot+1); } else { qualifiedStrings.add(""); typeName = qualifiedTypeName; } int memberIndex = typeName.indexOf('$'); if (memberIndex > 0) typeName = typeName.substring(0, memberIndex); if (!simpleStrings.contains(typeName)) { //??? O(n**2) simpleStrings.add(typeName); } //System.err.println("adding: " + qualifiedTypeName); } protected void addDependentsOf(File sourceFile) { InterimCompilationResult intRes = (InterimCompilationResult)resultsFromFile.get(sourceFile); if (intRes == null) return; for (int i = 0; i < intRes.unwovenClassFiles().length; i++) { addDependentsOf(intRes.unwovenClassFiles()[i].getClassName()); } } }
84,122
Bug 84122 Allow aspectPath to contain directories
The -aspectpath option to the compiler only allows jar/zip files, not directories. But inpath and classpath allow directories. This capability would improve the handling of aspects spanning multiple projects in Eclipse. AJDT can currently only support jar/zip files on the aspect path, which requires one of the projects to create an outjar instead of writing to the bin directory as usual. The iajc ant task could then also be enhanced to support aspectpath directories.
resolved fixed
68f6350
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T16:47:55Z
2005-02-01T09:26:40Z
tests/options/aspectpath/MyClass.java
84,122
Bug 84122 Allow aspectPath to contain directories
The -aspectpath option to the compiler only allows jar/zip files, not directories. But inpath and classpath allow directories. This capability would improve the handling of aspects spanning multiple projects in Eclipse. AJDT can currently only support jar/zip files on the aspect path, which requires one of the projects to create an outjar instead of writing to the bin directory as usual. The iajc ant task could then also be enhanced to support aspectpath directories.
resolved fixed
68f6350
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T16:47:55Z
2005-02-01T09:26: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; /** * 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 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 (System.getProperty("java.vm.version").startsWith("1.5")) { 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"); } // 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); } }
84,122
Bug 84122 Allow aspectPath to contain directories
The -aspectpath option to the compiler only allows jar/zip files, not directories. But inpath and classpath allow directories. This capability would improve the handling of aspects spanning multiple projects in Eclipse. AJDT can currently only support jar/zip files on the aspect path, which requires one of the projects to create an outjar instead of writing to the bin directory as usual. The iajc ant task could then also be enhanced to support aspectpath directories.
resolved fixed
68f6350
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T16:47:55Z
2005-02-01T09:26:40Z
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.jar.Attributes.Name; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.CrosscuttingMembersSet; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.IWeaver; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.BindingAnnotationTypePattern; import org.aspectj.weaver.patterns.BindingTypePattern; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.ConcreteCflowPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NameBindingPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.patterns.WithinPointcut; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; public BcelWeaver(BcelWorld world) { super(); WeaverMetrics.reset(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } public void addLibraryAspect(String aspectName) { ResolvedTypeX type = world.resolve(aspectName); //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { xcutSet.addOrReplaceAspect(type); } else { throw new RuntimeException("unimplemented"); } } public void addLibraryJarFile(File inFile) throws IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedTypeX aspectX = (ResolvedTypeX) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; private Set alreadyConfirmedReweavableState; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarFile inJar = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inJar = new JarFile(inFile); addManifest(inJar.getManifest()); Enumeration entries = inJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); InputStream inStream = inJar.getInputStream(entry); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); // System.out.println("? addJarFile() filename='" + filename + "'"); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.close(); } inJar.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inJar != null) { try {inJar.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(TypeX.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void prepareForWeave() { needToReweaveWorld = false; CflowPointcut.clearCaches(); // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedTypeX type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(TypeX.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); rewritePointcuts(shadowMungerList); typeMungerList = xcutSet.getTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); //XXX this gets us a stable (but completely meaningless) order Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }); } /* * Rewrite all of the pointcuts in the world into their most efficient * form for subsequent matching. Also ensure that if pc1.equals(pc2) * then pc1 == pc2 (for non-binding pcds) by making references all * point to the same instance. * Since pointcuts remember their match decision on the last shadow, * this makes matching faster when many pointcuts share common elements, * or even when one single pointcut has one common element (which can * be a side-effect of DNF rewriting). */ private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) { PointcutRewriter rewriter = new PointcutRewriter(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = rewriter.rewrite(p); // validateBindings now whilst we still have around the pointcut // that resembles what the user actually wrote in their program // text. if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getSignature() != null) { int numFormals = advice.getBaseParameterCount(); if (numFormals > 0) { String[] names = advice.getBaseParameterNames(world); validateBindings(newP,p,numFormals,names); } } } munger.setPointcut(newP); } // now that we have optimized individual pointcuts, optimize // across the set of pointcuts.... // Use a map from key based on pc equality, to value based on // pc identity. Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); munger.setPointcut(shareEntriesFromMap(p,pcMap)); } } private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) { // some things cant be shared... if (p instanceof NameBindingPointcut) return p; if (p instanceof IfPointcut) return p; if (p instanceof ConcreteCflowPointcut) return p; if (p instanceof AndPointcut) { AndPointcut apc = (AndPointcut) p; Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap); return new AndPointcut(left,right); } else if (p instanceof OrPointcut) { OrPointcut opc = (OrPointcut) p; Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap); return new OrPointcut(left,right); } else if (p instanceof NotPointcut) { NotPointcut npc = (NotPointcut) p; Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap); return new NotPointcut(not); } else { // primitive pcd if (pcMap.containsKey(p)) { // based on equality return (Pointcut) pcMap.get(p); // same instance (identity) } else { pcMap.put(p,p); return p; } } } // userPointcut is the pointcut that the user wrote in the program text. // dnfPointcut is the same pointcut rewritten in DNF // numFormals is the number of formal parameters in the pointcut // if numFormals > 0 then every branch of a disjunction must bind each formal once and only once. // in addition, the left and right branches of a disjunction must hold on join point kinds in // common. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) { if (numFormals == 0) return; // nothing to check if (dnfPointcut.couldMatchKinds().isEmpty()) return; // cant have problems if you dont match! if (dnfPointcut instanceof OrPointcut) { OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut; Pointcut[] leftBindings = new Pointcut[numFormals]; Pointcut[] rightBindings = new Pointcut[numFormals]; validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings); } else { Pointcut[] bindings = new Pointcut[numFormals]; validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings); } } private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) { Pointcut left = pc.getLeft(); Pointcut right = pc.getRight(); if (left instanceof OrPointcut) { Pointcut[] newRightBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings); } else { if (left.couldMatchKinds().size() > 0) validateSingleBranch(left, userPointcut, numFormals, names, leftBindings); } if (right instanceof OrPointcut) { Pointcut[] newLeftBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings); } else { if (right.couldMatchKinds().size() > 0) validateSingleBranch(right, userPointcut, numFormals, names, rightBindings); } Set kindsInCommon = left.couldMatchKinds(); kindsInCommon.retainAll(right.couldMatchKinds()); if (!kindsInCommon.isEmpty() && couldEverMatchSameJoinPoints(left,right)) { // we know that every branch binds every formal, so there is no ambiguity // if each branch binds it in exactly the same way... List ambiguousNames = new ArrayList(); for (int i = 0; i < numFormals; i++) { if (!leftBindings[i].equals(rightBindings[i])) { ambiguousNames.add(names[i]); } } if (!ambiguousNames.isEmpty()) raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames); } } // pc is a pointcut that does not contain any disjunctions // check that every formal is bound (negation doesn't count). // we know that numFormals > 0 or else we would not be called private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) { boolean[] foundFormals = new boolean[numFormals]; for (int i = 0; i < foundFormals.length; i++) { foundFormals[i] = false; } validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings); for (int i = 0; i < foundFormals.length; i++) { if (!foundFormals[i]) { raiseUnboundFormalError(names[i],userPointcut); } } } // each formal must appear exactly once private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) { if (pc instanceof NotPointcut) { // nots can only appear at leaves in DNF NotPointcut not = (NotPointcut) pc; if (not.getNegatedPointcut() instanceof NameBindingPointcut) { NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut(); if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) raiseNegationBindingError(userPointcut); } } else if (pc instanceof AndPointcut) { AndPointcut and = (AndPointcut) pc; validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings); validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings); } else if (pc instanceof NameBindingPointcut) { List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns(); for (Iterator iter = btps.iterator(); iter.hasNext();) { BindingTypePattern btp = (BindingTypePattern) iter.next(); int index = btp.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns(); for (Iterator iter = baps.iterator(); iter.hasNext();) { BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next(); int index = bap.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); for (int i = 0; i < slots.length; i++) { bindings[slots[i]] = cfp; if (foundFormals[slots[i]]) { raiseAmbiguousBindingError(names[slots[i]],userPointcut); } else { foundFormals[slots[i]] = true; } } } } // By returning false from this method, we are allowing binding of the same // variable on either side of an or. // Be conservative :- have to consider overriding, varargs, autoboxing, // the effects of itds (on within for example), interfaces, the fact that // join points can have multiple signatures and so on. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) { if ((left instanceof OrPointcut) || (right instanceof OrPointcut)) return true; // look for withins WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class); WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class); if ((leftWithin != null) && (rightWithin != null)) { if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false; } // look for kinded KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class); KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class); if ((leftKind != null) && (rightKind != null)) { if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false; } return true; } private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) { if (toSearch instanceof NotPointcut) return null; if (toLookFor.isInstance(toSearch)) return toSearch; if (toSearch instanceof AndPointcut) { AndPointcut apc = (AndPointcut) toSearch; Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor); if (left != null) return left; return findFirstPointcutIn(apc.getRight(),toLookFor); } return null; } /** * @param userPointcut */ private void raiseNegationBindingError(Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param string * @param userPointcut */ private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param userPointcut */ private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) { StringBuffer formalNames = new StringBuffer(names.get(0).toString()); for (int i = 1; i < names.size(); i++) { formalNames.append(", "); formalNames.append(names.get(i)); } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param string * @param userPointcut */ private void raiseUnboundFormalError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); requestor.processingReweavableState(); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); processReweavableStateIfPresent(className, classType); } requestor.addingTypeMungers(); // We process type mungers in two groups, first mungers that change the type // hierarchy, then 'normal' ITD type mungers. // Process the types in a predictable order (rather than the order encountered). // For class A, the order is superclasses of A then superinterfaces of A // (and this mechanism is applied recursively) List typesToProcess = new ArrayList(); for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = (UnwovenClassFile) iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size()>0) { weaveParentsFor(typesToProcess,(String)typesToProcess.get(0)); } for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addNormalTypeMungers(className); } requestor.weavingAspects(); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (classType.isAspect()) { weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } requestor.weavingClasses(); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (! classType.isAspect()) { weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning if (world.behaveInJava5Way && world.getLint().adviceDidNotMatch.isEnabled()) { List l = world.getCrosscuttingMembersSet().getShadowMungers(); for (Iterator iter = l.iterator(); iter.hasNext();) { ShadowMunger element = (ShadowMunger) iter.next(); if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers BcelAdvice ba = (BcelAdvice)element; if (!ba.hasMatchedSomething()) { BcelMethod meth = (BcelMethod)ba.getSignature(); if (meth!=null) { AnnotationX[] anns = (AnnotationX[])meth.getAnnotations(); // Check if they want to suppress the warning on this piece of advice if (!Utility.isSuppressing(anns,"adviceDidNotMatch")) { world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().getNameAsIdentifier(),element.getSourceLocation()); } } } } } } requestor.weaveCompleted(); return wovenClassNames; } /** * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process * supertypes (classes/interfaces) of 'typeToWeave' that are in the * 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from * the 'typesForWeaving' list. * * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may * break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it * may choose to weave them in either order - but you'll probably have other problems if * you are supplying partial hierarchies like that ! */ private void weaveParentsFor(List typesForWeaving,String typeToWeave) { // Look at the supertype first ResolvedTypeX rtx = world.resolve(typeToWeave); ResolvedTypeX superType = rtx.getSuperclass(); if (superType!=null && typesForWeaving.contains(superType.getClassName())) { weaveParentsFor(typesForWeaving,superType.getClassName()); } // Then look at the superinterface list ResolvedTypeX[] interfaceTypes = rtx.getDeclaredInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ResolvedTypeX rtxI = interfaceTypes[i]; if (typesForWeaving.contains(rtxI.getClassName())) { weaveParentsFor(typesForWeaving,rtxI.getClassName()); } } weaveParentTypeMungers(rtx); // Now do this type typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process } public void prepareToProcessReweavableState() { if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); alreadyConfirmedReweavableState = new HashSet(); } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()), null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedTypeX rtx = world.resolve(TypeX.forName(requiredTypeName),true); boolean exists = rtx!=ResolvedTypeX.MISSING; if (!exists) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className), classType.getSourceLocation(), null); } else { if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()), null,null); alreadyConfirmedReweavableState.add(requiredTypeName); } } } } classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); } else { classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } } // helper method public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addParentTypeMungers(String typeName) { weaveParentTypeMungers(world.resolve(typeName)); } public void addNormalTypeMungers(String typeName) { weaveNormalTypeMungers(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes()); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } /** * Weaves new parents and annotations onto a type ("declare parents" and "declare @type") * * Algorithm: * 1. First pass, do parents then do annotations. During this pass record: * - any parent mungers that don't match but have a non-wild annotation type pattern * - any annotation mungers that don't match * 2. Multiple subsequent passes which go over the munger lists constructed in the first * pass, repeatedly applying them until nothing changes. * FIXME asc confirm that algorithm is optimal ?? */ public void weaveParentTypeMungers(ResolvedTypeX onType) { onType.clearInterTypeMungers(); List decpToRepeat = new ArrayList(); List decaToRepeat = new ArrayList(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents decp = (DeclareParents)i.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { // Perhaps it would have matched if a 'dec @type' had modified the type if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation)i.next(); boolean typeChanged = applyDeclareAtType(decA,onType,true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List decpToRepeatNextTime = new ArrayList(); for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = (DeclareParents) iter.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA,onType,false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedTypeX onType,boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { //FIXME asc CRITICAL this should be guarded by the 'already has annotation' check below but isn't since the compiler is producing classfiles with deca affected things in... AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation()); if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) { // FIXME asc Could put out a lint here for an already annotated type - the problem is that it may have // picked up the annotation during 'source weaving' in which case the message is misleading. Leaving it // off for now... // if (reportProblems) { // world.getLint().elementAlreadyAnnotated.signal( // new String[]{onType.toString(),decA.getAnnotationTypeX().toString()}, // onType.getSourceLocation(),new ISourceLocation[]{decA.getSourceLocation()}); // } return false; } AnnotationX annoX = decA.getAnnotationX(); // check the annotation is suitable for the target boolean problemReported = verifyTargetIsOK(decA, onType, annoX,reportProblems); if (!problemReported) { didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation * to be attached to the target type that matched. */ private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedTypeX onType, AnnotationX annoX,boolean outputProblems) { boolean problemReported = false; if (annoX.specifiesTarget()) { if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { if (outputProblems) { if (decA.isExactPattern()) { world.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation())); } else { if (world.getLint().invalidTargetForAnnotation.isEnabled()) { world.getLint().invalidTargetForAnnotation.signal( new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()}); } } } problemReported = true; } } return problemReported; } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedTypeX onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType,true); if (!newParents.isEmpty()) { didSomething=true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedTypeX newParent = (ResolvedTypeX)j.next(); // We set it here so that the imminent matching for ITDs can succeed - we // still haven't done the necessary changes to the class file itself // (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent() classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } return didSomething; } public void weaveNormalTypeMungers(ResolvedTypeX onType) { for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (m.matches(onType)) { onType.addInterTypeMunger(m); } } } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { if (dump) dumpUnchanged(classFile); return null; } // JavaClass javaClass = classType.getJavaClass(); List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); LazyClassGen clazz = null; if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() || world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0 ) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers); if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { System.err.println("trouble in: "); //XXXclazz.print(System.err); throw re; } catch (Error re) { System.err.println("trouble in: "); clazz.print(System.err); throw re; } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedTypeX type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info if (fb.maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean mode,boolean compress) { inReweavableMode = mode; WeaverStateInfo.setReweavableModeDefaults(mode,compress); BcelClassWeaver.setReweavableMode(mode,compress); } public boolean isReweavable() { return inReweavableMode; } }
84,333
Bug 84333 BCException: Bad type name: TypeX.nameToSignature(TypeX.java:635)
null
resolved fixed
fb01cad
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T20:26:21Z
2005-02-03T14:13:20Z
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.ajdt.internal.core.builder.AsmHierarchyBuilder; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.World; 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.impl.Constant; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; 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.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; /** * @author Jim Hugunin */ public class EclipseFactory { public static boolean DEBUG = false; private AjBuildManager buildManager; private LookupEnvironment lookupEnvironment; private boolean xSerializableAspects; private World world; private AsmHierarchyBuilder asmHierarchyBuilder; private Map/*TypeX, TypeBinding*/ typexToBinding = new HashMap(); //XXX currently unused // private Map/*TypeBinding, ResolvedTypeX*/ 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 ResolvedTypeX fromEclipse(ReferenceBinding binding) { if (binding == null) return ResolvedTypeX.MISSING; //??? this seems terribly inefficient //System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding)); ResolvedTypeX ret = getWorld().resolve(fromBinding(binding)); //System.err.println(" got: " + ret); return ret; } public ResolvedTypeX fromTypeBindingToRTX(TypeBinding tb) { if (tb == null) return ResolvedTypeX.MISSING; ResolvedTypeX ret = getWorld().resolve(fromBinding(tb)); return ret; } public ResolvedTypeX[] fromEclipse(ReferenceBinding[] bindings) { if (bindings == null) { return ResolvedTypeX.NONE; } int len = bindings.length; ResolvedTypeX[] ret = new ResolvedTypeX[len]; for (int i=0; i < len; i++) { ret[i] = fromEclipse(bindings[i]); } return ret; } private static String getName(TypeBinding binding) { 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); } //??? going back and forth between strings and bindings is a waste of cycles public static TypeX fromBinding(TypeBinding binding) { if (binding instanceof HelperInterfaceBinding) { return ((HelperInterfaceBinding) binding).getTypeX(); } if (binding == null || binding.qualifiedSourceName() == null) { return ResolvedTypeX.MISSING; } return TypeX.forName(getName(binding)); } public static TypeX[] fromBindings(TypeBinding[] bindings) { if (bindings == null) return TypeX.NONE; int len = bindings.length; TypeX[] ret = new TypeX[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(); 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 static ResolvedMember makeResolvedMember(MethodBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } public static ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) { //System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName)); ResolvedMember ret = new ResolvedMember( binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD, fromBinding(declaringType), binding.modifiers, fromBinding(binding.returnType), new String(binding.selector), fromBindings(binding.parameters), fromBindings(binding.thrownExceptions)); return ret; } public static ResolvedMember makeResolvedMember(FieldBinding binding) { return makeResolvedMember(binding, binding.declaringClass); } public static ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) { return new ResolvedMember( Member.FIELD, fromBinding(receiverType), binding.modifiers, fromBinding(binding.type), new String(binding.name), TypeX.NONE); } public TypeBinding makeTypeBinding(TypeX typeX) { TypeBinding ret = (TypeBinding)typexToBinding.get(typeX); if (ret == null) { ret = makeTypeBinding1(typeX); typexToBinding.put(typeX, ret); } if (ret == null) { System.out.println("can't find: " + typeX); } return ret; } private TypeBinding makeTypeBinding1(TypeX typeX) { if (typeX.isPrimitive()) { if (typeX == ResolvedTypeX.BOOLEAN) return BaseTypes.BooleanBinding; if (typeX == ResolvedTypeX.BYTE) return BaseTypes.ByteBinding; if (typeX == ResolvedTypeX.CHAR) return BaseTypes.CharBinding; if (typeX == ResolvedTypeX.DOUBLE) return BaseTypes.DoubleBinding; if (typeX == ResolvedTypeX.FLOAT) return BaseTypes.FloatBinding; if (typeX == ResolvedTypeX.INT) return BaseTypes.IntBinding; if (typeX == ResolvedTypeX.LONG) return BaseTypes.LongBinding; if (typeX == ResolvedTypeX.SHORT) return BaseTypes.ShortBinding; if (typeX == ResolvedTypeX.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 { String n = typeX.getName(); char[][] name = CharOperation.splitOn('.', n.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 (n.equals("java.lang.Class")) rb = lookupEnvironment.createRawType(rb,rb.enclosingType()); return rb; } } public TypeBinding[] makeTypeBindings(TypeX[] 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(TypeX[] 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) { return new FieldBinding(member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), member.getModifiers(), (ReferenceBinding)makeTypeBinding(member.getDeclaringType()), Constant.NotAConstant); } public MethodBinding makeMethodBinding(ResolvedMember member) { return new MethodBinding(member.getModifiers(), member.getName().toCharArray(), makeTypeBinding(member.getReturnType()), makeTypeBindings(member.getParameterTypes()), makeReferenceBindings(member.getExceptions()), (ReferenceBinding)makeTypeBinding(member.getDeclaringType())); } 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) { TypeDeclaration decl = binding.scope.referenceContext; ResolvedTypeX.Name name = getWorld().lookupOrCreateName(TypeX.forName(getName(binding))); EclipseSourceType t = new EclipseSourceType(name, this, binding, decl); 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]); } } // 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; } }
84,333
Bug 84333 BCException: Bad type name: TypeX.nameToSignature(TypeX.java:635)
null
resolved fixed
fb01cad
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T20:26:21Z
2005-02-03T14:13:20Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import 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; /** * 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 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 (System.getProperty("java.vm.version").startsWith("1.5")) { 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"); } // 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); } }
84,333
Bug 84333 BCException: Bad type name: TypeX.nameToSignature(TypeX.java:635)
null
resolved fixed
fb01cad
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T20:26:21Z
2005-02-03T14:13:20Z
tests/src/org/aspectj/systemtest/ajc150/GenericsTests.java
88,862
Bug 88862 Declare annotation on ITDs
I'll use this bug to capture info on the implementation...
resolved fixed
0d14ccf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T21:31:49Z
2005-03-23T15:00:00Z
tests/src/org/aspectj/systemtest/ajc150/AnnotationBinding.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 AnnotationBinding extends XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(AnnotationBinding.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } ///////////////////////////////////// @ANNOTATION and CALL // Very simple annotation binding for 'call() && @annotation()' public void testCallAnnotationBinding1() { runTest("call annotation binding 1"); } // 'call() && @annotation()' when the called method has multiple arguments public void testCallAnnotationBinding2() { runTest("call annotation binding 2"); } // 'call() && @annotation()' when the called method takes primitive arguments (YUCK!) public void testCallAnnotationBinding3() { runTest("call annotation binding 3"); } // 'call() && @annotation()' when runtime type will exhibit different annotation (due to interface implementing) public void testCallAnnotationBinding4() { runTest("call annotation binding 4"); } // 'call() && @annotation()' when target doesnt have an annotation ! public void testCallAnnotationBinding5() { runTest("call annotation binding 5"); } // 'call() && @annotation()' when runtime type will exhibit different annotation (due to subclassing) public void testCallAnnotationBinding6() { runTest("call annotation binding 6"); } // 'call() && @annotation()' using named pointcut public void testCallAnnotationBinding7() { runTest("call annotation binding 7"); } ///////////////////////////////////// @TARGET // 'call() && @target()' public void testAtTargetAnnotationBinding1() { runTest("@target annotation binding 1"); } // 'call() && @target() && @target' public void testAtTargetAnnotationBinding2() { runTest("@target annotation binding 2"); } // 'call() && @target()' - using a type hierarchy where some levels are missing annotations public void testAtTargetAnnotationBinding3() { runTest("@target annotation binding 3"); } // 'call() && @target()' - using a type hierarchy where some levels are missing annotations // but the annotation is inherited public void testAtTargetAnnotationBinding4() { runTest("@target annotation binding 4"); } // @target() with an annotation in a package public void testAtTargetAnnotationBinding5() { runTest("@target annotation binding 5"); } ///////////////////////////////////// @THIS // 'call() && @this()' public void testAtThisAnnotationBinding1() { runTest("@this annotation binding 1"); } // 'call() && @this() && @this' public void testAtThisAnnotationBinding2() { runTest("@this annotation binding 2"); } // 'call() && @this()' - using a type hierarchy where some levels are missing annotations public void testAtThisAnnotationBinding3() { runTest("@this annotation binding 3"); } // 'call() && @this()' - using a type hierarchy where some levels are missing annotations // but the annotation is inherited public void testAtThisAnnotationBinding4() { runTest("@this annotation binding 4"); } // '@this() and @target()' used together public void testAtThisAtTargetAnnotationBinding() { runTest("@this annotation binding 5"); } ///////////////////////////////////// @ARGS // complex case when there are 3 parameters public void testAtArgs1() { runTest("@args annotation binding 1"); } // simple case when there is only one parameter public void testAtArgs2() { runTest("@args annotation binding 2"); } // simple case when there is only one parameter and no binding public void testAtArgs3() { runTest("@args annotation binding 3"); } // complex case binding different annotation kinds public void testAtArgs4() { runTest("@args annotation binding 4"); } // check @args and execution() public void testAtArgs5() { runTest("@args annotation binding 5"); } ///////////////////////////////////// @ANNOTATION and EXECUTION // 'execution() && @annotation()' public void testExecutionAnnotationBinding1() { runTest("execution and @annotation"); } ///////////////////////////////////// @ANNOTATION and SET // 'set() && @annotation()' public void testFieldAnnotationBinding1() { runTest("set and @annotation"); } // 'get() && @annotation()' public void testFieldAnnotationBinding2() { runTest("get and @annotation"); } // 'get() && @annotation()' when using array fields public void testFieldAnnotationBinding3() { runTest("get and @annotation with arrays"); } ///////////////////////////////////// @ANNOTATION and CTOR-CALL // 'ctor-call(new) && @annotation()' public void testCtorCallAnnotationBinding1() { runTest("cons call and @annotation"); } ///////////////////////////////////// @ANNOTATION and CTOR-CALL // 'ctor-execution() && @annotation()' public void testCtorExecAnnotationBinding1() { runTest("cons exe and @annotation"); } ///////////////////////////////////// @ANNOTATION and STATICINITIALIZATION // 'staticinitialization() && @annotation()' public void testStaticInitAnnotationBinding1() { runTest("staticinit and @annotation"); } ///////////////////////////////////// @ANNOTATION and PREINITIALIZATION // 'preinitialization() && @annotation()' public void testPreInitAnnotationBinding1() { runTest("preinit and @annotation"); } ///////////////////////////////////// @ANNOTATION and INITIALIZATION // 'initialization() && @annotation()' public void testInitAnnotationBinding1() { runTest("init and @annotation"); } ///////////////////////////////////// @ANNOTATION and ADVICEEXECUTION // 'adviceexecution() && @annotation()' public void testAdviceExecAnnotationBinding1() { runTest("adviceexecution and @annotation"); } ///////////////////////////////////// @ANNOTATION and HANDLER // 'handler() && @annotation()' public void testHandlerAnnotationBinding1() { runTest("handler and @annotation"); } ///////////////////////////////////// @WITHIN // '@within()' public void testWithinBinding1() { runTest("@within"); } //'@within()' but multiple types around (some annotated) public void testWithinBinding2() { runTest("@within - multiple types"); } ///////////////////////////////////// @WITHINCODE // '@withincode() && call(* println(..))' public void testWithinCodeBinding1() { runTest("@withincode() and call(* println(..))"); } ///////////////////////////////////// @ANNOTATION complex tests // Using package names for the types (including the annotation) - NO BINDING public void testPackageNamedTypesNoBinding() { runTest("packages and no binding"); } // Using package names for the types (including the annotation) - INCLUDES BINDING public void testPackageNamedTypesWithBinding() { runTest("packages and binding"); } // declare parents: @Color * implements Serializable public void testDeclareParentsWithAnnotatedAnyPattern() { runTest("annotated any pattern"); } // Should error (in a nice way!) on usage of an annotation that isnt imported public void testAnnotationUsedButNotImported() { runTest("annotation not imported"); } // Binding with calls/executions of static methods public void testCallsAndExecutionsOfStaticMethods() { runTest("binding with static methods"); } }
88,862
Bug 88862 Declare annotation on ITDs
I'll use this bug to capture info on the implementation...
resolved fixed
0d14ccf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T21:31:49Z
2005-03-23T15:00:00Z
tests/src/org/aspectj/systemtest/ajc150/Annotations.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.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.testing.XMLBasedAjcTestCase; public class Annotations extends XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Annotations.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void testCompilingAnnotation() { runTest("compiling an annotation"); } public void testCompilingAnnotatedFile() { runTest("compiling annotated file"); } public void testCompilingUsingWithinAndAnnotationTypePattern() { runTest("annotations and within (src)"); } /** * We had a bug where annotations were not present in the output class file for methods * that got woven. This was due to unpacking bugs in LazyMethodGen. This test compiles * a simple program then checks the annotations were copied across. */ public void testBugWithAnnotationsLostOnWovenMethods() throws ClassNotFoundException { runTest("losing annotations..."); if (getCurrentTest().canRunOnThisVM()) { JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Program"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (method.getName().equals("m1")) { assertTrue("Didn't have annotations - were they lost? method="+method.getName(),method.getAnnotations().length==1); } } } } public void testAnnotatedAnnotations() { runTest("annotated annotations (@Target)"); } public void testSimpleAnnotatedAspectMembers() { runTest("simple annotated aspect members"); } public void testAnnotatedAspectMembersWithWrongAnnotationType() { runTest("simple annotated aspect members with bad target"); } // more implementation work needed before this test passes public void testAnnotatedITDs() { runTest("annotated itds"); } public void testAnnotatedITDsWithWrongAnnotationType() { runTest("annotated itds with bad target"); } public void testAnnotatedAdvice() { runTest("annotated advice"); } public void testAnnotatedAdviceWithWrongAnnotationType() { runTest("annotated advice with bad target"); } public void testAnnotatedPointcut() { runTest("annotated pointcut"); } // FIXME asc uncomment this test when parser is opened up // public void testAnnotatedDeclareStatements() { // runTest("annotated declare statements"); // } public void testBasicDeclareAnnotation() { runTest("basic declare annotation parse test"); } public void testAJDKAnnotatingAspects() { runTest("ajdk: annotating aspects chapter"); } public void testAJDKAnnotatingAspects2() { runTest("ajdk: annotating aspects chapter, ex 2"); } public void testAnnotationPatterns() { runTest("ajdk: annotation pattern matching"); } public void testAnnotationTypePatterns() { runTest("ajdk: annotation type pattern matching"); } public void testAnnotationSigPatterns() { runTest("ajdk: annotations in sig patterns"); } public void testAnnotationRuntimeMatching() { runTest("ajdk: runtime annotations"); } public void testAnnotationRetentionChecking() { runTest("ajdk: @retention checking"); } public void testAnnotationInheritance() { runTest("ajdk: @inherited"); } public void testAnnotationDEOW() { runTest("ajdk: deow-ann"); } public void testAnnotationDecp() { runTest("ajdk: decp-ann"); } public void testAnnotationDecPrecedence() { runTest("ajdk: dec precedence"); } public void testAnnotationDecAnnotation() { runTest("ajdk: dec annotation"); } public void testAnnotationsAndITDs() { runTest("nasty annotation and itds test"); } // 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,862
Bug 88862 Declare annotation on ITDs
I'll use this bug to capture info on the implementation...
resolved fixed
0d14ccf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T21:31:49Z
2005-03-23T15:00:00Z
weaver/src/org/aspectj/weaver/NewFieldTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Set; public class NewFieldTypeMunger extends ResolvedTypeMunger { public NewFieldTypeMunger(ResolvedMember signature, Set superMethodsCalled) { super(Field, signature); this.setSuperMethodsCalled(superMethodsCalled); } public ResolvedMember getInitMethod(TypeX aspectType) { return AjcMemberMaker.interFieldInitializer(signature, aspectType); } public void write(DataOutputStream s) throws IOException { kind.write(s); signature.write(s); writeSuperMethodsCalled(s); if (ResolvedTypeMunger.persistSourceLocation) writeSourceLocation(s); } public static ResolvedTypeMunger readField(DataInputStream s, ISourceContext context) throws IOException { ResolvedTypeMunger munger = new NewFieldTypeMunger( ResolvedMember.readResolvedMember(s, context), readSuperMethodsCalled(s)); if (ResolvedTypeMunger.persistSourceLocation) munger.setSourceLocation(readSourceLocation(s)); return munger; } public ResolvedMember getMatchingSyntheticMember(Member member, ResolvedTypeX aspectType) { //??? might give a field where a method is expected ResolvedTypeX onType = aspectType.getWorld().resolve(getSignature().getDeclaringType()); ResolvedMember ret = AjcMemberMaker.interFieldGetDispatcher(getSignature(), aspectType); if (ResolvedTypeX.matches(ret, member)) return getSignature(); ret = AjcMemberMaker.interFieldSetDispatcher(getSignature(), aspectType); if (ResolvedTypeX.matches(ret, member)) return getSignature(); ret = AjcMemberMaker.interFieldInterfaceGetter(getSignature(), onType, aspectType); if (ResolvedTypeX.matches(ret, member)) return getSignature(); ret = AjcMemberMaker.interFieldInterfaceSetter(getSignature(), onType, aspectType); if (ResolvedTypeX.matches(ret, member)) return getSignature(); return super.getMatchingSyntheticMember(member, aspectType); } }
88,862
Bug 88862 Declare annotation on ITDs
I'll use this bug to capture info on the implementation...
resolved fixed
0d14ccf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T21:31:49Z
2005-03-23T15:00:00Z
weaver/src/org/aspectj/weaver/ResolvedMember.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import org.aspectj.bridge.ISourceLocation; /** * This is the declared member, i.e. it will always correspond to an * actual method/... declaration */ public class ResolvedMember extends Member implements IHasPosition, AnnotatedElement { public String[] parameterNames = null; protected TypeX[] checkedExceptions = TypeX.NONE; // 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 ResolvedMember( Kind kind, TypeX declaringType, int modifiers, TypeX returnType, String name, TypeX[] parameterTypes) { super(kind, declaringType, modifiers, returnType, name, parameterTypes); } public ResolvedMember( Kind kind, TypeX declaringType, int modifiers, TypeX returnType, String name, TypeX[] parameterTypes, TypeX[] checkedExceptions) { super(kind, declaringType, modifiers, returnType, name, parameterTypes); this.checkedExceptions = checkedExceptions; } public ResolvedMember( Kind kind, TypeX declaringType, int modifiers, String name, String signature) { super(kind, declaringType, modifiers, name, signature); } public static final ResolvedMember[] NONE = new ResolvedMember[0]; // ---- public final int getModifiers(World world) { return modifiers; } public final int getModifiers() { return modifiers; } // ---- public final TypeX[] getExceptions(World world) { return getExceptions(); } public TypeX[] getExceptions() { return checkedExceptions; } public ShadowMunger getAssociatedShadowMunger() { return null; } // ??? true or false? public boolean isAjSynthetic() { return true; } public boolean hasAnnotation(TypeX 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 return false; } public ResolvedTypeX[] 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 return null; } 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()); TypeX.writeArray(getExceptions(), s); s.writeInt(getStart()); s.writeInt(getEnd()); } 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 ResolvedMember readResolvedMember(DataInputStream s, ISourceContext sourceContext) throws IOException { ResolvedMember m = new ResolvedMember(Kind.read(s), TypeX.read(s), s.readInt(), s.readUTF(), s.readUTF()); m.checkedExceptions = TypeX.readArray(s); m.start = s.readInt(); m.end = s.readInt(); m.sourceContext = sourceContext; return m; } public static ResolvedMember[] readResolvedMemberArray(DataInputStream s, ISourceContext context) throws IOException { int len = s.readInt(); ResolvedMember[] members = new ResolvedMember[len]; for (int i=0; i < len; i++) { members[i] = ResolvedMember.readResolvedMember(s, context); } return members; } public ResolvedMember resolve(World 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 isDefault() { return !(isPublic() || isProtected() || isPrivate()); } public boolean isVisible(ResolvedTypeX fromType) { World world = fromType.getWorld(); return ResolvedTypeX.isVisible(getModifiers(), getDeclaringType().resolve(world), fromType); } public void setCheckedExceptions(TypeX[] checkedExceptions) { this.checkedExceptions = checkedExceptions; } }
88,862
Bug 88862 Declare annotation on ITDs
I'll use this bug to capture info on the implementation...
resolved fixed
0d14ccf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T21:31:49Z
2005-03-23T15:00:00Z
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.CPInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.IndexedInstruction; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LocalVariableInstruction; import org.aspectj.apache.bcel.generic.NEW; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUTFIELD; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.RET; import org.aspectj.apache.bcel.generic.ReturnInstruction; import org.aspectj.apache.bcel.generic.Select; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.util.FuzzyBoolean; import org.aspectj.util.PartialOrder; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.IClassWeaver; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.Shadow.Kind; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.FastMatchInfo; class BcelClassWeaver implements IClassWeaver { /** * This is called from {@link BcelWeaver} to perform the per-class weaving process. */ public static boolean weave( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers) { boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers).weave(); //System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState()); //clazz.print(); return b; } // -------------------------------------------- private final LazyClassGen clazz; private final List shadowMungers; private final List typeMungers; private final BcelObjectType ty; // alias of clazz.getType() private final BcelWorld world; // alias of ty.getWorld() private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen() private final InstructionFactory fact; // alias of clazz.getFactory(); private final List addedLazyMethodGens = new ArrayList(); private final Set addedDispatchTargets = new HashSet(); // Static setting across BcelClassWeavers private static boolean inReweavableMode = false; private static boolean compressReweavableAttributes = false; private List addedSuperInitializersAsList = null; // List<IfaceInitList> private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger> private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger> private BcelShadow clinitShadow = null; /** * This holds the initialization and pre-initialization shadows for this class * that were actually matched by mungers (if no match, then we don't even create the * shadows really). */ private final List initializationShadows = new ArrayList(1); private BcelClassWeaver( BcelWorld world, LazyClassGen clazz, List shadowMungers, List typeMungers) { super(); // assert world == clazz.getType().getWorld() this.world = world; this.clazz = clazz; this.shadowMungers = shadowMungers; this.typeMungers = typeMungers; this.ty = clazz.getBcelObjectType(); this.cpg = clazz.getConstantPoolGen(); this.fact = clazz.getFactory(); fastMatchShadowMungers(shadowMungers); initializeSuperInitializerMap(ty.getResolvedTypeX()); } private List[] perKindShadowMungers; private boolean canMatchBodyShadows = false; private boolean canMatchInitialization = false; private void fastMatchShadowMungers(List shadowMungers) { // beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) ! perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1]; for (int i = 0; i < perKindShadowMungers.length; i++) { ArrayList mungers = new ArrayList(0); perKindShadowMungers[i] = new ArrayList(0); } for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Set couldMatchKinds = munger.getPointcut().couldMatchKinds(); for (Iterator kindIterator = couldMatchKinds.iterator(); kindIterator.hasNext();) { Shadow.Kind aKind = (Shadow.Kind) kindIterator.next(); perKindShadowMungers[aKind.getKey()].add(munger); } } if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty()) canMatchInitialization = true; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { Shadow.Kind kind = Shadow.SHADOW_KINDS[i]; if (!kind.isEnclosingKind() && !perKindShadowMungers[i+1].isEmpty()) { canMatchBodyShadows = true; } if (perKindShadowMungers[i+1].isEmpty()) { perKindShadowMungers[i+1] = null; } } } private boolean canMatch(Shadow.Kind kind) { return perKindShadowMungers[kind.getKey()] != null; } private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) { FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind); for (Iterator i = shadowMungers.iterator(); i.hasNext();) { ShadowMunger munger = (ShadowMunger) i.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString() if (fb.maybeTrue()) mungers.add(munger); } } private void initializeSuperInitializerMap(ResolvedTypeX child) { ResolvedTypeX[] superInterfaces = child.getDeclaredInterfaces(); for (int i=0, len=superInterfaces.length; i < len; i++) { if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) { if (addSuperInitializer(superInterfaces[i])) { initializeSuperInitializerMap(superInterfaces[i]); } } } } private boolean addSuperInitializer(ResolvedTypeX onType) { IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); if (l != null) return false; l = new IfaceInitList(onType); addedSuperInitializers.put(onType, l); return true; } public void addInitializer(ConcreteTypeMunger cm) { NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger(); ResolvedTypeX onType = m.getSignature().getDeclaringType().resolve(world); if (m.getSignature().isStatic()) { addedClassInitializers.add(cm); } else { if (onType == ty.getResolvedTypeX()) { addedThisInitializers.add(cm); } else { IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType); l.list.add(cm); } } } private static class IfaceInitList implements PartialOrder.PartialComparable { final ResolvedTypeX onType; List list = new ArrayList(); IfaceInitList(ResolvedTypeX onType) { this.onType = onType; } public int compareTo(Object other) { IfaceInitList o = (IfaceInitList)other; if (onType.isAssignableFrom(o.onType)) return +1; else if (o.onType.isAssignableFrom(onType)) return -1; else return 0; } public int fallbackCompareTo(Object other) { return 0; } } // XXX this is being called, but the result doesn't seem to be being used public boolean addDispatchTarget(ResolvedMember m) { return addedDispatchTargets.add(m); } public void addLazyMethodGen(LazyMethodGen gen) { addedLazyMethodGens.add(gen); } public void addOrReplaceLazyMethodGen(LazyMethodGen mg) { if (alreadyDefined(clazz, mg)) return; for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (existing.definingType == null) { // this means existing was introduced on the class itself return; } else if (mg.definingType.isAssignableFrom(existing.definingType)) { // existing is mg's subtype and dominates mg return; } else if (existing.definingType.isAssignableFrom(mg.definingType)) { // mg is existing's subtype and dominates existing i.remove(); addedLazyMethodGens.add(mg); return; } else { throw new BCException("conflict between: " + mg + " and " + existing); } } } addedLazyMethodGens.add(mg); } private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) { for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen existing = (LazyMethodGen)i.next(); if (signaturesMatch(mg, existing)) { if (!mg.isAbstract() && existing.isAbstract()) { i.remove(); return false; } return true; } } return false; } private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) { return mg.getName().equals(existing.getName()) && mg.getSignature().equals(existing.getSignature()); } // ---- public boolean weave() { if (clazz.isWoven() && !clazz.isReweavable()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()), ty.getSourceLocation(), null); return false; } Set aspectsAffectingType = null; if (inReweavableMode) aspectsAffectingType = new HashSet(); boolean isChanged = false; // we want to "touch" all aspects if (clazz.getType().isAspect()) isChanged = true; // start by munging all typeMungers for (Iterator i = typeMungers.iterator(); i.hasNext(); ) { Object o = i.next(); if ( !(o instanceof BcelTypeMunger) ) { //???System.err.println("surprising: " + o); continue; } BcelTypeMunger munger = (BcelTypeMunger)o; boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { isChanged = true; if (inReweavableMode) aspectsAffectingType.add(munger.getAspectType().getName()); } } // Weave special half type/half shadow mungers... isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged; isChanged = weaveDeclareAtField(clazz) || isChanged; // XXX do major sort of stuff // sort according to: Major: type hierarchy // within each list: dominates // don't forget to sort addedThisInitialiers according to dominates addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values()); addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList); if (addedSuperInitializersAsList == null) { throw new BCException("circularity in inter-types"); } // this will create a static initializer if there isn't one // this is in just as bad taste as NOPs LazyMethodGen staticInit = clazz.getStaticInitializer(); staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true)); // now go through each method, and match against each method. This // sets up each method's {@link LazyMethodGen#matchedShadows} field, // and it also possibly adds to {@link #initializationShadows}. List methodGens = new ArrayList(clazz.getMethodGens()); for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); //mg.getBody(); if (! mg.hasBody()) continue; boolean shadowMungerMatched = match(mg); if (shadowMungerMatched) { // For matching mungers, add their declaring aspects to the list that affected this type if (inReweavableMode) aspectsAffectingType.addAll(findAspectsForMungers(mg)); isChanged = true; } } if (! isChanged) return false; // now we weave all but the initialization shadows for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen)i.next(); if (! mg.hasBody()) continue; implement(mg); } // if we matched any initialization shadows, we inline and weave if (! initializationShadows.isEmpty()) { // Repeat next step until nothing left to inline...cant go on // infinetly as compiler will have detected and reported // "Recursive constructor invocation" while (inlineSelfConstructors(methodGens)); positionAndImplement(initializationShadows); } // finally, if we changed, we add in the introduced methods. if (isChanged) { clazz.getOrCreateWeaverStateInfo(); weaveInAddedMethods(); // FIXME asc are these potentially affected by declare annotation? } if (inReweavableMode) { WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(); wsi.addAspectsAffectingType(aspectsAffectingType); wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes()); wsi.setReweavable(true,compressReweavableAttributes); } else { clazz.getOrCreateWeaverStateInfo().setReweavable(false,false); } return isChanged; } /** * Weave any declare @method/@ctor statements into the members of the supplied class */ private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) { boolean isChanged = false; List decaMs = getMatchingSubset(world.getDeclareAnnotationOnMethods(),clazz.getType()); List members = clazz.getMethodGens(); if (!members.isEmpty() && !decaMs.isEmpty()) { // go through all the fields for (int memberCounter = 0;memberCounter<members.size();memberCounter++) { LazyMethodGen mg = (LazyMethodGen)members.get(memberCounter); if (!mg.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; // go through all the declare @field statements for (Iterator iter = decaMs.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,true)) continue; // skip this one... mg.addAnnotation(decaM.getAnnotationX()); //System.err.println("Mloc ("+mg+") ="+mg.getSourceLocation()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); isChanged = true; modificationOccured = true; } else { if (!decaM.isStarredAnnotationPattern()) worthRetrying.add(decaM); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaM = (DeclareAnnotation) iter.next(); if (decaM.matches(mg.getMemberView(),world)) { if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,false)) continue; // skip this one... mg.addAnnotation(decaM.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod()); isChanged = true; modificationOccured = true; forRemoval.add(decaM); } } worthRetrying.removeAll(forRemoval); } } } } return isChanged; } /** * Looks through a list of declare annotation statements and only returns * those that could possibly match on a field/method/ctor in type. */ private List getMatchingSubset(List declareAnnotations, ResolvedTypeX type) { List subset = new ArrayList(); //System.err.println("For type="+type+"\nPrior set: "+declareAnnotations); for (Iterator iter = declareAnnotations.iterator(); iter.hasNext();) { DeclareAnnotation da = (DeclareAnnotation) iter.next(); if (da.couldEverMatch(type)) { subset.add(da); } } //System.err.println("After set: "+subset); return subset; } /** * Weave any declare @field statements into the fields of the supplied class */ private boolean weaveDeclareAtField(LazyClassGen clazz) { // BUGWARNING not getting enough warnings out on declare @field ? // There is a potential problem here with warnings not coming out - this // will occur if they are created on the second iteration round this loop. // We currently deactivate error reporting for the second time round. // A possible solution is to record what annotations were added by what // decafs and check that to see if an error needs to be reported - this // would be expensive so lets skip it for now List decaFs = getMatchingSubset(world.getDeclareAnnotationOnFields(),clazz.getType()); boolean isChanged = false; Field[] fields = clazz.getFieldGens(); if (fields!=null && !decaFs.isEmpty()) { // go through all the fields for (int fieldCounter = 0;fieldCounter<fields.length;fieldCounter++) { BcelField aBcelField = new BcelField(clazz.getBcelObjectType(),fields[fieldCounter]); if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) { // Single first pass List worthRetrying = new ArrayList(); boolean modificationOccured = false; // go through all the declare @field statements for (Iterator iter = decaFs.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { if (doesAlreadyHaveAnnotation(aBcelField,decaF,true)) continue; // skip this one... aBcelField.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); isChanged = true; modificationOccured = true; } else { if (!decaF.isStarredAnnotationPattern()) worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf } } // Multiple secondary passes while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; // lets have another go List forRemoval = new ArrayList(); for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) { DeclareAnnotation decaF = (DeclareAnnotation) iter.next(); if (decaF.matches(aBcelField,world)) { if (doesAlreadyHaveAnnotation(aBcelField,decaF,false)) continue; // skip this one... aBcelField.addAnnotation(decaF.getAnnotationX()); AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]); isChanged = true; modificationOccured = true; forRemoval.add(decaF); } } worthRetrying.removeAll(forRemoval); } } } } return isChanged; } /** * Check if a resolved member (field/method/ctor) already has an annotation, if it * does then put out a warning and return true */ private boolean doesAlreadyHaveAnnotation(ResolvedMember rm,DeclareAnnotation deca,boolean reportProblems) { if (rm.hasAnnotation(deca.getAnnotationTypeX())) { if (reportProblems) { world.getLint().elementAlreadyAnnotated.signal( new String[]{rm.toString(),deca.getAnnotationTypeX().toString()}, rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()}); } return true; } return false; } private Set findAspectsForMungers(LazyMethodGen mg) { Set aspectsAffectingType = new HashSet(); for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) { BcelShadow aShadow = (BcelShadow) iter.next(); // Mungers in effect on that shadow for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) { ShadowMunger aMunger = (ShadowMunger) iter2.next(); if (aMunger instanceof BcelAdvice) { BcelAdvice bAdvice = (BcelAdvice)aMunger; aspectsAffectingType.add(bAdvice.getConcreteAspect().getName()); } else { // It is a 'Checker' - we don't need to remember aspects that only contributed Checkers... } } } return aspectsAffectingType; } private boolean inlineSelfConstructors(List methodGens) { boolean inlinedSomething = false; for (Iterator i = methodGens.iterator(); i.hasNext();) { LazyMethodGen mg = (LazyMethodGen) i.next(); if (! mg.getName().equals("<init>")) continue; InstructionHandle ih = findSuperOrThisCall(mg); if (ih != null && isThisCall(ih)) { LazyMethodGen donor = getCalledMethod(ih); inlineMethod(donor, mg, ih); inlinedSomething = true; } } return inlinedSomething; } private void positionAndImplement(List initializationShadows) { for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) { BcelShadow s = (BcelShadow) i.next(); positionInitializationShadow(s); //s.getEnclosingMethod().print(); s.implement(); } } private void positionInitializationShadow(BcelShadow s) { LazyMethodGen mg = s.getEnclosingMethod(); InstructionHandle call = findSuperOrThisCall(mg); InstructionList body = mg.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow((BcelShadow) s); if (s.getKind() == Shadow.PreInitialization) { // XXX assert first instruction is an ALOAD_0. // a pre shadow goes from AFTER the first instruction (which we believe to // be an ALOAD_0) to just before the call to super r.associateWithTargets( Range.genStart(body, body.getStart().getNext()), Range.genEnd(body, call.getPrev())); } else { // assert s.getKind() == Shadow.Initialization r.associateWithTargets( Range.genStart(body, call.getNext()), Range.genEnd(body)); } } private boolean isThisCall(InstructionHandle ih) { INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction(); return inst.getClassName(cpg).equals(clazz.getName()); } /** inline a particular call in bytecode. * * @param donor the method we want to inline * @param recipient the method containing the call we want to inline * @param call the instructionHandle in recipient's body holding the call we want to * inline. */ public static void inlineMethod( LazyMethodGen donor, LazyMethodGen recipient, InstructionHandle call) { // assert recipient.contains(call) /* Implementation notes: * * We allocate two slots for every tempvar so we don't screw up * longs and doubles which may share space. This could be conservatively avoided * (no reference to a long/double instruction, don't do it) or packed later. * Right now we don't bother to pack. * * Allocate a new var for each formal param of the inlined. Fill with stack * contents. Then copy the inlined instructions in with the appropriate remap * table. Any framelocs used by locals in inlined are reallocated to top of * frame, */ final InstructionFactory fact = recipient.getEnclosingClass().getFactory(); IntMap frameEnv = new IntMap(); // this also sets up the initial environment InstructionList argumentStores = genArgumentStores(donor, recipient, frameEnv, fact); InstructionList inlineInstructions = genInlineInstructions(donor, recipient, frameEnv, fact, false); inlineInstructions.insert(argumentStores); recipient.getBody().append(call, inlineInstructions); Utility.deleteInstruction(call, recipient); } /** generate the instructions to be inlined. * * @param donor the method from which we will copy (and adjust frame and jumps) * instructions. * @param recipient the method the instructions will go into. Used to get the frame * size so we can allocate new frame locations for locals in donor. * @param frameEnv an environment to map from donor frame to recipient frame, * initially populated with argument locations. * @param fact an instruction factory for recipient */ static InstructionList genInlineInstructions( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact, boolean keepReturns) { InstructionList footer = new InstructionList(); InstructionHandle end = footer.append(InstructionConstants.NOP); InstructionList ret = new InstructionList(); InstructionList sourceList = donor.getBody(); Map srcToDest = new HashMap(); ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen(); ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen(); boolean isAcrossClass = donorCpg != recipientCpg; // first pass: copy the instructions directly, populate the srcToDest map, // fix frame instructions for (InstructionHandle src = sourceList.getStart(); src != null; src = src.getNext()) { Instruction fresh = Utility.copyInstruction(src.getInstruction()); InstructionHandle dest; if (fresh instanceof CPInstruction) { // need to reset index to go to new constant pool. This is totally // a computation leak... we're testing this LOTS of times. Sigh. if (isAcrossClass) { CPInstruction cpi = (CPInstruction) fresh; cpi.setIndex( recipientCpg.addConstant( donorCpg.getConstant(cpi.getIndex()), donorCpg)); } } if (src.getInstruction() == Range.RANGEINSTRUCTION) { dest = ret.append(Range.RANGEINSTRUCTION); } else if (fresh instanceof ReturnInstruction) { if (keepReturns) { dest = ret.append(fresh); } else { dest = ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end)); } } else if (fresh instanceof BranchInstruction) { dest = ret.append((BranchInstruction) fresh); } else if ( fresh instanceof LocalVariableInstruction || fresh instanceof RET) { IndexedInstruction indexed = (IndexedInstruction) fresh; int oldIndex = indexed.getIndex(); int freshIndex; if (!frameEnv.hasKey(oldIndex)) { freshIndex = recipient.allocateLocal(2); frameEnv.put(oldIndex, freshIndex); } else { freshIndex = frameEnv.get(oldIndex); } indexed.setIndex(freshIndex); dest = ret.append(fresh); } else { dest = ret.append(fresh); } srcToDest.put(src, dest); } // second pass: retarget branch instructions, copy ranges and tags Map tagMap = new HashMap(); Map shadowMap = new HashMap(); for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart(); dest != null; dest = dest.getNext(), src = src.getNext()) { Instruction inst = dest.getInstruction(); // retarget branches if (inst instanceof BranchInstruction) { BranchInstruction branch = (BranchInstruction) inst; InstructionHandle oldTarget = branch.getTarget(); InstructionHandle newTarget = (InstructionHandle) srcToDest.get(oldTarget); if (newTarget == null) { // assert this is a GOTO // this was a return instruction we previously replaced } else { branch.setTarget(newTarget); if (branch instanceof Select) { Select select = (Select) branch; InstructionHandle[] oldTargets = select.getTargets(); for (int k = oldTargets.length - 1; k >= 0; k--) { select.setTarget( k, (InstructionHandle) srcToDest.get(oldTargets[k])); } } } } //copy over tags and range attributes InstructionTargeter[] srcTargeters = src.getTargeters(); if (srcTargeters != null) { for (int j = srcTargeters.length - 1; j >= 0; j--) { InstructionTargeter old = srcTargeters[j]; if (old instanceof Tag) { Tag oldTag = (Tag) old; Tag fresh = (Tag) tagMap.get(oldTag); if (fresh == null) { fresh = oldTag.copy(); tagMap.put(oldTag, fresh); } dest.addTargeter(fresh); } else if (old instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) old; if (er.getStart() == src) { ExceptionRange freshEr = new ExceptionRange( recipient.getBody(), er.getCatchType(), er.getPriority()); freshEr.associateWithTargets( dest, (InstructionHandle)srcToDest.get(er.getEnd()), (InstructionHandle)srcToDest.get(er.getHandler())); } } else if (old instanceof ShadowRange) { ShadowRange oldRange = (ShadowRange) old; if (oldRange.getStart() == src) { BcelShadow oldShadow = oldRange.getShadow(); BcelShadow freshEnclosing = oldShadow.getEnclosingShadow() == null ? null : (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow()); BcelShadow freshShadow = oldShadow.copyInto(recipient, freshEnclosing); ShadowRange freshRange = new ShadowRange(recipient.getBody()); freshRange.associateWithShadow(freshShadow); freshRange.associateWithTargets( dest, (InstructionHandle) srcToDest.get(oldRange.getEnd())); shadowMap.put(oldRange, freshRange); //recipient.matchedShadows.add(freshShadow); // XXX should go through the NEW copied shadow and update // the thisVar, targetVar, and argsVar // ??? Might want to also go through at this time and add // "extra" vars to the shadow. } } } } } if (!keepReturns) ret.append(footer); return ret; } /** generate the argument stores in preparation for inlining. * * @param donor the method we will inline from. Used to get the signature. * @param recipient the method we will inline into. Used to get the frame size * so we can allocate fresh locations. * @param frameEnv an empty environment we populate with a map from donor frame to * recipient frame. * @param fact an instruction factory for recipient */ private static InstructionList genArgumentStores( LazyMethodGen donor, LazyMethodGen recipient, IntMap frameEnv, InstructionFactory fact) { InstructionList ret = new InstructionList(); int donorFramePos = 0; // writing ret back to front because we're popping. if (! donor.isStatic()) { int targetSlot = recipient.allocateLocal(Type.OBJECT); ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot)); frameEnv.put(donorFramePos, targetSlot); donorFramePos += 1; } Type[] argTypes = donor.getArgumentTypes(); for (int i = 0, len = argTypes.length; i < len; i++) { Type argType = argTypes[i]; int argSlot = recipient.allocateLocal(argType); ret.insert(InstructionFactory.createStore(argType, argSlot)); frameEnv.put(donorFramePos, argSlot); donorFramePos += argType.getSize(); } return ret; } /** get a called method: Assumes the called method is in this class, * and the reference to it is exact (a la INVOKESPECIAL). * * @param ih The InvokeInstruction instructionHandle pointing to the called method. */ private LazyMethodGen getCalledMethod( InstructionHandle ih) { InvokeInstruction inst = (InvokeInstruction) ih.getInstruction(); String methodName = inst.getName(cpg); String signature = inst.getSignature(cpg); return clazz.getLazyMethodGen(methodName, signature); } private void weaveInAddedMethods() { Collections.sort(addedLazyMethodGens, new Comparator() { public int compare(Object a, Object b) { LazyMethodGen aa = (LazyMethodGen) a; LazyMethodGen bb = (LazyMethodGen) b; int i = aa.getName().compareTo(bb.getName()); if (i != 0) return i; return aa.getSignature().compareTo(bb.getSignature()); } } ); for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) { clazz.addMethodGen((LazyMethodGen)i.next()); } } void addPerSingletonField(Member field) { ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType()); String aspectName = field.getReturnType().getName(); LazyMethodGen clinit = clazz.getStaticInitializer(); InstructionList setup = new InstructionList(); InstructionFactory fact = clazz.getFactory(); setup.append(fact.createNew(aspectType)); setup.append(InstructionFactory.createDup(1)); setup.append(fact.createInvoke( aspectName, "<init>", Type.VOID, new Type[0], Constants.INVOKESPECIAL)); setup.append( fact.createFieldAccess( aspectName, field.getName(), aspectType, Constants.PUTSTATIC)); clinit.getBody().insert(setup); } /** * Returns null if this is not a Java constructor, and then we won't * weave into it at all */ private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) { int depth = 1; InstructionHandle start = mg.getBody().getStart(); while (true) { if (start == null) return null; Instruction inst = start.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth--; if (depth == 0) return start; } else if (inst instanceof NEW) { depth++; } start = start.getNext(); } } // ---- private boolean match(LazyMethodGen mg) { BcelShadow enclosingShadow; List shadowAccumulator = new ArrayList(); // we want to match ajsynthetic constructors... if (mg.getName().equals("<init>")) { return matchInit(mg, shadowAccumulator); } else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) { return false; } else { if (mg.getName().equals("<clinit>")) { clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg); //System.err.println(enclosingShadow); } else if (mg.isAdviceMethod()) { enclosingShadow = BcelShadow.makeAdviceExecution(world, mg); } else { AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature(); if (effective == null) { enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows); } else if (effective.isWeaveBody()) { enclosingShadow = BcelShadow.makeShadowForMethod( world, mg, effective.getShadowKind(), effective.getEffectiveSignature()); } else { return false; } } if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { match(mg, h, enclosingShadow, shadowAccumulator); } } if (canMatch(enclosingShadow.getKind())) { if (match(enclosingShadow, shadowAccumulator)) { enclosingShadow.init(); } } mg.matchedShadows = shadowAccumulator; return !shadowAccumulator.isEmpty(); } } private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) { BcelShadow enclosingShadow; // XXX the enclosing join point is wrong for things before ignoreMe. InstructionHandle superOrThisCall = findSuperOrThisCall(mg); // we don't walk bodies of things where it's a wrong constructor thingie if (superOrThisCall == null) return false; enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall); // walk the body boolean beforeSuperOrThisCall = true; if (shouldWeaveBody(mg)) { if (canMatchBodyShadows) { for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) { if (h == superOrThisCall) { beforeSuperOrThisCall = false; continue; } match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator); } } if (canMatch(Shadow.ConstructorExecution)) match(enclosingShadow, shadowAccumulator); } // XXX we don't do pre-inits of interfaces // now add interface inits if (superOrThisCall != null && ! isThisCall(superOrThisCall)) { InstructionHandle curr = enclosingShadow.getRange().getStart(); for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) { IfaceInitList l = (IfaceInitList) i.next(); Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType); BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig); // insert code in place InstructionList inits = genInitInstructions(l.list, false); if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) { initShadow.initIfaceInitializer(curr); initShadow.getRange().insert(inits, Range.OutsideBefore); } } // now we add our initialization code InstructionList inits = genInitInstructions(addedThisInitializers, false); enclosingShadow.getRange().insert(inits, Range.OutsideBefore); } // actually, you only need to inline the self constructors that are // in a particular group (partition the constructors into groups where members // call or are called only by those in the group). Then only inline // constructors // in groups where at least one initialization jp matched. Future work. boolean addedInitialization = match( BcelShadow.makeUnfinishedInitialization(world, mg), initializationShadows); addedInitialization |= match( BcelShadow.makeUnfinishedPreinitialization(world, mg), initializationShadows); mg.matchedShadows = shadowAccumulator; return addedInitialization || !shadowAccumulator.isEmpty(); } private boolean shouldWeaveBody(LazyMethodGen mg) { if (mg.isBridgeMethod()) return false; if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>"); AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature(); if (a != null) return a.isWeaveBody(); return true; } /** * first sorts the mungers, then gens the initializers in the right order */ private InstructionList genInitInstructions(List list, boolean isStatic) { list = PartialOrder.sort(list); if (list == null) { throw new BCException("circularity in inter-types"); } InstructionList ret = new InstructionList(); for (Iterator i = list.iterator(); i.hasNext();) { ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next(); NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger(); ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType()); if (!isStatic) ret.append(InstructionConstants.ALOAD_0); ret.append(Utility.createInvoke(fact, world, initMethod)); } return ret; } private void match( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { Instruction i = ih.getInstruction(); if ((i instanceof FieldInstruction) && (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) ) { FieldInstruction fi = (FieldInstruction) i; if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) { // check for sets of constant fields. We first check the previous // instruction. If the previous instruction is a LD_WHATEVER (push // constant on the stack) then we must resolve the field to determine // if it's final. If it is final, then we don't generate a shadow. InstructionHandle prevHandle = ih.getPrev(); Instruction prevI = prevHandle.getInstruction(); if (Utility.isConstantPushInstruction(prevI)) { Member field = BcelWorld.makeFieldSignature(clazz, (FieldInstruction) i); ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. } else if (Modifier.isFinal(resolvedField.getModifiers())) { // it's final, so it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldSet)) matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else { if (canMatch(Shadow.FieldGet)) matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator); } } else if (i instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction) i; if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) { if (canMatch(Shadow.ConstructorCall)) match( BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow), shadowAccumulator); } else if (ii instanceof INVOKESPECIAL) { String onTypeName = ii.getClassName(cpg); if (onTypeName.equals(mg.getEnclosingClass().getName())) { // we are private matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } else { // we are a super call, and this is not a join point in AspectJ-1.{0,1} } } else { matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator); } } // performance optimization... we only actually care about ASTORE instructions, // since that's what every javac type thing ever uses to start a handler, but for // now we'll do this for everybody. if (!canMatch(Shadow.ExceptionHandler)) return; if (Range.isRangeHandle(ih)) return; InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int j = 0; j < targeters.length; j++) { InstructionTargeter t = targeters[j]; if (t instanceof ExceptionRange) { // assert t.getHandler() == ih ExceptionRange er = (ExceptionRange) t; if (er.getCatchType() == null) continue; if (isInitFailureHandler(ih)) return; match( BcelShadow.makeExceptionHandler( world, er, mg, ih, enclosingShadow), shadowAccumulator); } } } } private boolean isInitFailureHandler(InstructionHandle ih) { // Skip the astore_0 and aload_0 at the start of the handler and // then check if the instruction following these is // 'putstatic ajc$initFailureCause'. If it is then we are // in the handler we created in AspectClinit.generatePostSyntheticCode() InstructionHandle twoInstructionsAway = ih.getNext().getNext(); if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) { String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg); if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true; } return false; } private void matchSetInstruction( LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if ( Modifier.isFinal(resolvedField.getModifiers()) && Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) { // it's the set of a final constant, so it's // not a join point according to 1.0.6 and 1.1. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { match( BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow), shadowAccumulator); } } private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) { FieldInstruction fi = (FieldInstruction) ih.getInstruction(); Member field = BcelWorld.makeFieldSignature(clazz, fi); // synthetic fields are never join points if (field.getName().startsWith(NameMangler.PREFIX)) return; ResolvedMember resolvedField = field.resolve(world); if (resolvedField == null) { // we can't find the field, so it's not a join point. return; } else if (resolvedField.isSynthetic()) { // sets of synthetics aren't join points in 1.1 return; } else { match(BcelShadow.makeFieldGet(world, mg, ih, enclosingShadow), shadowAccumulator); } } private void matchInvokeInstruction(LazyMethodGen mg, InstructionHandle ih, InvokeInstruction invoke, BcelShadow enclosingShadow, List shadowAccumulator) { String methodName = invoke.getName(cpg); if (methodName.startsWith(NameMangler.PREFIX)) { Member method = BcelWorld.makeMethodSignature(clazz, invoke); ResolvedMember declaredSig = method.resolve(world); //System.err.println(method + ", declaredSig: " +declaredSig); if (declaredSig == null) return; if (declaredSig.getKind() == Member.FIELD) { Shadow.Kind kind; if (method.getReturnType().equals(ResolvedTypeX.VOID)) { kind = Shadow.FieldSet; } else { kind = Shadow.FieldGet; } if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet)) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, kind, declaredSig), shadowAccumulator); } else { AjAttribute.EffectiveSignatureAttribute effectiveSig = declaredSig.getEffectiveSignature(); if (effectiveSig == null) return; //System.err.println("call to inter-type member: " + effectiveSig); if (effectiveSig.isWeaveBody()) return; if (canMatch(effectiveSig.getShadowKind())) match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, effectiveSig.getShadowKind(), effectiveSig.getEffectiveSignature()), shadowAccumulator); } } else { if (canMatch(Shadow.MethodCall)) match( BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow), shadowAccumulator); } } private boolean match(BcelShadow shadow, List shadowAccumulator) { //System.err.println("match: " + shadow); boolean isMatched = false; for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) { ShadowMunger munger = (ShadowMunger)i.next(); if (munger.match(shadow, world)) { WeaverMetrics.recordMatchResult(true);// Could pass: munger shadow.addMunger(munger); isMatched = true; if (shadow.getKind() == Shadow.StaticInitialization) { clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation()); } } else { WeaverMetrics.recordMatchResult(false); // Could pass: munger } } if (isMatched) shadowAccumulator.add(shadow); return isMatched; } // ---- private void implement(LazyMethodGen mg) { List shadows = mg.matchedShadows; if (shadows == null) return; // We depend on a partial order such that inner shadows are earlier on the list // than outer shadows. That's fine. This order is preserved if: // A preceeds B iff B.getStart() is LATER THAN A.getStart(). for (Iterator i = shadows.iterator(); i.hasNext(); ) { BcelShadow shadow = (BcelShadow)i.next(); shadow.implement(); } mg.matchedShadows = null; } // ---- public LazyClassGen getLazyClassGen() { return clazz; } public List getShadowMungers() { return shadowMungers; } public BcelWorld getWorld() { return world; } // Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info public static void setReweavableMode(boolean mode,boolean compress) { inReweavableMode = mode; compressReweavableAttributes = compress; } }
88,862
Bug 88862 Declare annotation on ITDs
I'll use this bug to capture info on the implementation...
resolved fixed
0d14ccf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T21:31:49Z
2005-03-23T15:00:00Z
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.generic.ACONST_NULL; import org.aspectj.apache.bcel.generic.ANEWARRAY; import org.aspectj.apache.bcel.generic.ArrayType; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.DUP; import org.aspectj.apache.bcel.generic.DUP_X1; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.INVOKESTATIC; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.InstructionTargeter; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.LoadInstruction; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.NEW; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUSH; import org.aspectj.apache.bcel.generic.ReturnInstruction; import org.aspectj.apache.bcel.generic.SWAP; import org.aspectj.apache.bcel.generic.StoreInstruction; import org.aspectj.apache.bcel.generic.TargetLostException; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.BCException; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Var; /* * Some fun implementation stuff: * * * expressionKind advice is non-execution advice * * may have a target. * * if the body is extracted, it will be extracted into * a static method. The first argument to the static * method is the target * * advice may expose a this object, but that's the advice's * consideration, not ours. This object will NOT be cached in another * local, but will always come from frame zero. * * * non-expressionKind advice is execution advice * * may have a this. * * target is same as this, and is exposed that way to advice * (i.e., target will not be cached, will always come from frame zero) * * if the body is extracted, it will be extracted into a method * with same static/dynamic modifier as enclosing method. If non-static, * target of callback call will be this. * * * because of these two facts, the setup of the actual arguments (including * possible target) callback method is the same for both kinds of advice: * push the targetVar, if it exists (it will not exist for advice on static * things), then push all the argVars. * * Protected things: * * * the above is sufficient for non-expressionKind advice for protected things, * since the target will always be this. * * * For expressionKind things, we have to modify the signature of the callback * method slightly. For non-static expressionKind things, we modify * the first argument of the callback method NOT to be the type specified * by the method/field signature (the owner), but rather we type it to * the currentlyEnclosing type. We are guaranteed this will be fine, * since the verifier verifies that the target is a subtype of the currently * enclosingType. * * Worries: * * * ConstructorCalls will be weirder than all of these, since they * supposedly don't have a target (according to AspectJ), but they clearly * do have a target of sorts, just one that needs to be pushed on the stack, * dupped, and not touched otherwise until the constructor runs. * * @author Jim Hugunin * @author Erik Hilsdale * */ public class BcelShadow extends Shadow { private ShadowRange range; private final BcelWorld world; private final LazyMethodGen enclosingMethod; private boolean fallsThrough; //XXX not used anymore // ---- initialization /** * This generates an unassociated shadow, rooted in a particular method but not rooted * to any particular point in the code. It should be given to a rooted ShadowRange * in the {@link ShadowRange#associateWithShadow(BcelShadow)} method. */ public BcelShadow( BcelWorld world, Kind kind, Member signature, LazyMethodGen enclosingMethod, BcelShadow enclosingShadow) { super(kind, signature, enclosingShadow); this.world = world; this.enclosingMethod = enclosingMethod; fallsThrough = kind.argsOnStack(); } // ---- copies all state, including Shadow's mungers... public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) { BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing); List src = mungers; List dest = s.mungers; for (Iterator i = src.iterator(); i.hasNext(); ) { dest.add(i.next()); } return s; } // ---- overridden behaviour public World getIWorld() { return world; } private void deleteNewAndDup() { final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen(); int depth = 1; InstructionHandle ih = range.getStart(); while (true) { Instruction inst = ih.getInstruction(); if (inst instanceof INVOKESPECIAL && ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) { depth++; } else if (inst instanceof NEW) { depth--; if (depth == 0) break; } ih = ih.getPrev(); } // now IH points to the NEW. We're followed by the DUP, and that is followed // by the actual instruciton we care about. InstructionHandle newHandle = ih; InstructionHandle endHandle = newHandle.getNext(); InstructionHandle nextHandle; if (endHandle.getInstruction() instanceof DUP) { nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else if (endHandle.getInstruction() instanceof DUP_X1) { InstructionHandle dupHandle = endHandle; endHandle = endHandle.getNext(); nextHandle = endHandle.getNext(); if (endHandle.getInstruction() instanceof SWAP) {} else { // XXX see next XXX comment throw new RuntimeException("Unhandled kind of new " + endHandle); } retargetFrom(newHandle, nextHandle); retargetFrom(dupHandle, nextHandle); retargetFrom(endHandle, nextHandle); } else { endHandle = newHandle; nextHandle = endHandle.getNext(); retargetFrom(newHandle, nextHandle); // add a POP here... we found a NEW w/o a dup or anything else, so // we must be in statement context. getRange().insert(InstructionConstants.POP, Range.OutsideAfter); } // assert (dupHandle.getInstruction() instanceof DUP); try { range.getBody().delete(newHandle, endHandle); } catch (TargetLostException e) { throw new BCException("shouldn't happen"); } } private void retargetFrom(InstructionHandle old, InstructionHandle fresh) { InstructionTargeter[] sources = old.getTargeters(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { sources[i].updateTarget(old, fresh); } } } protected void prepareForMungers() { // if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap, // and store all our // arguments on the frame. // ??? This is a bit of a hack (for the Java langauge). We do this because // we sometime add code "outsideBefore" when dealing with weaving join points. We only // do this for exposing state that is on the stack. It turns out to just work for // everything except for constructor calls and exception handlers. If we were to clean // this up, every ShadowRange would have three instructionHandle points, the start of // the arg-setup code, the start of the running code, and the end of the running code. if (getKind() == ConstructorCall) { deleteNewAndDup(); initializeArgVars(); } else if (getKind() == PreInitialization) { // pr74952 ShadowRange range = getRange(); range.insert(InstructionConstants.NOP,Range.InsideAfter); } else if (getKind() == ExceptionHandler) { ShadowRange range = getRange(); InstructionList body = range.getBody(); InstructionHandle start = range.getStart(); // Create a store instruction to put the value from the top of the // stack into a local variable slot. This is a trimmed version of // what is in initializeArgVars() (since there is only one argument // at a handler jp and only before advice is supported) (pr46298) argVars = new BcelVar[1]; int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); TypeX tx = getArgType(0); argVars[0] = genTempVar(tx, "ajc$arg0"); InstructionHandle insertedInstruction = range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore); // Now the exception range starts just after our new instruction. // The next bit of code changes the exception range to point at // the store instruction InstructionTargeter[] targeters = start.getTargeters(); for (int i = 0; i < targeters.length; i++) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) t; er.updateTarget(start, insertedInstruction, body); } } } // now we ask each munger to request our state isThisJoinPointLazy = world.isXlazyTjp(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.specializeOn(this); } initializeThisJoinPoint(); // If we are an expression kind, we require our target/arguments on the stack // before we do our actual thing. However, they may have been removed // from the stack as the shadowMungers have requested state. // if any of our shadowMungers requested either the arguments or target, // the munger will have added code // to pop the target/arguments into temporary variables, represented by // targetVar and argVars. In such a case, we must make sure to re-push the // values. // If we are nonExpressionKind, we don't expect arguments on the stack // so this is moot. If our argVars happen to be null, then we know that // no ShadowMunger has squirrelled away our arguments, so they're still // on the stack. InstructionFactory fact = getFactory(); if (getKind().argsOnStack() && argVars != null) { // Special case first (pr46298). If we are an exception handler and the instruction // just after the shadow is a POP then we should remove the pop. The code // above which generated the store instruction has already cleared the stack. // We also don't generate any code for the arguments in this case as it would be // an incorrect aload. if (getKind() == ExceptionHandler && range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) { // easier than deleting it ... range.getEnd().getNext().setInstruction(InstructionConstants.NOP); } else { range.insert( BcelRenderer.renderExprs(fact, world, argVars), Range.InsideBefore); if (targetVar != null) { range.insert( BcelRenderer.renderExpr(fact, world, targetVar), Range.InsideBefore); } if (getKind() == ConstructorCall) { range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore); range.insert( fact.createNew( (ObjectType) BcelWorld.makeBcelType( getSignature().getDeclaringType())), Range.InsideBefore); } } } } // ---- getters public ShadowRange getRange() { return range; } public void setRange(ShadowRange range) { this.range = range; } public int getSourceLine() { // if the kind of join point for which we are a shadow represents // a method or constructor execution, then the best source line is // the one from the enclosingMethod declarationLineNumber if available. Kind kind = getKind(); if ( (kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution) || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) { if (getEnclosingMethod().hasDeclaredLineNumberInfo()) { return getEnclosingMethod().getDeclarationLineNumber(); } } if (range == null) { if (getEnclosingMethod().hasBody()) { return Utility.getSourceLine(getEnclosingMethod().getBody().getStart()); } else { return 0; } } int ret = Utility.getSourceLine(range.getStart()); if (ret < 0) return 0; return ret; } // overrides public TypeX getEnclosingType() { return getEnclosingClass().getType(); } public LazyClassGen getEnclosingClass() { return enclosingMethod.getEnclosingClass(); } public BcelWorld getWorld() { return world; } // ---- factory methods public static BcelShadow makeConstructorExecution( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle justBeforeStart) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, ConstructorExecution, world.makeMethodSignature(enclosingMethod), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, justBeforeStart.getNext()), Range.genEnd(body)); return s; } public static BcelShadow makeStaticInitialization( BcelWorld world, LazyMethodGen enclosingMethod) { InstructionList body = enclosingMethod.getBody(); // move the start past ajc$preClinit InstructionHandle clinitStart = body.getStart(); if (clinitStart.getInstruction() instanceof InvokeInstruction) { InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction(); if (ii .getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()) .equals(NameMangler.AJC_PRE_CLINIT_NAME)) { clinitStart = clinitStart.getNext(); } } InstructionHandle clinitEnd = body.getEnd(); //XXX should move the end before the postClinit, but the return is then tricky... // if (clinitEnd.getInstruction() instanceof InvokeInstruction) { // InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction(); // if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) { // clinitEnd = clinitEnd.getPrev(); // } // } BcelShadow s = new BcelShadow( world, StaticInitialization, world.makeMethodSignature(enclosingMethod), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, clinitStart), Range.genEnd(body, clinitEnd)); return s; } /** Make the shadow for an exception handler. Currently makes an empty shadow that * only allows before advice to be woven into it. */ public static BcelShadow makeExceptionHandler( BcelWorld world, ExceptionRange exceptionRange, LazyMethodGen enclosingMethod, InstructionHandle startOfHandler, BcelShadow enclosingShadow) { InstructionList body = enclosingMethod.getBody(); TypeX catchType = exceptionRange.getCatchType(); TypeX inType = enclosingMethod.getEnclosingClass().getType(); ResolvedMember sig = Member.makeExceptionHandlerSignature(inType, catchType); sig.parameterNames = new String[] {findHandlerParamName(startOfHandler)}; BcelShadow s = new BcelShadow( world, ExceptionHandler, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); InstructionHandle start = Range.genStart(body, startOfHandler); InstructionHandle end = Range.genEnd(body, start); r.associateWithTargets(start, end); exceptionRange.updateTarget(startOfHandler, start, body); return s; } private static String findHandlerParamName(InstructionHandle startOfHandler) { if (startOfHandler.getInstruction() instanceof StoreInstruction && startOfHandler.getNext() != null) { int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex(); //System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index); InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters(); if (targeters!=null) { for (int i=targeters.length-1; i >= 0; i--) { if (targeters[i] instanceof LocalVariableTag) { LocalVariableTag t = (LocalVariableTag)targeters[i]; if (t.getSlot() == slot) { return t.getName(); } //System.out.println("tag: " + targeters[i]); } } } } return "<missing>"; } /** create an init join point associated w/ an interface in the body of a constructor */ public static BcelShadow makeIfaceInitialization( BcelWorld world, LazyMethodGen constructor, Member interfaceConstructorSignature) { InstructionList body = constructor.getBody(); // TypeX inType = constructor.getEnclosingClass().getType(); BcelShadow s = new BcelShadow( world, Initialization, interfaceConstructorSignature, constructor, null); s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // InstructionHandle start = Range.genStart(body, handle); // InstructionHandle end = Range.genEnd(body, handle); // // r.associateWithTargets(start, end); return s; } public void initIfaceInitializer(InstructionHandle end) { final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); InstructionHandle nop = body.insert(end, InstructionConstants.NOP); r.associateWithTargets( Range.genStart(body, nop), Range.genEnd(body, nop)); } // public static BcelShadow makeIfaceConstructorExecution( // BcelWorld world, // LazyMethodGen constructor, // InstructionHandle next, // Member interfaceConstructorSignature) // { // // final InstructionFactory fact = constructor.getEnclosingClass().getFactory(); // InstructionList body = constructor.getBody(); // // TypeX inType = constructor.getEnclosingClass().getType(); // BcelShadow s = // new BcelShadow( // world, // ConstructorExecution, // interfaceConstructorSignature, // constructor, // null); // s.fallsThrough = true; // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // // ??? this may or may not work // InstructionHandle start = Range.genStart(body, next); // //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP)); // InstructionHandle end = Range.genStart(body, next); // //body.append(start, fact.NOP); // // r.associateWithTargets(start, end); // return s; // } /** Create an initialization join point associated with a constructor, but not * with any body of code yet. If this is actually matched, it's range will be set * when we inline self constructors. * * @param constructor The constructor starting this initialization. */ public static BcelShadow makeUnfinishedInitialization( BcelWorld world, LazyMethodGen constructor) { return new BcelShadow( world, Initialization, world.makeMethodSignature(constructor), constructor, null); } public static BcelShadow makeUnfinishedPreinitialization( BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow( world, PreInitialization, world.makeMethodSignature(constructor), constructor, null); ret.fallsThrough = true; return ret; } public static BcelShadow makeMethodExecution( BcelWorld world, LazyMethodGen enclosingMethod, boolean lazyInit) { if (!lazyInit) return makeMethodExecution(world, enclosingMethod); BcelShadow s = new BcelShadow( world, MethodExecution, enclosingMethod.getMemberView(), enclosingMethod, null); return s; } public void init() { if (range != null) return; final InstructionList body = enclosingMethod.getBody(); ShadowRange r = new ShadowRange(body); r.associateWithShadow(this); r.associateWithTargets( Range.genStart(body), Range.genEnd(body)); } public static BcelShadow makeMethodExecution( BcelWorld world, LazyMethodGen enclosingMethod) { return makeShadowForMethod(world, enclosingMethod, MethodExecution, enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod)); } public static BcelShadow makeShadowForMethod(BcelWorld world, LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, kind, sig, enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body), Range.genEnd(body)); return s; } public static BcelShadow makeAdviceExecution( BcelWorld world, LazyMethodGen enclosingMethod) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, AdviceExecution, world.makeMethodSignature(enclosingMethod, Member.ADVICE), enclosingMethod, null); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets(Range.genStart(body), Range.genEnd(body)); return s; } // constructor call shadows are <em>initially</em> just around the // call to the constructor. If ANY advice gets put on it, we move // the NEW instruction inside the join point, which involves putting // all the arguments in temps. public static BcelShadow makeConstructorCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = BcelWorld.makeMethodSignature( enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()); BcelShadow s = new BcelShadow( world, ConstructorCall, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeMethodCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, MethodCall, BcelWorld.makeMethodSignature( enclosingMethod.getEnclosingClass(), (InvokeInstruction) callHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeShadowForMethodCall( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle callHandle, BcelShadow enclosingShadow, Kind kind, ResolvedMember sig) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, kind, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, callHandle), Range.genEnd(body, callHandle)); retargetAllBranches(callHandle, r.getStart()); return s; } public static BcelShadow makeFieldGet( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle getHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldGet, BcelWorld.makeFieldSignature( enclosingMethod.getEnclosingClass(), (FieldInstruction) getHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, getHandle), Range.genEnd(body, getHandle)); retargetAllBranches(getHandle, r.getStart()); return s; } public static BcelShadow makeFieldSet( BcelWorld world, LazyMethodGen enclosingMethod, InstructionHandle setHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldSet, BcelWorld.makeFieldSignature( enclosingMethod.getEnclosingClass(), (FieldInstruction) setHandle.getInstruction()), enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, setHandle), Range.genEnd(body, setHandle)); retargetAllBranches(setHandle, r.getStart()); return s; } public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) { InstructionTargeter[] sources = from.getTargeters(); if (sources != null) { for (int i = sources.length - 1; i >= 0; i--) { InstructionTargeter source = sources[i]; if (source instanceof BranchInstruction) { source.updateTarget(from, to); } } } } // // ---- type access methods // private ObjectType getTargetBcelType() { // return (ObjectType) BcelWorld.makeBcelType(getTargetType()); // } // private Type getArgBcelType(int arg) { // return BcelWorld.makeBcelType(getArgType(arg)); // } // ---- kinding /** * If the end of my range has no real instructions following then * my context needs a return at the end. */ public boolean terminatesWithReturn() { return getRange().getRealNext() == null; } /** * Is arg0 occupied with the value of this */ public boolean arg0HoldsThis() { if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { //XXX this is mostly right // this doesn't do the right thing for calls in the pre part of introduced constructors. return !enclosingMethod.isStatic(); } else { return ((BcelShadow)enclosingShadow).arg0HoldsThis(); } } // ---- argument getting methods private BcelVar thisVar = null; private BcelVar targetVar = null; private BcelVar[] argVars = null; private Map/*<TypeX,BcelVar>*/ kindedAnnotationVars = null; private Map/*<TypeX,BcelVar>*/ thisAnnotationVars = null; private Map/*<TypeX,BcelVar>*/ targetAnnotationVars = null; private Map/*<TypeX,BcelVar>*/[] argAnnotationVars = null; private Map/*<TypeX,BcelVar>*/ withinAnnotationVars = null; private Map/*<TypeX,BcelVar>*/ withincodeAnnotationVars = null; public Var getThisVar() { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisVar(); return thisVar; } public Var getThisAnnotationVar(TypeX forAnnotationType) { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one? // Even if we can't find one, we have to return one as we might have this annotation at runtime Var v = (Var) thisAnnotationVars.get(forAnnotationType); if (v==null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getThisVar()); return v; } public Var getTargetVar() { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetVar(); return targetVar; } public Var getTargetAnnotationVar(TypeX forAnnotationType) { if (!hasTarget()) { throw new IllegalStateException("no target"); } initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one? Var v =(Var) targetAnnotationVars.get(forAnnotationType); // Even if we can't find one, we have to return one as we might have this annotation at runtime if (v==null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getTargetVar()); return v; } public Var getArgVar(int i) { initializeArgVars(); return argVars[i]; } public Var getArgAnnotationVar(int i,TypeX forAnnotationType) { initializeArgAnnotationVars(); Var v= (Var) argAnnotationVars[i].get(forAnnotationType); if (v==null) v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getArgVar(i)); return v; } public Var getKindedAnnotationVar(TypeX forAnnotationType) { initializeKindedAnnotationVars(); return (Var) kindedAnnotationVars.get(forAnnotationType); } public Var getWithinAnnotationVar(TypeX forAnnotationType) { initializeWithinAnnotationVars(); return (Var) withinAnnotationVars.get(forAnnotationType); } public Var getWithinCodeAnnotationVar(TypeX forAnnotationType) { initializeWithinCodeAnnotationVars(); return (Var) withincodeAnnotationVars.get(forAnnotationType); } // reflective thisJoinPoint support private BcelVar thisJoinPointVar = null; private boolean isThisJoinPointLazy; private int lazyTjpConsumers = 0; private BcelVar thisJoinPointStaticPartVar = null; // private BcelVar thisEnclosingJoinPointStaticPartVar = null; public final Var getThisJoinPointStaticPartVar() { return getThisJoinPointStaticPartBcelVar(); } public final Var getThisEnclosingJoinPointStaticPartVar() { return getThisEnclosingJoinPointStaticPartBcelVar(); } public void requireThisJoinPoint(boolean hasGuardTest) { if (!hasGuardTest) { isThisJoinPointLazy = false; } else { lazyTjpConsumers++; } if (thisJoinPointVar == null) { thisJoinPointVar = genTempVar(TypeX.forName("org.aspectj.lang.JoinPoint")); } } public Var getThisJoinPointVar() { requireThisJoinPoint(false); return thisJoinPointVar; } void initializeThisJoinPoint() { if (thisJoinPointVar == null) return; if (isThisJoinPointLazy) { isThisJoinPointLazy = checkLazyTjp(); } if (isThisJoinPointLazy) { createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); il.append(InstructionConstants.ACONST_NULL); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } else { InstructionFactory fact = getFactory(); InstructionList il = createThisJoinPoint(); il.append(thisJoinPointVar.createStore(fact)); range.insert(il, Range.OutsideBefore); } } private boolean checkLazyTjp() { // check for around advice for (Iterator i = mungers.iterator(); i.hasNext();) { ShadowMunger munger = (ShadowMunger) i.next(); if (munger instanceof Advice) { if ( ((Advice)munger).getKind() == AdviceKind.Around) { world.getLint().canNotImplementLazyTjp.signal( new String[] {toString()}, getSourceLocation(), new ISourceLocation[] { munger.getSourceLocation() } ); return false; } } } return true; } InstructionList loadThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); if (isThisJoinPointLazy) { il.append(createThisJoinPoint()); if (lazyTjpConsumers > 1) { il.append(thisJoinPointVar.createStore(fact)); InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact)); il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end)); il.insert(thisJoinPointVar.createLoad(fact)); } } else { thisJoinPointVar.appendLoad(il, fact); } return il; } InstructionList createThisJoinPoint() { InstructionFactory fact = getFactory(); InstructionList il = new InstructionList(); BcelVar staticPart = getThisJoinPointStaticPartBcelVar(); staticPart.appendLoad(il, fact); if (hasThis()) { ((BcelVar)getThisVar()).appendLoad(il, fact); } else { il.append(new ACONST_NULL()); } if (hasTarget()) { ((BcelVar)getTargetVar()).appendLoad(il, fact); } else { il.append(new ACONST_NULL()); } switch(getArgCount()) { case 0: il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; case 1: ((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; case 2: ((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.OBJECT)); ((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedTypeX.OBJECT)); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT}, Constants.INVOKESTATIC)); break; default: il.append(makeArgsObjectArray()); il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory", "makeJP", LazyClassGen.tjpType, new Type[] { LazyClassGen.staticTjpType, Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)}, Constants.INVOKESTATIC)); break; } return il; } public BcelVar getThisJoinPointStaticPartBcelVar() { if (thisJoinPointStaticPartVar == null) { Field field = getEnclosingClass().getTjpField(this); thisJoinPointStaticPartVar = new BcelFieldRef( world.getCoreType(TypeX.forName("org.aspectj.lang.JoinPoint$StaticPart")), getEnclosingClass().getClassName(), field.getName()); // getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation()); } return thisJoinPointStaticPartVar; } public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() { if (enclosingShadow == null) { // the enclosing of an execution is itself return getThisJoinPointStaticPartBcelVar(); } else { return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(); } } //??? need to better understand all the enclosing variants public Member getEnclosingCodeSignature() { if (getKind().isEnclosingKind()) { return getSignature(); } else if (getKind() == Shadow.PreInitialization) { // PreInit doesn't enclose code but its signature // is correctly the signature of the ctor. return getSignature(); } else if (enclosingShadow == null) { return getEnclosingMethod().getMemberView(); } else { return enclosingShadow.getSignature(); } } private InstructionList makeArgsObjectArray() { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); final InstructionList il = new InstructionList(); int alen = getArgCount() ; il.append(Utility.createConstant(fact, alen)); il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(il, fact); int stateIndex = 0; for (int i = 0, len = getArgCount(); i<len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i)); stateIndex++; } arrayVar.appendLoad(il, fact); return il; } // ---- initializing var tables /* initializing this is doesn't do anything, because this * is protected from side-effects, so we don't need to copy its location */ private void initializeThisVar() { if (thisVar != null) return; thisVar = new BcelVar(getThisType().resolve(world), 0); thisVar.setPositionInAroundState(0); } public void initializeTargetVar() { InstructionFactory fact = getFactory(); if (targetVar != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisVar(); targetVar = thisVar; } else { initializeArgVars(); // gotta pop off the args before we find the target TypeX type = getTargetType(); type = ensureTargetTypeIsCorrect(type); targetVar = genTempVar(type, "ajc$target"); range.insert(targetVar.createStore(fact), Range.OutsideBefore); targetVar.setPositionInAroundState(hasThis() ? 1 : 0); } } /* PR 72528 * This method double checks the target type under certain conditions. The Java 1.4 * compilers seem to take calls to clone methods on array types and create bytecode that * looks like clone is being called on Object. If we advise a clone call with around * advice we extract the call into a helper method which we can then refer to. Because the * type in the bytecode for the call to clone is Object we create a helper method with * an Object parameter - this is not correct as we have lost the fact that the actual * type is an array type. If we don't do the check below we will create code that fails * java verification. This method checks for the peculiar set of conditions and if they * are true, it has a sneak peek at the code before the call to see what is on the stack. */ public TypeX ensureTargetTypeIsCorrect(TypeX tx) { if (tx.equals(ResolvedTypeX.OBJECT) && getKind() == MethodCall && getSignature().getReturnType().equals(ResolvedTypeX.OBJECT) && getSignature().getArity()==0 && getSignature().getName().charAt(0) == 'c' && getSignature().getName().equals("clone")) { // Lets go back through the code from the start of the shadow InstructionHandle searchPtr = range.getStart().getPrev(); while (Range.isRangeHandle(searchPtr) || searchPtr.getInstruction() instanceof StoreInstruction) { // ignore this instruction - it doesnt give us the info we want searchPtr = searchPtr.getPrev(); } // A load instruction may tell us the real type of what the clone() call is on if (searchPtr.getInstruction() instanceof LoadInstruction) { LoadInstruction li = (LoadInstruction)searchPtr.getInstruction(); li.getIndex(); LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr,li.getIndex()); return lvt.getType(); } // A field access instruction may tell us the real type of what the clone() call is on if (searchPtr.getInstruction() instanceof FieldInstruction) { FieldInstruction si = (FieldInstruction)searchPtr.getInstruction(); Type t = si.getFieldType(getEnclosingClass().getConstantPoolGen()); return BcelWorld.fromBcel(t); } // A new array instruction obviously tells us it is an array type ! if (searchPtr.getInstruction() instanceof ANEWARRAY) { //ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction(); //Type t = ana.getType(getEnclosingClass().getConstantPoolGen()); // Just use a standard java.lang.object array - that will work fine return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,1)); } // A multi new array instruction obviously tells us it is an array type ! if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) { MULTIANEWARRAY ana = (MULTIANEWARRAY)searchPtr.getInstruction(); // Type t = ana.getType(getEnclosingClass().getConstantPoolGen()); // t = new ArrayType(t,ana.getDimensions()); // Just use a standard java.lang.object array - that will work fine return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,ana.getDimensions())); } throw new BCException("Can't determine real target of clone() when processing instruction "+ searchPtr.getInstruction()); } return tx; } public void initializeArgVars() { if (argVars != null) return; InstructionFactory fact = getFactory(); int len = getArgCount(); argVars = new BcelVar[len]; int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0); if (getKind().argsOnStack()) { // we move backwards because we're popping off the stack for (int i = len - 1; i >= 0; i--) { TypeX type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createStore(getFactory()), Range.OutsideBefore); int position = i; position += positionOffset; tmp.setPositionInAroundState(position); argVars[i] = tmp; } } else { int index = 0; if (arg0HoldsThis()) index++; for (int i = 0; i < len; i++) { TypeX type = getArgType(i); BcelVar tmp = genTempVar(type, "ajc$arg" + i); range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore); argVars[i] = tmp; int position = i; position += positionOffset; // System.out.println("set position: " + tmp + ", " + position + " in " + this); // System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget()); tmp.setPositionInAroundState(position); index += type.getSize(); } } } public void initializeForAroundClosure() { initializeArgVars(); if (hasTarget()) initializeTargetVar(); if (hasThis()) initializeThisVar(); // System.out.println("initialized: " + this + " thisVar = " + thisVar); } public void initializeThisAnnotationVars() { if (thisAnnotationVars != null) return; thisAnnotationVars = new HashMap(); // populate.. } public void initializeTargetAnnotationVars() { if (targetAnnotationVars != null) return; if (getKind().isTargetSameAsThis()) { if (hasThis()) initializeThisAnnotationVars(); targetAnnotationVars = thisAnnotationVars; } else { targetAnnotationVars = new HashMap(); ResolvedTypeX[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent gotten yet but we will get in subclasses? for (int i = 0; i < rtx.length; i++) { ResolvedTypeX typeX = rtx[i]; targetAnnotationVars.put(typeX,new TypeAnnotationAccessVar(typeX,(BcelVar)getTargetVar())); } // populate. } } public void initializeArgAnnotationVars() { if (argAnnotationVars != null) return; int numArgs = getArgCount(); argAnnotationVars = new Map[numArgs]; for (int i = 0; i < argAnnotationVars.length; i++) { argAnnotationVars[i] = new HashMap(); //FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time // what the full set of annotations could be (due to static/dynamic type differences...) } } public void initializeKindedAnnotationVars() { if (kindedAnnotationVars != null) return; kindedAnnotationVars = new HashMap(); // by determining what "kind" of shadow we are, we can find out the // annotations on the appropriate element (method, field, constructor, type). // Then create one BcelVar entry in the map for each annotation, keyed by // annotation type (TypeX). // FIXME asc Refactor these once all shadow kinds added - there is lots of commonality ResolvedTypeX[] annotations = null; TypeX relevantType = null; if (getKind() == Shadow.StaticInitialization) { relevantType = getSignature().getDeclaringType(); annotations = relevantType.resolve(world).getAnnotationTypes(); } if (getKind() == Shadow.ExceptionHandler) { relevantType = getSignature().getParameterTypes()[0]; annotations = relevantType.resolve(world).getAnnotationTypes(); } if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) { relevantType = getSignature().getDeclaringType(); ResolvedMember rm[] = relevantType.getDeclaredMethods(world); ResolvedMember found = null; String searchString = getSignature().getName()+getSignature().getParameterSignature(); for (int i = 0; i < rm.length && found==null; i++) { ResolvedMember member = rm[i]; if ((member.getName()+member.getParameterSignature()).equals(searchString)) { found = member; } } annotations = found.getAnnotationTypes(); } if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution || getKind() == Shadow.AdviceExecution) { relevantType = getSignature().getDeclaringType(); ResolvedMember rm[] = relevantType.getDeclaredMethods(world); ResolvedMember found = null; String searchString = getSignature().getName()+getSignature().getParameterSignature(); for (int i = 0; i < rm.length && found==null; i++) { ResolvedMember member = rm[i]; if ((member.getName()+member.getParameterSignature()).equals(searchString)) { found = member; } } annotations = found.getAnnotationTypes(); } if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) { relevantType = getSignature().getDeclaringType(); ResolvedMember rm[] = relevantType.getDeclaredMethods(world); ResolvedMember found = null; String searchString = getSignature().getName()+getSignature().getParameterSignature(); for (int i = 0; i < rm.length && found==null; i++) { ResolvedMember member = rm[i]; if ((member.getName()+member.getParameterSignature()).equals(searchString)) { found = member; } } annotations = found.getAnnotationTypes(); } if (getKind() == Shadow.FieldSet) { relevantType = getSignature().getDeclaringType(); ResolvedMember rm[] = relevantType.getDeclaredFields(world); ResolvedMember found = null; for (int i = 0; i < rm.length && found==null; i++) { ResolvedMember member = rm[i]; if ( member.getName().equals(getSignature().getName()) && member.getType().equals(getSignature().getType())) { found = member; } } annotations = found.getAnnotationTypes(); } if (getKind() == Shadow.FieldGet) { relevantType = getSignature().getDeclaringType(); ResolvedMember rm[] = relevantType.getDeclaredFields(world); ResolvedMember found = null; for (int i = 0; i < rm.length && found==null; i++) { ResolvedMember member = rm[i]; if ( member.getName().equals(getSignature().getName()) && member.getType().equals(getSignature().getType())) { found = member; } } annotations = found.getAnnotationTypes(); } if (annotations == null) { // We can't have recognized the shadow - should blow up now to be on the safe side throw new BCException("Didn't recognize shadow: "+getKind()); } for (int i = 0; i < annotations.length; i++) { ResolvedTypeX aTX = annotations[i]; kindedAnnotationVars.put(aTX, new KindedAnnotationAccessVar(getKind(),aTX.resolve(world),relevantType,getSignature())); } } public void initializeWithinAnnotationVars() { if (withinAnnotationVars != null) return; withinAnnotationVars = new HashMap(); ResolvedTypeX[] annotations = getEnclosingType().getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { ResolvedTypeX ann = annotations[i]; Kind k = Shadow.StaticInitialization; withinAnnotationVars.put(ann,new KindedAnnotationAccessVar(k,ann,getEnclosingType(),null)); } } public void initializeWithinCodeAnnotationVars() { if (withincodeAnnotationVars != null) return; withincodeAnnotationVars = new HashMap(); // For some shadow we are interested in annotations on the method containing that shadow. ResolvedTypeX[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { ResolvedTypeX ann = annotations[i]; Kind k = (getEnclosingMethod().getMemberView().getKind()==Member.CONSTRUCTOR? Shadow.ConstructorExecution:Shadow.MethodExecution); withincodeAnnotationVars.put(ann, new KindedAnnotationAccessVar(k,ann,getEnclosingType(),getEnclosingCodeSignature())); } } // ---- weave methods void weaveBefore(BcelAdvice munger) { range.insert( munger.getAdviceInstructions(this, null, range.getRealStart()), Range.InsideBefore); } public void weaveAfter(BcelAdvice munger) { weaveAfterThrowing(munger, TypeX.THROWABLE); weaveAfterReturning(munger); } /** * We guarantee that the return value is on the top of the stack when * munger.getAdviceInstructions() will be run * (Unless we have a void return type in which case there's nothing) */ public void weaveAfterReturning(BcelAdvice munger) { // InstructionFactory fact = getFactory(); List returns = new ArrayList(); Instruction ret = null; for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { if (ih.getInstruction() instanceof ReturnInstruction) { returns.add(ih); ret = Utility.copyInstruction(ih.getInstruction()); } } InstructionList retList; InstructionHandle afterAdvice; if (ret != null) { retList = new InstructionList(ret); afterAdvice = retList.getStart(); } else /* if (munger.hasDynamicTests()) */ { /* * 27: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter; 30: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V 33: aload 6 35: athrow 36: nop 37: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter; 40: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V 43: d2i 44: invokespecial #23; //Method java/lang/Object."<init>":()V */ retList = new InstructionList(InstructionConstants.NOP); afterAdvice = retList.getStart(); // } else { // retList = new InstructionList(); // afterAdvice = null; } InstructionList advice = new InstructionList(); BcelVar tempVar = null; if (munger.hasExtraParameter()) { TypeX tempVarType = getReturnType(); if (tempVarType.equals(ResolvedTypeX.VOID)) { tempVar = genTempVar(TypeX.OBJECT); advice.append(InstructionConstants.ACONST_NULL); tempVar.appendStore(advice, getFactory()); } else { tempVar = genTempVar(tempVarType); advice.append(InstructionFactory.createDup(tempVarType.getSize())); tempVar.appendStore(advice, getFactory()); } } advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice)); if (ret != null) { InstructionHandle gotoTarget = advice.getStart(); for (Iterator i = returns.iterator(); i.hasNext();) { InstructionHandle ih = (InstructionHandle) i.next(); Utility.replaceInstruction( ih, InstructionFactory.createBranchInstruction( Constants.GOTO, gotoTarget), enclosingMethod); } range.append(advice); range.append(retList); } else { range.append(advice); range.append(retList); } } public void weaveAfterThrowing(BcelAdvice munger, TypeX catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); exceptionVar.appendStore(handler, fact); // pr62642 // I will now jump through some firey BCEL hoops to generate a trivial bit of code: // if (exc instanceof ExceptionInInitializerError) // throw (ExceptionInInitializerError)exc; if (this.getEnclosingMethod().getName().equals("<clinit>")) { ResolvedTypeX eiieType = world.resolve("java.lang.ExceptionInInitializerError"); ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType); InstructionList ih = new InstructionList(InstructionConstants.NOP); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInstanceOf(eiieBcelType)); BranchInstruction bi = InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart()); handler.append(bi); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createCheckCast(eiieBcelType)); handler.append(InstructionConstants.ATHROW); handler.append(ih); } InstructionList endHandler = new InstructionList( exceptionVar.createLoad(fact)); handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart())); handler.append(endHandler); handler.append(InstructionConstants.ATHROW); InstructionHandle handlerStart = handler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP); handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } InstructionHandle protectedEnd = handler.getStart(); range.insert(handler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE, // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } //??? this shares a lot of code with the above weaveAfterThrowing //??? would be nice to abstract that to say things only once public void weaveSoftener(BcelAdvice munger, TypeX catchType) { // a good optimization would be not to generate anything here // if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even // a shadow, inside me). if (getRange().getStart().getNext() == getRange().getEnd()) return; InstructionFactory fact = getFactory(); InstructionList handler = new InstructionList(); InstructionList rtExHandler = new InstructionList(); BcelVar exceptionVar = genTempVar(catchType); handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE)); handler.append(InstructionFactory.createDup(1)); handler.append(exceptionVar.createLoad(fact)); handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>", Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special handler.append(InstructionConstants.ATHROW); // ENH 42737 exceptionVar.appendStore(rtExHandler, fact); // aload_1 rtExHandler.append(exceptionVar.createLoad(fact)); // instanceof class java/lang/RuntimeException rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException"))); // ifeq go to new SOFT_EXCEPTION_TYPE instruction rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ,handler.getStart())); // aload_1 rtExHandler.append(exceptionVar.createLoad(fact)); // athrow rtExHandler.append(InstructionFactory.ATHROW); InstructionHandle handlerStart = rtExHandler.getStart(); if (isFallsThrough()) { InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP); rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget)); } rtExHandler.append(handler); InstructionHandle protectedEnd = rtExHandler.getStart(); range.insert(rtExHandler, Range.InsideAfter); enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(), handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), // high priority if our args are on the stack getKind().hasHighPriorityExceptions()); } public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) { final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); onVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( Utility.createInvoke(fact, world, AjcMemberMaker.perObjectBind(munger.getConcreteAspect()))); InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } // PTWIMPL Create static initializer to call the aspect factory /** * Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf() */ public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger,TypeX t) { if (t.isInterface(world)) return; // Don't initialize statics in final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); BcelObjectType aspectType = BcelWorld.getBcelObjectType(munger.getConcreteAspect()); String aspectname = munger.getConcreteAspect().getName(); String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect()); entrySuccessInstructions.append(new PUSH(fact.getConstantPool(),t.getName())); entrySuccessInstructions.append(fact.createInvoke(aspectname,"ajc$createAspectInstance",new ObjectType(aspectname), new Type[]{new ObjectType("java.lang.String")},Constants.INVOKESTATIC)); entrySuccessInstructions.append(fact.createPutStatic(t.getName(),ptwField, new ObjectType(aspectname))); entryInstructions.append(entrySuccessInstructions); range.insert(entryInstructions, Range.InsideBefore); } public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) { final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry || munger.getKind() == AdviceKind.PerCflowEntry; final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionFactory fact = getFactory(); final BcelVar testResult = genTempVar(ResolvedTypeX.BOOLEAN); InstructionList entryInstructions = new InstructionList(); { InstructionList entrySuccessInstructions = new InstructionList(); if (munger.hasDynamicTests()) { entryInstructions.append(Utility.createConstant(fact, 0)); testResult.appendStore(entryInstructions, fact); entrySuccessInstructions.append(Utility.createConstant(fact, 1)); testResult.appendStore(entrySuccessInstructions, fact); } if (isPer) { entrySuccessInstructions.append( fact.createInvoke(munger.getConcreteAspect().getName(), NameMangler.PERCFLOW_PUSH_METHOD, Type.VOID, new Type[] { }, Constants.INVOKESTATIC)); } else { BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars(); if (cflowStateVars.length == 0) { // This should be getting managed by a counter - lets make sure. if (!cflowField.getType().getName().endsWith("CFlowCounter")) throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow"); entrySuccessInstructions.append( Utility.createGet(fact, cflowField)); //arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE,"inc",Type.VOID,new Type[] { },Constants.INVOKEVIRTUAL)); } else { BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); int alen = cflowStateVars.length; entrySuccessInstructions.append(Utility.createConstant(fact, alen)); entrySuccessInstructions.append( (Instruction) fact.createNewArray(Type.OBJECT, (short) 1)); arrayVar.appendStore(entrySuccessInstructions, fact); for (int i = 0; i < alen; i++) { arrayVar.appendConvertableArrayStore( entrySuccessInstructions, fact, i, cflowStateVars[i]); } entrySuccessInstructions.append( Utility.createGet(fact, cflowField)); arrayVar.appendLoad(entrySuccessInstructions, fact); entrySuccessInstructions.append( fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID, new Type[] { objectArrayType }, Constants.INVOKEVIRTUAL)); } } InstructionList testInstructions = munger.getTestInstructions(this, entrySuccessInstructions.getStart(), range.getRealStart(), entrySuccessInstructions.getStart()); entryInstructions.append(testInstructions); entryInstructions.append(entrySuccessInstructions); } // this is the same for both per and non-per weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) { public InstructionList getAdviceInstructions( BcelShadow s, BcelVar extraArgVar, InstructionHandle ifNoAdvice) { InstructionList exitInstructions = new InstructionList(); if (munger.hasDynamicTests()) { testResult.appendLoad(exitInstructions, fact); exitInstructions.append( InstructionFactory.createBranchInstruction( Constants.IFEQ, ifNoAdvice)); } exitInstructions.append(Utility.createGet(fact, cflowField)); if (munger.getKind() != AdviceKind.PerCflowEntry && munger.getKind() != AdviceKind.PerCflowBelowEntry && munger.getExposedStateAsBcelVars().length==0) { exitInstructions .append( fact .createInvoke( NameMangler.CFLOW_COUNTER_TYPE, "dec", Type.VOID, new Type[] { }, Constants.INVOKEVIRTUAL)); } else { exitInstructions .append( fact .createInvoke( NameMangler.CFLOW_STACK_TYPE, "pop", Type.VOID, new Type[] { }, Constants.INVOKEVIRTUAL)); } return exitInstructions; } }); range.insert(entryInstructions, Range.InsideBefore); } public void weaveAroundInline( BcelAdvice munger, boolean hasDynamicTest) { /* Implementation notes: * * AroundInline still extracts the instructions of the original shadow into * an extracted method. This allows inlining of even that advice that doesn't * call proceed or calls proceed more than once. * * It extracts the instructions of the original shadow into a method. * * Then it extracts the instructions of the advice into a new method defined on * this enclosing class. This new method can then be specialized as below. * * Then it searches in the instructions of the advice for any call to the * proceed method. * * At such a call, there is stuff on the stack representing the arguments to * proceed. Pop these into the frame. * * Now build the stack for the call to the extracted method, taking values * either from the join point state or from the new frame locs from proceed. * Now call the extracted method. The right return value should be on the * stack, so no cast is necessary. * * If only one call to proceed is made, we can re-inline the original shadow. * We are not doing that presently. * * If the body of the advice can be determined to not alter the stack, or if * this shadow doesn't care about the stack, i.e. method-execution, then the * new method for the advice can also be re-lined. We are not doing that * presently. */ // !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...); Member mungerSig = munger.getSignature(); ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType(),true); if (declaringType == ResolvedTypeX.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()), "",IMessage.ERROR,getSourceLocation(),null, new ISourceLocation[]{ munger.getSourceLocation()}); world.getMessageHandler().handleMessage(msg); } //??? might want some checks here to give better errors BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType); LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } // We can't inline around methods if they have around advice on them, this // is because the weaving will extract the body and hence the proceed call. //??? should consider optimizations to recognize simple cases that don't require body extraction enclosingMethod.setCanInline(false); // start by exposing various useful things into the frame final InstructionFactory fact = getFactory(); // now generate the aroundBody method LazyMethodGen extractedMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()), Modifier.PRIVATE, munger); // now extract the advice into its own method String adviceMethodName = NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()) + "$advice"; List argVarList = new ArrayList(); List proceedVarList = new ArrayList(); int extraParamOffset = 0; // Create the extra parameters that are needed for passing to proceed // This code is very similar to that found in makeCallToCallback and should // be rationalized in the future if (thisVar != null) { argVarList.add(thisVar); proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset)); extraParamOffset += thisVar.getType().getSize(); } if (targetVar != null && targetVar != thisVar) { argVarList.add(targetVar); proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset)); extraParamOffset += targetVar.getType().getSize(); } for (int i = 0, len = getArgCount(); i < len; i++) { argVarList.add(argVars[i]); proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset)); extraParamOffset += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { argVarList.add(thisJoinPointVar); proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset)); extraParamOffset += thisJoinPointVar.getType().getSize(); } Type[] adviceParameterTypes = adviceMethod.getArgumentTypes(); Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes(); Type[] parameterTypes = new Type[extractedMethodParameterTypes.length + adviceParameterTypes.length + 1]; int parameterIndex = 0; System.arraycopy( extractedMethodParameterTypes, 0, parameterTypes, parameterIndex, extractedMethodParameterTypes.length); parameterIndex += extractedMethodParameterTypes.length; parameterTypes[parameterIndex++] = BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType()); System.arraycopy( adviceParameterTypes, 0, parameterTypes, parameterIndex, adviceParameterTypes.length); LazyMethodGen localAdviceMethod = new LazyMethodGen( Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC, adviceMethod.getReturnType(), adviceMethodName, parameterTypes, new String[0], getEnclosingClass()); String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName(); String recipientFileName = getEnclosingClass().getInternalFileName(); // System.err.println("donor " + donorFileName); // System.err.println("recip " + recipientFileName); if (! donorFileName.equals(recipientFileName)) { localAdviceMethod.fromFilename = donorFileName; getEnclosingClass().addInlinedSourceFileInfo( donorFileName, adviceMethod.highestLineNumber); } getEnclosingClass().addMethodGen(localAdviceMethod); // create a map that will move all slots in advice method forward by extraParamOffset // in order to make room for the new proceed-required arguments that are added at // the beginning of the parameter list int nVars = adviceMethod.getMaxLocals() + extraParamOffset; IntMap varMap = IntMap.idMap(nVars); for (int i=extraParamOffset; i < nVars; i++) { varMap.put(i-extraParamOffset, i); } localAdviceMethod.getBody().insert( BcelClassWeaver.genInlineInstructions(adviceMethod, localAdviceMethod, varMap, fact, true)); localAdviceMethod.setMaxLocals(nVars); //System.err.println(localAdviceMethod); // the shadow is now empty. First, create a correct call // to the around advice. This includes both the call (which may involve // value conversion of the advice arguments) and the return // (which may involve value conversion of the return value). Right now // we push a null for the unused closure. It's sad, but there it is. InstructionList advice = new InstructionList(); // InstructionHandle adviceMethodInvocation; { for (Iterator i = argVarList.iterator(); i.hasNext(); ) { BcelVar var = (BcelVar)i.next(); var.appendLoad(advice, fact); } // ??? we don't actually need to push NULL for the closure if we take care advice.append( munger.getAdviceArgSetup( this, null, new InstructionList(InstructionConstants.ACONST_NULL))); // adviceMethodInvocation = advice.append( Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature())); advice.append( Utility.createConversion( getFactory(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()), extractedMethod.getReturnType())); if (! isFallsThrough()) { advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType())); } } // now, situate the call inside the possible dynamic tests, // and actually add the whole mess to the shadow if (! hasDynamicTest) { range.append(advice); } else { InstructionList afterThingie = new InstructionList(InstructionConstants.NOP); InstructionList callback = makeCallToCallback(extractedMethod); if (terminatesWithReturn()) { callback.append( InstructionFactory.createReturn(extractedMethod.getReturnType())); } else { //InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter); advice.append( InstructionFactory.createBranchInstruction( Constants.GOTO, afterThingie.getStart())); } range.append( munger.getTestInstructions( this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(afterThingie); } // now search through the advice, looking for a call to PROCEED. // Then we replace the call to proceed with some argument setup, and a // call to the extracted method. String proceedName = NameMangler.proceedMethodName(munger.getSignature().getName()); InstructionHandle curr = localAdviceMethod.getBody().getStart(); InstructionHandle end = localAdviceMethod.getBody().getEnd(); ConstantPoolGen cpg = localAdviceMethod.getEnclosingClass().getConstantPoolGen(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof INVOKESTATIC) && proceedName.equals(((INVOKESTATIC) inst).getMethodName(cpg))) { localAdviceMethod.getBody().append( curr, getRedoneProceedCall( fact, extractedMethod, munger, localAdviceMethod, proceedVarList)); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } // and that's it. } private InstructionList getRedoneProceedCall( InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List argVarList) { InstructionList ret = new InstructionList(); // we have on stack all the arguments for the ADVICE call. // we have in frame somewhere all the arguments for the non-advice call. BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); IntMap proceedMap = makeProceedArgumentMap(adviceVars); // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); ResolvedTypeX[] proceedParamTypes = world.resolve(munger.getSignature().getParameterTypes()); // remove this*JoinPoint* as arguments to proceed if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) { int len = munger.getBaseParameterCount()+1; ResolvedTypeX[] newTypes = new ResolvedTypeX[len]; System.arraycopy(proceedParamTypes, 0, newTypes, 0, len); proceedParamTypes = newTypes; } //System.out.println("stateTypes: " + Arrays.asList(stateTypes)); BcelVar[] proceedVars = Utility.pushAndReturnArrayOfVars(proceedParamTypes, ret, fact, localAdviceMethod); Type[] stateTypes = callbackMethod.getArgumentTypes(); // System.out.println("stateTypes: " + Arrays.asList(stateTypes)); for (int i=0, len=stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { //throw new RuntimeException("unimplemented"); proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); } else { ((BcelVar) argVarList.get(i)).appendLoad(ret, fact); } } ret.append(Utility.createInvoke(fact, callbackMethod)); ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); return ret; } public void weaveAroundClosure( BcelAdvice munger, boolean hasDynamicTest) { InstructionFactory fact = getFactory(); enclosingMethod.setCanInline(false); // MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD! LazyMethodGen callbackMethod = extractMethod( NameMangler.aroundCallbackMethodName( getSignature(), getEnclosingClass()), 0, munger); BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(); String closureClassName = NameMangler.makeClosureClassName( getEnclosingClass().getType(), getEnclosingClass().getNewGeneratedNameTag()); Member constructorSig = new Member(Member.CONSTRUCTOR, TypeX.forName(closureClassName), 0, "<init>", "([Ljava/lang/Object;)V"); BcelVar closureHolder = null; // This is not being used currently since getKind() == preinitializaiton // cannot happen in around advice if (getKind() == PreInitialization) { closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE); } InstructionList closureInstantiation = makeClosureInstantiation(constructorSig, closureHolder); /*LazyMethodGen constructor = */ makeClosureClassAndReturnConstructor( closureClassName, callbackMethod, makeProceedArgumentMap(adviceVars) ); InstructionList returnConversionCode; if (getKind() == PreInitialization) { returnConversionCode = new InstructionList(); BcelVar stateTempVar = genTempVar(TypeX.OBJECTARRAY); closureHolder.appendLoad(returnConversionCode, fact); returnConversionCode.append( Utility.createInvoke( fact, world, AjcMemberMaker.aroundClosurePreInitializationGetter())); stateTempVar.appendStore(returnConversionCode, fact); Type[] stateTypes = getSuperConstructorParameterTypes(); returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack for (int i = 0, len = stateTypes.length; i < len; i++) { TypeX bcelTX = BcelWorld.fromBcel(stateTypes[i]); ResolvedTypeX stateRTX = world.resolve(bcelTX,true); if (stateRTX == ResolvedTypeX.MISSING) { IMessage msg = new Message( WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()), "",IMessage.ERROR,getSourceLocation(),null, new ISourceLocation[]{ munger.getSourceLocation()}); world.getMessageHandler().handleMessage(msg); } stateTempVar.appendConvertableArrayLoad( returnConversionCode, fact, i, stateRTX); } } else { returnConversionCode = Utility.createConversion( getFactory(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()), callbackMethod.getReturnType()); if (!isFallsThrough()) { returnConversionCode.append( InstructionFactory.createReturn(callbackMethod.getReturnType())); } } InstructionList advice = new InstructionList(); advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation)); // advice.append(closureInstantiation); advice.append(munger.getNonTestAdviceInstructions(this)); advice.append(returnConversionCode); if (!hasDynamicTest) { range.append(advice); } else { InstructionList callback = makeCallToCallback(callbackMethod); InstructionList postCallback = new InstructionList(); if (terminatesWithReturn()) { callback.append( InstructionFactory.createReturn(callbackMethod.getReturnType())); } else { advice.append( InstructionFactory.createBranchInstruction( Constants.GOTO, postCallback.append(InstructionConstants.NOP))); } range.append( munger.getTestInstructions( this, advice.getStart(), callback.getStart(), advice.getStart())); range.append(advice); range.append(callback); range.append(postCallback); } } // exposed for testing InstructionList makeCallToCallback(LazyMethodGen callbackMethod) { InstructionFactory fact = getFactory(); InstructionList callback = new InstructionList(); if (thisVar != null) { callback.append(InstructionConstants.ALOAD_0); } if (targetVar != null && targetVar != thisVar) { callback.append(BcelRenderer.renderExpr(fact, world, targetVar)); } callback.append(BcelRenderer.renderExprs(fact, world, argVars)); // remember to render tjps if (thisJoinPointVar != null) { callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar)); } callback.append(Utility.createInvoke(fact, callbackMethod)); return callback; } /** side-effect-free */ private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) { // LazyMethodGen constructor) { InstructionFactory fact = getFactory(); BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY); //final Type objectArrayType = new ArrayType(Type.OBJECT, 1); final InstructionList il = new InstructionList(); int alen = getArgCount() + (thisVar == null ? 0 : 1) + ((targetVar != null && targetVar != thisVar) ? 1 : 0) + (thisJoinPointVar == null ? 0 : 1); il.append(Utility.createConstant(fact, alen)); il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(il, fact); int stateIndex = 0; if (thisVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar); thisVar.setPositionInAroundState(stateIndex); stateIndex++; } if (targetVar != null && targetVar != thisVar) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar); targetVar.setPositionInAroundState(stateIndex); stateIndex++; } for (int i = 0, len = getArgCount(); i<len; i++) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]); argVars[i].setPositionInAroundState(stateIndex); stateIndex++; } if (thisJoinPointVar != null) { arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar); thisJoinPointVar.setPositionInAroundState(stateIndex); stateIndex++; } il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName()))); il.append(new DUP()); arrayVar.appendLoad(il, fact); il.append(Utility.createInvoke(fact, world, constructor)); if (getKind() == PreInitialization) { il.append(InstructionConstants.DUP); holder.appendStore(il, fact); } return il; } private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) { //System.err.println("coming in with " + Arrays.asList(adviceArgs)); IntMap ret = new IntMap(); for(int i = 0, len = adviceArgs.length; i < len; i++) { BcelVar v = (BcelVar) adviceArgs[i]; if (v == null) continue; // XXX we don't know why this is required int pos = v.getPositionInAroundState(); if (pos >= 0) { // need this test to avoid args bound via cflow ret.put(pos, i); } } //System.err.println("returning " + ret); return ret; } /** * * * @param callbackMethod the method we will call back to when our run method gets called. * * @param proceedMap A map from state position to proceed argument position. May be * non covering on state position. */ private LazyMethodGen makeClosureClassAndReturnConstructor( String closureClassName, LazyMethodGen callbackMethod, IntMap proceedMap) { String superClassName = "org.aspectj.runtime.internal.AroundClosure"; Type objectArrayType = new ArrayType(Type.OBJECT, 1); LazyClassGen closureClass = new LazyClassGen(closureClassName, superClassName, getEnclosingClass().getFileName(), Modifier.PUBLIC, new String[] {}); InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen()); // constructor LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", new Type[] {objectArrayType}, new String[] {}, closureClass); InstructionList cbody = constructor.getBody(); cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0)); cbody.append(InstructionFactory.createLoad(objectArrayType, 1)); cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID, new Type[] {objectArrayType}, Constants.INVOKESPECIAL)); cbody.append(InstructionFactory.createReturn(Type.VOID)); closureClass.addMethodGen(constructor); // method LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC, Type.OBJECT, "run", new Type[] {objectArrayType}, new String[] {}, closureClass); InstructionList mbody = runMethod.getBody(); BcelVar proceedVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), 1); // int proceedVarIndex = 1; BcelVar stateVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1)); // int stateVarIndex = runMethod.allocateLocal(1); mbody.append(InstructionFactory.createThis()); mbody.append(fact.createGetField(superClassName, "state", objectArrayType)); mbody.append(stateVar.createStore(fact)); // mbody.append(fact.createStore(objectArrayType, stateVarIndex)); Type[] stateTypes = callbackMethod.getArgumentTypes(); for (int i=0, len=stateTypes.length; i < len; i++) { Type stateType = stateTypes[i]; ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world); if (proceedMap.hasKey(i)) { mbody.append( proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i), stateTypeX)); } else { mbody.append( stateVar.createConvertableArrayLoad(fact, i, stateTypeX)); } } mbody.append(Utility.createInvoke(fact, callbackMethod)); if (getKind() == PreInitialization) { mbody.append(Utility.createSet( fact, AjcMemberMaker.aroundClosurePreInitializationField())); mbody.append(InstructionConstants.ACONST_NULL); } else { mbody.append( Utility.createConversion( fact, callbackMethod.getReturnType(), Type.OBJECT)); } mbody.append(InstructionFactory.createReturn(Type.OBJECT)); closureClass.addMethodGen(runMethod); // class getEnclosingClass().addGeneratedInner(closureClass); return constructor; } // ---- extraction methods public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) { LazyMethodGen.assertGoodBody(range.getBody(), newMethodName); if (!getKind().allowsExtraction()) throw new BCException(); LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier); // System.err.println("******"); // System.err.println("ABOUT TO EXTRACT METHOD for" + this); // enclosingMethod.print(System.err); // System.err.println("INTO"); // freshMethod.print(System.err); // System.err.println("WITH REMAP"); // System.err.println(makeRemap()); range.extractInstructionsInto(freshMethod, makeRemap(), (getKind() != PreInitialization) && isFallsThrough()); if (getKind() == PreInitialization) { addPreInitializationReturnCode( freshMethod, getSuperConstructorParameterTypes()); } getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation()); return freshMethod; } private void addPreInitializationReturnCode( LazyMethodGen extractedMethod, Type[] superConstructorTypes) { InstructionList body = extractedMethod.getBody(); final InstructionFactory fact = getFactory(); BcelVar arrayVar = new BcelVar( world.getCoreType(TypeX.OBJECTARRAY), extractedMethod.allocateLocal(1)); int len = superConstructorTypes.length; body.append(Utility.createConstant(fact, len)); body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1)); arrayVar.appendStore(body, fact); for (int i = len - 1; i >= 0; i++) { // convert thing on top of stack to object body.append( Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT)); // push object array arrayVar.appendLoad(body, fact); // swap body.append(InstructionConstants.SWAP); // do object array store. body.append(Utility.createConstant(fact, i)); body.append(InstructionConstants.SWAP); body.append(InstructionFactory.createArrayStore(Type.OBJECT)); } arrayVar.appendLoad(body, fact); body.append(InstructionConstants.ARETURN); } private Type[] getSuperConstructorParameterTypes() { // assert getKind() == PreInitialization InstructionHandle superCallHandle = getRange().getEnd().getNext(); InvokeInstruction superCallInstruction = (InvokeInstruction) superCallHandle.getInstruction(); return superCallInstruction.getArgumentTypes( getEnclosingClass().getConstantPoolGen()); } /** make a map from old frame location to new frame location. Any unkeyed frame * location picks out a copied local */ private IntMap makeRemap() { IntMap ret = new IntMap(5); int reti = 0; if (thisVar != null) { ret.put(0, reti++); // thisVar guaranteed to be 0 } if (targetVar != null && targetVar != thisVar) { ret.put(targetVar.getSlot(), reti++); } for (int i = 0, len = argVars.length; i < len; i++) { ret.put(argVars[i].getSlot(), reti); reti += argVars[i].getType().getSize(); } if (thisJoinPointVar != null) { ret.put(thisJoinPointVar.getSlot(), reti++); } // we not only need to put the arguments, we also need to remap their // aliases, which we so helpfully put into temps at the beginning of this join // point. if (! getKind().argsOnStack()) { int oldi = 0; int newi = 0; // if we're passing in a this and we're not argsOnStack we're always // passing in a target too if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; } //assert targetVar == thisVar for (int i = 0; i < getArgCount(); i++) { TypeX type = getArgType(i); ret.put(oldi, newi); oldi += type.getSize(); newi += type.getSize(); } } // System.err.println("making remap for : " + this); // if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot()); // if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot()); // System.err.println(ret); return ret; } /** * The new method always static. * It may take some extra arguments: this, target. * If it's argsOnStack, then it must take both this/target * If it's argsOnFrame, it shares this and target. * ??? rewrite this to do less array munging, please */ private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) { Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes()); int modifiers = Modifier.FINAL | visibilityModifier; // XXX some bug // if (! isExpressionKind() && getSignature().isStrict(world)) { // modifiers |= Modifier.STRICT; // } modifiers |= Modifier.STATIC; if (targetVar != null && targetVar != thisVar) { TypeX targetType = getTargetType(); targetType = ensureTargetTypeIsCorrect(targetType); ResolvedMember resolvedMember = getSignature().resolve(world); if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) && !samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) && !resolvedMember.getName().equals("clone")) { if (!targetType.isAssignableFrom(getThisType(), world)) { throw new BCException("bad bytecode"); } targetType = getThisType(); } parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes); } if (thisVar != null) { TypeX thisType = getThisType(); parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes); } // We always want to pass down thisJoinPoint in case we have already woven // some advice in here. If we only have a single piece of around advice on a // join point, it is unnecessary to accept (and pass) tjp. if (thisJoinPointVar != null) { parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes); } TypeX returnType; if (getKind() == PreInitialization) { returnType = TypeX.OBJECTARRAY; } else { returnType = getReturnType(); } return new LazyMethodGen( modifiers, BcelWorld.makeBcelType(returnType), newMethodName, parameterTypes, new String[0], // XXX again, we need to look up methods! // TypeX.getNames(getSignature().getExceptions(world)), getEnclosingClass()); } private boolean samePackage(String p1, String p2) { if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } private Type[] addType(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len+1]; ret[0] = type; System.arraycopy(types, 0, ret, 1, len); return ret; } private Type[] addTypeToEnd(Type type, Type[] types) { int len = types.length; Type[] ret = new Type[len+1]; ret[len] = type; System.arraycopy(types, 0, ret, 0, len); return ret; } public BcelVar genTempVar(TypeX typeX) { return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize())); } // public static final boolean CREATE_TEMP_NAMES = true; public BcelVar genTempVar(TypeX typeX, String localName) { BcelVar tv = genTempVar(typeX); // if (CREATE_TEMP_NAMES) { // for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) { // if (Range.isRangeHandle(ih)) continue; // ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot())); // } // } return tv; } // eh doesn't think we need to garbage collect these (64K is a big number...) private int genTempVarIndex(int size) { return enclosingMethod.allocateLocal(size); } public InstructionFactory getFactory() { return getEnclosingClass().getFactory(); } public ISourceLocation getSourceLocation() { int sourceLine = getSourceLine(); if (sourceLine == 0 || sourceLine == -1) { // Thread.currentThread().dumpStack(); // System.err.println(this + ": " + range); return getEnclosingClass().getType().getSourceLocation(); } else { return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine); } } public Shadow getEnclosingShadow() { return enclosingShadow; } public LazyMethodGen getEnclosingMethod() { return enclosingMethod; } public boolean isFallsThrough() { return !terminatesWithReturn(); //fallsThrough; } }
88,862
Bug 88862 Declare annotation on ITDs
I'll use this bug to capture info on the implementation...
resolved fixed
0d14ccf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T21:31:49Z
2005-03-23T15:00:00Z
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.jar.Attributes.Name; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.CrosscuttingMembersSet; import org.aspectj.weaver.IClassFileProvider; import org.aspectj.weaver.IWeaveRequestor; import org.aspectj.weaver.IWeaver; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.BindingAnnotationTypePattern; import org.aspectj.weaver.patterns.BindingTypePattern; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.ConcreteCflowPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NameBindingPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.patterns.WithinPointcut; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; public BcelWeaver(BcelWorld world) { super(); WeaverMetrics.reset(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } public void addLibraryAspect(String aspectName) { ResolvedTypeX type = world.resolve(aspectName); //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { xcutSet.addOrReplaceAspect(type); } else { throw new RuntimeException("unimplemented"); } } public void addLibraryJarFile(File inFile) throws IOException { List addedAspects = null; if (inFile.isDirectory()) { addedAspects = addAspectsFromDirectory(inFile); } else { addedAspects = addAspectsFromJarFile(inFile); } for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedTypeX aspectX = (ResolvedTypeX) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } addIfAspect(FileUtil.readAsByteArray(inStream), entry.getName(), addedAspects); inStream.closeEntry(); } inStream.close(); return addedAspects; } private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{ List addedAspects = new ArrayList(); File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){ public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }); for (int i = 0; i < classFiles.length; i++) { FileInputStream fis = new FileInputStream(classFiles[i]); byte[] bytes = FileUtil.readAsByteArray(fis); addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects); } return addedAspects; } private void addIfAspect(byte[] bytes, String name, List toList) throws IOException { ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name); JavaClass jc = parser.parse(); ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { toList.add(type); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; private Set alreadyConfirmedReweavableState; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarFile inJar = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inJar = new JarFile(inFile); addManifest(inJar.getManifest()); Enumeration entries = inJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); InputStream inStream = inJar.getInputStream(entry); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); // System.out.println("? addJarFile() filename='" + filename + "'"); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.close(); } inJar.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inJar != null) { try {inJar.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(TypeX.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void prepareForWeave() { needToReweaveWorld = false; CflowPointcut.clearCaches(); // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedTypeX type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(TypeX.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); rewritePointcuts(shadowMungerList); typeMungerList = xcutSet.getTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); //XXX this gets us a stable (but completely meaningless) order Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }); } /* * Rewrite all of the pointcuts in the world into their most efficient * form for subsequent matching. Also ensure that if pc1.equals(pc2) * then pc1 == pc2 (for non-binding pcds) by making references all * point to the same instance. * Since pointcuts remember their match decision on the last shadow, * this makes matching faster when many pointcuts share common elements, * or even when one single pointcut has one common element (which can * be a side-effect of DNF rewriting). */ private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) { PointcutRewriter rewriter = new PointcutRewriter(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = rewriter.rewrite(p); // validateBindings now whilst we still have around the pointcut // that resembles what the user actually wrote in their program // text. if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getSignature() != null) { int numFormals = advice.getBaseParameterCount(); if (numFormals > 0) { String[] names = advice.getBaseParameterNames(world); validateBindings(newP,p,numFormals,names); } } } munger.setPointcut(newP); } // now that we have optimized individual pointcuts, optimize // across the set of pointcuts.... // Use a map from key based on pc equality, to value based on // pc identity. Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); munger.setPointcut(shareEntriesFromMap(p,pcMap)); } } private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) { // some things cant be shared... if (p instanceof NameBindingPointcut) return p; if (p instanceof IfPointcut) return p; if (p instanceof ConcreteCflowPointcut) return p; if (p instanceof AndPointcut) { AndPointcut apc = (AndPointcut) p; Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap); return new AndPointcut(left,right); } else if (p instanceof OrPointcut) { OrPointcut opc = (OrPointcut) p; Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap); return new OrPointcut(left,right); } else if (p instanceof NotPointcut) { NotPointcut npc = (NotPointcut) p; Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap); return new NotPointcut(not); } else { // primitive pcd if (pcMap.containsKey(p)) { // based on equality return (Pointcut) pcMap.get(p); // same instance (identity) } else { pcMap.put(p,p); return p; } } } // userPointcut is the pointcut that the user wrote in the program text. // dnfPointcut is the same pointcut rewritten in DNF // numFormals is the number of formal parameters in the pointcut // if numFormals > 0 then every branch of a disjunction must bind each formal once and only once. // in addition, the left and right branches of a disjunction must hold on join point kinds in // common. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) { if (numFormals == 0) return; // nothing to check if (dnfPointcut.couldMatchKinds().isEmpty()) return; // cant have problems if you dont match! if (dnfPointcut instanceof OrPointcut) { OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut; Pointcut[] leftBindings = new Pointcut[numFormals]; Pointcut[] rightBindings = new Pointcut[numFormals]; validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings); } else { Pointcut[] bindings = new Pointcut[numFormals]; validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings); } } private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) { Pointcut left = pc.getLeft(); Pointcut right = pc.getRight(); if (left instanceof OrPointcut) { Pointcut[] newRightBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings); } else { if (left.couldMatchKinds().size() > 0) validateSingleBranch(left, userPointcut, numFormals, names, leftBindings); } if (right instanceof OrPointcut) { Pointcut[] newLeftBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings); } else { if (right.couldMatchKinds().size() > 0) validateSingleBranch(right, userPointcut, numFormals, names, rightBindings); } Set kindsInCommon = left.couldMatchKinds(); kindsInCommon.retainAll(right.couldMatchKinds()); if (!kindsInCommon.isEmpty() && couldEverMatchSameJoinPoints(left,right)) { // we know that every branch binds every formal, so there is no ambiguity // if each branch binds it in exactly the same way... List ambiguousNames = new ArrayList(); for (int i = 0; i < numFormals; i++) { if (!leftBindings[i].equals(rightBindings[i])) { ambiguousNames.add(names[i]); } } if (!ambiguousNames.isEmpty()) raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames); } } // pc is a pointcut that does not contain any disjunctions // check that every formal is bound (negation doesn't count). // we know that numFormals > 0 or else we would not be called private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) { boolean[] foundFormals = new boolean[numFormals]; for (int i = 0; i < foundFormals.length; i++) { foundFormals[i] = false; } validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings); for (int i = 0; i < foundFormals.length; i++) { if (!foundFormals[i]) { raiseUnboundFormalError(names[i],userPointcut); } } } // each formal must appear exactly once private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) { if (pc instanceof NotPointcut) { // nots can only appear at leaves in DNF NotPointcut not = (NotPointcut) pc; if (not.getNegatedPointcut() instanceof NameBindingPointcut) { NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut(); if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) raiseNegationBindingError(userPointcut); } } else if (pc instanceof AndPointcut) { AndPointcut and = (AndPointcut) pc; validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings); validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings); } else if (pc instanceof NameBindingPointcut) { List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns(); for (Iterator iter = btps.iterator(); iter.hasNext();) { BindingTypePattern btp = (BindingTypePattern) iter.next(); int index = btp.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns(); for (Iterator iter = baps.iterator(); iter.hasNext();) { BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next(); int index = bap.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); for (int i = 0; i < slots.length; i++) { bindings[slots[i]] = cfp; if (foundFormals[slots[i]]) { raiseAmbiguousBindingError(names[slots[i]],userPointcut); } else { foundFormals[slots[i]] = true; } } } } // By returning false from this method, we are allowing binding of the same // variable on either side of an or. // Be conservative :- have to consider overriding, varargs, autoboxing, // the effects of itds (on within for example), interfaces, the fact that // join points can have multiple signatures and so on. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) { if ((left instanceof OrPointcut) || (right instanceof OrPointcut)) return true; // look for withins WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class); WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class); if ((leftWithin != null) && (rightWithin != null)) { if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false; } // look for kinded KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class); KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class); if ((leftKind != null) && (rightKind != null)) { if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false; } return true; } private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) { if (toSearch instanceof NotPointcut) return null; if (toLookFor.isInstance(toSearch)) return toSearch; if (toSearch instanceof AndPointcut) { AndPointcut apc = (AndPointcut) toSearch; Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor); if (left != null) return left; return findFirstPointcutIn(apc.getRight(),toLookFor); } return null; } /** * @param userPointcut */ private void raiseNegationBindingError(Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param string * @param userPointcut */ private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param userPointcut */ private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) { StringBuffer formalNames = new StringBuffer(names.get(0).toString()); for (int i = 1; i < names.size(); i++) { formalNames.append(", "); formalNames.append(names.get(i)); } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param string * @param userPointcut */ private void raiseUnboundFormalError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); requestor.processingReweavableState(); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); processReweavableStateIfPresent(className, classType); } requestor.addingTypeMungers(); // We process type mungers in two groups, first mungers that change the type // hierarchy, then 'normal' ITD type mungers. // Process the types in a predictable order (rather than the order encountered). // For class A, the order is superclasses of A then superinterfaces of A // (and this mechanism is applied recursively) List typesToProcess = new ArrayList(); for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = (UnwovenClassFile) iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size()>0) { weaveParentsFor(typesToProcess,(String)typesToProcess.get(0)); } for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addNormalTypeMungers(className); } requestor.weavingAspects(); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (classType.isAspect()) { weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } requestor.weavingClasses(); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); if (! classType.isAspect()) { weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning if (world.behaveInJava5Way && world.getLint().adviceDidNotMatch.isEnabled()) { List l = world.getCrosscuttingMembersSet().getShadowMungers(); for (Iterator iter = l.iterator(); iter.hasNext();) { ShadowMunger element = (ShadowMunger) iter.next(); if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers BcelAdvice ba = (BcelAdvice)element; if (!ba.hasMatchedSomething()) { BcelMethod meth = (BcelMethod)ba.getSignature(); if (meth!=null) { AnnotationX[] anns = (AnnotationX[])meth.getAnnotations(); // Check if they want to suppress the warning on this piece of advice if (!Utility.isSuppressing(anns,"adviceDidNotMatch")) { world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().getNameAsIdentifier(),element.getSourceLocation()); } } } } } } requestor.weaveCompleted(); return wovenClassNames; } /** * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process * supertypes (classes/interfaces) of 'typeToWeave' that are in the * 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from * the 'typesForWeaving' list. * * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may * break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it * may choose to weave them in either order - but you'll probably have other problems if * you are supplying partial hierarchies like that ! */ private void weaveParentsFor(List typesForWeaving,String typeToWeave) { // Look at the supertype first ResolvedTypeX rtx = world.resolve(typeToWeave); ResolvedTypeX superType = rtx.getSuperclass(); if (superType!=null && typesForWeaving.contains(superType.getClassName())) { weaveParentsFor(typesForWeaving,superType.getClassName()); } // Then look at the superinterface list ResolvedTypeX[] interfaceTypes = rtx.getDeclaredInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ResolvedTypeX rtxI = interfaceTypes[i]; if (typesForWeaving.contains(rtxI.getClassName())) { weaveParentsFor(typesForWeaving,rtxI.getClassName()); } } weaveParentTypeMungers(rtx); // Now do this type typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process } public void prepareToProcessReweavableState() { if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); alreadyConfirmedReweavableState = new HashSet(); } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()), null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedTypeX rtx = world.resolve(TypeX.forName(requiredTypeName),true); boolean exists = rtx!=ResolvedTypeX.MISSING; if (!exists) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className), classType.getSourceLocation(), null); } else { if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()), null,null); alreadyConfirmedReweavableState.add(requiredTypeName); } } } } classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); } else { classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } } // helper method public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addParentTypeMungers(String typeName) { weaveParentTypeMungers(world.resolve(typeName)); } public void addNormalTypeMungers(String typeName) { weaveNormalTypeMungers(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes()); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } /** * Weaves new parents and annotations onto a type ("declare parents" and "declare @type") * * Algorithm: * 1. First pass, do parents then do annotations. During this pass record: * - any parent mungers that don't match but have a non-wild annotation type pattern * - any annotation mungers that don't match * 2. Multiple subsequent passes which go over the munger lists constructed in the first * pass, repeatedly applying them until nothing changes. * FIXME asc confirm that algorithm is optimal ?? */ public void weaveParentTypeMungers(ResolvedTypeX onType) { onType.clearInterTypeMungers(); List decpToRepeat = new ArrayList(); List decaToRepeat = new ArrayList(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents decp = (DeclareParents)i.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { // Perhaps it would have matched if a 'dec @type' had modified the type if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation)i.next(); boolean typeChanged = applyDeclareAtType(decA,onType,true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List decpToRepeatNextTime = new ArrayList(); for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = (DeclareParents) iter.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA,onType,false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedTypeX onType,boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { //FIXME asc CRITICAL this should be guarded by the 'already has annotation' check below but isn't since the compiler is producing classfiles with deca affected things in... AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation()); if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) { // FIXME asc Could put out a lint here for an already annotated type - the problem is that it may have // picked up the annotation during 'source weaving' in which case the message is misleading. Leaving it // off for now... // if (reportProblems) { // world.getLint().elementAlreadyAnnotated.signal( // new String[]{onType.toString(),decA.getAnnotationTypeX().toString()}, // onType.getSourceLocation(),new ISourceLocation[]{decA.getSourceLocation()}); // } return false; } AnnotationX annoX = decA.getAnnotationX(); // check the annotation is suitable for the target boolean problemReported = verifyTargetIsOK(decA, onType, annoX,reportProblems); if (!problemReported) { didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation * to be attached to the target type that matched. */ private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedTypeX onType, AnnotationX annoX,boolean outputProblems) { boolean problemReported = false; if (annoX.specifiesTarget()) { if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { if (outputProblems) { if (decA.isExactPattern()) { world.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation())); } else { if (world.getLint().invalidTargetForAnnotation.isEnabled()) { world.getLint().invalidTargetForAnnotation.signal( new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()}); } } } problemReported = true; } } return problemReported; } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedTypeX onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType,true); if (!newParents.isEmpty()) { didSomething=true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedTypeX newParent = (ResolvedTypeX)j.next(); // We set it here so that the imminent matching for ITDs can succeed - we // still haven't done the necessary changes to the class file itself // (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent() classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } return didSomething; } public void weaveNormalTypeMungers(ResolvedTypeX onType) { for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (m.matches(onType)) { onType.addInterTypeMunger(m); } } } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { if (dump) dumpUnchanged(classFile); return null; } // JavaClass javaClass = classType.getJavaClass(); List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); LazyClassGen clazz = null; if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() || world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0 ) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers); if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { System.err.println("trouble in: "); //XXXclazz.print(System.err); throw re; } catch (Error re) { System.err.println("trouble in: "); clazz.print(System.err); throw re; } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedTypeX type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info if (fb.maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean mode,boolean compress) { inReweavableMode = mode; WeaverStateInfo.setReweavableModeDefaults(mode,compress); BcelClassWeaver.setReweavableMode(mode,compress); } public boolean isReweavable() { return inReweavableMode; } }
88,862
Bug 88862 Declare annotation on ITDs
I'll use this bug to capture info on the implementation...
resolved fixed
0d14ccf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T21:31:49Z
2005-03-23T15: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.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.Member; import org.aspectj.weaver.ResolvedTypeX; import org.aspectj.weaver.WeaverMessages; /** * 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 AnnotationGen[] annotations; /* private */ final LazyClassGen enclosingClass; private final BcelMethod memberView; 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 ResolvedTypeX 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(); } 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(); } public boolean hasDeclaredLineNumberInfo() { return (memberView != null && memberView.hasDeclarationLineNumberInfo()); } public int getDeclarationLineNumber() { if (hasDeclaredLineNumberInfo()) { return memberView.getDeclarationLineNumber(); } else { return -1; } } public void addAnnotation(AnnotationX ax) { initialize(); // if (!hasAnnotation(TypeX.forSignature(a.getTypeSignature()))) { AnnotationGen ag = new AnnotationGen(ax.getBcelAnnotation(),enclosingClass.getConstantPoolGen(),true); AnnotationGen[] newAnnotations = new AnnotationGen[annotations.length+1]; System.arraycopy(annotations,0,newAnnotations,0,annotations.length); newAnnotations[annotations.length]=ag; annotations = newAnnotations; // FIXME asc does this mean we are managing two levels of annotations again? // one here and one in the memberView??!? memberView.addAnnotation(ax); } 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 = TypeX.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() { return toLongString(); } 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() { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s)); return new String(s.toByteArray()); } public void print() { print(System.out); } public void print(PrintStream out) { out.print(" " + toShortString()); printAspectAttributes(out); InstructionList body = getBody(); if (body == null) { out.println(";"); return; } out.println(":"); new BodyPrinter(out).run(); out.println(" end " + toShortString()); } private void printAspectAttributes(PrintStream out) { ISourceContext context = null; if (enclosingClass != null && enclosingClass.getType() != null) { context = enclosingClass.getType().getSourceContext(); } List as = BcelAttributes.readAjAttributes(getClassName(),attributes, context,null); 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 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 (annotations!=null) { for (int i = 0, len = annotations.length; i < len; i++) { gen.addAnnotation(annotations[i]); } } 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; return memberView.getEffectiveSignature(); } public String getSignature() { if (memberView!=null) return memberView.getSignature(); return Member.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes())); } public String getParameterSignature() { if (memberView!=null) return memberView.getParameterSignature(); return Member.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; } }
88,862
Bug 88862 Declare annotation on ITDs
I'll use this bug to capture info on the implementation...
resolved fixed
0d14ccf
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2005-03-23T21:31:49Z
2005-03-23T15:00:00Z
weaver/src/org/aspectj/weaver/patterns/AnnotationPointcut.java
/* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; 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.ResolvedTypeX; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeX; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @annotation(@Foo) or @annotation(foo) * * Matches any join point where the subject of the join point has an * annotation matching the annotationTypePattern: * * Join Point Kind Subject * ================================ * method call the target method * method execution the method * constructor call the constructor * constructor execution the constructor * get the target field * set the target field * adviceexecution the advice * initialization the constructor * preinitialization the constructor * staticinitialization the type being initialized * handler the declared type of the handled exception */ public class AnnotationPointcut extends NameBindingPointcut { private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger = null; // only set after concretization public AnnotationPointcut(ExactAnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = Pointcut.ANNOTATION; } public AnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { if (info.getKind() == Shadow.StaticInitialization) { return annotationTypePattern.fastMatches(info.getType()); } else { return FuzzyBoolean.MAYBE; } } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { AnnotatedElement toMatchAgainst = null; Member member = shadow.getSignature(); ResolvedMember rMember = member.resolve(shadow.getIWorld()); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } Shadow.Kind kind = shadow.getKind(); if (kind == Shadow.StaticInitialization) { toMatchAgainst = rMember.getDeclaringType().resolve(shadow.getIWorld()); } else if ( (kind == Shadow.ExceptionHandler)) { toMatchAgainst = rMember.getParameterTypes()[0].resolve(shadow.getIWorld()); } else { toMatchAgainst = rMember; } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(toMatchAgainst); } /* (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.ResolvedTypeX, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new AnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (shadow.getKind()!=Shadow.MethodCall && shadow.getKind()!=Shadow.ConstructorCall && shadow.getKind()!=Shadow.ConstructorExecution && shadow.getKind()!=Shadow.MethodExecution && shadow.getKind()!=Shadow.FieldSet && shadow.getKind()!=Shadow.FieldGet && shadow.getKind()!=Shadow.StaticInitialization && shadow.getKind()!=Shadow.PreInitialization && shadow.getKind()!=Shadow.AdviceExecution && shadow.getKind()!=Shadow.Initialization && shadow.getKind()!=Shadow.ExceptionHandler ) { IMessage lim = MessageUtil.error("Binding not supported in @pcds (1.5.0 M2 limitation) for "+shadow.getKind()+" join points, see: " + getSourceLocation()); shadow.getIWorld().getMessageHandler().handleMessage(lim); throw new BCException("Binding not supported in @pcds (1.5.0 M2 limitation) for "+shadow.getKind()+" join points, see: " + getSourceLocation()); } if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; TypeX annotationType = btp.annotationType; Var var = shadow.getKindedAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]");//return Literal.FALSE; // Check if we have already bound something to this formal if ((state.get(btp.getFormalIndex())!=null) &&(lastMatchedShadowId == shadow.shadowId)) { // ISourceLocation pcdSloc = getSourceLocation(); // ISourceLocation shadowSloc = shadow.getSourceLocation(); // Message errorMessage = new Message( // "Cannot use @pointcut to match at this location and bind a formal to type '"+var.getType()+ // "' - the formal is already bound to type '"+state.get(btp.getFormalIndex()).getType()+"'"+ // ". The secondary source location points to the problematic binding.", // shadowSloc,true,new ISourceLocation[]{pcdSloc}); // shadow.getIWorld().getMessageHandler().handleMessage(errorMessage); state.setErroneousVar(btp.getFormalIndex()); } state.set(btp.getFormalIndex(),var); } 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.ANNOTATION); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); AnnotationPointcut ret = new AnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof AnnotationPointcut)) return false; AnnotationPointcut o = (AnnotationPointcut)other; return o.annotationTypePattern.equals(this.annotationTypePattern); } public int hashCode() { int result = 17; result = 37*result + annotationTypePattern.hashCode(); return result; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("@annotation("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); return buf.toString(); } }