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
122,347
Bug 122347 Contribution: Memory Efficient Expendable Type Map
Here is a patch for a single file (weaver/src/org/aspectj/weaver/World) that significantly improves the memory footprint of weaves (see details below). I would like help in resolving the one bug that this hit in the AspectJ weaver tests. It does the following: * Keeps Weak References to the values in the expendable map to allow evicting them (whereas the Weak Hash Map keeps weak references only to the keys) * Allows configuring the expendable map to keep hard references to up to N types with -Dorg.aspectj.weaver.World.cacheRetention=number (the current default is 0). It's a nice tuning option so projects can use a bit more memory to avoid evicting types. * Moves the isExpendible check from the typeMap to the world, to allow different worlds (such as the LTWWorld) to change what's evictable (this lets the LTWWorld not keep references to already defined classes) This change breaks 3 tests in the "run these tests before checking in code" suite, all of them an NPE in the same line of ReferenceType.getTypeVariables for generic signatures. Presumably this code is implicitly relying on "expendable" types never being evicted. I have attached the error output for all 3 cases. My initial tests have shown a relatively small performance loss in return for significant memory footprint gains. E.g., using the AspectJ in CVS HEAD with the standard BcelWorld implementation (not LTWWorld) as the world, in Tomcat with the Glassbox Inspector & 4 web apps the AspectJ overhead with this optimization is 48 million heap bytes (of 60 million total heap bytes) versus 61 million bytes using CVS HEAD. The optimization has limited benefit for a BcelWorld where almost all the code is exposed to the weaver (since few types are expendible). However, Martin Lippert tried a version of this in his AJEER Eclipse load-time weaving environment and reported a reduction from 230 MB of heap to 30 MB heap used at a cost of a 25% increase in start up time. Likewise, this facility is the major contributor to enabling my other LTW optimizations that can reduce the heap overhead in my test case to 9 million heap bytes (principally having the LTW world allow evicting types that are already woven and using reflective proxies). I see similar start up times when using this expendable map in my tests. The ability to increase the number of hard references in cache should provide users an ability to allocate more memory to speed up performance. Note that the only hard reference to the keys (the signatures) is from the values (at least I haven't noticed any cases in my load-time weaving tests), so the weak hash map is compacting itself properly: when the reference type is weakly reachable, the key is then weakly reachable and the map ultimately purges theses entries.
resolved wontfix
04067a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-18T17:59:28Z
2005-12-29T23:46:40Z
weaver/src/org/aspectj/weaver/World.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer, Andy Clement, overhaul for generics * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import org.aspectj.asm.IHierarchy; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.bridge.context.PinpointingMessageHandler; import org.aspectj.weaver.UnresolvedType.TypeKind; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; /** * A World is a collection of known types and crosscutting members. */ public abstract class World implements Dump.INode { /** handler for any messages produced during resolution etc. */ private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR; /** handler for cross-reference information produced during the weaving process */ private ICrossReferenceHandler xrefHandler = null; /** Currently 'active' scope in which to lookup (resolve) typevariable references */ private TypeVariableDeclaringElement typeVariableLookupScope; /** The heart of the world, a map from type signatures to resolved types */ protected TypeMap typeMap = new TypeMap(); // Signature to ResolvedType /** Calculator for working out aspect precedence */ private AspectPrecedenceCalculator precedenceCalculator; /** All of the type and shadow mungers known to us */ private CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this); /** Model holds ASM relationships */ private IHierarchy model = null; /** for processing Xlint messages */ private Lint lint = new Lint(this); /** XnoInline option setting passed down to weaver */ private boolean XnoInline; /** XlazyTjp option setting passed down to weaver */ private boolean XlazyTjp; /** XhasMember option setting passed down to weaver */ private boolean XhasMember = false; /** Xpinpoint controls whether we put out developer info showing the source of messages */ private boolean Xpinpoint = false; /** When behaving in a Java 5 way autoboxing is considered */ private boolean behaveInJava5Way = false; /** The level of the aspectjrt.jar the code we generate needs to run on */ private String targetAspectjRuntimeLevel = Constants.RUNTIME_LEVEL_DEFAULT; /** * A list of RuntimeExceptions containing full stack information for every * type we couldn't find. */ private List dumpState_cantFindTypeExceptions = null; /** * Play God. * On the first day, God created the primitive types and put them in the type * map. */ protected World() { super(); Dump.registerNode(this.getClass(),this); typeMap.put("B", ResolvedType.BYTE); typeMap.put("S", ResolvedType.SHORT); typeMap.put("I", ResolvedType.INT); typeMap.put("J", ResolvedType.LONG); typeMap.put("F", ResolvedType.FLOAT); typeMap.put("D", ResolvedType.DOUBLE); typeMap.put("C", ResolvedType.CHAR); typeMap.put("Z", ResolvedType.BOOLEAN); typeMap.put("V", ResolvedType.VOID); precedenceCalculator = new AspectPrecedenceCalculator(this); } /** * Dump processing when a fatal error occurs */ public void accept (Dump.IVisitor visitor) { visitor.visitString("Shadow mungers:"); visitor.visitList(crosscuttingMembersSet.getShadowMungers()); visitor.visitString("Type mungers:"); visitor.visitList(crosscuttingMembersSet.getTypeMungers()); visitor.visitString("Late Type mungers:"); visitor.visitList(crosscuttingMembersSet.getLateTypeMungers()); if (dumpState_cantFindTypeExceptions!=null) { visitor.visitString("Cant find type problems:"); visitor.visitList(dumpState_cantFindTypeExceptions); dumpState_cantFindTypeExceptions = null; } } // ============================================================================= // T Y P E R E S O L U T I O N // ============================================================================= /** * Resolve a type that we require to be present in the world */ public ResolvedType resolve(UnresolvedType ty) { return resolve(ty, false); } /** * Attempt to resolve a type - the source location gives you some context in which * resolution is taking place. In the case of an error where we can't find the * type - we can then at least report why (source location) we were trying to resolve it. */ public ResolvedType resolve(UnresolvedType ty,ISourceLocation isl) { ResolvedType ret = resolve(ty,true); if (ResolvedType.isMissing(ty)) { //IMessage msg = null; getLint().cantFindType.signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl); //if (isl!=null) { //msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl); //} else { //msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName())); //} //messageHandler.handleMessage(msg); } return ret; } /** * Convenience method for resolving an array of unresolved types * in one hit. Useful for e.g. resolving type parameters in signatures. */ public ResolvedType[] resolve(UnresolvedType[] types) { if (types == null) return new ResolvedType[0]; ResolvedType[] ret = new ResolvedType[types.length]; for (int i=0; i<types.length; i++) { ret[i] = resolve(types[i]); } return ret; } /** * Resolve a type. This the hub of type resolution. The resolved type is added * to the type map by signature. */ public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) { // special resolution processing for already resolved types. if (ty instanceof ResolvedType) { ResolvedType rty = (ResolvedType) ty; rty = resolve(rty); return rty; } // dispatch back to the type variable reference to resolve its constituent parts // don't do this for other unresolved types otherwise you'll end up in a loop if (ty.isTypeVariableReference()) { return ty.resolve(this); } // if we've already got a resolved type for the signature, just return it // after updating the world String signature = ty.getSignature(); ResolvedType ret = typeMap.get(signature); if (ret != null) { ret.world = this; // Set the world for the RTX return ret; } else if ( signature.equals("?") || signature.equals("*")) { // might be a problem here, not sure '?' should make it to here as a signature, the // proper signature for wildcard '?' is '*' // fault in generic wildcard, can't be done earlier because of init issues ResolvedType something = new BoundedReferenceType("?",this); typeMap.put("?",something); return something; } // no existing resolved type, create one if (ty.isArray()) { ResolvedType componentType = resolve(ty.getComponentType(),allowMissing); //String brackets = signature.substring(0,signature.lastIndexOf("[")+1); ret = new ResolvedType.Array(signature, "["+componentType.getErasureSignature(), this, componentType); } else { ret = resolveToReferenceType(ty); if (!allowMissing && ret.isMissing()) { ret = handleRequiredMissingTypeDuringResolution(ty); } } // Pulling in the type may have already put the right entry in the map if (typeMap.get(signature)==null && !ret.isMissing()) { typeMap.put(signature, ret); } return ret; } /** * We tried to resolve a type and couldn't find it... */ private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) { // defer the message until someone asks a question of the type that we can't answer // just from the signature. // MessageUtil.error(messageHandler, // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName())); if (dumpState_cantFindTypeExceptions==null) { dumpState_cantFindTypeExceptions = new ArrayList(); } dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type "+ty.getName())); return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),this); } /** * Some TypeFactory operations create resolved types directly, but these won't be * in the typeMap - this resolution process puts them there. Resolved types are * also told their world which is needed for the special autoboxing resolved types. */ public ResolvedType resolve(ResolvedType ty) { if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs... ResolvedType resolved = typeMap.get(ty.getSignature()); if (resolved == null) { typeMap.put(ty.getSignature(), ty); resolved = ty; } resolved.world = this; return resolved; } /** * Convenience method for finding a type by name and resolving it in one step. */ public ResolvedType resolve(String name) { return resolve(UnresolvedType.forName(name)); } public ResolvedType resolve(String name,boolean allowMissing) { return resolve(UnresolvedType.forName(name),allowMissing); } private ResolvedType currentlyResolvingBaseType; /** * Resolve to a ReferenceType - simple, raw, parameterized, or generic. * Raw, parameterized, and generic versions of a type share a delegate. */ private final ResolvedType resolveToReferenceType(UnresolvedType ty) { if (ty.isParameterizedType()) { // ======= parameterized types ================ ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false); currentlyResolvingBaseType = genericType; ReferenceType parameterizedType = TypeFactory.createParameterizedType(genericType, ty.typeParameters, this); currentlyResolvingBaseType = null; return parameterizedType; } else if (ty.isGenericType()) { // ======= generic types ====================== ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false); return genericType; } else if (ty.isGenericWildcard()) { // ======= generic wildcard types ============= return resolveGenericWildcardFor(ty); } else { // ======= simple and raw types =============== String erasedSignature = ty.getErasureSignature(); ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this); ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType); // 117854 // if (delegate == null) return ResolvedType.MISSING; if (delegate == null) return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),erasedSignature,this);//ResolvedType.MISSING; if (delegate.isGeneric() && behaveInJava5Way) { // ======== raw type =========== simpleOrRawType.typeKind = TypeKind.RAW; ReferenceType genericType = makeGenericTypeFrom(delegate,simpleOrRawType); // name = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(ty.getName()),this); simpleOrRawType.setDelegate(delegate); genericType.setDelegate(delegate); simpleOrRawType.setGenericType(genericType); return simpleOrRawType; } else { // ======== simple type ========= simpleOrRawType.setDelegate(delegate); return simpleOrRawType; } } } /** * Attempt to resolve a type that should be a generic type. */ public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) { // Look up the raw type by signature String rawSignature = anUnresolvedType.getRawType().getSignature(); ResolvedType rawType = (ResolvedType) typeMap.get(rawSignature); if (rawType==null) { rawType = resolve(UnresolvedType.forSignature(rawSignature),false); typeMap.put(rawSignature,rawType); } // Does the raw type know its generic form? (It will if we created the // raw type from a source type, it won't if its been created just through // being referenced, e.g. java.util.List ResolvedType genericType = rawType.getGenericType(); // There is a special case to consider here (testGenericsBang_pr95993 highlights it) // You may have an unresolvedType for a parameterized type but it // is backed by a simple type rather than a generic type. This occurs for // inner types of generic types that inherit their enclosing types // type variables. if (rawType.isSimpleType() && (anUnresolvedType.typeParameters==null || anUnresolvedType.typeParameters.length==0)) { rawType.world = this; return rawType; } if (genericType != null) { genericType.world = this; return genericType; } else { // Fault in the generic that underpins the raw type ;) ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType)rawType); ReferenceType genericRefType = makeGenericTypeFrom(delegate,((ReferenceType)rawType)); ((ReferenceType)rawType).setGenericType(genericRefType); genericRefType.setDelegate(delegate); ((ReferenceType)rawType).setDelegate(delegate); return genericRefType; } } private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) { String genericSig = delegate.getDeclaredGenericSignature(); if (genericSig != null) { return new ReferenceType( UnresolvedType.forGenericTypeSignature(rawType.getSignature(),delegate.getDeclaredGenericSignature()),this); } else { return new ReferenceType( UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),this); } } /** * Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType). */ private ReferenceType resolveGenericWildcardFor(UnresolvedType aType) { BoundedReferenceType ret = null; // FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?) if (aType.isExtends()) { ReferenceType upperBound = (ReferenceType)resolve(aType.getUpperBound()); ret = new BoundedReferenceType(upperBound,true,this); } else if (aType.isSuper()) { ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound()); ret = new BoundedReferenceType(lowerBound,false,this); } else { // must be ? on its own! } return ret; } /** * Find the ReferenceTypeDelegate behind this reference type so that it can * fulfill its contract. */ protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty); /** * Special resolution for "core" types like OBJECT. These are resolved just like * any other type, but if they are not found it is more serious and we issue an * error message immediately. */ public ResolvedType getCoreType(UnresolvedType tx) { ResolvedType coreTy = resolve(tx,true); if (coreTy.isMissing()) { MessageUtil.error(messageHandler, WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName())); } return coreTy; } /** * Lookup a type by signature, if not found then build one and put it in the * map. */ public ReferenceType lookupOrCreateName(UnresolvedType ty) { String signature = ty.getSignature(); ReferenceType ret = lookupBySignature(signature); if (ret == null) { ret = ReferenceType.fromTypeX(ty, this); typeMap.put(signature, ret); } return ret; } /** * Lookup a reference type in the world by its signature. Returns * null if not found. */ public ReferenceType lookupBySignature(String signature) { return (ReferenceType) typeMap.get(signature); } // ============================================================================= // T Y P E R E S O L U T I O N -- E N D // ============================================================================= /** * Member resolution is achieved by resolving the declaring type and then * looking up the member in the resolved declaring type. */ public ResolvedMember resolve(Member member) { ResolvedType declaring = member.getDeclaringType().resolve(this); if (declaring.isRawType()) declaring = declaring.getGenericType(); ResolvedMember ret; if (member.getKind() == Member.FIELD) { ret = declaring.lookupField(member); } else { ret = declaring.lookupMethod(member); } if (ret != null) return ret; return declaring.lookupSyntheticMember(member); } // Methods for creating various cross-cutting members... // =========================================================== /** * Create an advice shadow munger from the given advice attribute */ public abstract Advice createAdviceMunger( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature); /** * Create an advice shadow munger for the given advice kind */ public final Advice createAdviceMunger( AdviceKind kind, Pointcut p, Member signature, int extraParameterFlags, IHasSourceLocation loc) { AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext()); return createAdviceMunger(attribute, p, signature); } public abstract ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField); public abstract ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField); /** * Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed * @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind) */ public abstract ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind); public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType); /** * Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo */ public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.compareByPrecedence(aspect1, aspect2); } public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.getPrecedenceIfAny(aspect1, aspect2); } /** * compares by precedence with the additional rule that a super-aspect is * sorted before its sub-aspects */ public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) { return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2); } // simple property getter and setters // =========================================================== /** * Nobody should hold onto a copy of this message handler, or setMessageHandler won't * work right. */ public IMessageHandler getMessageHandler() { return messageHandler; } public void setMessageHandler(IMessageHandler messageHandler) { if (this.isInPinpointMode()) { this.messageHandler = new PinpointingMessageHandler(messageHandler); } else { this.messageHandler = messageHandler; } } /** * convenenience method for creating and issuing messages via the message handler - * if you supply two locations you will get two messages. */ public void showMessage( Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) { if (loc1 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc1)); if (loc2 != null) { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } else { messageHandler.handleMessage(new Message(message, kind, null, loc2)); } } public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) { this.xrefHandler = xrefHandler; } /** * Get the cross-reference handler for the world, may be null. */ public ICrossReferenceHandler getCrossReferenceHandler() { return this.xrefHandler; } public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) { this.typeVariableLookupScope = scope; } public TypeVariableDeclaringElement getTypeVariableLookupScope() { return typeVariableLookupScope; } public List getDeclareParents() { return crosscuttingMembersSet.getDeclareParents(); } public List getDeclareAnnotationOnTypes() { return crosscuttingMembersSet.getDeclareAnnotationOnTypes(); } public List getDeclareAnnotationOnFields() { return crosscuttingMembersSet.getDeclareAnnotationOnFields(); } public List getDeclareAnnotationOnMethods() { return crosscuttingMembersSet.getDeclareAnnotationOnMethods(); } public List getDeclareSoft() { return crosscuttingMembersSet.getDeclareSofts(); } public CrosscuttingMembersSet getCrosscuttingMembersSet() { return crosscuttingMembersSet; } public IHierarchy getModel() { return model; } public void setModel(IHierarchy model) { this.model = model; } public Lint getLint() { return lint; } public void setLint(Lint lint) { this.lint = lint; } public boolean isXnoInline() { return XnoInline; } public void setXnoInline(boolean xnoInline) { XnoInline = xnoInline; } public boolean isXlazyTjp() { return XlazyTjp; } public void setXlazyTjp(boolean b) { XlazyTjp = b; } public boolean isHasMemberSupportEnabled() { return XhasMember; } public void setXHasMemberSupportEnabled(boolean b) { XhasMember = b; } public boolean isInPinpointMode() { return Xpinpoint; } public void setPinpointMode(boolean b) { this.Xpinpoint = b; } public void setBehaveInJava5Way(boolean b) { behaveInJava5Way = b; } public boolean isInJava5Mode() { return behaveInJava5Way; } public void setTargetAspectjRuntimeLevel(String s) { targetAspectjRuntimeLevel = s; } public String getTargetAspectjRuntimeLevel() { return targetAspectjRuntimeLevel; } public boolean isTargettingAspectJRuntime12() { boolean b = false; // pr116679 if (!isInJava5Mode()) b=true; else b = getTargetAspectjRuntimeLevel().equals(org.aspectj.weaver.Constants.RUNTIME_LEVEL_12); //System.err.println("Asked if targetting runtime 1.2 , returning: "+b); return b; } /* * Map of types in the world, with soft links to expendable ones. * An expendable type is a reference type that is not exposed to the weaver (ie * just pulled in for type resolution purposes). */ protected static class TypeMap { /** Map of types that never get thrown away */ private Map tMap = new HashMap(); /** Map of types that may be ejected from the cache if we need space */ private Map expendableMap = new WeakHashMap(); private static final boolean debug = false; /** * Add a new type into the map, the key is the type signature. * Some types do *not* go in the map, these are ones involving * *member* type variables. The reason is that when all you have is the * signature which gives you a type variable name, you cannot * guarantee you are using the type variable in the same way * as someone previously working with a similarly * named type variable. So, these do not go into the map: * - TypeVariableReferenceType. * - ParameterizedType where a member type variable is involved. * - BoundedReferenceType when one of the bounds is a type variable. * * definition: "member type variables" - a tvar declared on a generic * method/ctor as opposed to those you see declared on a generic type. */ public ResolvedType put(String key, ResolvedType type) { if (type.isParameterizedType() && type.isParameterizedWithAMemberTypeVariable()) { if (debug) System.err.println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="+key+" type="+type); return type; } if (type.isTypeVariableReference()) { if (debug) System.err.println("Not putting a type variable reference type into the typemap: key="+key+" type="+type); return type; } // this test should be improved - only avoid putting them in if one of the // bounds is a member type variable if (type instanceof BoundedReferenceType) { if (debug) System.err.println("Not putting a bounded reference type into the typemap: key="+key+" type="+type); return type; } if (type instanceof MissingResolvedTypeWithKnownSignature) { if (debug) System.err.println("Not putting a missing type into the typemap: key="+key+" type="+type); return type; } if (isExpendable(type)) { return (ResolvedType) expendableMap.put(key,type); } else { return (ResolvedType) tMap.put(key,type); } } /** Lookup a type by its signature */ public ResolvedType get(String key) { ResolvedType ret = (ResolvedType) tMap.get(key); if (ret == null) ret = (ResolvedType) expendableMap.get(key); return ret; } /** Remove a type from the map */ public ResolvedType remove(String key) { ResolvedType ret = (ResolvedType) tMap.remove(key); if (ret == null) ret = (ResolvedType) expendableMap.remove(key); return ret; } /** Reference types we don't intend to weave may be ejected from * the cache if we need the space. */ private boolean isExpendable(ResolvedType type) { return ( (type != null) && (!type.isExposedToWeaver()) && (!type.isPrimitiveType()) ); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("types:\n"); sb.append(dumpthem(tMap)); sb.append("expendables:\n"); sb.append(dumpthem(expendableMap)); return sb.toString(); } private String dumpthem(Map m) { StringBuffer sb = new StringBuffer(); Set keys = m.keySet(); for (Iterator iter = keys.iterator(); iter.hasNext();) { String k = (String) iter.next(); sb.append(k+"="+m.get(k)).append("\n"); } return sb.toString(); } } /** * This class is used to compute and store precedence relationships between * aspects. */ private static class AspectPrecedenceCalculator { private World world; private Map cachedResults; public AspectPrecedenceCalculator(World forSomeWorld) { this.world = forSomeWorld; this.cachedResults = new HashMap(); } /** * Ask every declare precedence in the world to order the two aspects. * If more than one declare precedence gives an ordering, and the orderings * conflict, then that's an error. */ public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) { PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect,secondAspect); if (cachedResults.containsKey(key)) { return ((Integer) cachedResults.get(key)).intValue(); } else { int order = 0; DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering for (Iterator i = world.getCrosscuttingMembersSet().getDeclareDominates().iterator(); i.hasNext(); ) { DeclarePrecedence d = (DeclarePrecedence)i.next(); int thisOrder = d.compare(firstAspect, secondAspect); if (thisOrder != 0) { if (orderer==null) orderer = d; if (order != 0 && order != thisOrder) { ISourceLocation[] isls = new ISourceLocation[2]; isls[0]=orderer.getSourceLocation(); isls[1]=d.getSourceLocation(); Message m = new Message("conflicting declare precedence orderings for aspects: "+ firstAspect.getName()+" and "+secondAspect.getName(),null,true,isls); world.getMessageHandler().handleMessage(m); } else { order = thisOrder; } } } cachedResults.put(key, new Integer(order)); return order; } } public Integer getPrecedenceIfAny(ResolvedType aspect1,ResolvedType aspect2) { return (Integer)cachedResults.get(new PrecedenceCacheKey(aspect1,aspect2)); } public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) { if (firstAspect.equals(secondAspect)) return 0; int ret = compareByPrecedence(firstAspect, secondAspect); if (ret != 0) return ret; if (firstAspect.isAssignableFrom(secondAspect)) return -1; else if (secondAspect.isAssignableFrom(firstAspect)) return +1; return 0; } private static class PrecedenceCacheKey { public ResolvedType aspect1; public ResolvedType aspect2; public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) { this.aspect1 = a1; this.aspect2 = a2; } public boolean equals(Object obj) { if (!(obj instanceof PrecedenceCacheKey)) return false; PrecedenceCacheKey other = (PrecedenceCacheKey) obj; return (aspect1 == other.aspect1 && aspect2 == other.aspect2); } public int hashCode() { return aspect1.hashCode() + aspect2.hashCode(); } } } public void validateType(UnresolvedType type) { } // --- with java5 we can get into a recursive mess if we aren't careful when resolving types (*cough* java.lang.Enum) --- // --- this first map is for java15 delegates which may try and recursively access the same type variables. // --- I would rather stash this against a reference type - but we don't guarantee referencetypes are unique for // so we can't :( private Map workInProgress1 = new HashMap(); public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class baseClass) { return (TypeVariable[])workInProgress1.get(baseClass); } public void recordTypeVariablesCurrentlyBeingProcessed(Class baseClass, TypeVariable[] typeVariables) { workInProgress1.put(baseClass,typeVariables); } public void forgetTypeVariablesCurrentlyBeingProcessed(Class baseClass) { workInProgress1.remove(baseClass); } // --- }
122,347
Bug 122347 Contribution: Memory Efficient Expendable Type Map
Here is a patch for a single file (weaver/src/org/aspectj/weaver/World) that significantly improves the memory footprint of weaves (see details below). I would like help in resolving the one bug that this hit in the AspectJ weaver tests. It does the following: * Keeps Weak References to the values in the expendable map to allow evicting them (whereas the Weak Hash Map keeps weak references only to the keys) * Allows configuring the expendable map to keep hard references to up to N types with -Dorg.aspectj.weaver.World.cacheRetention=number (the current default is 0). It's a nice tuning option so projects can use a bit more memory to avoid evicting types. * Moves the isExpendible check from the typeMap to the world, to allow different worlds (such as the LTWWorld) to change what's evictable (this lets the LTWWorld not keep references to already defined classes) This change breaks 3 tests in the "run these tests before checking in code" suite, all of them an NPE in the same line of ReferenceType.getTypeVariables for generic signatures. Presumably this code is implicitly relying on "expendable" types never being evicted. I have attached the error output for all 3 cases. My initial tests have shown a relatively small performance loss in return for significant memory footprint gains. E.g., using the AspectJ in CVS HEAD with the standard BcelWorld implementation (not LTWWorld) as the world, in Tomcat with the Glassbox Inspector & 4 web apps the AspectJ overhead with this optimization is 48 million heap bytes (of 60 million total heap bytes) versus 61 million bytes using CVS HEAD. The optimization has limited benefit for a BcelWorld where almost all the code is exposed to the weaver (since few types are expendible). However, Martin Lippert tried a version of this in his AJEER Eclipse load-time weaving environment and reported a reduction from 230 MB of heap to 30 MB heap used at a cost of a 25% increase in start up time. Likewise, this facility is the major contributor to enabling my other LTW optimizations that can reduce the heap overhead in my test case to 9 million heap bytes (principally having the LTW world allow evicting types that are already woven and using reflective proxies). I see similar start up times when using this expendable map in my tests. The ability to increase the number of hard references in cache should provide users an ability to allocate more memory to speed up performance. Note that the only hard reference to the keys (the signatures) is from the values (at least I haven't noticed any cases in my load-time weaving tests), so the weak hash map is compacting itself properly: when the reference type is weakly reachable, the key is then weakly reachable and the map ultimately purges theses entries.
resolved wontfix
04067a6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-18T17:59:28Z
2005-12-29T23:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelWorld.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur perClause support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.GETSTATIC; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.INVOKESTATIC; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.util.ClassLoaderRepository; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.Repository; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ICrossReferenceHandler; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.Aspect; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.SimpleScope; public class BcelWorld extends World implements Repository { private ClassPathManager classPath; private Repository delegate; //private ClassPathManager aspectPath = null; // private List aspectPathEntries; // ---- constructors public BcelWorld() { this(""); } public BcelWorld(String cp) { this(makeDefaultClasspath(cp), IMessageHandler.THROW, null); } private static List makeDefaultClasspath(String cp) { List classPath = new ArrayList(); classPath.addAll(getPathEntries(cp)); classPath.addAll(getPathEntries(ClassPath.getClassPath())); //System.err.println("classpath: " + classPath); return classPath; } private static List getPathEntries(String s) { List ret = new ArrayList(); StringTokenizer tok = new StringTokenizer(s, File.pathSeparator); while(tok.hasMoreTokens()) ret.add(tok.nextToken()); return ret; } public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { //this.aspectPath = new ClassPathManager(aspectPath, handler); this.classPath = new ClassPathManager(classPath, handler); setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { this.classPath = cpm; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } /** * Build a World from a ClassLoader, for LTW support * * @param loader * @param handler * @param xrefHandler */ public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { this.classPath = null; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = new ClassLoaderRepository(loader); // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } public void addPath (String name) { classPath.addPath(name, this.getMessageHandler()); } /** * Parse a string into advice. * * <blockquote><pre> * Kind ( Id , ... ) : Pointcut -> MethodSignature * </pre></blockquote> */ public Advice shadowMunger(String str, int extraFlag) { str = str.trim(); int start = 0; int i = str.indexOf('('); AdviceKind kind = AdviceKind.stringToKind(str.substring(start, i)); start = ++i; i = str.indexOf(')', i); String[] ids = parseIds(str.substring(start, i).trim()); //start = ++i; i = str.indexOf(':', i); start = ++i; i = str.indexOf("->", i); Pointcut pointcut = Pointcut.fromString(str.substring(start, i).trim()); Member m = MemberImpl.methodFromString(str.substring(i+2, str.length()).trim()); // now, we resolve UnresolvedType[] types = m.getParameterTypes(); FormalBinding[] bindings = new FormalBinding[ids.length]; for (int j = 0, len = ids.length; j < len; j++) { bindings[j] = new FormalBinding(types[j], ids[j], j, 0, 0, "fromString"); } Pointcut p = pointcut.resolve(new SimpleScope(this, bindings)); return new BcelAdvice(kind, p, m, extraFlag, 0, 0, null, null); } private String[] parseIds(String str) { if (str.length() == 0) return ZERO_STRINGS; List l = new ArrayList(); int start = 0; while (true) { int i = str.indexOf(',', start); if (i == -1) { l.add(str.substring(start).trim()); break; } l.add(str.substring(start, i).trim()); start = i+1; } return (String[]) l.toArray(new String[l.size()]); } // ---- various interactions with bcel public static Type makeBcelType(UnresolvedType type) { return Type.getType(type.getErasureSignature()); } static Type[] makeBcelTypes(UnresolvedType[] types) { Type[] ret = new Type[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = makeBcelType(types[i]); } return ret; } static String[] makeBcelTypesAsClassNames(UnresolvedType[] types) { String[] ret = new String[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = types[i].getClassName();//makeBcelType(types[i]); } return ret; } public static UnresolvedType fromBcel(Type t) { return UnresolvedType.forSignature(t.getSignature()); } static UnresolvedType[] fromBcel(Type[] ts) { UnresolvedType[] ret = new UnresolvedType[ts.length]; for (int i = 0, len = ts.length; i < len; i++) { ret[i] = fromBcel(ts[i]); } return ret; } public ResolvedType resolve(Type t) { return resolve(fromBcel(t)); } protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) { String name = ty.getName(); JavaClass jc = null; //UnwovenClassFile classFile = (UnwovenClassFile)sourceJavaClasses.get(name); //if (classFile != null) jc = classFile.getJavaClass(); // if (jc == null) { // jc = lookupJavaClass(aspectPath, name); // } if (jc == null) { jc = lookupJavaClass(classPath, name); } if (jc == null) { return null; } else { return makeBcelObjectType(ty, jc, false); } } protected BcelObjectType makeBcelObjectType(ReferenceType resolvedTypeX, JavaClass jc, boolean exposedToWeaver) { BcelObjectType ret = new BcelObjectType(resolvedTypeX, jc, exposedToWeaver); return ret; } private JavaClass lookupJavaClass(ClassPathManager classPath, String name) { if (classPath == null) { try { return delegate.loadClass(name); } catch (ClassNotFoundException e) { return null; } } try { ClassPathManager.ClassFile file = classPath.find(UnresolvedType.forName(name)); if (file == null) return null; ClassParser parser = new ClassParser(file.getInputStream(), file.getPath()); JavaClass jc = parser.parse(); file.close(); return jc; } catch (IOException ioe) { return null; } } public BcelObjectType addSourceObjectType(JavaClass jc) { BcelObjectType ret = null; String signature = UnresolvedType.forName(jc.getClassName()).getSignature(); Object fromTheMap = typeMap.get(signature); if (fromTheMap!=null && !(fromTheMap instanceof ReferenceType)) { // what on earth is it then? See pr 112243 StringBuffer exceptionText = new StringBuffer(); exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. "); exceptionText.append("Signature=["+signature+"] Found=["+fromTheMap+"] Class=["+fromTheMap.getClass()+"]"); throw new BCException(exceptionText.toString()); } ReferenceType nameTypeX = (ReferenceType)fromTheMap; if (nameTypeX == null) { if (jc.isGeneric()) { nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()),this); ret = makeBcelObjectType(nameTypeX, jc, true); ReferenceType genericRefType = new ReferenceType( UnresolvedType.forGenericTypeSignature(signature,ret.getDeclaredGenericSignature()),this); nameTypeX.setDelegate(ret); genericRefType.setDelegate(ret); nameTypeX.setGenericType(genericRefType); typeMap.put(signature, nameTypeX); } else { nameTypeX = new ReferenceType(signature, this); ret = makeBcelObjectType(nameTypeX, jc, true); typeMap.put(signature, nameTypeX); } } else { ret = makeBcelObjectType(nameTypeX, jc, true); } return ret; } void deleteSourceObjectType(UnresolvedType ty) { typeMap.remove(ty.getSignature()); } public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) { ConstantPoolGen cpg = cg.getConstantPoolGen(); return MemberImpl.field( fi.getClassName(cpg), (fi instanceof GETSTATIC || fi instanceof PUTSTATIC) ? Modifier.STATIC: 0, fi.getName(cpg), fi.getSignature(cpg)); } // public static Member makeFieldSetSignature(LazyClassGen cg, FieldInstruction fi) { // ConstantPoolGen cpg = cg.getConstantPoolGen(); // return // MemberImpl.field( // fi.getClassName(cpg), // (fi instanceof GETSTATIC || fi instanceof PUTSTATIC) // ? Modifier.STATIC // : 0, // fi.getName(cpg), // "(" + fi.getSignature(cpg) + ")" +fi.getSignature(cpg)); // } public Member makeJoinPointSignature(LazyMethodGen mg) { return makeJoinPointSignatureFromMethod(mg, null); } public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberImpl.Kind kind) { Member ret = mg.getMemberView(); if (ret == null) { int mods = mg.getAccessFlags(); if (mg.getEnclosingClass().isInterface()) { mods |= Modifier.INTERFACE; } if (kind == null) { if (mg.getName().equals("<init>")) { kind = Member.CONSTRUCTOR; } else if (mg.getName().equals("<clinit>")) { kind = Member.STATIC_INITIALIZATION; } else { kind = Member.METHOD; } } return new ResolvedMemberImpl(kind, UnresolvedType.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()), mg.getName(), fromBcel(mg.getArgumentTypes()) ); } else { return ret; } } public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) { ConstantPoolGen cpg = cg.getConstantPoolGen(); String name = ii.getName(cpg); String declaring = ii.getClassName(cpg); UnresolvedType declaringType = null; String signature = ii.getSignature(cpg); int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE : (ii instanceof INVOKESTATIC) ? Modifier.STATIC : (ii instanceof INVOKESPECIAL && ! name.equals("<init>")) ? Modifier.PRIVATE : 0; // in Java 1.4 and after, static method call of super class within subclass method appears // as declared by the subclass in the bytecode - but they are not // see #104212 if (ii instanceof INVOKESTATIC) { ResolvedType appearsDeclaredBy = resolve(declaring); // look for the method there for (Iterator iterator = appearsDeclaredBy.getMethods(); iterator.hasNext();) { ResolvedMember method = (ResolvedMember) iterator.next(); if (method.isStatic()) { if (name.equals(method.getName()) && signature.equals(method.getSignature())) { // we found it declaringType = method.getDeclaringType(); break; } } } } if (declaringType == null) { if (declaring.charAt(0)=='[') declaringType = UnresolvedType.forSignature(declaring); else declaringType = UnresolvedType.forName(declaring); } return MemberImpl.method(declaringType, modifier, name, signature); } public static Member makeMungerMethodSignature(JavaClass javaClass, Method method) { int mods = 0; if (method.isStatic()) mods = Modifier.STATIC; else if (javaClass.isInterface()) mods = Modifier.INTERFACE; else if (method.isPrivate()) mods = Modifier.PRIVATE; return MemberImpl.method( UnresolvedType.forName(javaClass.getClassName()), mods, method.getName(), method.getSignature()); } private static final String[] ZERO_STRINGS = new String[0]; public String toString() { StringBuffer buf = new StringBuffer(); buf.append("BcelWorld("); //buf.append(shadowMungerMap); buf.append(")"); return buf.toString(); } public Advice createAdviceMunger( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature) { //System.err.println("concrete advice: " + signature + " context " + sourceContext); return new BcelAdvice(attribute, pointcut, signature, null); } public ConcreteTypeMunger concreteTypeMunger( ResolvedTypeMunger munger, ResolvedType aspectType) { return new BcelTypeMunger(munger, aspectType); } public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) { return new BcelCflowStackFieldAdder(cflowField); } public ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField) { return new BcelCflowCounterFieldAdder(cflowField); } /** * Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed * * @param aspect * @param kind * @return munger */ public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind) { return new BcelPerClauseAspectAdder(aspect, kind); } /** * Retrieve a bcel delegate for an aspect - this will return NULL if the * delegate is an EclipseSourceType and not a BcelObjectType - this happens * quite often when incrementally compiling. */ public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) { ReferenceTypeDelegate rtDelegate = ((ReferenceType)concreteAspect).getDelegate(); if (rtDelegate instanceof BcelObjectType) { return (BcelObjectType)rtDelegate; } else { return null; } } public void tidyUp() { // At end of compile, close any open files so deletion of those archives is possible classPath.closeArchives(); } /// The repository interface methods public JavaClass findClass(String className) { return lookupJavaClass(classPath,className); } public JavaClass loadClass(String className) throws ClassNotFoundException { return lookupJavaClass(classPath,className); } public void storeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public void removeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public JavaClass loadClass(Class clazz) throws ClassNotFoundException { throw new RuntimeException("Not implemented"); } public void clear() { throw new RuntimeException("Not implemented"); } // @Override /** * The aim of this method is to make sure a particular type is 'ok'. Some * operations on the delegate for a type modify it and this method is * intended to undo that... see pr85132 */ public void validateType(UnresolvedType type) { ResolvedType result = typeMap.get(type.getSignature()); if (result==null) return; // We haven't heard of it yet if (!result.isExposedToWeaver()) return; // cant need resetting ReferenceType rt = (ReferenceType)result; rt.getDelegate().ensureDelegateConsistent(); // If we want to rebuild it 'from scratch' then: // ClassParser cp = new ClassParser(new ByteArrayInputStream(newbytes),new String(cs)); // try { // rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true)); // } catch (ClassFormatException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } } /** * Checks if given bytecode is an @AspectJ aspect * * @param name * @param bytes * @return true if so */ public boolean isAnnotationStyleAspect(String name, byte[] bytes) { try { ClassParser cp = new ClassParser(new ByteArrayInputStream(bytes), null); JavaClass jc = cp.parse(); if (!jc.isClass()) { return false; } Annotation anns[] = jc.getAnnotations(); if (anns.length == 0) { return false; } boolean couldBeAtAspectJStyle = false; for (int i = 0; i < anns.length; i++) { Annotation ann = anns[i]; if ("Lorg/aspectj/lang/annotation/Aspect;".equals(ann.getTypeSignature())) { couldBeAtAspectJStyle = true; } } if (!couldBeAtAspectJStyle) return false; // ok, so it has the annotation, but it could have been put // on a code style aspect by the annotation visitor Attribute[] attributes = jc.getAttributes(); for (int i = 0; i < attributes.length; i++) { if (attributes[i].getName().equals(Aspect.AttributeName)) { return false; } } return true; } catch (IOException e) { // assume it is one as a best effort return true; } } }
124,803
Bug 124803 [generics] mixing and matching numbers of type variables/parameters in a hierarchy
Hi guys! I didn't talk to you for a while, but I've found several new issues related to generics. Here is the first and the most annoying one: 1) Just compile the testcase with iajc and you will get "java.lang.IllegalStateException: Wrong number of type parameters supplied" Java Code: ========= public interface Generic1<T extends Number> { public void foo(T p); } public interface Generic2<T extends Number, Y extends Number> extends Generic1<T> { public void foo2(Y p); } public class Test<Y extends Number> implements Generic2<Y,Y>{ public void foo2(Y p) { } public void foo(Y p) { } } Aspect: ======= public privileged aspect TestAspect { pointcut TestInheritance(Test test) : target(test) && execution (* com.mprv.secsph.Generic1.*(..)); after (Test test) : TestInheritance(test) { System.out.println("GO Aspects!"); } } Exception: ========== iajc abort trouble in: public class com.mprv.secsph.Test extends java.lang.Object implements com.mprv.secsph.Generic2: public void <init>(): ALOAD_0 // com.mprv.secsph.Test this (line 10) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void com.mprv.secsph.Test.<init>()) | RETURN constructor-execution(void com.mprv.secsph.Test.<init>()) end public void <init>() public void foo2(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 11:259 : RETURN (line 12) end public void foo2(Number) public void foo(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 13:287 : RETURN (line 14) end public void foo(Number) end public class com.mprv.secsph.Test -- (IllegalStateException) Wrong number of type parameters supplied Wrong number of type parameters supplied java.lang.IllegalStateException: Wrong number of type parameters supplied at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:609) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:590) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:472) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:262) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:301) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:375) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:177) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:68) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:286) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:106) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2149) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1716) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:458) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:105) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:819) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:234) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:157) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:326) at org.aspectj.tools.ajc.Main.runMain(Main.java:240) at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTask.java:1254) at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1048) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275) at org.apache.tools.ant.Task.perform(Task.java:364) at org.apache.tools.ant.Target.execute(Target.java:341) at org.apache.tools.ant.Target.performTasks(Target.java:369) at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216) at org.apache.tools.ant.Project.executeTarget(Project.java:1185) at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:40) at org.apache.tools.ant.Project.executeTargets(Project.java:1068) at org.apache.tools.ant.Main.runBuild(Main.java:668) at org.apache.tools.ant.Main.startAnt(Main.java:187) at org.apache.tools.ant.launch.Launcher.run(Launcher.java:246) at org.apache.tools.ant.launch.Launcher.main(Launcher.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.ant.execution.AntMain2.main(AntMain2.java:16) warning at after (Test test) : TestInheritance(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:44:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch]
resolved fixed
8676df9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T10:47:29Z
2006-01-22T14:26:40Z
tests/bugs151/pr124803/Test.java
124,803
Bug 124803 [generics] mixing and matching numbers of type variables/parameters in a hierarchy
Hi guys! I didn't talk to you for a while, but I've found several new issues related to generics. Here is the first and the most annoying one: 1) Just compile the testcase with iajc and you will get "java.lang.IllegalStateException: Wrong number of type parameters supplied" Java Code: ========= public interface Generic1<T extends Number> { public void foo(T p); } public interface Generic2<T extends Number, Y extends Number> extends Generic1<T> { public void foo2(Y p); } public class Test<Y extends Number> implements Generic2<Y,Y>{ public void foo2(Y p) { } public void foo(Y p) { } } Aspect: ======= public privileged aspect TestAspect { pointcut TestInheritance(Test test) : target(test) && execution (* com.mprv.secsph.Generic1.*(..)); after (Test test) : TestInheritance(test) { System.out.println("GO Aspects!"); } } Exception: ========== iajc abort trouble in: public class com.mprv.secsph.Test extends java.lang.Object implements com.mprv.secsph.Generic2: public void <init>(): ALOAD_0 // com.mprv.secsph.Test this (line 10) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void com.mprv.secsph.Test.<init>()) | RETURN constructor-execution(void com.mprv.secsph.Test.<init>()) end public void <init>() public void foo2(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 11:259 : RETURN (line 12) end public void foo2(Number) public void foo(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 13:287 : RETURN (line 14) end public void foo(Number) end public class com.mprv.secsph.Test -- (IllegalStateException) Wrong number of type parameters supplied Wrong number of type parameters supplied java.lang.IllegalStateException: Wrong number of type parameters supplied at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:609) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:590) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:472) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:262) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:301) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:375) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:177) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:68) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:286) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:106) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2149) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1716) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:458) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:105) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:819) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:234) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:157) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:326) at org.aspectj.tools.ajc.Main.runMain(Main.java:240) at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTask.java:1254) at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1048) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275) at org.apache.tools.ant.Task.perform(Task.java:364) at org.apache.tools.ant.Target.execute(Target.java:341) at org.apache.tools.ant.Target.performTasks(Target.java:369) at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216) at org.apache.tools.ant.Project.executeTarget(Project.java:1185) at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:40) at org.apache.tools.ant.Project.executeTargets(Project.java:1068) at org.apache.tools.ant.Main.runBuild(Main.java:668) at org.apache.tools.ant.Main.startAnt(Main.java:187) at org.apache.tools.ant.launch.Launcher.run(Launcher.java:246) at org.apache.tools.ant.launch.Launcher.main(Launcher.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.ant.execution.AntMain2.main(AntMain2.java:16) warning at after (Test test) : TestInheritance(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:44:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch]
resolved fixed
8676df9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T10:47:29Z
2006-01-22T14:26:40Z
tests/bugs151/pr124803/Test2.java
124,803
Bug 124803 [generics] mixing and matching numbers of type variables/parameters in a hierarchy
Hi guys! I didn't talk to you for a while, but I've found several new issues related to generics. Here is the first and the most annoying one: 1) Just compile the testcase with iajc and you will get "java.lang.IllegalStateException: Wrong number of type parameters supplied" Java Code: ========= public interface Generic1<T extends Number> { public void foo(T p); } public interface Generic2<T extends Number, Y extends Number> extends Generic1<T> { public void foo2(Y p); } public class Test<Y extends Number> implements Generic2<Y,Y>{ public void foo2(Y p) { } public void foo(Y p) { } } Aspect: ======= public privileged aspect TestAspect { pointcut TestInheritance(Test test) : target(test) && execution (* com.mprv.secsph.Generic1.*(..)); after (Test test) : TestInheritance(test) { System.out.println("GO Aspects!"); } } Exception: ========== iajc abort trouble in: public class com.mprv.secsph.Test extends java.lang.Object implements com.mprv.secsph.Generic2: public void <init>(): ALOAD_0 // com.mprv.secsph.Test this (line 10) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void com.mprv.secsph.Test.<init>()) | RETURN constructor-execution(void com.mprv.secsph.Test.<init>()) end public void <init>() public void foo2(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 11:259 : RETURN (line 12) end public void foo2(Number) public void foo(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 13:287 : RETURN (line 14) end public void foo(Number) end public class com.mprv.secsph.Test -- (IllegalStateException) Wrong number of type parameters supplied Wrong number of type parameters supplied java.lang.IllegalStateException: Wrong number of type parameters supplied at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:609) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:590) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:472) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:262) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:301) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:375) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:177) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:68) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:286) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:106) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2149) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1716) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:458) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:105) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:819) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:234) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:157) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:326) at org.aspectj.tools.ajc.Main.runMain(Main.java:240) at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTask.java:1254) at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1048) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275) at org.apache.tools.ant.Task.perform(Task.java:364) at org.apache.tools.ant.Target.execute(Target.java:341) at org.apache.tools.ant.Target.performTasks(Target.java:369) at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216) at org.apache.tools.ant.Project.executeTarget(Project.java:1185) at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:40) at org.apache.tools.ant.Project.executeTargets(Project.java:1068) at org.apache.tools.ant.Main.runBuild(Main.java:668) at org.apache.tools.ant.Main.startAnt(Main.java:187) at org.apache.tools.ant.launch.Launcher.run(Launcher.java:246) at org.apache.tools.ant.launch.Launcher.main(Launcher.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.ant.execution.AntMain2.main(AntMain2.java:16) warning at after (Test test) : TestInheritance(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:44:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch]
resolved fixed
8676df9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T10:47:29Z
2006-01-22T14:26:40Z
tests/bugs151/pr124803/TestAspect.java
124,803
Bug 124803 [generics] mixing and matching numbers of type variables/parameters in a hierarchy
Hi guys! I didn't talk to you for a while, but I've found several new issues related to generics. Here is the first and the most annoying one: 1) Just compile the testcase with iajc and you will get "java.lang.IllegalStateException: Wrong number of type parameters supplied" Java Code: ========= public interface Generic1<T extends Number> { public void foo(T p); } public interface Generic2<T extends Number, Y extends Number> extends Generic1<T> { public void foo2(Y p); } public class Test<Y extends Number> implements Generic2<Y,Y>{ public void foo2(Y p) { } public void foo(Y p) { } } Aspect: ======= public privileged aspect TestAspect { pointcut TestInheritance(Test test) : target(test) && execution (* com.mprv.secsph.Generic1.*(..)); after (Test test) : TestInheritance(test) { System.out.println("GO Aspects!"); } } Exception: ========== iajc abort trouble in: public class com.mprv.secsph.Test extends java.lang.Object implements com.mprv.secsph.Generic2: public void <init>(): ALOAD_0 // com.mprv.secsph.Test this (line 10) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void com.mprv.secsph.Test.<init>()) | RETURN constructor-execution(void com.mprv.secsph.Test.<init>()) end public void <init>() public void foo2(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 11:259 : RETURN (line 12) end public void foo2(Number) public void foo(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 13:287 : RETURN (line 14) end public void foo(Number) end public class com.mprv.secsph.Test -- (IllegalStateException) Wrong number of type parameters supplied Wrong number of type parameters supplied java.lang.IllegalStateException: Wrong number of type parameters supplied at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:609) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:590) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:472) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:262) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:301) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:375) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:177) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:68) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:286) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:106) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2149) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1716) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:458) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:105) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:819) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:234) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:157) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:326) at org.aspectj.tools.ajc.Main.runMain(Main.java:240) at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTask.java:1254) at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1048) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275) at org.apache.tools.ant.Task.perform(Task.java:364) at org.apache.tools.ant.Target.execute(Target.java:341) at org.apache.tools.ant.Target.performTasks(Target.java:369) at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216) at org.apache.tools.ant.Project.executeTarget(Project.java:1185) at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:40) at org.apache.tools.ant.Project.executeTargets(Project.java:1068) at org.apache.tools.ant.Main.runBuild(Main.java:668) at org.apache.tools.ant.Main.startAnt(Main.java:187) at org.apache.tools.ant.launch.Launcher.run(Launcher.java:246) at org.apache.tools.ant.launch.Launcher.main(Launcher.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.ant.execution.AntMain2.main(AntMain2.java:16) warning at after (Test test) : TestInheritance(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:44:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch]
resolved fixed
8676df9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T10:47:29Z
2006-01-22T14:26:40Z
tests/bugs151/pr124803/TestAspect2.java
124,803
Bug 124803 [generics] mixing and matching numbers of type variables/parameters in a hierarchy
Hi guys! I didn't talk to you for a while, but I've found several new issues related to generics. Here is the first and the most annoying one: 1) Just compile the testcase with iajc and you will get "java.lang.IllegalStateException: Wrong number of type parameters supplied" Java Code: ========= public interface Generic1<T extends Number> { public void foo(T p); } public interface Generic2<T extends Number, Y extends Number> extends Generic1<T> { public void foo2(Y p); } public class Test<Y extends Number> implements Generic2<Y,Y>{ public void foo2(Y p) { } public void foo(Y p) { } } Aspect: ======= public privileged aspect TestAspect { pointcut TestInheritance(Test test) : target(test) && execution (* com.mprv.secsph.Generic1.*(..)); after (Test test) : TestInheritance(test) { System.out.println("GO Aspects!"); } } Exception: ========== iajc abort trouble in: public class com.mprv.secsph.Test extends java.lang.Object implements com.mprv.secsph.Generic2: public void <init>(): ALOAD_0 // com.mprv.secsph.Test this (line 10) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void com.mprv.secsph.Test.<init>()) | RETURN constructor-execution(void com.mprv.secsph.Test.<init>()) end public void <init>() public void foo2(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 11:259 : RETURN (line 12) end public void foo2(Number) public void foo(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 13:287 : RETURN (line 14) end public void foo(Number) end public class com.mprv.secsph.Test -- (IllegalStateException) Wrong number of type parameters supplied Wrong number of type parameters supplied java.lang.IllegalStateException: Wrong number of type parameters supplied at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:609) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:590) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:472) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:262) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:301) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:375) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:177) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:68) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:286) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:106) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2149) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1716) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:458) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:105) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:819) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:234) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:157) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:326) at org.aspectj.tools.ajc.Main.runMain(Main.java:240) at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTask.java:1254) at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1048) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275) at org.apache.tools.ant.Task.perform(Task.java:364) at org.apache.tools.ant.Target.execute(Target.java:341) at org.apache.tools.ant.Target.performTasks(Target.java:369) at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216) at org.apache.tools.ant.Project.executeTarget(Project.java:1185) at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:40) at org.apache.tools.ant.Project.executeTargets(Project.java:1068) at org.apache.tools.ant.Main.runBuild(Main.java:668) at org.apache.tools.ant.Main.startAnt(Main.java:187) at org.apache.tools.ant.launch.Launcher.run(Launcher.java:246) at org.apache.tools.ant.launch.Launcher.main(Launcher.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.ant.execution.AntMain2.main(AntMain2.java:16) warning at after (Test test) : TestInheritance(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:44:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch]
resolved fixed
8676df9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T10:47:29Z
2006-01-22T14:26:40Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
124,803
Bug 124803 [generics] mixing and matching numbers of type variables/parameters in a hierarchy
Hi guys! I didn't talk to you for a while, but I've found several new issues related to generics. Here is the first and the most annoying one: 1) Just compile the testcase with iajc and you will get "java.lang.IllegalStateException: Wrong number of type parameters supplied" Java Code: ========= public interface Generic1<T extends Number> { public void foo(T p); } public interface Generic2<T extends Number, Y extends Number> extends Generic1<T> { public void foo2(Y p); } public class Test<Y extends Number> implements Generic2<Y,Y>{ public void foo2(Y p) { } public void foo(Y p) { } } Aspect: ======= public privileged aspect TestAspect { pointcut TestInheritance(Test test) : target(test) && execution (* com.mprv.secsph.Generic1.*(..)); after (Test test) : TestInheritance(test) { System.out.println("GO Aspects!"); } } Exception: ========== iajc abort trouble in: public class com.mprv.secsph.Test extends java.lang.Object implements com.mprv.secsph.Generic2: public void <init>(): ALOAD_0 // com.mprv.secsph.Test this (line 10) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void com.mprv.secsph.Test.<init>()) | RETURN constructor-execution(void com.mprv.secsph.Test.<init>()) end public void <init>() public void foo2(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 11:259 : RETURN (line 12) end public void foo2(Number) public void foo(Number) org.aspectj.weaver.MethodDeclarationLineNumber: 13:287 : RETURN (line 14) end public void foo(Number) end public class com.mprv.secsph.Test -- (IllegalStateException) Wrong number of type parameters supplied Wrong number of type parameters supplied java.lang.IllegalStateException: Wrong number of type parameters supplied at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:609) at org.aspectj.weaver.ResolvedMemberImpl.parameterizedWith(ResolvedMemberImpl.java:590) at org.aspectj.weaver.ReferenceType.getDeclaredMethods(ReferenceType.java:472) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:262) at org.aspectj.weaver.ResolvedType.addAndRecurse(ResolvedType.java:301) at org.aspectj.weaver.ResolvedType.getMethodsWithoutIterator(ResolvedType.java:257) at org.aspectj.weaver.ResolvedType.lookupResolvedMember(ResolvedType.java:375) at org.aspectj.weaver.JoinPointSignatureIterator.findSignaturesFromSupertypes(JoinPointSignatureIterator.java:177) at org.aspectj.weaver.JoinPointSignatureIterator.hasNext(JoinPointSignatureIterator.java:68) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:286) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:106) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:64) at org.aspectj.weaver.Advice.match(Advice.java:109) at org.aspectj.weaver.bcel.BcelAdvice.match(BcelAdvice.java:104) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:2149) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1716) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:458) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:105) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:819) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:234) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:157) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:112) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:326) at org.aspectj.tools.ajc.Main.runMain(Main.java:240) at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTask.java:1254) at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1048) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275) at org.apache.tools.ant.Task.perform(Task.java:364) at org.apache.tools.ant.Target.execute(Target.java:341) at org.apache.tools.ant.Target.performTasks(Target.java:369) at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1216) at org.apache.tools.ant.Project.executeTarget(Project.java:1185) at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:40) at org.apache.tools.ant.Project.executeTargets(Project.java:1068) at org.apache.tools.ant.Main.runBuild(Main.java:668) at org.apache.tools.ant.Main.startAnt(Main.java:187) at org.apache.tools.ant.launch.Launcher.run(Launcher.java:246) at org.apache.tools.ant.launch.Launcher.main(Launcher.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.ant.execution.AntMain2.main(AntMain2.java:16) warning at after (Test test) : TestInheritance(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:44:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch]
resolved fixed
8676df9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T10:47:29Z
2006-01-22T14:26:40Z
weaver/src/org/aspectj/weaver/ReferenceType.java
/* ******************************************************************* * Copyright (c) 2002 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Andy Clement - June 2005 - separated out from ResolvedType * ******************************************************************/ package org.aspectj.weaver; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.patterns.Declare; import org.aspectj.weaver.patterns.PerClause; /** * A reference type represents some 'real' type, not a primitive, not an array - but * a real type, for example java.util.List. Each ReferenceType has a delegate * that is the underlying artifact - either an eclipse artifact or a * bcel artifact. If the type represents a raw type (i.e. there is * a generic form) then the genericType field is set to point to the * generic type. If it is for a parameterized type then the generic type * is also set to point to the generic form. */ public class ReferenceType extends ResolvedType { /** * For generic types, this list holds references to all the derived raw * and parameterized versions. We need this so that if the generic delegate * is swapped during incremental compilation, the delegate of the derivatives * is swapped also. */ private List/*ReferenceType*/ derivativeTypes = new ArrayList(); /** * For parameterized types (or the raw type) - this field points to the actual * reference type from which they are derived. */ ReferenceType genericType = null; ReferenceTypeDelegate delegate = null; ISourceContext sourceContext = null; int startPos = 0; int endPos = 0; public static ReferenceType fromTypeX(UnresolvedType tx, World world) { ReferenceType rt = new ReferenceType(tx.getErasureSignature(),world); rt.typeKind = tx.typeKind; return rt; } // cached values for members ResolvedMember[] parameterizedMethods = null; ResolvedMember[] parameterizedFields = null; ResolvedMember[] parameterizedPointcuts = null; ResolvedType[] parameterizedInterfaces = null; Collection parameterizedDeclares = null; //??? should set delegate before any use public ReferenceType(String signature, World world) { super(signature, world); } /** * Constructor used when creating a parameterized type. */ public ReferenceType( ResolvedType theGenericType, ResolvedType[] theParameters, World aWorld) { super(makeParameterizedSignature(theGenericType,theParameters), theGenericType.signatureErasure, aWorld); ReferenceType genericReferenceType = (ReferenceType) theGenericType; this.typeParameters = theParameters; this.genericType = genericReferenceType; this.typeKind = TypeKind.PARAMETERIZED; this.delegate = genericReferenceType.getDelegate(); genericReferenceType.addDependentType(this); } /** * Constructor used when creating a raw type. */ public ReferenceType( ResolvedType theGenericType, World aWorld) { super(theGenericType.getErasureSignature(), theGenericType.getErasureSignature(), aWorld); ReferenceType genericReferenceType = (ReferenceType) theGenericType; this.typeParameters = null; this.genericType = genericReferenceType; this.typeKind = TypeKind.RAW; this.delegate = genericReferenceType.getDelegate(); genericReferenceType.addDependentType(this); } private void addDependentType(ReferenceType dependent) { this.derivativeTypes.add(dependent); } public String getSignatureForAttribute() { if (genericType == null || typeParameters == null) return getSignature(); return makeDeclaredSignature(genericType,typeParameters); } /** * Create a reference type for a generic type */ public ReferenceType(UnresolvedType genericType, World world) { super(genericType.getSignature(),world); typeKind=TypeKind.GENERIC; } public final boolean isClass() { return delegate.isClass(); } public final boolean isGenericType() { return !isParameterizedType() && !isRawType() && delegate.isGeneric(); } public AnnotationX[] getAnnotations() { return delegate.getAnnotations(); } public void addAnnotation(AnnotationX annotationX) { delegate.addAnnotation(annotationX); } public boolean hasAnnotation(UnresolvedType ofType) { return delegate.hasAnnotation(ofType); } public ResolvedType[] getAnnotationTypes() { return delegate.getAnnotationTypes(); } public boolean isAspect() { return delegate.isAspect(); } public boolean isAnnotationStyleAspect() { return delegate.isAnnotationStyleAspect(); } public boolean isEnum() { return delegate.isEnum(); } public boolean isAnnotation() { return delegate.isAnnotation(); } public boolean isAnonymous() { return delegate.isAnonymous(); } public boolean isNested() { return delegate.isNested(); } public String getRetentionPolicy() { return delegate.getRetentionPolicy(); } public boolean isAnnotationWithRuntimeRetention() { return delegate.isAnnotationWithRuntimeRetention(); } public boolean canAnnotationTargetType() { return delegate.canAnnotationTargetType(); } public AnnotationTargetKind[] getAnnotationTargetKinds() { return delegate.getAnnotationTargetKinds(); } // true iff the statement "this = (ThisType) other" would compile public final boolean isCoerceableFrom(ResolvedType o) { ResolvedType other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } if (this.isParameterizedType() && other.isParameterizedType()) { return isCoerceableFromParameterizedType(other); } if (!this.isInterface() && !other.isInterface()) { return false; } if (this.isFinal() || other.isFinal()) { return false; } // ??? needs to be Methods, not just declared methods? JLS 5.5 unclear ResolvedMember[] a = getDeclaredMethods(); ResolvedMember[] b = other.getDeclaredMethods(); //??? is this cast always safe for (int ai = 0, alen = a.length; ai < alen; ai++) { for (int bi = 0, blen = b.length; bi < blen; bi++) { if (! b[bi].isCompatibleWith(a[ai])) return false; } } return true; } private final boolean isCoerceableFromParameterizedType(ResolvedType other) { if (!other.isParameterizedType()) return false; ResolvedType myRawType = (ResolvedType) getRawType(); ResolvedType theirRawType = (ResolvedType) other.getRawType(); if (myRawType == theirRawType) { if (getTypeParameters().length == other.getTypeParameters().length) { // there's a chance it can be done ResolvedType[] myTypeParameters = getResolvedTypeParameters(); ResolvedType[] theirTypeParameters = other.getResolvedTypeParameters(); for (int i = 0; i < myTypeParameters.length; i++) { if (myTypeParameters[i] != theirTypeParameters[i]) { // thin ice now... but List<String> may still be coerceable from e.g. List<T> if (myTypeParameters[i].isGenericWildcard()) { BoundedReferenceType wildcard = (BoundedReferenceType) myTypeParameters[i]; if (!wildcard.canBeCoercedTo(theirTypeParameters[i])) return false; } else if (myTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) myTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(theirTypeParameters[i])) return false; } else if (theirTypeParameters[i].isTypeVariableReference()) { TypeVariableReferenceType tvrt = (TypeVariableReferenceType) theirTypeParameters[i]; TypeVariable tv = tvrt.getTypeVariable(); tv.resolve(world); if (!tv.canBeBoundTo(myTypeParameters[i])) return false; } else { return false; } } } return true; } } else { // we do this walk for situations like the following: // Base<T>, Sub<S,T> extends Base<S> // is Sub<Y,Z> coerceable from Base<X> ??? for(Iterator i = getDirectSupertypes(); i.hasNext(); ) { ReferenceType parent = (ReferenceType) i.next(); if (parent.isCoerceableFromParameterizedType(other)) return true; } } return false; } public final boolean isAssignableFrom(ResolvedType other) { return isAssignableFrom(other,false); } // true iff the statement "this = other" would compile. public final boolean isAssignableFrom(ResolvedType other,boolean allowMissing) { if (other.isPrimitiveType()) { if (!world.isInJava5Mode()) return false; if (ResolvedType.validBoxing.contains(this.getSignature()+other.getSignature())) return true; } if (this == other) return true; if (this.getSignature().equals(ResolvedType.OBJECT.getSignature())) return true; if ((this.isRawType() || this.isGenericType()) && other.isParameterizedType()) { if (isAssignableFrom((ResolvedType)other.getRawType())) return true; } if (this.isRawType() && other.isGenericType()) { if (isAssignableFrom((ResolvedType)other.getRawType())) return true; } if (this.isGenericType() && other.isRawType()) { if (isAssignableFrom((ResolvedType)other.getGenericType())) return true; } if (this.isParameterizedType()) { // look at wildcards... if (((ReferenceType)this.getRawType()).isAssignableFrom(other)) { boolean wildcardsAllTheWay = true; ResolvedType[] myParameters = this.getResolvedTypeParameters(); for (int i = 0; i < myParameters.length; i++) { if (!myParameters[i].isGenericWildcard()) { wildcardsAllTheWay = false; } else if (myParameters[i].isExtends() || myParameters[i].isSuper()) { wildcardsAllTheWay = false; } } if (wildcardsAllTheWay && !other.isParameterizedType()) return true; // we have to match by parameters one at a time ResolvedType[] theirParameters = other.getResolvedTypeParameters(); boolean parametersAssignable = true; if (myParameters.length == theirParameters.length) { for (int i = 0; i < myParameters.length; i++) { if (myParameters[i] == theirParameters[i]) continue; if (!myParameters[i].isGenericWildcard()) { parametersAssignable = false; break; } else { BoundedReferenceType wildcardType = (BoundedReferenceType) myParameters[i]; if (!wildcardType.alwaysMatches(theirParameters[i])) { parametersAssignable = false; break; } } } } else { parametersAssignable = false; } if (parametersAssignable) return true; } } if (isTypeVariableReference() && !other.isTypeVariableReference()) { // eg. this=T other=Ljava/lang/Object; TypeVariable aVar = ((TypeVariableReference)this).getTypeVariable(); return aVar.resolve(world).canBeBoundTo(other); } if (other.isTypeVariableReference()) { TypeVariableReferenceType otherType = (TypeVariableReferenceType) other; if (this instanceof TypeVariableReference) { return ((TypeVariableReference)this).getTypeVariable()==otherType.getTypeVariable(); } else { // FIXME asc should this say canBeBoundTo?? return this.isAssignableFrom(otherType.getTypeVariable().getFirstBound().resolve(world)); } } if (allowMissing && other.isMissing()) return false; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { if (this.isAssignableFrom((ResolvedType) i.next(),allowMissing)) return true; } return false; } public ISourceContext getSourceContext() { return sourceContext; } public ISourceLocation getSourceLocation() { if (sourceContext == null) return null; return sourceContext.makeSourceLocation(new Position(startPos, endPos)); } public boolean isExposedToWeaver() { return (delegate == null) || delegate.isExposedToWeaver(); //??? where does this belong } public WeaverStateInfo getWeaverState() { return delegate.getWeaverState(); } public ResolvedMember[] getDeclaredFields() { if (parameterizedFields != null) return parameterizedFields; if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateFields = delegate.getDeclaredFields(); parameterizedFields = new ResolvedMember[delegateFields.length]; for (int i = 0; i < delegateFields.length; i++) { parameterizedFields[i] = delegateFields[i].parameterizedWith(getTypesForMemberParameterization(),this, isParameterizedType()); } return parameterizedFields; } else { return delegate.getDeclaredFields(); } } /** * Find out from the generic signature the true signature of any interfaces * I implement. If I am parameterized, these may then need to be parameterized * before returning. */ public ResolvedType[] getDeclaredInterfaces() { if (parameterizedInterfaces != null) return parameterizedInterfaces; if (isParameterizedType()) { ResolvedType[] delegateInterfaces = delegate.getDeclaredInterfaces(); UnresolvedType[] paramTypes = getTypesForMemberParameterization(); parameterizedInterfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0; i < delegateInterfaces.length; i++) { parameterizedInterfaces[i] = delegateInterfaces[i].parameterizedWith(paramTypes); } return parameterizedInterfaces; } else if (isRawType()){ ResolvedType[] delegateInterfaces = delegate.getDeclaredInterfaces(); UnresolvedType[] paramTypes = getTypesForMemberParameterization(); parameterizedInterfaces = new ResolvedType[delegateInterfaces.length]; for (int i = 0; i < parameterizedInterfaces.length; i++) { parameterizedInterfaces[i] = delegateInterfaces[i]; if (parameterizedInterfaces[i].isGenericType()) { // a generic supertype of a raw type is replaced by its raw equivalent parameterizedInterfaces[i] = parameterizedInterfaces[i].getRawType().resolve(getWorld()); } else if (parameterizedInterfaces[i].isParameterizedType()) { // a parameterized supertype collapses any type vars to their upper bounds UnresolvedType[] toUseForParameterization = determineThoseTypesToUse(parameterizedInterfaces[i],paramTypes); parameterizedInterfaces[i] = parameterizedInterfaces[i].parameterizedWith(toUseForParameterization); } } return parameterizedInterfaces; } return delegate.getDeclaredInterfaces(); } /** * It is possible this type has multiple type variables but the interface we are about to parameterize * only uses a subset - this method determines the subset to use by looking at the type variable names * used. For example: * <code> * class Foo<T extends String,E extends Number> implements SuperInterface<T> {} * </code> * where * <code> * interface SuperInterface<Z> {} * </code> * In that example, a use of the 'Foo' raw type should know that it implements * the SuperInterface<String>. */ private UnresolvedType[] determineThoseTypesToUse(ResolvedType parameterizedInterface,UnresolvedType[] paramTypes) { // What are the type parameters for the supertype? UnresolvedType[] tParms = parameterizedInterface.getTypeParameters(); UnresolvedType[] retVal = new UnresolvedType[tParms.length]; // Go through the supertypes type parameters, if any of them is a type variable, use the // real type variable on the declaring type. // it is possibly overkill to look up the type variable - ideally the entry in the type parameter list for the // interface should be the a ref to the type variable in the current type ... but I'm not 100% confident right now. for (int i = 0; i < tParms.length; i++) { UnresolvedType tParm = tParms[i]; if (tParm.isTypeVariableReference()) { TypeVariableReference tvrt = (TypeVariableReference)tParm; TypeVariable tv = tvrt.getTypeVariable(); int rank = getRank(tv.getName()); retVal[i]= paramTypes[rank]; } else { retVal[i] = tParms[i]; } } return retVal; } /** * Returns the position within the set of type variables for this type for the specified type variable name. * Returns -1 if there is no type variable with the specified name. */ private int getRank(String tvname) { TypeVariable[] thisTypesTVars = getGenericType().getTypeVariables(); for (int i = 0; i < thisTypesTVars.length; i++) { TypeVariable tv = thisTypesTVars[i]; if (tv.getName().equals(tvname)) return i; } return -1; } public ResolvedMember[] getDeclaredMethods() { if (parameterizedMethods != null) return parameterizedMethods; if (isParameterizedType() || isRawType()) { ResolvedMember[] delegateMethods = delegate.getDeclaredMethods(); UnresolvedType[] parameters = getTypesForMemberParameterization(); parameterizedMethods = new ResolvedMember[delegateMethods.length]; for (int i = 0; i < delegateMethods.length; i++) { parameterizedMethods[i] = delegateMethods[i].parameterizedWith(parameters,this,isParameterizedType()); } return parameterizedMethods; } else { return delegate.getDeclaredMethods(); } } public ResolvedMember[] getDeclaredPointcuts() { if (parameterizedPointcuts != null) return parameterizedPointcuts; if (isParameterizedType()) { ResolvedMember[] delegatePointcuts = delegate.getDeclaredPointcuts(); parameterizedPointcuts = new ResolvedMember[delegatePointcuts.length]; for (int i = 0; i < delegatePointcuts.length; i++) { parameterizedPointcuts[i] = delegatePointcuts[i].parameterizedWith(getTypesForMemberParameterization(),this,isParameterizedType()); } return parameterizedPointcuts; } else { return delegate.getDeclaredPointcuts(); } } private UnresolvedType[] getTypesForMemberParameterization() { UnresolvedType[] parameters = null; if (isParameterizedType()) { parameters = getTypeParameters(); } else if (isRawType()){ // raw type, use upper bounds of type variables on generic type TypeVariable[] tvs = getGenericType().getTypeVariables(); parameters = new UnresolvedType[tvs.length]; for (int i = 0; i < tvs.length; i++) { parameters[i] = tvs[i].getFirstBound(); } } return parameters; } public UnresolvedType getRawType() { return super.getRawType().resolve(getWorld()); } public TypeVariable[] getTypeVariables() { if (this.typeVariables == null) { this.typeVariables = delegate.getTypeVariables(); for (int i = 0; i < this.typeVariables.length; i++) { this.typeVariables[i].resolve(world); } } return this.typeVariables; } public PerClause getPerClause() { PerClause pclause = delegate.getPerClause(); if (isParameterizedType()) { // could cache the result here... Map parameterizationMap = getAjMemberParameterizationMap(); pclause = (PerClause)pclause.parameterizeWith(parameterizationMap); } return pclause; } protected Collection getDeclares() { if (parameterizedDeclares != null) return parameterizedDeclares; Collection declares = null; if (ajMembersNeedParameterization()) { Collection genericDeclares = delegate.getDeclares(); parameterizedDeclares = new ArrayList(); Map parameterizationMap = getAjMemberParameterizationMap(); for (Iterator iter = genericDeclares.iterator(); iter.hasNext();) { Declare declareStatement = (Declare) iter.next(); parameterizedDeclares.add(declareStatement.parameterizeWith(parameterizationMap)); } declares = parameterizedDeclares; } else { declares = delegate.getDeclares(); } for (Iterator iter = declares.iterator(); iter.hasNext();) { Declare d = (Declare) iter.next(); d.setDeclaringType(this); } return declares; } protected Collection getTypeMungers() { return delegate.getTypeMungers(); } protected Collection getPrivilegedAccesses() { return delegate.getPrivilegedAccesses(); } public int getModifiers() { return delegate.getModifiers(); } public ResolvedType getSuperclass() { ResolvedType ret = delegate.getSuperclass(); if (this.isParameterizedType() && ret.isParameterizedType()) { ret = ret.parameterize(getMemberParameterizationMap()).resolve(getWorld()); } return ret; } public ReferenceTypeDelegate getDelegate() { return delegate; } public void setDelegate(ReferenceTypeDelegate delegate) { this.delegate = delegate; for(Iterator it = this.derivativeTypes.iterator(); it.hasNext(); ) { ReferenceType dependent = (ReferenceType) it.next(); dependent.setDelegate(delegate); } // If we are raw, we have a generic type - we should ensure it uses the // same delegate if (isRawType() && getGenericType()!=null ) { ReferenceType genType = (ReferenceType) getGenericType(); if (genType.getDelegate() != delegate) { // avoids circular updates genType.setDelegate(delegate); } } clearParameterizationCaches(); } private void clearParameterizationCaches() { parameterizedFields = null; parameterizedInterfaces = null; parameterizedMethods = null; parameterizedPointcuts = null; } public int getEndPos() { return endPos; } public int getStartPos() { return startPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public void setSourceContext(ISourceContext sourceContext) { this.sourceContext = sourceContext; } public void setStartPos(int startPos) { this.startPos = startPos; } public boolean doesNotExposeShadowMungers() { return delegate.doesNotExposeShadowMungers(); } public String getDeclaredGenericSignature() { return delegate.getDeclaredGenericSignature(); } public void setGenericType(ReferenceType rt) { genericType = rt; // Should we 'promote' this reference type from simple to raw? // makes sense if someone is specifying that it has a generic form if ( typeKind == TypeKind.SIMPLE ) { typeKind = TypeKind.RAW; signatureErasure = signature; } } public ResolvedType getGenericType() { if (isGenericType()) return this; return genericType; } /** * a parameterized signature starts with a "P" in place of the "L", * see the comment on signatures in UnresolvedType. * @param aGenericType * @param someParameters * @return */ private static String makeParameterizedSignature(ResolvedType aGenericType, ResolvedType[] someParameters) { String rawSignature = aGenericType.getErasureSignature(); String prefix = PARAMETERIZED_TYPE_IDENTIFIER + rawSignature.substring(1,rawSignature.length()-1); StringBuffer ret = new StringBuffer(); ret.append(prefix); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { ret.append(someParameters[i].getSignature()); } ret.append(">;"); return ret.toString(); } private static String makeDeclaredSignature(ResolvedType aGenericType, UnresolvedType[] someParameters) { StringBuffer ret = new StringBuffer(); String rawSig = aGenericType.getErasureSignature(); ret.append(rawSig.substring(0,rawSig.length()-1)); ret.append("<"); for (int i = 0; i < someParameters.length; i++) { ret.append(someParameters[i].getSignature()); } ret.append(">;"); return ret.toString(); } }
124,808
Bug 124808 [generics] detecting field-get of field of parameterized type.
Hi, Here is the second generics issue: Java code: ========== public class Test<T extends Integer> { Set<T> ints = new HashSet<T>(); public Set<T> foo() { return ints; } public static void main(String[] args) { Test<Integer> t = new Test<Integer>(); Set<Integer> ints = t.foo(); } } Aspect: ======= public privileged aspect TestAspect { pointcut gettingMemberCollection(Test t) : target(t) && get(!public Set<Number+> com.mprv.secsph.*.*) && !within(TestAspect); after (Test test) : gettingMemberCollection(test) { System.out.println("GO Aspects!"); } } Compiler output: ================ warning at after (Test test) : gettingMemberCollection(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:19:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch] I would expect "gettingMemberCollection" to catch access to "ints" member of "Test" ... Thanks a lot! Misha.
resolved fixed
01a8b2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T14:25:06Z
2006-01-22T17:13:20Z
tests/bugs151/pr124808/Test.java
124,808
Bug 124808 [generics] detecting field-get of field of parameterized type.
Hi, Here is the second generics issue: Java code: ========== public class Test<T extends Integer> { Set<T> ints = new HashSet<T>(); public Set<T> foo() { return ints; } public static void main(String[] args) { Test<Integer> t = new Test<Integer>(); Set<Integer> ints = t.foo(); } } Aspect: ======= public privileged aspect TestAspect { pointcut gettingMemberCollection(Test t) : target(t) && get(!public Set<Number+> com.mprv.secsph.*.*) && !within(TestAspect); after (Test test) : gettingMemberCollection(test) { System.out.println("GO Aspects!"); } } Compiler output: ================ warning at after (Test test) : gettingMemberCollection(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:19:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch] I would expect "gettingMemberCollection" to catch access to "ints" member of "Test" ... Thanks a lot! Misha.
resolved fixed
01a8b2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T14:25:06Z
2006-01-22T17:13:20Z
tests/bugs151/pr124808/TestAspect.java
124,808
Bug 124808 [generics] detecting field-get of field of parameterized type.
Hi, Here is the second generics issue: Java code: ========== public class Test<T extends Integer> { Set<T> ints = new HashSet<T>(); public Set<T> foo() { return ints; } public static void main(String[] args) { Test<Integer> t = new Test<Integer>(); Set<Integer> ints = t.foo(); } } Aspect: ======= public privileged aspect TestAspect { pointcut gettingMemberCollection(Test t) : target(t) && get(!public Set<Number+> com.mprv.secsph.*.*) && !within(TestAspect); after (Test test) : gettingMemberCollection(test) { System.out.println("GO Aspects!"); } } Compiler output: ================ warning at after (Test test) : gettingMemberCollection(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:19:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch] I would expect "gettingMemberCollection" to catch access to "ints" member of "Test" ... Thanks a lot! Misha.
resolved fixed
01a8b2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T14:25:06Z
2006-01-22T17:13:20Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
124,808
Bug 124808 [generics] detecting field-get of field of parameterized type.
Hi, Here is the second generics issue: Java code: ========== public class Test<T extends Integer> { Set<T> ints = new HashSet<T>(); public Set<T> foo() { return ints; } public static void main(String[] args) { Test<Integer> t = new Test<Integer>(); Set<Integer> ints = t.foo(); } } Aspect: ======= public privileged aspect TestAspect { pointcut gettingMemberCollection(Test t) : target(t) && get(!public Set<Number+> com.mprv.secsph.*.*) && !within(TestAspect); after (Test test) : gettingMemberCollection(test) { System.out.println("GO Aspects!"); } } Compiler output: ================ warning at after (Test test) : gettingMemberCollection(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:19:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch] I would expect "gettingMemberCollection" to catch access to "ints" member of "Test" ... Thanks a lot! Misha.
resolved fixed
01a8b2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T14:25:06Z
2006-01-22T17:13:20Z
weaver/src/org/aspectj/weaver/patterns/ExactTypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.TypeVariableReferenceType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; public class ExactTypePattern extends TypePattern { protected UnresolvedType type; public static final Map primitiveTypesMap; public static final Map boxedPrimitivesMap; private static final Map boxedTypesMap; static { primitiveTypesMap = new HashMap(); primitiveTypesMap.put("int",int.class); primitiveTypesMap.put("short",short.class); primitiveTypesMap.put("long",long.class); primitiveTypesMap.put("byte",byte.class); primitiveTypesMap.put("char",char.class); primitiveTypesMap.put("float",float.class); primitiveTypesMap.put("double",double.class); boxedPrimitivesMap = new HashMap(); boxedPrimitivesMap.put("java.lang.Integer",Integer.class); boxedPrimitivesMap.put("java.lang.Short",Short.class); boxedPrimitivesMap.put("java.lang.Long",Long.class); boxedPrimitivesMap.put("java.lang.Byte",Byte.class); boxedPrimitivesMap.put("java.lang.Character",Character.class); boxedPrimitivesMap.put("java.lang.Float",Float.class); boxedPrimitivesMap.put("java.lang.Double",Double.class); boxedTypesMap = new HashMap(); boxedTypesMap.put("int",Integer.class); boxedTypesMap.put("short",Short.class); boxedTypesMap.put("long",Long.class); boxedTypesMap.put("byte",Byte.class); boxedTypesMap.put("char",Character.class); boxedTypesMap.put("float",Float.class); boxedTypesMap.put("double",Double.class); } public ExactTypePattern(UnresolvedType type, boolean includeSubtypes,boolean isVarArgs) { super(includeSubtypes,isVarArgs); this.type = type; } public boolean isArray() { return type.isArray(); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (super.couldEverMatchSameTypesAs(other)) return true; // false is necessary but not sufficient UnresolvedType otherType = other.getExactType(); if (!ResolvedType.isMissing(otherType)) { return type.equals(otherType); } if (other instanceof WildTypePattern) { WildTypePattern owtp = (WildTypePattern) other; String yourSimpleNamePrefix = owtp.getNamePatterns()[0].maybeGetSimpleName(); if (yourSimpleNamePrefix != null) { return (type.getName().startsWith(yourSimpleNamePrefix)); } } return true; } protected boolean matchesExactly(ResolvedType matchType) { boolean typeMatch = this.type.equals(matchType); if (!typeMatch && (matchType.isParameterizedType() || matchType.isGenericType())) { typeMatch = this.type.equals(matchType.getRawType()); } if (!typeMatch && matchType.isTypeVariableReference()) { typeMatch = matchesTypeVariable((TypeVariableReferenceType)matchType); } annotationPattern.resolve(matchType.getWorld()); boolean annMatch = this.annotationPattern.matches(matchType).alwaysTrue(); return (typeMatch && annMatch); } private boolean matchesTypeVariable(TypeVariableReferenceType matchType) { return false; } protected boolean matchesExactly(ResolvedType matchType, ResolvedType annotatedType) { boolean typeMatch = this.type.equals(matchType); if (!typeMatch && (matchType.isParameterizedType() || matchType.isGenericType())) { typeMatch = this.type.equals(matchType.getRawType()); } if (!typeMatch && matchType.isTypeVariableReference()) { typeMatch = matchesTypeVariable((TypeVariableReferenceType)matchType); } annotationPattern.resolve(matchType.getWorld()); boolean annMatch = this.annotationPattern.matches(annotatedType).alwaysTrue(); return (typeMatch && annMatch); } public UnresolvedType getType() { return type; } // true if (matchType instanceof this.type) public FuzzyBoolean matchesInstanceof(ResolvedType matchType) { // in our world, Object is assignable from anything if (type.equals(ResolvedType.OBJECT)) return FuzzyBoolean.YES.and(annotationPattern.matches(matchType)); if (type.resolve(matchType.getWorld()).isAssignableFrom(matchType)) { return FuzzyBoolean.YES.and(annotationPattern.matches(matchType)); } // fix for PR 64262 - shouldn't try to coerce primitives if (type.isPrimitiveType()) { return FuzzyBoolean.NO; } else { return matchType.isCoerceableFrom(type.resolve(matchType.getWorld())) ? FuzzyBoolean.MAYBE : FuzzyBoolean.NO; } } public boolean equals(Object other) { if (!(other instanceof ExactTypePattern)) return false; if (other instanceof BindingTypePattern) return false; ExactTypePattern o = (ExactTypePattern)other; if (includeSubtypes != o.includeSubtypes) return false; if (isVarArgs != o.isVarArgs) return false; if (!typeParameters.equals(o.typeParameters)) return false; return (o.type.equals(this.type) && o.annotationPattern.equals(this.annotationPattern)); } public int hashCode() { int result = 17; result = 37*result + type.hashCode(); result = 37*result + new Boolean(includeSubtypes).hashCode(); result = 37*result + new Boolean(isVarArgs).hashCode(); result = 37*result + typeParameters.hashCode(); result = 37*result + annotationPattern.hashCode(); return result; } private static final byte EXACT_VERSION = 1; // rev if changed public void write(DataOutputStream out) throws IOException { out.writeByte(TypePattern.EXACT); out.writeByte(EXACT_VERSION); type.write(out); out.writeBoolean(includeSubtypes); out.writeBoolean(isVarArgs); annotationPattern.write(out); typeParameters.write(out); writeLocation(out); } public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) { return readTypePattern150(s,context); } else { return readTypePatternOldStyle(s,context); } } public static TypePattern readTypePattern150(VersionedDataInputStream s, ISourceContext context) throws IOException { byte version = s.readByte(); if (version > EXACT_VERSION) throw new BCException("ExactTypePattern was written by a more recent version of AspectJ"); TypePattern ret = new ExactTypePattern(UnresolvedType.read(s), s.readBoolean(), s.readBoolean()); ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context)); ret.setTypeParameters(TypePatternList.read(s,context)); ret.readLocation(context, s); return ret; } public static TypePattern readTypePatternOldStyle(DataInputStream s, ISourceContext context) throws IOException { TypePattern ret = new ExactTypePattern(UnresolvedType.read(s), s.readBoolean(),false); ret.readLocation(context, s); return ret; } public String toString() { StringBuffer buff = new StringBuffer(); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append('('); buff.append(annotationPattern.toString()); buff.append(' '); } String typeString = type.toString(); if (isVarArgs) typeString = typeString.substring(0,typeString.lastIndexOf('[')); buff.append(typeString); if (includeSubtypes) buff.append('+'); if (isVarArgs) buff.append("..."); if (annotationPattern != AnnotationTypePattern.ANY) { buff.append(')'); } return buff.toString(); } public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { throw new BCException("trying to re-resolve"); } /** * return a version of this type pattern with all type variables references replaced * by the corresponding entry in the map. */ public TypePattern parameterizeWith(Map typeVariableMap) { UnresolvedType newType = type; if (type.isTypeVariableReference()) { TypeVariableReference t = (TypeVariableReference) type; String key = t.getTypeVariable().getName(); if (typeVariableMap.containsKey(key)) { newType = (UnresolvedType) typeVariableMap.get(key); } } else if (type.isParameterizedType()) { newType = type.parameterize(typeVariableMap); } ExactTypePattern ret = new ExactTypePattern(newType,includeSubtypes,isVarArgs); ret.annotationPattern = annotationPattern.parameterizeWith(typeVariableMap); ret.copyLocationFrom(this); return ret; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
124,808
Bug 124808 [generics] detecting field-get of field of parameterized type.
Hi, Here is the second generics issue: Java code: ========== public class Test<T extends Integer> { Set<T> ints = new HashSet<T>(); public Set<T> foo() { return ints; } public static void main(String[] args) { Test<Integer> t = new Test<Integer>(); Set<Integer> ints = t.foo(); } } Aspect: ======= public privileged aspect TestAspect { pointcut gettingMemberCollection(Test t) : target(t) && get(!public Set<Number+> com.mprv.secsph.*.*) && !within(TestAspect); after (Test test) : gettingMemberCollection(test) { System.out.println("GO Aspects!"); } } Compiler output: ================ warning at after (Test test) : gettingMemberCollection(test) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /root/IdeaProjects/aspectsTest/src/com/mprv/secsph/TestAspect.aj:19:0::0 advice defined in com.mprv.secsph.TestAspect has not been applied [Xlint:adviceDidNotMatch] I would expect "gettingMemberCollection" to catch access to "ints" member of "Test" ... Thanks a lot! Misha.
resolved fixed
01a8b2e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T14:25:06Z
2006-01-22T17:13:20Z
weaver/src/org/aspectj/weaver/patterns/TypePattern.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * On creation, type pattern only contains WildTypePattern nodes, not BindingType or ExactType. * * <p>Then we call resolveBindings() during compilation * During concretization of enclosing pointcuts, we call remapAdviceFormals * * @author Erik Hilsdale * @author Jim Hugunin */ public abstract class TypePattern extends PatternNode { public static class MatchKind { private String name; public MatchKind(String name) { this.name = name; } public String toString() { return name; } } public static final MatchKind STATIC = new MatchKind("STATIC"); public static final MatchKind DYNAMIC = new MatchKind("DYNAMIC"); public static final TypePattern ELLIPSIS = new EllipsisTypePattern(); public static final TypePattern ANY = new AnyTypePattern(); public static final TypePattern NO = new NoTypePattern(); protected boolean includeSubtypes; protected boolean isVarArgs = false; protected AnnotationTypePattern annotationPattern = AnnotationTypePattern.ANY; protected TypePatternList typeParameters = TypePatternList.EMPTY; protected TypePattern(boolean includeSubtypes,boolean isVarArgs,TypePatternList typeParams) { this.includeSubtypes = includeSubtypes; this.isVarArgs = isVarArgs; this.typeParameters = (typeParams == null ? TypePatternList.EMPTY : typeParams); } protected TypePattern(boolean includeSubtypes, boolean isVarArgs) { this(includeSubtypes,isVarArgs,null); } public AnnotationTypePattern getAnnotationPattern() { return annotationPattern; } public boolean isVarArgs() { return isVarArgs; } public boolean isStarAnnotation() { return annotationPattern == AnnotationTypePattern.ANY; } public boolean isArray() { return false; } protected TypePattern(boolean includeSubtypes) { this(includeSubtypes,false); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { this.annotationPattern = annPatt; } public void setTypeParameters(TypePatternList typeParams) { this.typeParameters = typeParams; } public TypePatternList getTypeParameters() { return this.typeParameters; } public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; } // answer conservatively... protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (this.includeSubtypes || other.includeSubtypes) return true; if (this.annotationPattern != AnnotationTypePattern.ANY) return true; if (other.annotationPattern != AnnotationTypePattern.ANY) return true; return false; } //XXX non-final for Not, && and || public boolean matchesStatically(ResolvedType type) { if (includeSubtypes) { return matchesSubtypes(type); } else { return matchesExactly(type); } } public abstract FuzzyBoolean matchesInstanceof(ResolvedType type); public final FuzzyBoolean matches(ResolvedType type, MatchKind kind) { FuzzyBoolean typeMatch = null; //??? This is part of gracefully handling missing references if (type.isMissing()) return FuzzyBoolean.NO; if (kind == STATIC) { // typeMatch = FuzzyBoolean.fromBoolean(matchesStatically(type)); // return typeMatch.and(annotationPattern.matches(type)); return FuzzyBoolean.fromBoolean(matchesStatically(type)); } else if (kind == DYNAMIC) { //System.err.println("matching: " + this + " with " + type); // typeMatch = matchesInstanceof(type); //System.err.println(" got: " + ret); // return typeMatch.and(annotationPattern.matches(type)); return matchesInstanceof(type); } else { throw new IllegalArgumentException("kind must be DYNAMIC or STATIC"); } } protected abstract boolean matchesExactly(ResolvedType type); protected abstract boolean matchesExactly(ResolvedType type, ResolvedType annotatedType); protected boolean matchesSubtypes(ResolvedType type) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(type)) { //System.out.println(" true"); return true; } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = type.getDirectSupertypes(); i.hasNext(); ) { ResolvedType superType = (ResolvedType)i.next(); // TODO asc generics, temporary whilst matching isnt aware.. //if (superType.isParameterizedType()) superType = superType.getRawType().resolve(superType.getWorld()); if (matchesSubtypes(superType,type)) return true; } return false; } protected boolean matchesSubtypes(ResolvedType superType, ResolvedType annotatedType) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(superType,annotatedType)) { //System.out.println(" true"); return true; } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = superType.getDirectSupertypes(); i.hasNext(); ) { ResolvedType superSuperType = (ResolvedType)i.next(); if (matchesSubtypes(superSuperType,annotatedType)) return true; } return false; } public UnresolvedType resolveExactType(IScope scope, Bindings bindings) { TypePattern p = resolveBindings(scope, bindings, false, true); if (p == NO) return ResolvedType.MISSING; return ((ExactTypePattern)p).getType(); } public UnresolvedType getExactType() { if (this instanceof ExactTypePattern) return ((ExactTypePattern)this).getType(); else return ResolvedType.MISSING; } protected TypePattern notExactType(IScope s) { s.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.EXACT_TYPE_PATTERN_REQD), getSourceLocation())); return NO; } // public boolean assertExactType(IMessageHandler m) { // if (this instanceof ExactTypePattern) return true; // // //XXX should try harder to avoid multiple errors for one problem // m.handleMessage(MessageUtil.error("exact type pattern required", getSourceLocation())); // return false; // } /** * This can modify in place, or return a new TypePattern if the type changes. */ public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); return this; } public void resolve(World world) { annotationPattern.resolve(world); } /** * return a version of this type pattern in which all type variable references have been * replaced by their corresponding entry in the map. */ public abstract TypePattern parameterizeWith(Map typeVariableMap); public void postRead(ResolvedType enclosingType) { } public boolean isStar() { return false; } /** * This is called during concretization of pointcuts, it is used by BindingTypePattern * to return a new BindingTypePattern with a formal index appropiate for the advice, * rather than for the lexical declaration, i.e. this handles transforamtions through * named pointcuts. * <pre> * pointcut foo(String name): args(name); * --&gt; This makes a BindingTypePattern(0) pointing to the 0th formal * * before(Foo f, String n): this(f) && foo(n) { ... } * --&gt; when resolveReferences is called on the args from the above, it * will return a BindingTypePattern(1) * * before(Foo f): this(f) && foo(*) { ... } * --&gt; when resolveReferences is called on the args from the above, it * will return an ExactTypePattern(String) * </pre> */ public TypePattern remapAdviceFormals(IntMap bindings) { return this; } public static final byte WILD = 1; public static final byte EXACT = 2; public static final byte BINDING = 3; public static final byte ELLIPSIS_KEY = 4; public static final byte ANY_KEY = 5; public static final byte NOT = 6; public static final byte OR = 7; public static final byte AND = 8; public static final byte NO_KEY = 9; public static final byte ANY_WITH_ANNO = 10; public static final byte HAS_MEMBER = 11; public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { byte key = s.readByte(); switch(key) { case WILD: return WildTypePattern.read(s, context); case EXACT: return ExactTypePattern.read(s, context); case BINDING: return BindingTypePattern.read(s, context); case ELLIPSIS_KEY: return ELLIPSIS; case ANY_KEY: return ANY; case NO_KEY: return NO; case NOT: return NotTypePattern.read(s, context); case OR: return OrTypePattern.read(s, context); case AND: return AndTypePattern.read(s, context); case ANY_WITH_ANNO: return AnyWithAnnotationTypePattern.read(s,context); case HAS_MEMBER: return HasMemberTypePattern.read(s,context); } throw new BCException("unknown TypePattern kind: " + key); } public boolean isIncludeSubtypes() { return includeSubtypes; } } class EllipsisTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public EllipsisTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return false; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(ELLIPSIS_KEY); } public String toString() { return ".."; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (obj instanceof EllipsisTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 * 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map typeVariableMap) { return this; } } class AnyTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public AnyTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return true; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.YES; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(ANY_KEY); } /** * @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind) */ // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType) */ protected boolean matchesSubtypes(ResolvedType type) { return true; } public boolean isStar() { return true; } public String toString() { return "*"; } public boolean equals(Object obj) { return (obj instanceof AnyTypePattern); } public int hashCode() { return 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map arg0) { return this; } } /** * This type represents a type pattern of '*' but with an annotation specified, * e.g. '@Color *' */ class AnyWithAnnotationTypePattern extends TypePattern { public AnyWithAnnotationTypePattern(AnnotationTypePattern atp) { super(false,false); annotationPattern = atp; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } protected boolean matchesExactly(ResolvedType type) { annotationPattern.resolve(type.getWorld()); return annotationPattern.matches(type).alwaysTrue(); } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { annotationPattern.resolve(type.getWorld()); return annotationPattern.matches(annotatedType).alwaysTrue(); } public FuzzyBoolean matchesInstanceof(ResolvedType type) { if (Modifier.isFinal(type.getModifiers())) { return FuzzyBoolean.fromBoolean(matchesExactly(type)); } return FuzzyBoolean.MAYBE; } public TypePattern parameterizeWith(Map typeVariableMap) { AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(this.annotationPattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.ANY_WITH_ANNO); annotationPattern.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s,ISourceContext c) throws IOException { AnnotationTypePattern annPatt = AnnotationTypePattern.read(s,c); AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annPatt); ret.readLocation(c, s); return ret; } // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } protected boolean matchesSubtypes(ResolvedType type) { return true; } public boolean isStar() { return false; } public String toString() { return annotationPattern+" *"; } public boolean equals(Object obj) { if (!(obj instanceof AnyWithAnnotationTypePattern)) return false; AnyWithAnnotationTypePattern awatp = (AnyWithAnnotationTypePattern) obj; return (annotationPattern.equals(awatp.annotationPattern)); } public int hashCode() { return annotationPattern.hashCode(); } } class NoTypePattern extends TypePattern { public NoTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return false; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(NO_KEY); } /** * @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind) */ // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType) */ protected boolean matchesSubtypes(ResolvedType type) { return false; } public boolean isStar() { return false; } public String toString() { return "<nothing>"; }//FIXME AV - bad! toString() cannot be parsed back (not idempotent) /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (obj instanceof NoTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 * 37 * 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map arg0) { return this; } }
124,654
Bug 124654 Capture method annotation in generic aspect does not compile
null
resolved fixed
28f8c69
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T15:21:18Z
2006-01-20T15:13:20Z
tests/bugs151/pr124654/GenericAnnotation.java
124,654
Bug 124654 Capture method annotation in generic aspect does not compile
null
resolved fixed
28f8c69
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T15:21:18Z
2006-01-20T15:13:20Z
tests/bugs151/pr124654/TestSubAspect.java
124,654
Bug 124654 Capture method annotation in generic aspect does not compile
null
resolved fixed
28f8c69
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T15:21:18Z
2006-01-20T15:13:20Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
124,654
Bug 124654 Capture method annotation in generic aspect does not compile
null
resolved fixed
28f8c69
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-23T15:21:18Z
2006-01-20T15:13:20Z
weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Test; /** */ //XXX needs check that arguments contains no WildTypePatterns public class ReferencePointcut extends Pointcut { public UnresolvedType onType; public TypePattern onTypeSymbolic; public String name; public TypePatternList arguments; /** * if this is non-null then when the pointcut is concretized the result will be parameterized too. */ private Map typeVariableMap; //public ResolvedPointcut binding; public ReferencePointcut(TypePattern onTypeSymbolic, String name, TypePatternList arguments) { this.onTypeSymbolic = onTypeSymbolic; this.name = name; this.arguments = arguments; this.pointcutKind = REFERENCE; } public ReferencePointcut(UnresolvedType onType, String name, TypePatternList arguments) { this.onType = onType; this.name = name; this.arguments = arguments; this.pointcutKind = REFERENCE; } public Set couldMatchKinds() { return Shadow.ALL_SHADOW_KINDS; } //??? do either of these match methods make any sense??? public FuzzyBoolean fastMatch(FastMatchInfo type) { return FuzzyBoolean.MAYBE; } /** * Do I really match this shadow? */ protected FuzzyBoolean matchInternal(Shadow shadow) { return FuzzyBoolean.NO; } public String toString() { StringBuffer buf = new StringBuffer(); if (onType != null) { buf.append(onType); buf.append("."); // for (int i=0, len=fromType.length; i < len; i++) { // buf.append(fromType[i]); // buf.append("."); // } } buf.append(name); buf.append(arguments.toString()); return buf.toString(); } public void write(DataOutputStream s) throws IOException { //XXX ignores onType s.writeByte(Pointcut.REFERENCE); if (onType != null) { s.writeBoolean(true); onType.write(s); } else { s.writeBoolean(false); } s.writeUTF(name); arguments.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { UnresolvedType onType = null; if (s.readBoolean()) { onType = UnresolvedType.read(s); } ReferencePointcut ret = new ReferencePointcut(onType, s.readUTF(), TypePatternList.read(s, context)); ret.readLocation(context, s); return ret; } public void resolveBindings(IScope scope, Bindings bindings) { if (onTypeSymbolic != null) { onType = onTypeSymbolic.resolveExactType(scope, bindings); // in this case we've already signalled an error if (ResolvedType.isMissing(onType)) return; } ResolvedType searchType; if (onType != null) { searchType = scope.getWorld().resolve(onType); } else { searchType = scope.getEnclosingType(); } arguments.resolveBindings(scope, bindings, true, true); //XXX ensure that arguments has no ..'s in it // check that I refer to a real pointcut declaration and that I match ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name); // if we're not a static reference, then do a lookup of outers if (pointcutDef == null && onType == null) { while (true) { UnresolvedType declaringType = searchType.getDeclaringType(); if (declaringType == null) break; searchType = declaringType.resolve(scope.getWorld()); pointcutDef = searchType.findPointcut(name); if (pointcutDef != null) { // make this a static reference onType = searchType; break; } } } if (pointcutDef == null) { scope.message(IMessage.ERROR, this, "can't find referenced pointcut " + name); return; } // check visibility if (!pointcutDef.isVisible(scope.getEnclosingType())) { scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible"); return; } if (Modifier.isAbstract(pointcutDef.getModifiers())) { if (onType != null) { scope.message(IMessage.ERROR, this, "can't make static reference to abstract pointcut"); return; } else if (!searchType.isAbstract()) { scope.message(IMessage.ERROR, this, "can't use abstract pointcut in concrete context"); return; } } ResolvedType[] parameterTypes = scope.getWorld().resolve(pointcutDef.getParameterTypes()); if (parameterTypes.length != arguments.size()) { scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " + parameterTypes.length + " found " + arguments.size()); return; } //if (onType == null) onType = pointcutDef.getDeclaringType(); if (onType != null) { if (onType.isParameterizedType()) { // build a type map mapping type variable names in the generic type to // the type parameters presented typeVariableMap = new HashMap(); ResolvedType underlyingGenericType = ((ResolvedType) onType).getGenericType(); TypeVariable[] tVars = underlyingGenericType.getTypeVariables(); ResolvedType[] typeParams = ((ResolvedType)onType).getResolvedTypeParameters(); for (int i = 0; i < tVars.length; i++) { typeVariableMap.put(tVars[i].getName(),typeParams[i]); } } else if (onType.isGenericType()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_REFERENCE_POINTCUT_IN_RAW_TYPE), getSourceLocation())); } } 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 (typeVariableMap != null) { p = p.parameterizeWith(typeVariableMap); } if (p == TypePattern.NO) { scope.message(IMessage.ERROR, this, "bad parameter to pointcut reference"); return; } if (!p.matchesSubtypes(parameterTypes[i]) && !p.getExactType().equals(UnresolvedType.OBJECT)) { scope.message(IMessage.ERROR, p, "incompatible type, expected " + parameterTypes[i].getName() + " found " + p +". Check the type specified in your pointcut"); return; } } } public void postRead(ResolvedType enclosingType) { arguments.postRead(enclosingType); } protected Test findResidueInternal(Shadow shadow, ExposedState state) { throw new RuntimeException("shouldn't happen"); } //??? This is not thread safe, but this class is not designed for multi-threading private boolean concretizing = false; // declaring type is the type that declared the member referencing this pointcut. // If it declares a matching private pointcut, then that pointcut should be used // and not one in a subtype that happens to have the same name. public Pointcut concretize1(ResolvedType searchStart, ResolvedType declaringType, IntMap bindings) { if (concretizing) { //Thread.currentThread().dumpStack(); searchStart.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CIRCULAR_POINTCUT,this), getSourceLocation())); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } try { concretizing = true; ResolvedPointcutDefinition pointcutDec; if (onType != null) { searchStart = onType.resolve(searchStart.getWorld()); if (searchStart.isMissing()) { return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } } if (declaringType == null) declaringType = searchStart; pointcutDec = declaringType.findPointcut(name); boolean foundMatchingPointcut = (pointcutDec != null && pointcutDec.isPrivate()); if (!foundMatchingPointcut) { pointcutDec = searchStart.findPointcut(name); if (pointcutDec == null) { searchStart.getWorld().getMessageHandler().handleMessage( MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_POINTCUT,name,searchStart.getName()), getSourceLocation()) ); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } } if (pointcutDec.isAbstract()) { //Thread.currentThread().dumpStack(); ShadowMunger enclosingAdvice = bindings.getEnclosingAdvice(); searchStart.getWorld().showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ABSTRACT_POINTCUT,pointcutDec), getSourceLocation(), (null == enclosingAdvice) ? null : enclosingAdvice.getSourceLocation()); return Pointcut.makeMatchesNothing(Pointcut.CONCRETE); } //System.err.println("start: " + searchStart); ResolvedType[] parameterTypes = searchStart.getWorld().resolve(pointcutDec.getParameterTypes()); TypePatternList arguments = this.arguments.resolveReferences(bindings); IntMap newBindings = new IntMap(); for (int i=0,len=arguments.size(); i < len; i++) { TypePattern p = arguments.get(i); if (p == TypePattern.NO) continue; // we are allowed to bind to pointcuts which use subtypes as this is type safe // this will be checked in ReferencePointcut.resolveBindings(). Can't check it here // as we don't know about any new parents added via decp. if (p instanceof BindingTypePattern) { newBindings.put(i, ((BindingTypePattern)p).getFormalIndex()); } } if (searchStart.isParameterizedType()) { // build a type map mapping type variable names in the generic type to // the type parameters presented typeVariableMap = new HashMap(); ResolvedType underlyingGenericType = searchStart.getGenericType(); TypeVariable[] tVars = underlyingGenericType.getTypeVariables(); ResolvedType[] typeParams = searchStart.getResolvedTypeParameters(); for (int i = 0; i < tVars.length; i++) { typeVariableMap.put(tVars[i].getName(),typeParams[i]); } } newBindings.copyContext(bindings); newBindings.pushEnclosingDefinition(pointcutDec); try { Pointcut ret = pointcutDec.getPointcut(); if (typeVariableMap != null && !hasBeenParameterized) { ret = ret.parameterizeWith(typeVariableMap); ret.hasBeenParameterized=true; } return ret.concretize(searchStart, declaringType, newBindings); } finally { newBindings.popEnclosingDefinitition(); } } finally { concretizing = false; } } /** * make a version of this pointcut with any refs to typeVariables replaced by their entry in the map. * Tricky thing is, we can't do this at the point in time this method will be called, so we make a * version that will parameterize the pointcut it ultimately resolves to. */ public Pointcut parameterizeWith(Map typeVariableMap) { ReferencePointcut ret = new ReferencePointcut(onType,name,arguments); ret.onTypeSymbolic = onTypeSymbolic; ret.typeVariableMap = typeVariableMap; return ret; } // We want to keep the original source location, not the reference location protected boolean shouldCopyLocationForConcretize() { return false; } public boolean equals(Object other) { if (!(other instanceof ReferencePointcut)) return false; if (this == other) return true; ReferencePointcut o = (ReferencePointcut)other; return o.name.equals(name) && o.arguments.equals(arguments) && ((o.onType == null) ? (onType == null) : o.onType.equals(onType)); } public int hashCode() { int result = 17; result = 37*result + ((onType == null) ? 0 : onType.hashCode()); result = 37*result + arguments.hashCode(); result = 37*result + name.hashCode(); return result; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
124,399
Bug 124399 AJDT AspectJ Internal Compiler Error
In Eclipse 3.1.1 with AJDT 1.3 (the December 20th 2005 release) I got this message in an error dialog: org.aspectj.weaver.BCException at org.aspectj.weaver.bcel.LazyClassGen.getLazyMethodGen(LazyClassGen.java:1216) at org.aspectj.weaver.bcel.LazyClassGen.getLazyMethodGen(LazyClassGen.java:1201) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2048) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:232) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:588) at org.aspectj.weaver.Shadow.implement(Shadow.java:405) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:254) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public class edu.ucsd.aosd.MyApplication extends java.lang.Object: public void <init>(): ALOAD_0 // edu.ucsd.aosd.MyApplication this (line 5) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void edu.ucsd.aosd.MyApplication.<init>()) | RETURN constructor-execution(void edu.ucsd.aosd.MyApplication.<init>()) end public void <init>() public static void main(String[]) org.aspectj.weaver.MethodDeclarationLineNumber: 8:124 : method-execution(void edu.ucsd.aosd.MyApplication.main(java.lang.String[])) | ALOAD_0 // java.lang.String[] args (line 9) | ASTORE 4 | ICONST_0 | ISTORE_2 | ALOAD 4 | ARRAYLENGTH | ISTORE_3 | GOTO L1 | L0: ALOAD 4 | ILOAD_2 | AALOAD | ASTORE_1 | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 10) | NEW java.lang.StringBuilder | DUP | LDC "got: " | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | ALOAD_1 // java.lang.String arg | method-call(java.lang.StringBuilder java.lang.StringBuilder.append(java.lang.String)) | | INVOKEVIRTUAL java.lang.StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder; | method-call(java.lang.StringBuilder java.lang.StringBuilder.append(java.lang.String)) | method-call(java.lang.String java.lang.StringBuilder.toString()) | | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | method-call(java.lang.String java.lang.StringBuilder.toString()) | ASTORE 5 | ASTORE 6 | method-call(void java.io.PrintStream.println(java.lang.String)) | | ALOAD 6 | | ALOAD 5 | | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | method-call(void java.io.PrintStream.println(java.lang.String)) | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 11) | LDC "got: %s\n" | ICONST_1 | ANEWARRAY java.lang.Object | DUP | ICONST_0 | ALOAD_1 // java.lang.String arg | AASTORE | method-call(java.io.PrintStream java.io.PrintStream.printf(java.lang.String, java.lang.Object[])) | | INVOKEVIRTUAL java.io.PrintStream.printf (Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream; | method-call(java.io.PrintStream java.io.PrintStream.printf(java.lang.String, java.lang.Object[])) | POP | IINC 2 1 (line 9) | L1: ILOAD_2 | ILOAD_3 | IF_ICMPLT L0 | RETURN (line 13) method-execution(void edu.ucsd.aosd.MyApplication.main(java.lang.String[])) end public static void main(String[]) end public class edu.ucsd.aosd.MyApplication when implementing on shadow method-call(void java.io.PrintStream.println(java.lang.String)) when weaving type edu.ucsd.aosd.MyApplication when weaving classes when weaving when incrementally building BuildConfig[C:\EclipseWorkspace\.metadata\.plugins\org.eclipse.ajdt.core\AspectJSemanticsTest.generated.lst] #Files=2 It occured when I editing this file, in an AspectJ project with an recently renamed .aj extension: package edu.ucsd.aosd; import java.io.PrintStream; public class MyApplication { // main public static void main(String[] args) { for (String arg : args) { System.out.println("got: " + arg); System.out.printf("got: %s\n", arg); } } } aspect Printing { pointcut printlnCalls(PrintStream ps, String out): call(* PrintStream+.println(String)) && target(ps) && args(out); Object around(PrintStream ps, String out): printlnCalls(ps, out) && !adviceexecution() { return proceed(ps, out); } pointcut printfCalls(PrintStream ps, String fmt, Object[] objs): call(* PrintStream+.printf(String, Object...#####)) && target(ps) && args(fmt, objs); } Where "#####" is where my cursor was when I saved. My previously saved version didn't have the printfCalls pointcut nor the call to printf in the main. (Thus, you might want to try the println version first, save it, and then make the new additions. Though, I hope the debug information is enough.)
resolved fixed
d916002
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-24T09:59:17Z
2006-01-18T21:33:20Z
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.systemtest.incremental.tools; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.aspectj.ajdt.internal.core.builder.AjState; import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.IMessage; import org.aspectj.testing.util.FileUtil; /** * The superclass knows all about talking through Ajde to the compiler. * The superclass isn't in charge of knowing how to simulate overlays * for incremental builds, that is in here. As is the ability to * generate valid build configs based on a directory structure. To * support this we just need access to a sandbox directory - this * sandbox is managed by the superclass (it only assumes all builds occur * in <sandboxDir>/<projectName>/ ) * * The idea is you can initialize multiple projects in the sandbox and * they can all be built independently, hopefully exploiting * incremental compilation. Between builds you can alter the contents * of a project using the alter() method that overlays some set of * new files onto the current set (adding new files/changing existing * ones) - you can then drive a new build and check it behaves as * expected. */ public class MultiProjectIncrementalTests extends AjdeInteractionTestbed { public static boolean VERBOSE = false; protected void setUp() throws Exception { super.setUp(); AjdeInteractionTestbed.VERBOSE = VERBOSE; } // Compile a single simple project public void testTheBasics() { initialiseProject("P1"); build("P1"); // This first build will be batch build("P1"); checkWasntFullBuild(); checkCompileWeaveCount(0,0); } // Make simple changes to a project, adding a class public void testSimpleChanges() { initialiseProject("P1"); build("P1"); // This first build will be batch alter("P1","inc1"); // adds a single class build("P1"); checkCompileWeaveCount(1,-1); build("P1"); checkCompileWeaveCount(0,-1); } // Make simple changes to a project, adding a class and an aspect public void testAddingAnAspect() { initialiseProject("P1"); build("P1"); alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); long timeTakenForFullBuildAndWeave = getTimeTakenForBuild(); checkWasntFullBuild(); checkCompileWeaveCount(2,3); build("P1"); long timeTakenForSimpleIncBuild = getTimeTakenForBuild(); // I don't think this test will have timing issues as the times should be *RADICALLY* different // On my config, first build time is 2093ms and the second is 30ms assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+ "ms second="+timeTakenForSimpleIncBuild+"ms", timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave); } public void testBuildingTwoProjectsInTurns() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); } /** * In order for this next test to run, I had to move the weaver/world pair we keep in the * AjBuildManager instance down into the state object - this makes perfect sense - otherwise * when reusing the state for another project we'd not be switching to the right weaver/world * for that project. */ public void testBuildingTwoProjectsMakingSmallChanges() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); checkWasntFullBuild(); } /** * Setup up two simple projects and build them in turn - check the * structure model is right after each build */ public void testBuildingTwoProjectsAndVerifyingModel() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } // Setup up two simple projects and build them in turn - check the // structure model is right after each build public void testBuildingTwoProjectsAndVerifyingStuff() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, adding a new method and check structural changes is 1. */ public void testStateManagement1() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be a state object for project P1",ajs!=null); assertTrue("Should be no structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc3"); // adds a method to the class C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Should be one structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, changing body of a method, not the structure and * check struc changes is still 0. */ public void testStateManagement2() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making // it a structural change build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be state for project P1",ajs!=null); assertTrue("Should be no struc changes as its a full build: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); } /** * Now the most complex test. Create a dependancy between two projects. Building * one may affect whether the other does an incremental or full build. The * structural information recorded in the state object should be getting used * to control whether a full build is necessary... */ public void testBuildingDependantProjects() { initialiseProject("P1"); initialiseProject("P2"); configureNewProjectDependency("P2","P1"); build("P1"); build("P2"); // now everything is consistent and compiled alter("P1","inc1"); // adds a second class build("P1"); build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :) checkWasntFullBuild(); alter("P1","inc3"); // structurally changes one of the classes build("P1"); build("P2"); // build notices the structural change checkWasFullBuild(); alter("P1","inc4"); build("P1"); build("P2"); // build sees a change but works out its not structural checkWasntFullBuild(); } public void testPr85132() { initialiseProject("PR85132"); build("PR85132"); alter("PR85132","inc1"); build("PR85132"); } public void testPr92837() { initialiseProject("PR92837"); build("PR92837"); alter("PR92837","inc1"); build("PR92837"); } public void testPr119570() { initialiseProject("PR119570"); build("PR119570"); assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0); } public void testPr119570_2() { initialiseProject("PR119570_2"); build("PR119570_2"); List l = MyTaskListManager.getWarningMessages(); assertTrue("Should be no warnings, but got "+l,l.size()==0); } // If you fiddle with the compiler options - you must manually reset the options at the end of the test public void testPr117209() { try { initialiseProject("pr117209"); configureNonStandardCompileOptions("-proceedOnError"); build("pr117209"); checkCompileWeaveCount(6,6); } finally { MyBuildOptionsAdapter.reset(); } } public void testPr114875() { initialiseProject("pr114875"); build("pr114875"); alter("pr114875","inc1"); build("pr114875"); checkWasntFullBuild(); alter("pr114875","inc2"); build("pr114875"); checkWasntFullBuild(); } public void testPr117882() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882"); build("PR117882"); checkWasFullBuild(); alter("PR117882","inc1"); build("PR117882"); checkWasntFullBuild(); // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr117882_2() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882_2"); build("PR117882_2"); checkWasFullBuild(); alter("PR117882_2","inc1"); build("PR117882_2"); checkWasntFullBuild(); //checkCompileWeaveCount(1,4); //fullBuild("PR117882_2"); //checkWasFullBuild(); // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr115251() { //AjdeInteractionTestbed.VERBOSE=true; initialiseProject("PR115251"); build("PR115251"); checkWasFullBuild(); alter("PR115251","inc1"); build("PR115251"); checkWasntFullBuild(); } public void testPr121384() { // AjdeInteractionTestbed.VERBOSE=true; // AsmManager.setReporting("c:/foo.txt",true,true,true,false); MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo"); configureBuildStructureModel(true); initialiseProject("pr121384"); build("pr121384"); checkWasFullBuild(); alter("pr121384","inc1"); build("pr121384"); checkWasntFullBuild(); } /* public void testPr111779() { super.VERBOSE=true; initialiseProject("PR111779"); build("PR111779"); alter("PR111779","inc1"); build("PR111779"); } */ public void testPr93310_1() { initialiseProject("PR93310_1"); build("PR93310_1"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_1","inc1"); build("PR93310_1"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1); String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java")); } public void testPr93310_2() { initialiseProject("PR93310_2"); build("PR93310_2"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_2","inc1"); build("PR93310_2"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1); String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java")); } // Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A. // Stage2: make the field private in class A > gives compile error // Stage3: Add a new aspect whilst there is a compile error ! public void testPr113531() { initialiseProject("PR113531"); build("PR113531"); assertFalse("build should have compiled ok", MyTaskListManager.hasErrorMessages()); alter("PR113531","inc1"); build("PR113531"); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); alter("PR113531","inc2"); build("PR113531"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); } public void testPr112736() { AjdeInteractionTestbed.VERBOSE = true; initialiseProject("PR112736"); build("PR112736"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java"; (new File(fileC2)).delete(); alter("PR112736","inc1"); build("PR112736"); checkWasFullBuild(); } /** * We have problems with multiple rewrites of a pointcut across incremental builds. */ public void testPr113257() { initialiseProject("PR113257"); build("PR113257"); alter("PR113257","inc1"); build("PR113257"); checkWasntFullBuild(); alter("PR113257","inc1"); build("PR113257"); } public void testPr123612() { initialiseProject("PR123612"); build("PR123612"); alter("PR123612","inc1"); build("PR123612"); checkWasntFullBuild(); } // other possible tests: // - memory usage (freemem calls?) // - relationship map // --------------------------------------------------------------------------------------------------- /** * Check we compiled/wove the right number of files, passing '-1' indicates you don't care about * that number. */ private void checkCompileWeaveCount(int expCompile,int expWoven) { if (expCompile!=-1 && getCompiledFiles().size()!=expCompile) fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+ "\n"+printCompiledAndWovenFiles()); if (expWoven!=-1 && getWovenClasses().size()!=expWoven) fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+ "\n"+printCompiledAndWovenFiles()); } private void checkWasntFullBuild() { assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild()); } private void checkWasFullBuild() { assertTrue("Should have been a full (batch) build",wasFullBuild()); } private void checkForNode(String packageName,String typeName,boolean shouldBeFound) { IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName); if (shouldBeFound) { if (ipe==null) printModel(); assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null); } else { if (ipe!=null) printModel(); assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null); } } private void printModel() { try { AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0); } catch (IOException e) { e.printStackTrace(); } } public void build(String projectName) { constructUpToDateLstFile(projectName,"build.lst"); build(projectName,"build.lst"); if (AjdeInteractionTestbed.VERBOSE) printBuildReport(); } public void fullBuild(String projectName) { constructUpToDateLstFile(projectName,"build.lst"); fullBuild(projectName,"build.lst"); if (AjdeInteractionTestbed.VERBOSE) printBuildReport(); } private void constructUpToDateLstFile(String pname,String configname) { File projectBase = new File(sandboxDir,pname); File toConstruct = new File(projectBase,configname); List filesForCompilation = new ArrayList(); collectUpFiles(projectBase,projectBase,filesForCompilation); try { FileOutputStream fos = new FileOutputStream(toConstruct); DataOutputStream dos = new DataOutputStream(fos); for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) { String file = (String) iter.next(); dos.writeBytes(file+"\n"); } dos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } private void collectUpFiles(File location,File base,List collectionPoint) { String contents[] = location.list(); if (contents==null) return; for (int i = 0; i < contents.length; i++) { String string = contents[i]; File f = new File(location,string); if (f.isDirectory()) { collectUpFiles(f,base,collectionPoint); } else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) { String fileFound; try { fileFound = f.getCanonicalPath(); String toRemove = base.getCanonicalPath(); if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove); collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator } catch (IOException e) { e.printStackTrace(); } } } } /** * Fill in the working directory with the project base files, * from the 'base' folder. */ protected void initialiseProject(String p) { File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base"); File destination=new File(getWorkingDir(),p); if (!destination.exists()) {destination.mkdir();} copy(projectSrc,destination);//,false); } /* * Applies an overlay onto the project being tested - copying * the contents of the specified overlay directory. */ private void alter(String projectName,String overlayDirectory) { File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+ File.separatorChar+overlayDirectory); File destination=new File(getWorkingDir(),projectName); copy(projectSrc,destination); } /** * Copy the contents of some directory to another location - the * copy is recursive. */ private void copy(File from, File to) { String contents[] = from.list(); if (contents==null) return; for (int i = 0; i < contents.length; i++) { String string = contents[i]; File f = new File(from,string); File t = new File(to,string); if (f.isDirectory() && !f.getName().startsWith("inc")) { t.mkdir(); copy(f,t); } else if (f.isFile()) { StringBuffer sb = new StringBuffer(); //if (VERBOSE) System.err.println("Copying "+f+" to "+t); FileUtil.copyFile(f,t,sb); if (sb.length()!=0) { System.err.println(sb.toString());} } } } private static void log(String msg) { if (VERBOSE) System.out.println(msg); } }
124,999
Bug 124999 [generics] Incorrect call to generic inherited method in around advice
null
resolved fixed
a4bd19d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-24T16:47:42Z
2006-01-24T13:40:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AccessForInlineVisitor.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; //import java.util.Arrays; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.InlineAccessFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ResolvedMember; import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor; //import org.aspectj.org.eclipse.jdt.internal.compiler.AbstractSyntaxTreeVisitorAdapter; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AssertStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; 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.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.VariableBinding; /** * Walks the body of around advice * * Makes sure that all member accesses are to public members. Will * convert to use access methods when needed to ensure that. This * makes it much simpler (and more modular) to inline the body of * an around. * * ??? constructors are handled different and require access to the * target type. changes to org.eclipse.jdt.internal.compiler.ast.AllocationExpression * would be required to fix this issue. * * @author Jim Hugunin */ public class AccessForInlineVisitor extends ASTVisitor { PrivilegedHandler handler; AspectDeclaration inAspect; EclipseFactory world; // alias for inAspect.world // set to true for ClassLiteralAccess and AssertStatement // ??? A better answer would be to transform these into inlinable forms public boolean isInlinable = true; public AccessForInlineVisitor(AspectDeclaration inAspect, PrivilegedHandler handler) { this.inAspect = inAspect; this.world = inAspect.factory; this.handler = handler; } public void endVisit(SingleNameReference ref, BlockScope scope) { if (ref.binding instanceof FieldBinding) { ref.binding = getAccessibleField((FieldBinding)ref.binding, ref.actualReceiverType); } } public void endVisit(QualifiedNameReference ref, BlockScope scope) { if (ref.binding instanceof FieldBinding) { ref.binding = getAccessibleField((FieldBinding)ref.binding, ref.actualReceiverType); } if (ref.otherBindings != null && ref.otherBindings.length > 0) { TypeBinding receiverType; if (ref.binding instanceof FieldBinding) { receiverType = ((FieldBinding)ref.binding).type; } else if (ref.binding instanceof VariableBinding) { receiverType = ((VariableBinding)ref.binding).type; } else { //!!! understand and fix this case later receiverType = ref.otherBindings[0].declaringClass; } for (int i=0, len=ref.otherBindings.length; i < len; i++) { FieldBinding binding = ref.otherBindings[i]; ref.otherBindings[i] = getAccessibleField(binding, receiverType); receiverType = binding.type; } } } public void endVisit(FieldReference ref, BlockScope scope) { ref.binding = getAccessibleField(ref.binding, ref.receiverType); } public void endVisit(MessageSend send, BlockScope scope) { if (send instanceof Proceed) return; if (send.binding == null || !send.binding.isValidBinding()) return; if (send.isSuperAccess() && !send.binding.isStatic()) { send.receiver = new ThisReference(send.sourceStart, send.sourceEnd); MethodBinding superAccessBinding = getSuperAccessMethod(send.binding); AstUtil.replaceMethodBinding(send, superAccessBinding); } else if (!isPublic(send.binding)) { send.syntheticAccessor = getAccessibleMethod(send.binding, send.actualReceiverType); } } public void endVisit(AllocationExpression send, BlockScope scope) { if (send.binding == null || !send.binding.isValidBinding()) return; //XXX TBD if (isPublic(send.binding)) return; makePublic(send.binding.declaringClass); send.binding = handler.getPrivilegedAccessMethod(send.binding, send); } public void endVisit( QualifiedTypeReference ref, BlockScope scope) { makePublic(ref.resolvedType); //getTypeBinding(scope)); //??? might be trouble } public void endVisit( SingleTypeReference ref, BlockScope scope) { makePublic(ref.resolvedType); //getTypeBinding(scope)); //??? might be trouble } private FieldBinding getAccessibleField(FieldBinding binding, TypeBinding receiverType) { //System.err.println("checking field: " + binding); if (binding == null || !binding.isValidBinding()) return binding; makePublic(receiverType); if (isPublic(binding)) return binding; if (binding instanceof PrivilegedFieldBinding) return binding; if (binding instanceof InterTypeFieldBinding) return binding; if (binding.isPrivate() && binding.declaringClass != inAspect.binding) { binding.modifiers = AstUtil.makePackageVisible(binding.modifiers); } ResolvedMember m = world.makeResolvedMember(binding, receiverType); if (inAspect.accessForInline.containsKey(m)) return (FieldBinding)inAspect.accessForInline.get(m); FieldBinding ret = new InlineAccessFieldBinding(inAspect, binding, m); //System.err.println(" made accessor: " + ret); inAspect.accessForInline.put(m, ret); return ret; } private MethodBinding getAccessibleMethod(MethodBinding binding, TypeBinding receiverType) { if (!binding.isValidBinding()) return binding; makePublic(receiverType); //??? if (isPublic(binding)) return binding; if (binding instanceof InterTypeMethodBinding) return binding; ResolvedMember m = null; if (binding.isPrivate() && binding.declaringClass != inAspect.binding) { // does this always mean that the aspect is an inner aspect of the bindings // declaring class? After all, the field is private but we can see it from // where we are. binding.modifiers = AstUtil.makePackageVisible(binding.modifiers); m = world.makeResolvedMember(binding); } else { // Sometimes receiverType and binding.declaringClass are *not* the same. // Sometimes receiverType is a subclass of binding.declaringClass. In these situations // we want the generated inline accessor to call the method on the subclass (at // runtime this will be satisfied by the super). m = world.makeResolvedMember(binding, receiverType); } if (inAspect.accessForInline.containsKey(m)) return (MethodBinding)inAspect.accessForInline.get(m); MethodBinding ret = world.makeMethodBinding( AjcMemberMaker.inlineAccessMethodForMethod(inAspect.typeX, m)); inAspect.accessForInline.put(m, ret); return ret; } static class SuperAccessMethodPair { public ResolvedMember originalMethod; public MethodBinding accessMethod; public SuperAccessMethodPair(ResolvedMember originalMethod, MethodBinding accessMethod) { this.originalMethod = originalMethod; this.accessMethod = accessMethod; } } private MethodBinding getSuperAccessMethod(MethodBinding binding) { ResolvedMember m = world.makeResolvedMember(binding); ResolvedMember superAccessMember = AjcMemberMaker.superAccessMethod(inAspect.typeX, m); if (inAspect.superAccessForInline.containsKey(superAccessMember)) { return ((SuperAccessMethodPair)inAspect.superAccessForInline.get(superAccessMember)).accessMethod; } MethodBinding ret = world.makeMethodBinding(superAccessMember); inAspect.superAccessForInline.put(superAccessMember, new SuperAccessMethodPair(m, ret)); return ret; } private boolean isPublic(FieldBinding fieldBinding) { // these are always effectively public to the inliner if (fieldBinding instanceof InterTypeFieldBinding) return true; return fieldBinding.isPublic(); } private boolean isPublic(MethodBinding methodBinding) { // these are always effectively public to the inliner if (methodBinding instanceof InterTypeMethodBinding) return true; return methodBinding.isPublic(); } private void makePublic(TypeBinding binding) { if (binding == null || !binding.isValidBinding()) return; // has already produced an error if (binding instanceof ReferenceBinding) { ReferenceBinding rb = (ReferenceBinding)binding; if (!rb.isPublic()) handler.notePrivilegedTypeAccess(rb, null); //??? } else if (binding instanceof ArrayBinding) { makePublic( ((ArrayBinding)binding).leafComponentType ); } else { return; } } public void endVisit(AssertStatement assertStatement, BlockScope scope) { isInlinable = false; } public void endVisit(ClassLiteralAccess classLiteral, BlockScope scope) { isInlinable = false; } public boolean visit( TypeDeclaration localTypeDeclaration, BlockScope scope) { // we don't want to transform any local anonymous classes as they won't be inlined return false; } }
124,999
Bug 124999 [generics] Incorrect call to generic inherited method in around advice
null
resolved fixed
a4bd19d
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-24T16:47:42Z
2006-01-24T13:40:00Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");} ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
125,101
Bug 125101 StackOverFlow in ReferenceType.isAssignableFrom()
Hi. I am weaving two aspects into a jar file "jar-to-jar". ajc 1.5.0 gives me a huge error message (see attachement). Would be great if I could get any recommendations on this. Thanks! Eric
resolved fixed
efb20c5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-25T17:41:21Z
2006-01-25T00:46:40Z
weaver/src/org/aspectj/weaver/bcel/BcelWorld.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur perClause support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.ANEWARRAY; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldInstruction; import org.aspectj.apache.bcel.generic.GETSTATIC; import org.aspectj.apache.bcel.generic.INVOKEINTERFACE; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.INVOKESTATIC; import org.aspectj.apache.bcel.generic.Instruction; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InvokeInstruction; import org.aspectj.apache.bcel.generic.MULTIANEWARRAY; import org.aspectj.apache.bcel.generic.NEWARRAY; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.PUTSTATIC; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.util.ClassLoaderRepository; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.Repository; import org.aspectj.bridge.IMessageHandler; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.ICrossReferenceHandler; import org.aspectj.weaver.Member; import org.aspectj.weaver.MemberImpl; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.Aspect; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.SimpleScope; public class BcelWorld extends World implements Repository { private ClassPathManager classPath; private Repository delegate; //private ClassPathManager aspectPath = null; // private List aspectPathEntries; // ---- constructors public BcelWorld() { this(""); } public BcelWorld(String cp) { this(makeDefaultClasspath(cp), IMessageHandler.THROW, null); } private static List makeDefaultClasspath(String cp) { List classPath = new ArrayList(); classPath.addAll(getPathEntries(cp)); classPath.addAll(getPathEntries(ClassPath.getClassPath())); //System.err.println("classpath: " + classPath); return classPath; } private static List getPathEntries(String s) { List ret = new ArrayList(); StringTokenizer tok = new StringTokenizer(s, File.pathSeparator); while(tok.hasMoreTokens()) ret.add(tok.nextToken()); return ret; } public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { //this.aspectPath = new ClassPathManager(aspectPath, handler); this.classPath = new ClassPathManager(classPath, handler); setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { this.classPath = cpm; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = this; // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } /** * Build a World from a ClassLoader, for LTW support * * @param loader * @param handler * @param xrefHandler */ public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) { this.classPath = null; setMessageHandler(handler); setCrossReferenceHandler(xrefHandler); // Tell BCEL to use us for resolving any classes delegate = new ClassLoaderRepository(loader); // TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate); // if so, how can that be safe in J2EE ?? (static stuff in Bcel) } public void addPath (String name) { classPath.addPath(name, this.getMessageHandler()); } /** * Parse a string into advice. * * <blockquote><pre> * Kind ( Id , ... ) : Pointcut -> MethodSignature * </pre></blockquote> */ public Advice shadowMunger(String str, int extraFlag) { str = str.trim(); int start = 0; int i = str.indexOf('('); AdviceKind kind = AdviceKind.stringToKind(str.substring(start, i)); start = ++i; i = str.indexOf(')', i); String[] ids = parseIds(str.substring(start, i).trim()); //start = ++i; i = str.indexOf(':', i); start = ++i; i = str.indexOf("->", i); Pointcut pointcut = Pointcut.fromString(str.substring(start, i).trim()); Member m = MemberImpl.methodFromString(str.substring(i+2, str.length()).trim()); // now, we resolve UnresolvedType[] types = m.getParameterTypes(); FormalBinding[] bindings = new FormalBinding[ids.length]; for (int j = 0, len = ids.length; j < len; j++) { bindings[j] = new FormalBinding(types[j], ids[j], j, 0, 0, "fromString"); } Pointcut p = pointcut.resolve(new SimpleScope(this, bindings)); return new BcelAdvice(kind, p, m, extraFlag, 0, 0, null, null); } private String[] parseIds(String str) { if (str.length() == 0) return ZERO_STRINGS; List l = new ArrayList(); int start = 0; while (true) { int i = str.indexOf(',', start); if (i == -1) { l.add(str.substring(start).trim()); break; } l.add(str.substring(start, i).trim()); start = i+1; } return (String[]) l.toArray(new String[l.size()]); } // ---- various interactions with bcel public static Type makeBcelType(UnresolvedType type) { return Type.getType(type.getErasureSignature()); } static Type[] makeBcelTypes(UnresolvedType[] types) { Type[] ret = new Type[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = makeBcelType(types[i]); } return ret; } static String[] makeBcelTypesAsClassNames(UnresolvedType[] types) { String[] ret = new String[types.length]; for (int i = 0, len = types.length; i < len; i++) { ret[i] = types[i].getClassName();//makeBcelType(types[i]); } return ret; } public static UnresolvedType fromBcel(Type t) { return UnresolvedType.forSignature(t.getSignature()); } static UnresolvedType[] fromBcel(Type[] ts) { UnresolvedType[] ret = new UnresolvedType[ts.length]; for (int i = 0, len = ts.length; i < len; i++) { ret[i] = fromBcel(ts[i]); } return ret; } public ResolvedType resolve(Type t) { return resolve(fromBcel(t)); } protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) { String name = ty.getName(); JavaClass jc = null; //UnwovenClassFile classFile = (UnwovenClassFile)sourceJavaClasses.get(name); //if (classFile != null) jc = classFile.getJavaClass(); // if (jc == null) { // jc = lookupJavaClass(aspectPath, name); // } if (jc == null) { jc = lookupJavaClass(classPath, name); } if (jc == null) { return null; } else { return makeBcelObjectType(ty, jc, false); } } protected BcelObjectType makeBcelObjectType(ReferenceType resolvedTypeX, JavaClass jc, boolean exposedToWeaver) { BcelObjectType ret = new BcelObjectType(resolvedTypeX, jc, exposedToWeaver); return ret; } private JavaClass lookupJavaClass(ClassPathManager classPath, String name) { if (classPath == null) { try { return delegate.loadClass(name); } catch (ClassNotFoundException e) { return null; } } try { ClassPathManager.ClassFile file = classPath.find(UnresolvedType.forName(name)); if (file == null) return null; ClassParser parser = new ClassParser(file.getInputStream(), file.getPath()); JavaClass jc = parser.parse(); file.close(); return jc; } catch (IOException ioe) { return null; } } public BcelObjectType addSourceObjectType(JavaClass jc) { BcelObjectType ret = null; String signature = UnresolvedType.forName(jc.getClassName()).getSignature(); Object fromTheMap = typeMap.get(signature); if (fromTheMap!=null && !(fromTheMap instanceof ReferenceType)) { // what on earth is it then? See pr 112243 StringBuffer exceptionText = new StringBuffer(); exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. "); exceptionText.append("Signature=["+signature+"] Found=["+fromTheMap+"] Class=["+fromTheMap.getClass()+"]"); throw new BCException(exceptionText.toString()); } ReferenceType nameTypeX = (ReferenceType)fromTheMap; if (nameTypeX == null) { if (jc.isGeneric() && isInJava5Mode()) { nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()),this); ret = makeBcelObjectType(nameTypeX, jc, true); ReferenceType genericRefType = new ReferenceType( UnresolvedType.forGenericTypeSignature(signature,ret.getDeclaredGenericSignature()),this); nameTypeX.setDelegate(ret); genericRefType.setDelegate(ret); nameTypeX.setGenericType(genericRefType); typeMap.put(signature, nameTypeX); } else { nameTypeX = new ReferenceType(signature, this); ret = makeBcelObjectType(nameTypeX, jc, true); typeMap.put(signature, nameTypeX); } } else { ret = makeBcelObjectType(nameTypeX, jc, true); } return ret; } void deleteSourceObjectType(UnresolvedType ty) { typeMap.remove(ty.getSignature()); } public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) { ConstantPoolGen cpg = cg.getConstantPoolGen(); return MemberImpl.field( fi.getClassName(cpg), (fi instanceof GETSTATIC || fi instanceof PUTSTATIC) ? Modifier.STATIC: 0, fi.getName(cpg), fi.getSignature(cpg)); } // public static Member makeFieldSetSignature(LazyClassGen cg, FieldInstruction fi) { // ConstantPoolGen cpg = cg.getConstantPoolGen(); // return // MemberImpl.field( // fi.getClassName(cpg), // (fi instanceof GETSTATIC || fi instanceof PUTSTATIC) // ? Modifier.STATIC // : 0, // fi.getName(cpg), // "(" + fi.getSignature(cpg) + ")" +fi.getSignature(cpg)); // } public Member makeJoinPointSignature(LazyMethodGen mg) { return makeJoinPointSignatureFromMethod(mg, null); } public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberImpl.Kind kind) { Member ret = mg.getMemberView(); if (ret == null) { int mods = mg.getAccessFlags(); if (mg.getEnclosingClass().isInterface()) { mods |= Modifier.INTERFACE; } if (kind == null) { if (mg.getName().equals("<init>")) { kind = Member.CONSTRUCTOR; } else if (mg.getName().equals("<clinit>")) { kind = Member.STATIC_INITIALIZATION; } else { kind = Member.METHOD; } } return new ResolvedMemberImpl(kind, UnresolvedType.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()), mg.getName(), fromBcel(mg.getArgumentTypes()) ); } else { return ret; } } public Member makeJoinPointSignatureForArrayConstruction(LazyClassGen cg, InstructionHandle handle) { Instruction i = handle.getInstruction(); ConstantPoolGen cpg = cg.getConstantPoolGen(); Member retval = null; if (i instanceof ANEWARRAY) { ANEWARRAY arrayInstruction = (ANEWARRAY)i; ObjectType ot = arrayInstruction.getLoadClassType(cpg); UnresolvedType ut = fromBcel(ot); ut = UnresolvedType.makeArray(ut,1); retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", new ResolvedType[]{ResolvedType.INT}); } else if (i instanceof MULTIANEWARRAY) { MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY)i; UnresolvedType ut = null; short dimensions = arrayInstruction.getDimensions(); ObjectType ot = arrayInstruction.getLoadClassType(cpg); if (ot!=null) { ut = fromBcel(ot); ut = UnresolvedType.makeArray(ut,dimensions); } else { Type t = arrayInstruction.getType(cpg); ut = fromBcel(t); } ResolvedType[] parms = new ResolvedType[dimensions]; for (int ii=0;ii<dimensions;ii++) parms[ii] = ResolvedType.INT; retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", parms); } else if (i instanceof NEWARRAY) { NEWARRAY arrayInstruction = (NEWARRAY)i; Type ot = arrayInstruction.getType(); UnresolvedType ut = fromBcel(ot); retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", new ResolvedType[]{ResolvedType.INT}); } else { throw new BCException("Cannot create array construction signature for this non-array instruction:"+i); } return retval; } public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) { ConstantPoolGen cpg = cg.getConstantPoolGen(); String name = ii.getName(cpg); String declaring = ii.getClassName(cpg); UnresolvedType declaringType = null; String signature = ii.getSignature(cpg); int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE : (ii instanceof INVOKESTATIC) ? Modifier.STATIC : (ii instanceof INVOKESPECIAL && ! name.equals("<init>")) ? Modifier.PRIVATE : 0; // in Java 1.4 and after, static method call of super class within subclass method appears // as declared by the subclass in the bytecode - but they are not // see #104212 if (ii instanceof INVOKESTATIC) { ResolvedType appearsDeclaredBy = resolve(declaring); // look for the method there for (Iterator iterator = appearsDeclaredBy.getMethods(); iterator.hasNext();) { ResolvedMember method = (ResolvedMember) iterator.next(); if (method.isStatic()) { if (name.equals(method.getName()) && signature.equals(method.getSignature())) { // we found it declaringType = method.getDeclaringType(); break; } } } } if (declaringType == null) { if (declaring.charAt(0)=='[') declaringType = UnresolvedType.forSignature(declaring); else declaringType = UnresolvedType.forName(declaring); } return MemberImpl.method(declaringType, modifier, name, signature); } public static Member makeMungerMethodSignature(JavaClass javaClass, Method method) { int mods = 0; if (method.isStatic()) mods = Modifier.STATIC; else if (javaClass.isInterface()) mods = Modifier.INTERFACE; else if (method.isPrivate()) mods = Modifier.PRIVATE; return MemberImpl.method( UnresolvedType.forName(javaClass.getClassName()), mods, method.getName(), method.getSignature()); } private static final String[] ZERO_STRINGS = new String[0]; public String toString() { StringBuffer buf = new StringBuffer(); buf.append("BcelWorld("); //buf.append(shadowMungerMap); buf.append(")"); return buf.toString(); } public Advice createAdviceMunger( AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature) { //System.err.println("concrete advice: " + signature + " context " + sourceContext); return new BcelAdvice(attribute, pointcut, signature, null); } public ConcreteTypeMunger concreteTypeMunger( ResolvedTypeMunger munger, ResolvedType aspectType) { return new BcelTypeMunger(munger, aspectType); } public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) { return new BcelCflowStackFieldAdder(cflowField); } public ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField) { return new BcelCflowCounterFieldAdder(cflowField); } /** * Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed * * @param aspect * @param kind * @return munger */ public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind) { return new BcelPerClauseAspectAdder(aspect, kind); } /** * Retrieve a bcel delegate for an aspect - this will return NULL if the * delegate is an EclipseSourceType and not a BcelObjectType - this happens * quite often when incrementally compiling. */ public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) { ReferenceTypeDelegate rtDelegate = ((ReferenceType)concreteAspect).getDelegate(); if (rtDelegate instanceof BcelObjectType) { return (BcelObjectType)rtDelegate; } else { return null; } } public void tidyUp() { // At end of compile, close any open files so deletion of those archives is possible classPath.closeArchives(); typeMap.report(); } /// The repository interface methods public JavaClass findClass(String className) { return lookupJavaClass(classPath,className); } public JavaClass loadClass(String className) throws ClassNotFoundException { return lookupJavaClass(classPath,className); } public void storeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public void removeClass(JavaClass clazz) { throw new RuntimeException("Not implemented"); } public JavaClass loadClass(Class clazz) throws ClassNotFoundException { throw new RuntimeException("Not implemented"); } public void clear() { throw new RuntimeException("Not implemented"); } // @Override /** * The aim of this method is to make sure a particular type is 'ok'. Some * operations on the delegate for a type modify it and this method is * intended to undo that... see pr85132 */ public void validateType(UnresolvedType type) { ResolvedType result = typeMap.get(type.getSignature()); if (result==null) return; // We haven't heard of it yet if (!result.isExposedToWeaver()) return; // cant need resetting ReferenceType rt = (ReferenceType)result; rt.getDelegate().ensureDelegateConsistent(); // If we want to rebuild it 'from scratch' then: // ClassParser cp = new ClassParser(new ByteArrayInputStream(newbytes),new String(cs)); // try { // rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true)); // } catch (ClassFormatException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } } /** * Checks if given bytecode is an @AspectJ aspect * * @param name * @param bytes * @return true if so */ public boolean isAnnotationStyleAspect(String name, byte[] bytes) { try { ClassParser cp = new ClassParser(new ByteArrayInputStream(bytes), null); JavaClass jc = cp.parse(); if (!jc.isClass()) { return false; } Annotation anns[] = jc.getAnnotations(); if (anns.length == 0) { return false; } boolean couldBeAtAspectJStyle = false; for (int i = 0; i < anns.length; i++) { Annotation ann = anns[i]; if ("Lorg/aspectj/lang/annotation/Aspect;".equals(ann.getTypeSignature())) { couldBeAtAspectJStyle = true; } } if (!couldBeAtAspectJStyle) return false; // ok, so it has the annotation, but it could have been put // on a code style aspect by the annotation visitor Attribute[] attributes = jc.getAttributes(); for (int i = 0; i < attributes.length; i++) { if (attributes[i].getName().equals(Aspect.AttributeName)) { return false; } } return true; } catch (IOException e) { // assume it is one as a best effort return true; } } }
125,295
Bug 125295 fix for bug 58520 caused AJDT test failures
null
resolved fixed
7e40a60
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-26T15:32:48Z
2006-01-26T10:06:40Z
asm/src/org/aspectj/asm/IProgramElement.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * ******************************************************************/ package org.aspectj.asm; import java.io.*; import java.util.*; import org.aspectj.bridge.*; /** * Represents program elements in the AspectJ containment hierarchy. * * @author Mik Kersten */ public interface IProgramElement extends Serializable { public List/*IProgramElement*/ getChildren(); public void setChildren(List children); public void addChild(IProgramElement child); // Extra stuff // Could be just a string but may prove more useful as an object in the long run ... public static class ExtraInformation implements Serializable { private static final long serialVersionUID = -3880735494840820638L; private String extraInfo; public ExtraInformation() { extraInfo = "";} public void setExtraAdviceInformation(String string) {extraInfo = string;} public String getExtraAdviceInformation() {return extraInfo;} public String toString() { return "ExtraInformation: ["+extraInfo+"]"; } } public void setExtraInfo(ExtraInformation info); public ExtraInformation getExtraInfo(); public IProgramElement getParent(); public void setParent(IProgramElement parent); public String getName(); public void setName(String name); public String getDetails(); public void setDetails(String details); public IProgramElement.Kind getKind(); public void setKind(Kind kind); public List getModifiers(); public void setModifiers(int i); public Accessibility getAccessibility(); public String getDeclaringType(); // TODO: remove (Emacs uses it) public String getPackageName(); /** * @param method return types or field types */ public void setCorrespondingType(String returnType); /** * This correponds to both method return types and field types. */ public String getCorrespondingType(); public String getCorrespondingType(boolean getFullyQualifiedType); public String toSignatureString(); public void setRunnable(boolean value); public boolean isRunnable(); public boolean isImplementor(); public void setImplementor(boolean value); public boolean isOverrider(); public void setOverrider(boolean value); public IMessage getMessage(); public void setMessage(IMessage message); public ISourceLocation getSourceLocation(); public void setSourceLocation(ISourceLocation sourceLocation); public String toString(); /** * @return the javadoc comment for this program element, null if not available */ public String getFormalComment(); public void setFormalComment(String comment); /** * Includes information about the origin of the node. */ public String toLinkLabelString(); /** * Includes name, parameter types (if any) and details (if any). */ public String toLabelString(); public List getParameterTypes(); public void setParameterTypes(List list); public List getParameterNames(); public void setParameterNames(List list); /** * The format of the string handle is not specified, but is stable across * compilation sessions. * * @return a string representtaion of this element */ public String getHandleIdentifier(); /** * @return a string representation of this node and all of its children (recursive) */ public String toLongString(); public String getBytecodeName(); public String getBytecodeSignature(); public void setBytecodeName(String bytecodeName); public void setBytecodeSignature(String bytecodeSignature); /** * @return the full signature of this element, as it appears in the source */ public String getSourceSignature(); public void setSourceSignature(String string); public IProgramElement walk(HierarchyWalker walker); /** * Uses "typesafe enum" pattern. */ public static class Modifiers implements Serializable { private static final long serialVersionUID = -8279300899976607927L; public static final Modifiers STATIC = new Modifiers("static"); public static final Modifiers FINAL = new Modifiers("final"); public static final Modifiers ABSTRACT = new Modifiers("abstract"); public static final Modifiers SYNCHRONIZED = new Modifiers("synchronized"); public static final Modifiers VOLATILE = new Modifiers("volatile"); public static final Modifiers STRICTFP = new Modifiers("strictfp"); public static final Modifiers TRANSIENT = new Modifiers("transient"); public static final Modifiers NATIVE = new Modifiers("native"); public static final Modifiers[] ALL = { STATIC, FINAL, ABSTRACT, SYNCHRONIZED, VOLATILE, STRICTFP, TRANSIENT, NATIVE }; private final String name; private Modifiers(String name) { this.name = name; } public String toString() { return name; } // The 4 declarations below are necessary for serialization private static int nextOrdinal = 0; private final int ordinal = nextOrdinal++; private Object readResolve() throws ObjectStreamException { return ALL[ordinal]; } } /** * Uses "typesafe enum" pattern. */ public static class Accessibility implements Serializable { private static final long serialVersionUID = 5371838588180918519L; public static final Accessibility PUBLIC = new Accessibility("public"); public static final Accessibility PACKAGE = new Accessibility("package"); public static final Accessibility PROTECTED = new Accessibility("protected"); public static final Accessibility PRIVATE = new Accessibility("private"); public static final Accessibility PRIVILEGED = new Accessibility("privileged"); public static final Accessibility[] ALL = { PUBLIC, PACKAGE, PROTECTED, PRIVATE, PRIVILEGED }; private final String name; private Accessibility(String name) { this.name = name; } public String toString() { return name; } // The 4 declarations below are necessary for serialization private static int nextOrdinal = 0; private final int ordinal = nextOrdinal++; private Object readResolve() throws ObjectStreamException { return ALL[ordinal]; } } /** * Uses "typesafe enum" pattern. */ public static class Kind implements Serializable { private static final long serialVersionUID = -1963553877479266124L; public static final Kind PROJECT = new Kind("project"); public static final Kind PACKAGE = new Kind("package"); public static final Kind FILE = new Kind("file"); public static final Kind FILE_JAVA = new Kind("java source file"); public static final Kind FILE_ASPECTJ = new Kind("aspect source file"); public static final Kind FILE_LST = new Kind("build configuration file"); public static final Kind IMPORT_REFERENCE = new Kind("import reference"); public static final Kind CLASS = new Kind("class"); public static final Kind INTERFACE = new Kind("interface"); public static final Kind ASPECT = new Kind("aspect"); public static final Kind ENUM = new Kind("enum"); public static final Kind ENUM_VALUE = new Kind("enumvalue"); public static final Kind ANNOTATION = new Kind("annotation"); public static final Kind INITIALIZER = new Kind("initializer"); public static final Kind INTER_TYPE_FIELD = new Kind("inter-type field"); public static final Kind INTER_TYPE_METHOD = new Kind("inter-type method"); public static final Kind INTER_TYPE_CONSTRUCTOR = new Kind("inter-type constructor"); public static final Kind INTER_TYPE_PARENT = new Kind("inter-type parent"); public static final Kind CONSTRUCTOR = new Kind("constructor"); public static final Kind METHOD = new Kind("method"); public static final Kind FIELD = new Kind("field"); public static final Kind POINTCUT = new Kind("pointcut"); public static final Kind ADVICE = new Kind("advice"); public static final Kind DECLARE_PARENTS = new Kind("declare parents"); public static final Kind DECLARE_WARNING = new Kind("declare warning"); public static final Kind DECLARE_ERROR = new Kind("declare error"); public static final Kind DECLARE_SOFT = new Kind("declare soft"); public static final Kind DECLARE_PRECEDENCE= new Kind("declare precedence"); public static final Kind CODE = new Kind("code"); public static final Kind ERROR = new Kind("error"); public static final Kind DECLARE_ANNOTATION_AT_CONSTRUCTOR = new Kind("declare @constructor"); public static final Kind DECLARE_ANNOTATION_AT_FIELD = new Kind("declare @field"); public static final Kind DECLARE_ANNOTATION_AT_METHOD = new Kind("declare @method"); public static final Kind DECLARE_ANNOTATION_AT_TYPE = new Kind("declare @type"); public static final Kind[] ALL = { PROJECT, PACKAGE, FILE, FILE_JAVA, FILE_ASPECTJ, FILE_LST, IMPORT_REFERENCE, CLASS, INTERFACE, ASPECT, ENUM, ENUM_VALUE, ANNOTATION, INITIALIZER, INTER_TYPE_FIELD, INTER_TYPE_METHOD, INTER_TYPE_CONSTRUCTOR, INTER_TYPE_PARENT, CONSTRUCTOR, METHOD, FIELD, POINTCUT, ADVICE, DECLARE_PARENTS, DECLARE_WARNING, DECLARE_ERROR, DECLARE_SOFT, DECLARE_PRECEDENCE, CODE, ERROR, DECLARE_ANNOTATION_AT_CONSTRUCTOR, DECLARE_ANNOTATION_AT_FIELD, DECLARE_ANNOTATION_AT_METHOD, DECLARE_ANNOTATION_AT_TYPE }; public static Kind getKindForString(String kindString) { for (int i = 0; i < ALL.length; i++) { if (ALL[i].toString().equals(kindString)) return ALL[i]; } return ERROR; } private final String name; private Kind(String name) { this.name = name; } public String toString() { return name; } public static List getNonAJMemberKinds() { List list = new ArrayList(); list.add(METHOD); list.add(ENUM_VALUE); list.add(FIELD); list.add(CONSTRUCTOR); return list; } public boolean isMember() { return this == FIELD || this == METHOD || this == CONSTRUCTOR || this == POINTCUT || this == ADVICE || this == ENUM_VALUE; } public boolean isInterTypeMember() { return this == INTER_TYPE_CONSTRUCTOR || this == INTER_TYPE_FIELD || this == INTER_TYPE_METHOD; } public boolean isType() { return this == CLASS || this == INTERFACE || this == ASPECT || this == ANNOTATION || this == ENUM; } public boolean isSourceFile() { return this == FILE_ASPECTJ || this == FILE_JAVA; } public boolean isDeclare() { return name.startsWith("declare"); } public boolean isDeclareAnnotation() { return name.startsWith("declare @"); } // The 4 declarations below are necessary for serialization private static int nextOrdinal = 0; private final int ordinal = nextOrdinal++; private Object readResolve() throws ObjectStreamException { return ALL[ordinal]; } } }
125,295
Bug 125295 fix for bug 58520 caused AJDT test failures
null
resolved fixed
7e40a60
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-26T15:32:48Z
2006-01-26T10:06:40Z
asm/src/org/aspectj/asm/internal/ProgramElement.java
/* ******************************************************************* * Copyright (c) 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Mik Kersten initial implementation * Andy Clement Extensions for better IDE representation * ******************************************************************/ package org.aspectj.asm.internal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.aspectj.asm.AsmManager; import org.aspectj.asm.HierarchyWalker; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; /** * @author Mik Kersten */ public class ProgramElement implements IProgramElement { private static final long serialVersionUID = 171673495267384449L; protected IProgramElement parent = null; protected String name = ""; // children.listIterator() should support remove() operation protected List children = new ArrayList(); protected IMessage message = null; protected ISourceLocation sourceLocation = null; private List modifiers = new ArrayList(); private List relations = new ArrayList(); private Kind kind; private Accessibility accessibility; private String declaringType = ""; private String formalComment = ""; //private String packageName = null; private boolean runnable = false; private boolean implementor = false; private boolean overrider = false; private String bytecodeName; private String bytecodeSignature; // private String fullSignature; private String returnType; private List parameterNames = null; private List parameterTypes = null; private String details = null; private ExtraInformation info; /** * Used during de-externalization. */ public ProgramElement() { } /** * Use to create program element nodes that do not correspond to source locations. */ public ProgramElement( String name, Kind kind, List children) { this.name = name; this.kind = kind; setChildren(children); } public ProgramElement( String name, IProgramElement.Kind kind, ISourceLocation sourceLocation, int modifiers, String formalComment, List children) { this(name, kind, children); this.sourceLocation = sourceLocation; this.kind = kind; this.formalComment = formalComment; this.modifiers = genModifiers(modifiers); this.accessibility = genAccessibility(modifiers); cacheByHandle(); } /** * Use to create program element nodes that correspond to source locations. */ public ProgramElement( String name, Kind kind, int modifiers, Accessibility accessibility, String declaringType, String packageName, String formalComment, ISourceLocation sourceLocation, List relations, List children, boolean member) { this(name, kind, children); this.sourceLocation = sourceLocation; this.kind = kind; this.modifiers = genModifiers(modifiers); this.accessibility = accessibility; this.declaringType = declaringType; //this.packageName = packageName; this.formalComment = formalComment; this.relations = relations; cacheByHandle(); } public List getModifiers() { return modifiers; } public Accessibility getAccessibility() { return accessibility; } public void setAccessibility(Accessibility a) { accessibility=a; } public String getDeclaringType() { return declaringType; } public String getPackageName() { if (kind == Kind.PACKAGE) return getName(); if (getParent() == null || !(getParent() instanceof IProgramElement)) { return ""; } return ((IProgramElement)getParent()).getPackageName(); } public Kind getKind() { return kind; } public boolean isCode() { return kind.equals(Kind.CODE); } public ISourceLocation getSourceLocation() { return sourceLocation; } public void setSourceLocation(ISourceLocation sourceLocation) { this.sourceLocation = sourceLocation; } public IMessage getMessage() { return message; } public void setMessage(IMessage message) { this.message = message; } public IProgramElement getParent() { return parent; } public void setParent(IProgramElement parent) { this.parent = parent; } public boolean isMemberKind() { return kind.isMember(); } public void setRunnable(boolean value) { this.runnable = value; } public boolean isRunnable() { return runnable; } public boolean isImplementor() { return implementor; } public void setImplementor(boolean value) { this.implementor = value; } public boolean isOverrider() { return overrider; } public void setOverrider(boolean value) { this.overrider = value; } public List getRelations() { return relations; } public void setRelations(List relations) { if (relations.size() > 0) { this.relations = relations; } } public String getFormalComment() { return formalComment; } public String toString() { return toLabelString(); } private static List genModifiers(int modifiers) { List modifiersList = new ArrayList(); if ((modifiers & AccStatic) != 0) modifiersList.add(IProgramElement.Modifiers.STATIC); if ((modifiers & AccFinal) != 0) modifiersList.add(IProgramElement.Modifiers.FINAL); if ((modifiers & AccSynchronized) != 0) modifiersList.add(IProgramElement.Modifiers.SYNCHRONIZED); if ((modifiers & AccVolatile) != 0) modifiersList.add(IProgramElement.Modifiers.VOLATILE); if ((modifiers & AccTransient) != 0) modifiersList.add(IProgramElement.Modifiers.TRANSIENT); if ((modifiers & AccNative) != 0) modifiersList.add(IProgramElement.Modifiers.NATIVE); if ((modifiers & AccAbstract) != 0) modifiersList.add(IProgramElement.Modifiers.ABSTRACT); return modifiersList; } public static IProgramElement.Accessibility genAccessibility(int modifiers) { if ((modifiers & AccPublic) != 0) return IProgramElement.Accessibility.PUBLIC; if ((modifiers & AccPrivate) != 0) return IProgramElement.Accessibility.PRIVATE; if ((modifiers & AccProtected) != 0) return IProgramElement.Accessibility.PROTECTED; if ((modifiers & AccPrivileged) != 0) return IProgramElement.Accessibility.PRIVILEGED; else return IProgramElement.Accessibility.PACKAGE; } // XXX these names and values are from org.eclipse.jdt.internal.compiler.env.IConstants private static int AccPublic = 0x0001; private static int AccPrivate = 0x0002; private static int AccProtected = 0x0004; private static int AccPrivileged = 0x0006; // XXX is this right? private static int AccStatic = 0x0008; private static int AccFinal = 0x0010; private static int AccSynchronized = 0x0020; private static int AccVolatile = 0x0040; private static int AccTransient = 0x0080; private static int AccNative = 0x0100; // private static int AccInterface = 0x0200; private static int AccAbstract = 0x0400; // private static int AccStrictfp = 0x0800; private String sourceSignature; public String getBytecodeName() { return bytecodeName; } public String getBytecodeSignature() { return bytecodeSignature; } public void setBytecodeName(String bytecodeName) { this.bytecodeName = bytecodeName; } public void setBytecodeSignature(String bytecodeSignature) { this.bytecodeSignature = bytecodeSignature; } public String getSourceSignature() { return sourceSignature; } public void setSourceSignature(String string) { sourceSignature = string; } public void setKind(Kind kind) { this.kind = kind; } public void setCorrespondingType(String returnType) { this.returnType = returnType; } public String getCorrespondingType() { return getCorrespondingType(false); } public String getCorrespondingType(boolean getFullyQualifiedType) { if (getFullyQualifiedType) { return returnType; } int index = returnType.lastIndexOf("."); if (index != -1) { return returnType.substring(index); } return returnType; } public String getName() { return name; } public List getChildren() { return children; } public void setChildren(List children) { this.children = children; if (children == null) return; for (Iterator it = children.iterator(); it.hasNext(); ) { ((IProgramElement)it.next()).setParent(this); } } public void addChild(IProgramElement child) { if (children == null) { children = new ArrayList(); } children.add(child); child.setParent(this); } public void addChild(int position, IProgramElement child) { if (children == null) { children = new ArrayList(); } children.add(position, child); child.setParent(this); } public boolean removeChild(IProgramElement child) { child.setParent(null); return children.remove(child); } public void setName(String string) { name = string; } public IProgramElement walk(HierarchyWalker walker) { if (children!=null) { for (Iterator it = children.iterator(); it.hasNext(); ) { IProgramElement child = (IProgramElement)it.next(); walker.process(child); } } return this; } public String toLongString() { final StringBuffer buffer = new StringBuffer(); HierarchyWalker walker = new HierarchyWalker() { private int depth = 0; public void preProcess(IProgramElement node) { for (int i = 0; i < depth; i++) buffer.append(' '); buffer.append(node.toString()); buffer.append('\n'); depth += 2; } public void postProcess(IProgramElement node) { depth -= 2; } }; walker.process(this); return buffer.toString(); } public void setModifiers(int i) { this.modifiers = genModifiers(i); } public String toSignatureString() { StringBuffer sb = new StringBuffer(); sb.append(name); if (parameterTypes != null ) { sb.append('('); for (Iterator it = parameterTypes.iterator(); it.hasNext(); ) { sb.append((String)it.next()); if (it.hasNext()) sb.append(", "); } sb.append(')'); } return sb.toString(); } public static boolean shortITDNames = true; /** * TODO: move the "parent != null"==>injar heuristic to more explicit */ public String toLinkLabelString() { String label; if (kind == Kind.CODE || kind == Kind.INITIALIZER) { label = parent.getParent().getName() + ": "; } else if (kind.isInterTypeMember()) { if (shortITDNames) { // if (name.indexOf('.')!=-1) return toLabelString().substring(name.indexOf('.')+1); label=""; } else { int dotIndex = name.indexOf('.'); if (dotIndex != -1) { return parent.getName() + ": " + toLabelString().substring(dotIndex+1); } else { label = parent.getName() + '.'; } } } else if (kind == Kind.CLASS || kind == Kind.ASPECT || kind == Kind.INTERFACE) { label = ""; } else if (kind.equals(Kind.DECLARE_PARENTS)) { label = ""; } else { if (parent != null) { label = parent.getName() + '.'; } else { label = "injar aspect: "; } } label += toLabelString(); return label; } public String toLabelString() { String label = toSignatureString(); if (details != null) { label += ": " + details; } return label; } private String handle = null; public String getHandleIdentifier() { if (null == handle) { if (sourceLocation != null) { return AsmManager.getDefault().getHandleProvider().createHandleIdentifier(sourceLocation); // return genHandleIdentifier(sourceLocation); } } return handle; } public List getParameterNames() { return parameterNames; } public List getParameterTypes() { return parameterTypes; } public void setParameterNames(List list) { parameterNames = list; } public void setParameterTypes(List list) { parameterTypes = list; } public String getDetails() { return details; } public void setDetails(String string) { details = string; } public void setFormalComment(String formalComment) { this.formalComment = formalComment; } /** AMC added to speed up findByHandle lookups in AspectJElementHierarchy */ private void cacheByHandle() { String handle = getHandleIdentifier(); if (handle != null) { AspectJElementHierarchy hierarchy = (AspectJElementHierarchy) AsmManager.getDefault().getHierarchy(); hierarchy.cache(handle,this); } } public void setExtraInfo(ExtraInformation info) { this.info = info; } public ExtraInformation getExtraInfo() { return info; } }
125,295
Bug 125295 fix for bug 58520 caused AJDT test failures
null
resolved fixed
7e40a60
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-26T15:32:48Z
2006-01-26T10:06:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ style * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.util.ArrayList; import java.util.List; import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration; import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeConstructorDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration; import org.aspectj.ajdt.internal.compiler.ast.InterTypeMethodDeclaration; import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.asm.IProgramElement; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.DeclareSoft; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.ReferencePointcut; import org.aspectj.weaver.patterns.TypePattern; import org.aspectj.weaver.patterns.TypePatternList; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; /** * @author Mik Kersten */ public class AsmElementFormatter { public static final String DECLARE_PRECEDENCE = "precedence"; public static final String DECLARE_SOFT = "soft"; public static final String DECLARE_PARENTS = "parents"; public static final String DECLARE_WARNING = "warning"; public static final String DECLARE_ERROR = "error"; public static final String DECLARE_UNKNONWN = "<unknown declare>"; public static final String POINTCUT_ABSTRACT = "<abstract pointcut>"; public static final String POINTCUT_ANONYMOUS = "<anonymous pointcut>"; public static final int MAX_MESSAGE_LENGTH = 18; public static final String DEC_LABEL = "declare"; public void genLabelAndKind(MethodDeclaration methodDeclaration, IProgramElement node) { if (methodDeclaration instanceof AdviceDeclaration) { AdviceDeclaration ad = (AdviceDeclaration)methodDeclaration; node.setKind(IProgramElement.Kind.ADVICE); if (ad.kind == AdviceKind.Around) { node.setCorrespondingType(ad.returnType.toString()); //returnTypeToString(0)); } String details = ""; if (ad.pointcutDesignator != null) { if (ad.pointcutDesignator.getPointcut() instanceof ReferencePointcut) { ReferencePointcut rp = (ReferencePointcut)ad.pointcutDesignator.getPointcut(); details += rp.name + ".."; } else if (ad.pointcutDesignator.getPointcut() instanceof AndPointcut) { AndPointcut ap = (AndPointcut)ad.pointcutDesignator.getPointcut(); if (ap.getLeft() instanceof ReferencePointcut) { details += ap.getLeft().toString() + ".."; } else { details += POINTCUT_ANONYMOUS + ".."; } } else if (ad.pointcutDesignator.getPointcut() instanceof OrPointcut) { OrPointcut op = (OrPointcut)ad.pointcutDesignator.getPointcut(); if (op.getLeft() instanceof ReferencePointcut) { details += op.getLeft().toString() + ".."; } else { details += POINTCUT_ANONYMOUS + ".."; } } else { details += POINTCUT_ANONYMOUS; } } else { details += POINTCUT_ABSTRACT; } node.setName(ad.kind.toString()); node.setDetails(details); setParameters(methodDeclaration, node); } else if (methodDeclaration instanceof PointcutDeclaration) { PointcutDeclaration pd = (PointcutDeclaration)methodDeclaration; node.setKind(IProgramElement.Kind.POINTCUT); node.setName(translatePointcutName(new String(methodDeclaration.selector))); setParameters(methodDeclaration, node); } else if (methodDeclaration instanceof DeclareDeclaration) { DeclareDeclaration declare = (DeclareDeclaration)methodDeclaration; String name = DEC_LABEL + " "; if (declare.declareDecl instanceof DeclareErrorOrWarning) { DeclareErrorOrWarning deow = (DeclareErrorOrWarning)declare.declareDecl; if (deow.isError()) { node.setKind( IProgramElement.Kind.DECLARE_ERROR); name += DECLARE_ERROR; } else { node.setKind( IProgramElement.Kind.DECLARE_WARNING); name += DECLARE_WARNING; } node.setName(name) ; node.setDetails("\"" + genDeclareMessage(deow.getMessage()) + "\""); } else if (declare.declareDecl instanceof DeclareParents) { node.setKind( IProgramElement.Kind.DECLARE_PARENTS); DeclareParents dp = (DeclareParents)declare.declareDecl; node.setName(name + DECLARE_PARENTS); String kindOfDP = null; StringBuffer details = new StringBuffer(""); TypePattern[] newParents = dp.getParents().getTypePatterns(); for (int i = 0; i < newParents.length; i++) { TypePattern tp = newParents[i]; UnresolvedType tx = tp.getExactType(); if (kindOfDP == null) { kindOfDP = "implements "; try { ResolvedType rtx = tx.resolve(((AjLookupEnvironment)declare.scope.environment()).factory.getWorld()); if (!rtx.isInterface()) kindOfDP = "extends "; } catch (Throwable t) { // What can go wrong???? who knows! } } String typename= tp.toString(); if (typename.lastIndexOf(".")!=-1) { typename=typename.substring(typename.lastIndexOf(".")+1); } details.append(typename); if ((i+1)<newParents.length) details.append(","); } node.setDetails(kindOfDP+details.toString()); } else if (declare.declareDecl instanceof DeclareSoft) { node.setKind( IProgramElement.Kind.DECLARE_SOFT); DeclareSoft ds = (DeclareSoft)declare.declareDecl; node.setName(name + DECLARE_SOFT); node.setDetails(genTypePatternLabel(ds.getException())); } else if (declare.declareDecl instanceof DeclarePrecedence) { node.setKind( IProgramElement.Kind.DECLARE_PRECEDENCE); DeclarePrecedence ds = (DeclarePrecedence)declare.declareDecl; node.setName(name + DECLARE_PRECEDENCE); node.setDetails(genPrecedenceListLabel(ds.getPatterns())); } else if (declare.declareDecl instanceof DeclareAnnotation) { DeclareAnnotation deca = (DeclareAnnotation)declare.declareDecl; String thekind = deca.getKind().toString(); node.setName(name+"@"+thekind.substring(3)); if (deca.getKind()==DeclareAnnotation.AT_CONSTRUCTOR) { node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR); } else if (deca.getKind()==DeclareAnnotation.AT_FIELD) { node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_FIELD); } else if (deca.getKind()==DeclareAnnotation.AT_METHOD) { node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD); } else if (deca.getKind()==DeclareAnnotation.AT_TYPE) { node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE); } node.setDetails(genDecaLabel(deca)); } else { node.setKind(IProgramElement.Kind.ERROR); node.setName(DECLARE_UNKNONWN); } } else if (methodDeclaration instanceof InterTypeDeclaration) { InterTypeDeclaration itd = (InterTypeDeclaration)methodDeclaration; String name = itd.getOnType().toString() + "." + new String(itd.getDeclaredSelector()); if (methodDeclaration instanceof InterTypeFieldDeclaration) { node.setKind(IProgramElement.Kind.INTER_TYPE_FIELD); node.setName(name); } else if (methodDeclaration instanceof InterTypeMethodDeclaration) { node.setKind(IProgramElement.Kind.INTER_TYPE_METHOD); node.setName(name); } else if (methodDeclaration instanceof InterTypeConstructorDeclaration) { node.setKind(IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR); // StringBuffer argumentsSignature = new StringBuffer("fubar"); // argumentsSignature.append("("); // if (methodDeclaration.arguments!=null && methodDeclaration.arguments.length>1) { // // for (int i = 1;i<methodDeclaration.arguments.length;i++) { // argumentsSignature.append(methodDeclaration.arguments[i]); // if (i+1<methodDeclaration.arguments.length) argumentsSignature.append(","); // } // } // argumentsSignature.append(")"); // InterTypeConstructorDeclaration itcd = (InterTypeConstructorDeclaration)methodDeclaration; node.setName(itd.getOnType().toString() + "." + itd.getOnType().toString()/*+argumentsSignature.toString()*/); } else { node.setKind(IProgramElement.Kind.ERROR); node.setName(name); } node.setCorrespondingType(itd.returnType.toString()); if (node.getKind() != IProgramElement.Kind.INTER_TYPE_FIELD) { setParameters(methodDeclaration, node); } } else { if (methodDeclaration.isConstructor()) { node.setKind(IProgramElement.Kind.CONSTRUCTOR); } else { node.setKind(IProgramElement.Kind.METHOD); //TODO AV - could speed up if we could dig only for @Aspect declaring types (or aspect if mixed style allowed) //??? how to : node.getParent().getKind().equals(IProgramElement.Kind.ASPECT)) { if (true && methodDeclaration.annotations != null) { for (int i = 0; i < methodDeclaration.annotations.length; i++) { //Note: AV: implicit single advice type support here (should be enforced somewhere as well (APT etc)) Annotation annotation = methodDeclaration.annotations[i]; String annotationSig = new String(annotation.type.getTypeBindingPublic(methodDeclaration.scope).signature()); if ("Lorg/aspectj/lang/annotation/Pointcut;".equals(annotationSig)) { node.setKind(IProgramElement.Kind.POINTCUT); break; } else if ("Lorg/aspectj/lang/annotation/Before;".equals(annotationSig) || "Lorg/aspectj/lang/annotation/After;".equals(annotationSig) || "Lorg/aspectj/lang/annotation/AfterReturning;".equals(annotationSig) || "Lorg/aspectj/lang/annotation/AfterThrowing;".equals(annotationSig) || "Lorg/aspectj/lang/annotation/Around;".equals(annotationSig)) { node.setKind(IProgramElement.Kind.ADVICE); //TODO AV - all are considered anonymous - is that ok? node.setDetails(POINTCUT_ANONYMOUS); break; } } } } node.setName(new String(methodDeclaration.selector)); setParameters(methodDeclaration, node); } } private String genDecaLabel(DeclareAnnotation deca) { StringBuffer sb = new StringBuffer(""); sb.append(deca.getPatternAsString()); sb.append(" : "); sb.append(deca.getAnnotationString()); return sb.toString(); } private String genPrecedenceListLabel(TypePatternList list) { String tpList = ""; for (int i = 0; i < list.size(); i++) { tpList += genTypePatternLabel(list.get(i)); if (i < list.size()-1) tpList += ", "; } return tpList; } // private String genArguments(MethodDeclaration md) { // String args = ""; // Argument[] argArray = md.arguments; // if (argArray == null) return args; // for (int i = 0; i < argArray.length; i++) { // String argName = new String(argArray[i].name); // String argType = argArray[i].type.toString(); // if (acceptArgument(argName, argType)) { // args += argType + ", "; // } // } // int lastSepIndex = args.lastIndexOf(','); // if (lastSepIndex != -1 && args.endsWith(", ")) args = args.substring(0, lastSepIndex); // return args; // } private void setParameters(MethodDeclaration md, IProgramElement pe) { Argument[] argArray = md.arguments; List names = new ArrayList(); List types = new ArrayList(); pe.setParameterNames(names); pe.setParameterTypes(types); if (argArray == null) return; for (int i = 0; i < argArray.length; i++) { String argName = new String(argArray[i].name); String argType = argArray[i].type.resolvedType.debugName(); if (acceptArgument(argName, argType)) { names.add(argName); types.add(argType); } } } // TODO: fix this way of determing ajc-added arguments, make subtype of Argument with extra info private boolean acceptArgument(String name, String type) { return !name.startsWith("ajc$this_") && !type.equals("org.aspectj.lang.JoinPoint.StaticPart") && !type.equals("org.aspectj.lang.JoinPoint") && !type.equals("org.aspectj.runtime.internal.AroundClosure"); } public String genTypePatternLabel(TypePattern tp) { final String TYPE_PATTERN_LITERAL = "<type pattern>"; String label; UnresolvedType typeX = tp.getExactType(); if (!ResolvedType.isMissing(typeX)) { label = typeX.getName(); if (tp.isIncludeSubtypes()) label += "+"; } else { label = TYPE_PATTERN_LITERAL; } return label; } public String genDeclareMessage(String message) { int length = message.length(); if (length < MAX_MESSAGE_LENGTH) { return message; } else { return message.substring(0, MAX_MESSAGE_LENGTH-1) + ".."; } } // // TODO: // private String translateAdviceName(String label) { // if (label.indexOf("before") != -1) return "before"; // if (label.indexOf("returning") != -1) return "after returning"; // if (label.indexOf("after") != -1) return "after"; // if (label.indexOf("around") != -1) return "around"; // else return "<advice>"; // } // // !!! move or replace // private String translateDeclareName(String name) { // int colonIndex = name.indexOf(":"); // if (colonIndex != -1) { // return name.substring(0, colonIndex); // } else { // return name; // } // } // !!! move or replace // private String translateInterTypeDecName(String name) { // int index = name.lastIndexOf('$'); // if (index != -1) { // return name.substring(index+1); // } else { // return name; // } // } // !!! move or replace private String translatePointcutName(String name) { int index = name.indexOf("$$")+2; int endIndex = name.lastIndexOf('$'); if (index != -1 && endIndex != -1) { return name.substring(index, endIndex); } else { return name; } } }
125,295
Bug 125295 fix for bug 58520 caused AJDT test failures
null
resolved fixed
7e40a60
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-26T15:32:48Z
2006-01-26T10:06:40Z
tests/bugs151/pr125295/pkg/C.java
125,295
Bug 125295 fix for bug 58520 caused AJDT test failures
null
resolved fixed
7e40a60
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-26T15:32:48Z
2006-01-26T10:06:40Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import junit.framework.Test; import org.aspectj.systemtest.ajc150.GenericsTests; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");} public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");} public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");} public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");} public void testMixingNumbersOfTypeParameters_pr125080() { runTest("mixing numbers of type parameters"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;"); } public void testMixingNumbersOfTypeParameters_pr125080_2() { runTest("mixing numbers of type parameters - 2"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;"); } ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
121,395
Bug 121395 invalid aspectj path throws filenotfoundexception
An invalid aspectj path (missing jar file) throws an filenotfoundexception: java.io.FileNotFoundException at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:106) at org.aspectj.weaver.bcel.BcelWeaver.addAspectsFromJarFile(BcelWeaver.java:202) at org.aspectj.weaver.bcel.BcelWeaver.addLibraryJarFile(BcelWeaver.java:192) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.initBcelWorld(AjBuildManager.java:623) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:209) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) FileNotFoundException thrown: /Users/frankstolle/Documents/workspace/lib_aspects/deploy/lib_aspects.jar (No such file or directory) should generate an problem entry in the problems-list.
resolved fixed
551b446
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-27T12:30:21Z
2005-12-19T11:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.ICompilerAdapter; import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.CountingMessageHandler; import org.aspectj.bridge.ILifecycleAware; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.Version; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextFormatter; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathDirectory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.util.FileUtil; import org.aspectj.weaver.Dump; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.core.runtime.OperationCanceledException; //import org.aspectj.org.eclipse.jdt.internal.compiler.util.HashtableOfObject; public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory { private static final String CROSSREFS_FILE_NAME = "build.lst"; private static final String CANT_WRITE_RESULT = "unable to write compilation result"; private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; static final boolean COPY_INPATH_DIR_RESOURCES = false; static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false; private static final FileFilter binarySourceFilter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".class"); }}; /** * This builder is static so that it can be subclassed and reset. However, note * that there is only one builder present, so if two extendsion reset it, only * the latter will get used. */ private static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder(); static { CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter()); CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter()); } private IProgressListener progressListener = null; private int compiledCount; private int sourceFileCount; private JarOutputStream zos; private boolean batchCompile = true; private INameEnvironment environment; private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap(); // FIXME asc should this really be in here? private IHierarchy structureModel; public AjBuildConfig buildConfig; private List aspectNames = new LinkedList(); AjState state = new AjState(this); public BcelWeaver getWeaver() { return state.getWeaver();} public BcelWorld getBcelWorld() { return state.getBcelWorld();} public CountingMessageHandler handler; public AjBuildManager(IMessageHandler holder) { super(); this.handler = CountingMessageHandler.makeCountingMessageHandler(holder); } /** @return true if we should generate a model as a side-effect */ public boolean doGenerateModel() { return buildConfig.isGenerateModelMode(); } public boolean batchBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, true); } public boolean incrementalBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, false); } /** @throws AbortException if check for runtime fails */ protected boolean doBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler, boolean batch) throws IOException, AbortException { boolean ret = true; batchCompile = batch; if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware)baseHandler).buildStarting(!batch); } int phase = batch ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD; ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase ,buildConfig); try { if (batch) { this.state = new AjState(this); } boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !batch) { // retry as batch? CompilationAndWeavingContext.leavingPhase(ct); return doBuild(buildConfig, baseHandler, true); } this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler); // XXX duplicate, no? remove? String check = checkRtJar(buildConfig); if (check != null) { if (FAIL_IF_RUNTIME_NOT_FOUND) { MessageUtil.error(handler, check); CompilationAndWeavingContext.leavingPhase(ct); return false; } else { MessageUtil.warn(handler, check); } } // if (batch) { setBuildConfig(buildConfig); //} if (batch || !AsmManager.attemptIncrementalModelRepairs) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(buildConfig); // } } if (batch) { initBcelWorld(handler); } if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } } if (batch) { // System.err.println("XXXX batch: " + buildConfig.getFiles()); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { getWorld().setModel(AsmManager.getDefault().getHierarchy()); // in incremental build, only get updated model? } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); performCompilation(buildConfig.getFiles()); if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After a batch build"); } else { // done already? // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { // bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel()); // } // System.err.println("XXXX start inc "); binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); List files = state.getFilesToCompile(true); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles); boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); for (int i = 0; (i < 5) && hereWeGoAgain; i++) { // System.err.println("XXXX inc: " + files); performCompilation(files); if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false); files = state.getFilesToCompile(false); hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); // TODO Andy - Needs some thought here... // I think here we might want to pass empty addedFiles/deletedFiles as they were // dealt with on the first call to processDelta - we are going through this loop // again because in compiling something we found something else we needed to // rebuild. But what case causes this? if (hereWeGoAgain) { if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.addedFiles,state.deletedFiles); } } if (!files.isEmpty()) { CompilationAndWeavingContext.leavingPhase(ct); return batchBuild(buildConfig, baseHandler); } else { if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After an incremental build"); } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(); } // for bug 113554: support ajsym file generation for command line builds if (buildConfig.isGenerateCrossRefsMode()) { String configFileProxy = buildConfig.getOutputDir().getAbsolutePath() + File.separator + CROSSREFS_FILE_NAME; AsmManager.getDefault().writeStructureModel(configFileProxy); } // have to tell state we succeeded or next is not incremental state.successfulCompile(buildConfig,batch); copyResourcesToDestination(); if (buildConfig.getOutxmlName() != null) { writeOutxmlFile(); } /*boolean weaved = *///weaveAndGenerateClassFiles(); // if not weaved, then no-op build, no model changes // but always returns true // XXX weaved not in Mik's incremental if (buildConfig.isGenerateModelMode()) { AsmManager.getDefault().fireModelUpdated(); } CompilationAndWeavingContext.leavingPhase(ct); } finally { if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware)baseHandler).buildFinished(!batch); } if (zos != null) { closeOutputStream(buildConfig.getOutputJar()); } ret = !handler.hasErrors(); if (getBcelWorld()!=null) getBcelWorld().tidyUp(); // bug 59895, don't release reference to handler as may be needed by a nested call //handler = null; } return ret; } private boolean openOutputStream(File outJar) { try { OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar()); zos = new JarOutputStream(os,getWeaver().getManifest(true)); } catch (IOException ex) { IMessage message = new Message("Unable to open outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); return false; } return true; } private void closeOutputStream(File outJar) { try { if (zos != null) zos.close(); zos = null; /* Ensure we don't write an incomplete JAR bug-71339 */ if (handler.hasErrors()) { outJar.delete(); } } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); } } private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); copyResourcesFromJarFile(inJar); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (inPathElement.isDirectory()) { copyResourcesFromDirectory(inPathElement); } else { copyResourcesFromJarFile(inPathElement); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) { String resource = (String)i.next(); File from = (File)buildConfig.getSourcePathResources().get(resource); copyResourcesFromFile(from,resource,from); } } writeManifest(); } private void copyResourcesFromJarFile(File jarFile) throws IOException { JarInputStream inStream = null; try { inStream = new JarInputStream(new FileInputStream(jarFile)); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; String filename = entry.getName(); // System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'"); if (!entry.isDirectory() && acceptResource(filename)) { byte[] bytes = FileUtil.readAsByteArray(inStream); writeResource(filename,bytes,jarFile); } inStream.closeEntry(); } } finally { if (inStream != null) inStream.close(); } } private void copyResourcesFromDirectory(File dir) throws IOException { if (!COPY_INPATH_DIR_RESOURCES) return; // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(dir,new FileFilter() { public boolean accept(File f) { boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ; return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = files[i].getAbsolutePath().substring( dir.getAbsolutePath().length()+1); copyResourcesFromFile(files[i],filename,dir); } } private void copyResourcesFromFile(File f,String filename,File src) throws IOException { if (!acceptResource(filename)) return; FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); writeResource(filename,bytes,src); } finally { if (fis != null) fis.close(); } } private void writeResource(String filename, byte[] content, File srcLocation) throws IOException { if (state.resources.contains(filename)) { IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); return; } if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(content); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename)); fos.write(content); fos.close(); } state.resources.add(filename); } /* * If we are writing to an output directory copy the manifest but only * if we already have one */ private void writeManifest () throws IOException { Manifest manifest = getWeaver().getManifest(false); if (manifest != null && zos == null) { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME)); manifest.write(fos); fos.close(); } } private boolean acceptResource(String resourceName) { if ( (resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS")) || (resourceName.endsWith(".class")) || (resourceName.toUpperCase().equals(MANIFEST_NAME)) ) { return false; } else { return true; } } private void writeOutxmlFile () throws IOException { String filename = buildConfig.getOutxmlName(); // System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename); // System.err.println("? AjBuildManager.writeOutxmlFile() outputDir=" + buildConfig.getOutputDir()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ps.println("<aspectj>"); ps.println("<aspects>"); for (Iterator i = aspectNames.iterator(); i.hasNext();) { String name = (String)i.next(); ps.println("<aspect name=\"" + name + "\"/>"); } ps.println("</aspects>"); ps.println("</aspectj>"); ps.println(); ps.close(); if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); zos.putNextEntry(newEntry); zos.write(baos.toByteArray()); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename)); fos.write(baos.toByteArray()); fos.close(); } } // public static void dumprels() { // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); // int ctr = 1; // Set entries = irm.getEntries(); // for (Iterator iter = entries.iterator(); iter.hasNext();) { // String hid = (String) iter.next(); // List rels = irm.get(hid); // for (Iterator iterator = rels.iterator(); iterator.hasNext();) { // IRelationship ir = (IRelationship) iterator.next(); // List targets = ir.getTargets(); // for (Iterator iterator2 = targets.iterator(); // iterator2.hasNext(); // ) { // String thid = (String) iterator2.next(); // System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid); // } // } // } // } /** * Responsible for managing the ASM model between builds. Contains the policy for * maintaining the persistance of elements in the model. * * This code is driven before each 'fresh' (batch) build to create * a new model. */ private void setupModel(AjBuildConfig config) { AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode()); if (!AsmManager.isCreatingModel()) return; AsmManager.getDefault().createNewASM(); // AsmManager.getDefault().getRelationshipMap().clear(); IHierarchy model = AsmManager.getDefault().getHierarchy(); String rootLabel = "<root>"; IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA; if (buildConfig.getConfigFile() != null) { rootLabel = buildConfig.getConfigFile().getName(); model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath()); kind = IProgramElement.Kind.FILE_LST; } model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList())); model.setFileMap(new HashMap()); setStructureModel(model); state.setStructureModel(model); state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap()); } // // private void dumplist(List l) { // System.err.println("---- "+l.size()); // for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i)); // } // private void accumulateFileNodes(IProgramElement ipe,List store) { // if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA || // ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) { // if (!ipe.getName().equals("<root>")) { // store.add(ipe); // return; // } // } // for (Iterator i = ipe.getChildren().iterator();i.hasNext();) { // accumulateFileNodes((IProgramElement)i.next(),store); // } // } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { List cp = buildConfig.getBootclasspath(); cp.addAll(buildConfig.getClasspath()); BcelWorld bcelWorld = new BcelWorld(cp, handler, null); bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way()); bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel()); bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints()); bcelWorld.setXnoInline(buildConfig.isXnoInline()); bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp()); bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled()); bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint()); BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld); state.setWorld(bcelWorld); state.setWeaver(bcelWeaver); state.binarySourceFiles = new HashMap(); for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) { File f = (File) i.next(); bcelWeaver.addLibraryJarFile(f); } // String lintMode = buildConfig.getLintMode(); if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) { bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(buildConfig.getLintMode()); } if (buildConfig.getLintSpecFile() != null) { bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile()); } //??? incremental issues for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false); state.binarySourceFiles.put(inJar.getPath(), unwovenClasses); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory()) { // its a jar file on the inpath // the weaver method can actually handle dirs, but we don't call it, see next block List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true); state.binarySourceFiles.put(inPathElement.getPath(),unwovenClasses); } else { // add each class file in an in-dir individually, this gives us the best error reporting // (they are like 'source' files then), and enables a cleaner incremental treatment of // class file changes in indirs. File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter); for (int j = 0; j < binSrcs.length; j++) { UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, buildConfig.getOutputDir()); List ucfl = new ArrayList(); ucfl.add(ucf); state.binarySourceFiles.put(binSrcs[j].getPath(),ucfl); } } } bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable()); //check for org.aspectj.runtime.JoinPoint ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint"); if (joinPoint.isMissing()) { IMessage message = new Message("classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)", null, true); handler.handleMessage(message); } } public World getWorld() { return getBcelWorld(); } void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException { for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); getWeaver().addClassFile(classFile); } } // public boolean weaveAndGenerateClassFiles() throws IOException { // handler.handleMessage(MessageUtil.info("weaving")); // if (progressListener != null) progressListener.setText("weaving aspects"); // bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size()); // //!!! doesn't provide intermediate progress during weaving // // XXX add all aspects even during incremental builds? // addAspectClassFilesToWeaver(state.addedClassFiles); // if (buildConfig.isNoWeave()) { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.dumpUnwoven(buildConfig.getOutputJar()); // } else { // bcelWeaver.dumpUnwoven(); // bcelWeaver.dumpResourcesToOutPath(); // } // } else { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.weave(buildConfig.getOutputJar()); // } else { // bcelWeaver.weave(); // bcelWeaver.dumpResourcesToOutPath(); // } // } // if (progressListener != null) progressListener.setProgress(1.0); // return true; // //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors(); // } public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) { String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ // Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every // element of the classpath is likely to be a directory. If we ensure every element of the array is set to // only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build // a classpathDirectory object that will attempt to look for source when it can't find binary. int[] classpathModes = new int[classpaths.length]; for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY; return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes); } public IProblemFactory getProblemFactory() { return new DefaultProblemFactory(Locale.getDefault()); } /* * Build the set of compilation source units */ public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) { int fileCount = filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; // HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ for (int i = 0; i < fileCount; i++) { String encoding = encodings[i]; if (encoding == null) encoding = defaultEncoding; units[i] = new CompilationUnit(null, filenames[i], encoding); } return units; } public String extractDestinationPathFromSourceFile(CompilationResult result) { ICompilationUnit compilationUnit = result.compilationUnit; if (compilationUnit != null) { char[] fileName = compilationUnit.getFileName(); int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName); if (lastIndex == -1) { return System.getProperty("user.dir"); //$NON-NLS-1$ } return new String(CharOperation.subarray(fileName, 0, lastIndex)); } return System.getProperty("user.dir"); //$NON-NLS-1$ } public void performCompilation(List files) { if (progressListener != null) { compiledCount=0; sourceFileCount = files.size(); progressListener.setText("compiling source files"); } //System.err.println("got files: " + files); String[] filenames = new String[files.size()]; String[] encodings = new String[files.size()]; //System.err.println("filename: " + this.filenames); for (int i=0; i < files.size(); i++) { filenames[i] = ((File)files.get(i)).getPath(); } List cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i=0; i < cps.size(); i++) { classpaths[i] = (String)cps.get(i); } //System.out.println("compiling"); environment = getLibraryAccess(classpaths, filenames); if (!state.classesFromName.isEmpty()) { environment = new StatefulNameEnvironment(environment, state.classesFromName); } org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this); org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(), getBatchRequestor(), getProblemFactory()); CompilerOptions options = compiler.options; options.produceReferenceInfo = true; //TODO turn off when not needed try { compiler.compile(getCompilationUnits(filenames, encodings)); } catch (OperationCanceledException oce) { handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null)); } // cleanup environment.cleanup(); environment = null; } /* * Answer the component to which will be handed back compilation results from the compiler */ public IIntermediateResultsRequestor getInterimResultRequestor() { return new IIntermediateResultsRequestor() { public void acceptResult(InterimCompilationResult result) { if (progressListener != null) { compiledCount++; progressListener.setProgress((compiledCount/2.0)/sourceFileCount); progressListener.setText("compiled: " + result.fileName()); } state.noteResult(result); if (progressListener!=null && progressListener.isCancelledRequested()) { throw new AbortCompilation(true, new OperationCanceledException("Compilation cancelled as requested")); } } }; } public ICompilerRequestor getBatchRequestor() { return new ICompilerRequestor() { public void acceptResult(CompilationResult unitResult) { // end of compile, must now write the results to the output destination // this is either a jar file or a file in a directory if (!(unitResult.hasErrors() && !proceedOnError())) { Collection classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile classFile = (ClassFile) iter.next(); String filename = new String(classFile.fileName()); String classname = filename.replace('/', '.'); filename = filename.replace('/', File.separatorChar) + ".class"; try { if (buildConfig.getOutputJar() == null) { writeDirectoryEntry(unitResult, classFile,filename); } else { writeZipEntry(classFile,filename); } if (shouldAddAspectName) addAspectName(classname); } catch (IOException ex) { IMessage message = EclipseAdapterUtils.makeErrorMessage( new String(unitResult.fileName), CANT_WRITE_RESULT, ex); handler.handleMessage(message); } } } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); for (int i=0; i < problems.length; i++) { IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i]); handler.handleMessage(message); } } } private void writeDirectoryEntry( CompilationResult unitResult, ClassFile classFile, String filename) throws IOException { File destinationPath = buildConfig.getOutputDir(); String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); } private void writeZipEntry(ClassFile classFile, String name) throws IOException { name = name.replace(File.separatorChar,'/'); ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(classFile.getBytes()); zos.closeEntry(); } private void addAspectName (String name) { BcelWorld world = getBcelWorld(); ResolvedType type = world.resolve(name); // System.err.println("? writeAspectName() type=" + type); if (type.isAspect()) { aspectNames.add(name); } } }; } protected boolean proceedOnError() { return buildConfig.getProceedOnError(); } // public void noteClassFiles(AjCompiler.InterimResult result) { // if (result == null) return; // CompilationResult unitResult = result.result; // String sourceFileName = result.fileName(); // if (!(unitResult.hasErrors() && !proceedOnError())) { // List unwovenClassFiles = new ArrayList(); // Enumeration classFiles = unitResult.compiledTypes.elements(); // while (classFiles.hasMoreElements()) { // ClassFile classFile = (ClassFile) classFiles.nextElement(); // String filename = new String(classFile.fileName()); // filename = filename.replace('/', File.separatorChar) + ".class"; // // File destinationPath = buildConfig.getOutputDir(); // if (destinationPath == null) { // filename = new File(filename).getName(); // filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath(); // } else { // filename = new File(destinationPath, filename).getPath(); // } // // //System.out.println("classfile: " + filename); // unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes())); // } // state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles); //// System.out.println("file: " + sourceFileName); //// for (int i=0; i < unitResult.simpleNameReferences.length; i++) { //// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i])); //// } //// for (int i=0; i < unitResult.qualifiedReferences.length; i++) { //// System.out.println("qualified: " + //// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/'))); //// } // } else { // state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST); // } // } // private void setBuildConfig(AjBuildConfig buildConfig) { this.buildConfig = buildConfig; handler.reset(); } String makeClasspathString(AjBuildConfig buildConfig) { if (buildConfig == null || buildConfig.getFullClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. * Otherwise it will return a string message indicating the problem. */ public String checkRtJar(AjBuildConfig buildConfig) { // omitting dev info if (Version.text.equals(Version.DEVELOPMENT)) { // in the development version we can't do this test usefully // MessageUtil.info(holder, "running development version of aspectj compiler"); return null; } if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified"; String ret = null; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { File p = new File( (String)it.next() ); // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) { try { String version = null; Manifest manifest = new JarFile(p).getManifest(); if (manifest == null) { ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text; continue; } Attributes attr = manifest.getAttributes("org/aspectj/lang/"); if (null != attr) { version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (null != version) { version = version.trim(); } } // assume that users of development aspectjrt.jar know what they're doing if (Version.DEVELOPMENT.equals(version)) { // MessageUtil.info(holder, // "running with development version of aspectjrt.jar in " + // p.getAbsolutePath()); return null; } else if (!Version.text.equals(version)) { ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found " + version; continue; } } catch (IOException ioe) { ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; } return null; // this is the "OK" return value! } else { // might want to catch other classpath errors } } if (ret != null) return ret; // last error found in potentially matching jars... return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("AjBuildManager("); buf.append(")"); return buf.toString(); } public void setStructureModel(IHierarchy structureModel) { this.structureModel = structureModel; } /** * Returns null if there is no structure model */ public IHierarchy getStructureModel() { return structureModel; } public IProgressListener getProgressListener() { return progressListener; } public void setProgressListener(IProgressListener progressListener) { this.progressListener = progressListener; } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[]) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { String filename = new String(eclipseClassFileName); filename = filename.replace('/', File.separatorChar) + ".class"; File destinationPath = buildConfig.getOutputDir(); String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } return outFile; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, getProblemFactory()); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment); EclipseFactory factory = new EclipseFactory(le,this); le.factory = factory; pr.factory = factory; forCompiler.lookupEnvironment = le; forCompiler.parser = new Parser( pr, forCompiler.options.parseLiteralExpressionsAsConstants); return new AjCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.binarySourceFiles, state.resultsFromFile.values(), buildConfig.isNoWeave(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing()); } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return binarySourcesForTheNextCompile; } public static AsmHierarchyBuilder getAsmHierarchyBuilder() { return asmHierarchyBuilder; } /** * Override the the default hierarchy builder. */ public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) { asmHierarchyBuilder = newBuilder; } public AjState getState() { return state; } public void setState(AjState buildState) { state = buildState; } private static class AjBuildContexFormatter implements ContextFormatter { public String formatEntry(int phaseId, Object data) { StringBuffer sb = new StringBuffer(); if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) { sb.append("batch building "); } else { sb.append("incrementally building "); } AjBuildConfig config = (AjBuildConfig) data; List classpath = config.getClasspath(); sb.append("with classpath: "); for (Iterator iter = classpath.iterator(); iter.hasNext();) { sb.append(iter.next().toString()); sb.append(File.pathSeparator); } return sb.toString(); } } }
121,395
Bug 121395 invalid aspectj path throws filenotfoundexception
An invalid aspectj path (missing jar file) throws an filenotfoundexception: java.io.FileNotFoundException at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:106) at org.aspectj.weaver.bcel.BcelWeaver.addAspectsFromJarFile(BcelWeaver.java:202) at org.aspectj.weaver.bcel.BcelWeaver.addLibraryJarFile(BcelWeaver.java:192) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.initBcelWorld(AjBuildManager.java:623) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:209) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) FileNotFoundException thrown: /Users/frankstolle/Documents/workspace/lib_aspects/deploy/lib_aspects.jar (No such file or directory) should generate an problem entry in the problems-list.
resolved fixed
551b446
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-27T12:30:21Z
2005-12-19T11:00:00Z
tests/src/org/aspectj/systemtest/incremental/tools/AjdeInteractionTestbed.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.systemtest.incremental.tools; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.aspectj.ajde.Ajde; import org.aspectj.ajde.BuildOptionsAdapter; import org.aspectj.ajde.BuildProgressMonitor; import org.aspectj.ajde.ErrorHandler; import org.aspectj.ajde.ProjectPropertiesAdapter; import org.aspectj.ajde.TaskListManager; import org.aspectj.ajdt.internal.core.builder.AbstractStateListener; import org.aspectj.ajdt.internal.core.builder.AjState; import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager; import org.aspectj.asm.AsmManager; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.IMessage.Kind; /** * This class uses Ajde in the same way that an IDE (e.g. AJDT) does. * * The build is driven through 'build(projectName,configFile)' but the * build can be configured by the methods beginning 'configure***'. * Information about what happened during a build is accessible * through the get*, was*, print* public methods... * * There are many methods across the multiple listeners that communicate * info with Ajde - not all are implemented. Those that are are * task tagged DOESSOMETHING :) */ public class AjdeInteractionTestbed extends TestCase { public static boolean VERBOSE = false; // do you want the gory details? public static String testdataSrcDir = "../tests/multiIncremental"; protected static File sandboxDir; private static final String SANDBOX_NAME = "ajcSandbox"; private static boolean buildModel; // Methods for configuring the build public static void configureBuildStructureModel(boolean b) { buildModel = b;} public static void configureNewProjectDependency(String fromProject, String projectItDependsOn) { MyProjectPropertiesAdapter.addDependancy(fromProject,projectItDependsOn); } public static void configureNonStandardCompileOptions(String options) { MyBuildOptionsAdapter.setNonStandardOptions(options); } // End of methods for configuring the build protected File getWorkingDir() { return sandboxDir; } protected void setUp() throws Exception { super.setUp(); MyStateListener.reset(); MyBuildProgressMonitor.reset(); MyTaskListManager.reset(); // Create a sandbox in which to work createEmptySandbox(); } /** Drives a build */ public boolean build(String projectName,String configFile) { return AjdeManager.build(projectName,configFile); } public boolean fullBuild(String projectName,String configFile) { return AjdeManager.fullBuild(projectName,configFile); } /** Looks after communicating with the singleton Ajde instance */ public static class AjdeManager { static { Ajde.init(null, MyTaskListManager.getInstance(), MyBuildProgressMonitor.getInstance(), MyProjectPropertiesAdapter.getInstance(), MyBuildOptionsAdapter.getInstance(), null,null, MyErrorHandler.getInstance()); MyStateListener sl = MyStateListener.getInstance(); AjState.stateListener = sl; } /** * Builds a specified project using a specified config file. Subsequent * calls to build the same project should result in incremental builds. */ private static boolean build(String projectName,String configFile) { pause(1000); // delay to allow previous runs build stamps to be OK lognoln("Building project '"+projectName+"'"); // Ajde.getDefault().enableLogging(System.out); //Ajde.getDefault().getBuildManager().setReportInfoMessages(true); // Configure the necessary providers and listeners for this compile MyBuildProgressMonitor.reset(); MyTaskListManager.reset(); MyStateListener.reset(); // MyBuildOptionsAdapter.reset(); needs manually resetting in a test MyProjectPropertiesAdapter.setActiveProject(projectName); AsmManager.attemptIncrementalModelRepairs=true; IncrementalStateManager.recordIncrementalStates=true; Ajde.getDefault().getBuildManager().setBuildModelMode(buildModel); // Do the compile Ajde.getDefault().getBuildManager().build(getFile(projectName,configFile)); // Wait for it to complete while (!MyBuildProgressMonitor.hasFinished()) { lognoln("."); pause(100); } log(""); // What happened? if (MyTaskListManager.hasErrorMessages()) { System.err.println("Build errors:"); for (Iterator iter = MyTaskListManager.getErrorMessages().iterator(); iter.hasNext();) { IMessage element = (IMessage) iter.next(); System.err.println(element); } System.err.println("---------"); } log("Build finished, time taken = "+MyBuildProgressMonitor.getTimeTaken()+"ms"); return true; } private static boolean fullBuild(String projectName,String configFile) { pause(1000); // delay to allow previous runs build stamps to be OK lognoln("Building project '"+projectName+"'"); // Ajde.getDefault().enableLogging(System.out); //Ajde.getDefault().getBuildManager().setReportInfoMessages(true); // Configure the necessary providers and listeners for this compile MyBuildProgressMonitor.reset(); MyTaskListManager.reset(); MyStateListener.reset(); MyProjectPropertiesAdapter.setActiveProject(projectName); //AsmManager.attemptIncrementalModelRepairs=true; //IncrementalStateManager.recordIncrementalStates=true; Ajde.getDefault().getBuildManager().setBuildModelMode(buildModel); // Do the compile Ajde.getDefault().getBuildManager().buildFresh(getFile(projectName,configFile)); // Wait for it to complete while (!MyBuildProgressMonitor.hasFinished()) { lognoln("."); pause(100); } log(""); // What happened? if (MyTaskListManager.hasErrorMessages()) { System.err.println("Build errors:"); for (Iterator iter = MyTaskListManager.getErrorMessages().iterator(); iter.hasNext();) { IMessage element = (IMessage) iter.next(); System.err.println(element); } System.err.println("---------"); } log("Build finished, time taken = "+MyBuildProgressMonitor.getTimeTaken()+"ms"); return true; } private static void pause(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ie) {} } // public static boolean lastCompileDefaultedToBatch() { // return MyTaskListManager.defaultedToBatch(); // } } // Methods for querying what happened during a build and accessing information // about the build: /** * Helper method for dumping info about which files were compiled and * woven during the last build. */ public String printCompiledAndWovenFiles() { StringBuffer sb = new StringBuffer(); if (getCompiledFiles().size()==0 && getWovenClasses().size()==0) sb.append("No files were compiled or woven\n"); for (Iterator iter = getCompiledFiles().iterator(); iter.hasNext();) { Object element = (Object) iter.next(); sb.append("compiled: "+element+"\n"); } for (Iterator iter = getWovenClasses().iterator(); iter.hasNext();) { Object element = (Object) iter.next(); sb.append("woven: "+element+"\n"); } return sb.toString(); } /** * Summary report on what happened in the most recent build */ public void printBuildReport() { System.out.println("\n============== BUILD REPORT ================="); System.out.println("Build took: "+getTimeTakenForBuild()+"ms"); List compiled=getCompiledFiles(); System.out.println("Compiled: "+compiled.size()+" files"); for (Iterator iter = compiled.iterator(); iter.hasNext();) { System.out.println(" :"+iter.next()); } List woven=getWovenClasses(); System.out.println("Wove: "+woven.size()+" files"); for (Iterator iter = woven.iterator(); iter.hasNext();) { System.out.println(" :"+iter.next()); } if (wasFullBuild()) System.out.println("It was a batch (full) build"); System.out.println("============================================="); } public boolean wasFullBuild() { return MyStateListener.wasFullBuild(); } public long getTimeTakenForBuild() { return MyBuildProgressMonitor.getTimeTaken(); } public List getCompiledFiles() { return MyBuildProgressMonitor.getCompiledFiles(); } public List getWovenClasses() { return MyBuildProgressMonitor.getWovenClasses(); } // Infrastructure below here private void createEmptySandbox() { String os = System.getProperty("os.name"); File tempDir = null; // AMC - I did this rather than use the JDK default as I hate having to go look // in c:\documents and settings\......... for the results of a failed test. if (os.startsWith("Windows")) { //Alex: try D first since NTFS on mine while FAT leads to failure.. tempDir = new File("D:\\temp"); if (!tempDir.exists()) { tempDir = new File("C:\\temp"); if (!tempDir.exists()) { tempDir.mkdir(); } } } else { tempDir = new File("/tmp"); } File sandboxRoot = new File(tempDir,SANDBOX_NAME); if (!sandboxRoot.exists()) { sandboxRoot.mkdir(); } org.aspectj.util.FileUtil.deleteContents(sandboxRoot); try { sandboxDir = File.createTempFile("ajcTest",".tmp",sandboxRoot); sandboxDir.delete(); sandboxDir.mkdir(); } catch (IOException ioEx) { throw new AssertionFailedError("Unable to create sandbox directory for test"); } } private static void log(String msg) { if (VERBOSE) System.out.println(msg); } private static void lognoln(String msg) { if (VERBOSE) System.out.print(msg); } /** Return the *full* path to this file which is taken relative to the project dir*/ protected static String getFile(String projectName, String path) { return new File(sandboxDir,projectName+File.separatorChar + path).getAbsolutePath(); } // Helper classes that communicate with Ajde static class MyErrorHandler implements ErrorHandler { static MyErrorHandler _instance = new MyErrorHandler(); private List errorMessages = new ArrayList(); private MyErrorHandler() {} public static ErrorHandler getInstance() { return _instance; } public void handleWarning(String message) { log("ErrorHandler.handleWarning("+message+")"); } public void handleError(String message) { log("ErrorHandler.handleWarning("+message+")"); errorMessages.add(message); } public void handleError(String message, Throwable t) { log("ErrorHandler.handleError("+message+","+t+")"); if (VERBOSE) t.printStackTrace(); errorMessages.add(message+","+t+")"); } public static List/*String*/ getErrorMessages() { return _instance.errorMessages; } } // ----------------- static class MyProjectPropertiesAdapter implements ProjectPropertiesAdapter { private final static boolean VERBOSE = false; static MyProjectPropertiesAdapter _instance = new MyProjectPropertiesAdapter(); private MyProjectPropertiesAdapter() {} public static ProjectPropertiesAdapter getInstance() { return _instance; } private String projectName = null; private String classPath = ""; public static void setActiveProject(String n) { _instance.projectName = n; } private static Hashtable dependants = new Hashtable(); public static void addDependancy(String project, String projectItDependsOn) { List l = (List)dependants.get(project); if (l == null) { List ps = new ArrayList(); ps.add(projectItDependsOn); dependants.put(project,ps); } else { l.add(projectItDependsOn); } } public void setClasspath(String path) { this.classPath = path; } // interface impl below // DOESSOMETHING public String getProjectName() { log("MyProjectProperties.getProjectName() [returning "+projectName+"]"); return projectName; } // DOESSOMETHING public String getRootProjectDir() { String dir = testdataSrcDir+File.separatorChar+projectName; log("MyProjectProperties.getRootProjectDir() [returning "+dir+"]"); return dir; } public List getBuildConfigFiles() { log("MyProjectProperties.getBuildConfigFiles()"); return null; } public String getDefaultBuildConfigFile() { log("MyProjectProperties.getDefaultBuildConfigFile()"); return null; } public String getLastActiveBuildConfigFile() { log("MyProjectProperties.getLastActiveBuildConfigFile()"); return null; } public List getProjectSourceFiles() { log("MyProjectProperties.getProjectSourceFiles()"); return null; } public String getProjectSourcePath() { log("MyProjectProperties.getProjectSourcePath()"); return null; } // DOESSOMETHING public String getClasspath() { log("MyProjectProperties.getClasspath()"); String cp = new File(testdataSrcDir) + File.pathSeparator + System.getProperty("sun.boot.class.path") + File.pathSeparator + "../runtime/bin" + File.pathSeparator + this.classPath + File.pathSeparator + System.getProperty("aspectjrt.path") + File.pathSeparator + "../lib/junit/junit.jar" + File.pathSeparator+".."+File.separator+"lib" + File.separator+"test"+File.separator+"aspectjrt.jar"; // look at dependant projects List projects = (List)dependants.get(projectName); if (projects!=null) { for (Iterator iter = projects.iterator(); iter.hasNext();) { cp = getFile((String)iter.next(),"bin")+File.pathSeparator+cp; } } //System.err.println("For project "+projectName+" getClasspath() returning "+cp); return cp; } public String getOutputPath() { String dir = getFile(projectName,"bin"); log("MyProjectProperties.getOutputPath() [returning "+dir+"]"); return dir; } public String getBootClasspath() { log("MyProjectProperties.getBootClasspath()"); return null; } public String getClassToExecute() { log("MyProjectProperties.getClassToExecute()"); return null; } public String getExecutionArgs() { log("MyProjectProperties.getExecutionArgs()"); return null; } public String getVmArgs() { log("MyProjectProperties.getVmArgs()"); return null; } public Set getInJars() { log("MyProjectProperties.getInJars()"); return null; } public Set getInpath() { log("MyProjectProperties.getInPath()"); return null; } public Map getSourcePathResources() { log("MyProjectProperties.getSourcePathResources()"); return null; } public String getOutJar() { log("MyProjectProperties.getOutJar()"); return null; } public Set getSourceRoots() { log("MyProjectProperties.getSourceRoots()"); return null; } public Set getAspectPath() { log("MyProjectProperties.getAspectPath()"); return null; } public static void log(String s) { if (VERBOSE) System.out.println(s); } } // ----------------------- static class MyBuildProgressMonitor implements BuildProgressMonitor { public static boolean VERBOSE = false; private static MyBuildProgressMonitor _instance = new MyBuildProgressMonitor(); private MyBuildProgressMonitor() {} private List compiledFiles=new ArrayList(); private List wovenClasses=new ArrayList(); public static BuildProgressMonitor getInstance() { return _instance; } public static void reset() { _instance.finished = false; _instance.compiledFiles.clear(); _instance.wovenClasses.clear(); } public static boolean hasFinished() { return _instance.finished; } public static List getCompiledFiles() { return _instance.compiledFiles;} public static List getWovenClasses() { return _instance.wovenClasses; } //--- private long starttime = 0; private long totaltimetaken = 0; private boolean finished = false; public void start(String configFile) { starttime = System.currentTimeMillis(); log("BuildProgressMonitor.start("+configFile+")"); } public void setProgressText(String text) { log("BuildProgressMonitor.setProgressText("+text+")"); if (text.startsWith("compiled: ")) { compiledFiles.add(text.substring(10)); } else if (text.startsWith("woven class ")) { wovenClasses.add(text.substring(12)); } else if (text.startsWith("woven aspect ")) { wovenClasses.add(text.substring(13)); } } public void setProgressBarVal(int newVal) { log("BuildProgressMonitor.setProgressBarVal("+newVal+")"); } public void incrementProgressBarVal() { log("BuildProgressMonitor.incrementProgressBarVal()"); } public void setProgressBarMax(int maxVal) { log("BuildProgressMonitor.setProgressBarMax("+maxVal+")"); } public int getProgressBarMax() { log("BuildProgressMonitor.getProgressBarMax() [returns 100]"); return 100; } public void finish() { log("BuildProgressMonitor.finish()"); _instance.finished=true; _instance.totaltimetaken=(System.currentTimeMillis()-starttime); } public static long getTimeTaken() { return _instance.totaltimetaken; } public static void log(String s) { if (VERBOSE) System.out.println(s); } } // ---- static class MyTaskListManager implements TaskListManager { private static final String CANT_BUILD_INCREMENTAL_INDICATION = "Unable to perform incremental build"; private static final String DOING_BATCH_BUILD_INDICATION = "Performing batch build for config"; private final static boolean VERBOSE = false; static MyTaskListManager _instance = new MyTaskListManager(); private MyTaskListManager() {} private boolean receivedNonIncrementalBuildMessage = false; private boolean receivedBatchBuildMessage = false; private List errorMessages = new ArrayList(); private List warningMessages = new ArrayList(); public static void reset() { _instance.receivedNonIncrementalBuildMessage=false; _instance.receivedBatchBuildMessage=false; _instance.errorMessages.clear(); _instance.warningMessages.clear(); } // public static boolean defaultedToBatch() { // return _instance.receivedNonIncrementalBuildMessage; // } // // public static boolean didBatchBuild() { // return _instance.receivedBatchBuildMessage; // } public static boolean hasErrorMessages() { return !_instance.errorMessages.isEmpty(); } public static List/*IMessage*/ getErrorMessages() { return _instance.errorMessages; } public static List/*IMessage*/ getWarningMessages() { return _instance.warningMessages; } public static TaskListManager getInstance() { return _instance; } public void addSourcelineTask(String message, ISourceLocation sourceLocation, Kind kind) { log("TaskListManager.addSourcelineTask("+message+","+sourceLocation+","+kind+")"); } // DOESSOMETHING public void addSourcelineTask(IMessage message) { // if (message.getKind()==IMessage.INFO) { // if (message.getMessage().startsWith(CANT_BUILD_INCREMENTAL_INDICATION)) _instance.receivedNonIncrementalBuildMessage=true; // if (message.getMessage().startsWith(DOING_BATCH_BUILD_INDICATION)) _instance.receivedBatchBuildMessage=true; // } if (message.getKind()==IMessage.ERROR) { errorMessages.add(message); } if (message.getKind()==IMessage.WARNING) { warningMessages.add(message); } log("TaskListManager.addSourcelineTask("+message+")"); } public boolean hasWarning() { log("TaskListManager.hasWarning() [returning "+(warningMessages.size()==0)+"]"); return warningMessages.size()==0; } public void addProjectTask(String message, Kind kind) { log("TaskListManager.addProjectTask("+message+","+kind+")"); } public void clearTasks() { log("TaskListManager.clearTasks()"); } public static void log(String s) { if (VERBOSE) System.out.println(s); } } // ---- static class MyBuildOptionsAdapter implements BuildOptionsAdapter { static MyBuildOptionsAdapter _instance = new MyBuildOptionsAdapter(); private MyBuildOptionsAdapter() {} public static void setNonStandardOptions(String options) { _instance.nonstandardoptions = options; } private String nonstandardoptions=null; public static void reset() { _instance.nonstandardoptions=null; } public static BuildOptionsAdapter getInstance() { return _instance; } public Map getJavaOptionsMap() { Hashtable ht = new Hashtable(); ht.put("org.eclipse.jdt.core.compiler.compliance","1.5"); ht.put("org.eclipse.jdt.core.compiler.codegen.targetPlatform","1.5"); return ht; } public boolean getUseJavacMode() { return false; } public String getWorkingOutputPath() { return null; } public boolean getPreprocessMode() { return false; } public String getCharacterEncoding() { return null; } public boolean getSourceOnePointFourMode() { return false; } // DOESSOMETHING public boolean getIncrementalMode() { return true; } public boolean getLenientSpecMode() { return false; } public boolean getStrictSpecMode() { return false; } public boolean getPortingMode() { return false; } public String getNonStandardOptions() { return nonstandardoptions; } public String getComplianceLevel() { return null; } public String getSourceCompatibilityLevel() { return "1.5"; } public Set getWarnings() { return null; } public Set getDebugLevel() { return null; } public boolean getNoImportError() { return false; } public boolean getPreserveAllLocals() { return false; } } static class MyStateListener extends AbstractStateListener { private static MyStateListener _instance = new MyStateListener(); private MyStateListener() {reset();} public static MyStateListener getInstance() { return _instance;} public static boolean informedAboutKindOfBuild; public static boolean fullBuildOccurred; public static List detectedDeletions = new ArrayList(); public static void reset() { informedAboutKindOfBuild=false; fullBuildOccurred=false; if (detectedDeletions!=null) detectedDeletions.clear(); } public boolean pathChange = false; public void pathChangeDetected() {pathChange = true;} public void aboutToCompareClasspaths(List oldClasspath, List newClasspath) {} public void detectedClassChangeInThisDir(File f) {} public void detectedAspectDeleted(File f) { detectedDeletions.add(f.toString()); } public void buildSuccessful(boolean wasFullBuild) { informedAboutKindOfBuild= true; fullBuildOccurred=wasFullBuild; } public static boolean wasFullBuild() { if (!informedAboutKindOfBuild) throw new RuntimeException("I never heard about what kind of build it was!!"); return fullBuildOccurred; } }; }
121,395
Bug 121395 invalid aspectj path throws filenotfoundexception
An invalid aspectj path (missing jar file) throws an filenotfoundexception: java.io.FileNotFoundException at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:106) at org.aspectj.weaver.bcel.BcelWeaver.addAspectsFromJarFile(BcelWeaver.java:202) at org.aspectj.weaver.bcel.BcelWeaver.addLibraryJarFile(BcelWeaver.java:192) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.initBcelWorld(AjBuildManager.java:623) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:209) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) FileNotFoundException thrown: /Users/frankstolle/Documents/workspace/lib_aspects/deploy/lib_aspects.jar (No such file or directory) should generate an problem entry in the problems-list.
resolved fixed
551b446
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-27T12:30:21Z
2005-12-19T11:00:00Z
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.systemtest.incremental.tools; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.aspectj.ajdt.internal.core.builder.AjState; import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.IMessage; import org.aspectj.testing.util.FileUtil; /** * The superclass knows all about talking through Ajde to the compiler. * The superclass isn't in charge of knowing how to simulate overlays * for incremental builds, that is in here. As is the ability to * generate valid build configs based on a directory structure. To * support this we just need access to a sandbox directory - this * sandbox is managed by the superclass (it only assumes all builds occur * in <sandboxDir>/<projectName>/ ) * * The idea is you can initialize multiple projects in the sandbox and * they can all be built independently, hopefully exploiting * incremental compilation. Between builds you can alter the contents * of a project using the alter() method that overlays some set of * new files onto the current set (adding new files/changing existing * ones) - you can then drive a new build and check it behaves as * expected. */ public class MultiProjectIncrementalTests extends AjdeInteractionTestbed { public static boolean VERBOSE = false; protected void setUp() throws Exception { super.setUp(); AjdeInteractionTestbed.VERBOSE = VERBOSE; } // Compile a single simple project public void testTheBasics() { initialiseProject("P1"); build("P1"); // This first build will be batch build("P1"); checkWasntFullBuild(); checkCompileWeaveCount(0,0); } // Make simple changes to a project, adding a class public void testSimpleChanges() { initialiseProject("P1"); build("P1"); // This first build will be batch alter("P1","inc1"); // adds a single class build("P1"); checkCompileWeaveCount(1,-1); build("P1"); checkCompileWeaveCount(0,-1); } // Make simple changes to a project, adding a class and an aspect public void testAddingAnAspect() { initialiseProject("P1"); build("P1"); alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); long timeTakenForFullBuildAndWeave = getTimeTakenForBuild(); checkWasntFullBuild(); checkCompileWeaveCount(2,3); build("P1"); long timeTakenForSimpleIncBuild = getTimeTakenForBuild(); // I don't think this test will have timing issues as the times should be *RADICALLY* different // On my config, first build time is 2093ms and the second is 30ms assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+ "ms second="+timeTakenForSimpleIncBuild+"ms", timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave); } public void testBuildingTwoProjectsInTurns() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); } /** * In order for this next test to run, I had to move the weaver/world pair we keep in the * AjBuildManager instance down into the state object - this makes perfect sense - otherwise * when reusing the state for another project we'd not be switching to the right weaver/world * for that project. */ public void testBuildingTwoProjectsMakingSmallChanges() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); checkWasntFullBuild(); } /** * Setup up two simple projects and build them in turn - check the * structure model is right after each build */ public void testBuildingTwoProjectsAndVerifyingModel() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } // Setup up two simple projects and build them in turn - check the // structure model is right after each build public void testBuildingTwoProjectsAndVerifyingStuff() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, adding a new method and check structural changes is 1. */ public void testStateManagement1() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be a state object for project P1",ajs!=null); assertTrue("Should be no structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc3"); // adds a method to the class C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Should be one structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, changing body of a method, not the structure and * check struc changes is still 0. */ public void testStateManagement2() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making // it a structural change build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be state for project P1",ajs!=null); assertTrue("Should be no struc changes as its a full build: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); } /** * Now the most complex test. Create a dependancy between two projects. Building * one may affect whether the other does an incremental or full build. The * structural information recorded in the state object should be getting used * to control whether a full build is necessary... */ public void testBuildingDependantProjects() { initialiseProject("P1"); initialiseProject("P2"); configureNewProjectDependency("P2","P1"); build("P1"); build("P2"); // now everything is consistent and compiled alter("P1","inc1"); // adds a second class build("P1"); build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :) checkWasntFullBuild(); alter("P1","inc3"); // structurally changes one of the classes build("P1"); build("P2"); // build notices the structural change checkWasFullBuild(); alter("P1","inc4"); build("P1"); build("P2"); // build sees a change but works out its not structural checkWasntFullBuild(); } public void testPr85132() { initialiseProject("PR85132"); build("PR85132"); alter("PR85132","inc1"); build("PR85132"); } // parameterization of generic aspects public void testPr125405() { initialiseProject("PR125405"); build("PR125405"); checkCompileWeaveCount(1,1); alter("PR125405","inc1"); build("PR125405"); // "only abstract aspects can have type parameters" checkForError("only abstract aspects can have type parameters"); alter("PR125405","inc2"); build("PR125405"); checkCompileWeaveCount(1,1); assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0); } public void testPr92837() { initialiseProject("PR92837"); build("PR92837"); alter("PR92837","inc1"); build("PR92837"); } public void testPr119570() { initialiseProject("PR119570"); build("PR119570"); assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0); } public void testPr119570_2() { initialiseProject("PR119570_2"); build("PR119570_2"); List l = MyTaskListManager.getWarningMessages(); assertTrue("Should be no warnings, but got "+l,l.size()==0); } // If you fiddle with the compiler options - you must manually reset the options at the end of the test public void testPr117209() { try { initialiseProject("pr117209"); configureNonStandardCompileOptions("-proceedOnError"); build("pr117209"); checkCompileWeaveCount(6,6); } finally { MyBuildOptionsAdapter.reset(); } } public void testPr114875() { initialiseProject("pr114875"); build("pr114875"); alter("pr114875","inc1"); build("pr114875"); checkWasntFullBuild(); alter("pr114875","inc2"); build("pr114875"); checkWasntFullBuild(); } public void testPr117882() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882"); build("PR117882"); checkWasFullBuild(); alter("PR117882","inc1"); build("PR117882"); checkWasntFullBuild(); // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr117882_2() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882_2"); build("PR117882_2"); checkWasFullBuild(); alter("PR117882_2","inc1"); build("PR117882_2"); checkWasntFullBuild(); //checkCompileWeaveCount(1,4); //fullBuild("PR117882_2"); //checkWasFullBuild(); // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr115251() { //AjdeInteractionTestbed.VERBOSE=true; initialiseProject("PR115251"); build("PR115251"); checkWasFullBuild(); alter("PR115251","inc1"); build("PR115251"); checkWasntFullBuild(); } // public void testPr124399() { // AjdeInteractionTestbed.VERBOSE=true; // configureBuildStructureModel(true); // initialiseProject("PR124399"); // build("PR124399"); // checkWasFullBuild(); // alter("PR124399","inc1"); // build("PR124399"); // checkWasntFullBuild(); // } public void testPr121384() { // AjdeInteractionTestbed.VERBOSE=true; // AsmManager.setReporting("c:/foo.txt",true,true,true,false); MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo"); configureBuildStructureModel(true); initialiseProject("pr121384"); build("pr121384"); checkWasFullBuild(); alter("pr121384","inc1"); build("pr121384"); checkWasntFullBuild(); } /* public void testPr111779() { super.VERBOSE=true; initialiseProject("PR111779"); build("PR111779"); alter("PR111779","inc1"); build("PR111779"); } */ public void testPr93310_1() { initialiseProject("PR93310_1"); build("PR93310_1"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_1","inc1"); build("PR93310_1"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1); String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java")); } public void testPr93310_2() { initialiseProject("PR93310_2"); build("PR93310_2"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_2","inc1"); build("PR93310_2"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1); String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java")); } // Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A. // Stage2: make the field private in class A > gives compile error // Stage3: Add a new aspect whilst there is a compile error ! public void testPr113531() { initialiseProject("PR113531"); build("PR113531"); assertFalse("build should have compiled ok", MyTaskListManager.hasErrorMessages()); alter("PR113531","inc1"); build("PR113531"); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); alter("PR113531","inc2"); build("PR113531"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); } public void testPr112736() { AjdeInteractionTestbed.VERBOSE = true; initialiseProject("PR112736"); build("PR112736"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java"; (new File(fileC2)).delete(); alter("PR112736","inc1"); build("PR112736"); checkWasFullBuild(); } /** * We have problems with multiple rewrites of a pointcut across incremental builds. */ public void testPr113257() { initialiseProject("PR113257"); build("PR113257"); alter("PR113257","inc1"); build("PR113257"); checkWasntFullBuild(); alter("PR113257","inc1"); build("PR113257"); } public void testPr123612() { initialiseProject("PR123612"); build("PR123612"); alter("PR123612","inc1"); build("PR123612"); checkWasntFullBuild(); } // other possible tests: // - memory usage (freemem calls?) // - relationship map // --------------------------------------------------------------------------------------------------- /** * Check we compiled/wove the right number of files, passing '-1' indicates you don't care about * that number. */ private void checkCompileWeaveCount(int expCompile,int expWoven) { if (expCompile!=-1 && getCompiledFiles().size()!=expCompile) fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+ "\n"+printCompiledAndWovenFiles()); if (expWoven!=-1 && getWovenClasses().size()!=expWoven) fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+ "\n"+printCompiledAndWovenFiles()); } private void checkWasntFullBuild() { assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild()); } private void checkWasFullBuild() { assertTrue("Should have been a full (batch) build",wasFullBuild()); } private void checkForNode(String packageName,String typeName,boolean shouldBeFound) { IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName); if (shouldBeFound) { if (ipe==null) printModel(); assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null); } else { if (ipe!=null) printModel(); assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null); } } private void printModel() { try { AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0); } catch (IOException e) { e.printStackTrace(); } } public void build(String projectName) { constructUpToDateLstFile(projectName,"build.lst"); build(projectName,"build.lst"); if (AjdeInteractionTestbed.VERBOSE) printBuildReport(); } public void fullBuild(String projectName) { constructUpToDateLstFile(projectName,"build.lst"); fullBuild(projectName,"build.lst"); if (AjdeInteractionTestbed.VERBOSE) printBuildReport(); } private void constructUpToDateLstFile(String pname,String configname) { File projectBase = new File(sandboxDir,pname); File toConstruct = new File(projectBase,configname); List filesForCompilation = new ArrayList(); collectUpFiles(projectBase,projectBase,filesForCompilation); try { FileOutputStream fos = new FileOutputStream(toConstruct); DataOutputStream dos = new DataOutputStream(fos); for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) { String file = (String) iter.next(); dos.writeBytes(file+"\n"); } dos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } public void checkForError(String anError) { List messages = MyTaskListManager.getErrorMessages(); for (Iterator iter = messages.iterator(); iter.hasNext();) { IMessage element = (IMessage) iter.next(); if (element.getMessage().indexOf(anError)!=-1) return; } fail("Didn't find the error message:\n'"+anError+"'.\nErrors that occurred:\n"+MyTaskListManager.getErrorMessages()); } private void collectUpFiles(File location,File base,List collectionPoint) { String contents[] = location.list(); if (contents==null) return; for (int i = 0; i < contents.length; i++) { String string = contents[i]; File f = new File(location,string); if (f.isDirectory()) { collectUpFiles(f,base,collectionPoint); } else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) { String fileFound; try { fileFound = f.getCanonicalPath(); String toRemove = base.getCanonicalPath(); if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove); collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator } catch (IOException e) { e.printStackTrace(); } } } } /** * Fill in the working directory with the project base files, * from the 'base' folder. */ protected void initialiseProject(String p) { File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base"); File destination=new File(getWorkingDir(),p); if (!destination.exists()) {destination.mkdir();} copy(projectSrc,destination);//,false); } /* * Applies an overlay onto the project being tested - copying * the contents of the specified overlay directory. */ private void alter(String projectName,String overlayDirectory) { File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+ File.separatorChar+overlayDirectory); File destination=new File(getWorkingDir(),projectName); copy(projectSrc,destination); } /** * Copy the contents of some directory to another location - the * copy is recursive. */ private void copy(File from, File to) { String contents[] = from.list(); if (contents==null) return; for (int i = 0; i < contents.length; i++) { String string = contents[i]; File f = new File(from,string); File t = new File(to,string); if (f.isDirectory() && !f.getName().startsWith("inc")) { t.mkdir(); copy(f,t); } else if (f.isFile()) { StringBuffer sb = new StringBuffer(); //if (VERBOSE) System.err.println("Copying "+f+" to "+t); FileUtil.copyFile(f,t,sb); if (sb.length()!=0) { System.err.println(sb.toString());} } } } private static void log(String msg) { if (VERBOSE) System.out.println(msg); } }
123,901
Bug 123901 NPE in AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:105)
java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:105) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference.traverse(QualifiedNameReference.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java(Compiled Code)) at org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration.resolveStatements(AdviceDeclaration.java:172) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java(Compiled Code)) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.resolve(AspectDeclaration.java:115) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java(Inlined Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:514) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java(Compiled Code)) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
resolved fixed
693945f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-29T10:12:10Z
2006-01-15T13:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AccessForInlineVisitor.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; //import java.util.Arrays; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.InlineAccessFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedFieldBinding; import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.ResolvedMember; import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor; //import org.aspectj.org.eclipse.jdt.internal.compiler.AbstractSyntaxTreeVisitorAdapter; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AssertStatement; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedMethodBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.VariableBinding; /** * Walks the body of around advice * * Makes sure that all member accesses are to public members. Will * convert to use access methods when needed to ensure that. This * makes it much simpler (and more modular) to inline the body of * an around. * * ??? constructors are handled different and require access to the * target type. changes to org.eclipse.jdt.internal.compiler.ast.AllocationExpression * would be required to fix this issue. * * @author Jim Hugunin */ public class AccessForInlineVisitor extends ASTVisitor { PrivilegedHandler handler; AspectDeclaration inAspect; EclipseFactory world; // alias for inAspect.world // set to true for ClassLiteralAccess and AssertStatement // ??? A better answer would be to transform these into inlinable forms public boolean isInlinable = true; public AccessForInlineVisitor(AspectDeclaration inAspect, PrivilegedHandler handler) { this.inAspect = inAspect; this.world = inAspect.factory; this.handler = handler; } public void endVisit(SingleNameReference ref, BlockScope scope) { if (ref.binding instanceof FieldBinding) { ref.binding = getAccessibleField((FieldBinding)ref.binding, ref.actualReceiverType); } } public void endVisit(QualifiedNameReference ref, BlockScope scope) { if (ref.binding instanceof FieldBinding) { ref.binding = getAccessibleField((FieldBinding)ref.binding, ref.actualReceiverType); } if (ref.otherBindings != null && ref.otherBindings.length > 0) { TypeBinding receiverType; if (ref.binding instanceof FieldBinding) { receiverType = ((FieldBinding)ref.binding).type; } else if (ref.binding instanceof VariableBinding) { receiverType = ((VariableBinding)ref.binding).type; } else { //!!! understand and fix this case later receiverType = ref.otherBindings[0].declaringClass; } for (int i=0, len=ref.otherBindings.length; i < len; i++) { FieldBinding binding = ref.otherBindings[i]; ref.otherBindings[i] = getAccessibleField(binding, receiverType); receiverType = binding.type; } } } public void endVisit(FieldReference ref, BlockScope scope) { ref.binding = getAccessibleField(ref.binding, ref.receiverType); } public void endVisit(MessageSend send, BlockScope scope) { if (send instanceof Proceed) return; if (send.binding == null || !send.binding.isValidBinding()) return; if (send.isSuperAccess() && !send.binding.isStatic()) { send.receiver = new ThisReference(send.sourceStart, send.sourceEnd); MethodBinding superAccessBinding = getSuperAccessMethod(send.binding); AstUtil.replaceMethodBinding(send, superAccessBinding); } else if (!isPublic(send.binding)) { send.syntheticAccessor = getAccessibleMethod(send.binding, send.actualReceiverType); } } public void endVisit(AllocationExpression send, BlockScope scope) { if (send.binding == null || !send.binding.isValidBinding()) return; //XXX TBD if (isPublic(send.binding)) return; makePublic(send.binding.declaringClass); send.binding = handler.getPrivilegedAccessMethod(send.binding, send); } public void endVisit( QualifiedTypeReference ref, BlockScope scope) { makePublic(ref.resolvedType); //getTypeBinding(scope)); //??? might be trouble } public void endVisit( SingleTypeReference ref, BlockScope scope) { makePublic(ref.resolvedType); //getTypeBinding(scope)); //??? might be trouble } private FieldBinding getAccessibleField(FieldBinding binding, TypeBinding receiverType) { //System.err.println("checking field: " + binding); if (binding == null || !binding.isValidBinding()) return binding; makePublic(receiverType); if (isPublic(binding)) return binding; if (binding instanceof PrivilegedFieldBinding) return binding; if (binding instanceof InterTypeFieldBinding) return binding; if (binding.isPrivate() && binding.declaringClass != inAspect.binding) { binding.modifiers = AstUtil.makePackageVisible(binding.modifiers); } ResolvedMember m = world.makeResolvedMember(binding, receiverType); if (inAspect.accessForInline.containsKey(m)) return (FieldBinding)inAspect.accessForInline.get(m); FieldBinding ret = new InlineAccessFieldBinding(inAspect, binding, m); //System.err.println(" made accessor: " + ret); inAspect.accessForInline.put(m, ret); return ret; } private MethodBinding getAccessibleMethod(MethodBinding binding, TypeBinding receiverType) { if (!binding.isValidBinding()) return binding; makePublic(receiverType); //??? if (isPublic(binding)) return binding; if (binding instanceof InterTypeMethodBinding) return binding; if (binding instanceof ParameterizedMethodBinding) { // pr124999 binding = binding.original(); } ResolvedMember m = null; if (binding.isPrivate() && binding.declaringClass != inAspect.binding) { // does this always mean that the aspect is an inner aspect of the bindings // declaring class? After all, the field is private but we can see it from // where we are. binding.modifiers = AstUtil.makePackageVisible(binding.modifiers); m = world.makeResolvedMember(binding); } else { // Sometimes receiverType and binding.declaringClass are *not* the same. // Sometimes receiverType is a subclass of binding.declaringClass. In these situations // we want the generated inline accessor to call the method on the subclass (at // runtime this will be satisfied by the super). m = world.makeResolvedMember(binding, receiverType); } if (inAspect.accessForInline.containsKey(m)) return (MethodBinding)inAspect.accessForInline.get(m); MethodBinding ret = world.makeMethodBinding( AjcMemberMaker.inlineAccessMethodForMethod(inAspect.typeX, m)); inAspect.accessForInline.put(m, ret); return ret; } static class SuperAccessMethodPair { public ResolvedMember originalMethod; public MethodBinding accessMethod; public SuperAccessMethodPair(ResolvedMember originalMethod, MethodBinding accessMethod) { this.originalMethod = originalMethod; this.accessMethod = accessMethod; } } private MethodBinding getSuperAccessMethod(MethodBinding binding) { ResolvedMember m = world.makeResolvedMember(binding); ResolvedMember superAccessMember = AjcMemberMaker.superAccessMethod(inAspect.typeX, m); if (inAspect.superAccessForInline.containsKey(superAccessMember)) { return ((SuperAccessMethodPair)inAspect.superAccessForInline.get(superAccessMember)).accessMethod; } MethodBinding ret = world.makeMethodBinding(superAccessMember); inAspect.superAccessForInline.put(superAccessMember, new SuperAccessMethodPair(m, ret)); return ret; } private boolean isPublic(FieldBinding fieldBinding) { // these are always effectively public to the inliner if (fieldBinding instanceof InterTypeFieldBinding) return true; return fieldBinding.isPublic(); } private boolean isPublic(MethodBinding methodBinding) { // these are always effectively public to the inliner if (methodBinding instanceof InterTypeMethodBinding) return true; return methodBinding.isPublic(); } private void makePublic(TypeBinding binding) { if (binding == null || !binding.isValidBinding()) return; // has already produced an error if (binding instanceof ReferenceBinding) { ReferenceBinding rb = (ReferenceBinding)binding; if (!rb.isPublic()) handler.notePrivilegedTypeAccess(rb, null); //??? } else if (binding instanceof ArrayBinding) { makePublic( ((ArrayBinding)binding).leafComponentType ); } else { return; } } public void endVisit(AssertStatement assertStatement, BlockScope scope) { isInlinable = false; } public void endVisit(ClassLiteralAccess classLiteral, BlockScope scope) { isInlinable = false; } public boolean visit( TypeDeclaration localTypeDeclaration, BlockScope scope) { // we don't want to transform any local anonymous classes as they won't be inlined return false; } }
123,901
Bug 123901 NPE in AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:105)
java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:105) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference.traverse(QualifiedNameReference.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java(Compiled Code)) at org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration.resolveStatements(AdviceDeclaration.java:172) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java(Compiled Code)) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.resolve(AspectDeclaration.java:115) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java(Inlined Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:514) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java(Compiled Code)) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
resolved fixed
693945f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-29T10:12:10Z
2006-01-15T13:00:00Z
tests/bugs151/pr123901/A.java
123,901
Bug 123901 NPE in AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:105)
java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:105) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference.traverse(QualifiedNameReference.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java(Compiled Code)) at org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration.resolveStatements(AdviceDeclaration.java:172) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java(Compiled Code)) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.resolve(AspectDeclaration.java:115) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java(Inlined Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:514) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java(Compiled Code)) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
resolved fixed
693945f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-29T10:12:10Z
2006-01-15T13:00:00Z
tests/bugs151/pr123901/B.java
123,901
Bug 123901 NPE in AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:105)
java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:105) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference.traverse(QualifiedNameReference.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java(Compiled Code)) at org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration.resolveStatements(AdviceDeclaration.java:172) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java(Compiled Code)) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.resolve(AspectDeclaration.java:115) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java(Inlined Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:514) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java(Compiled Code)) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
resolved fixed
693945f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-29T10:12:10Z
2006-01-15T13:00:00Z
tests/bugs151/pr125475/TestEmptyPointcutAtAspect.java
123,901
Bug 123901 NPE in AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:105)
java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.AccessForInlineVisitor.endVisit(AccessForInlineVisitor.java:105) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference.traverse(QualifiedNameReference.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.traverse(MessageSend.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java(Compiled Code)) at org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration.resolveStatements(AdviceDeclaration.java:172) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java(Compiled Code)) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.resolve(AspectDeclaration.java:115) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java(Inlined Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java(Compiled Code)) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:514) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java(Compiled Code)) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
resolved fixed
693945f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-29T10:12:10Z
2006-01-15T13:00:00Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.systemtest.ajc150.GenericsTests; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");} public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");} public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");} public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");} public void testMixingNumbersOfTypeParameters_pr125080() { runTest("mixing numbers of type parameters"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;"); } public void testMixingNumbersOfTypeParameters_pr125080_2() { runTest("mixing numbers of type parameters - 2"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;"); } public void testIProgramElementMethods_pr125295() { runTest("new IProgramElement methods"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForType("pkg","foo"); assertNotNull("Couldn't find 'foo' element in the tree",pe); // check that the defaults return the fully qualified arg assertEquals("foo(int, java.lang.Object)",pe.toLabelString()); assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString()); assertEquals("foo(int, java.lang.Object)",pe.toSignatureString()); // check that can get hold of the non qualified args assertEquals("foo(int, Object)",pe.toLabelString(false)); assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false)); assertEquals("foo(int, Object)",pe.toSignatureString(false)); IProgramElement pe2 = top.findElementForType("pkg","printParameters"); assertNotNull("Couldn't find 'printParameters' element in the tree",pe2); // the argument is org.aspectj.lang.JoinPoint, check that this is added assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty()); } ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
125,657
Bug 125657 NullPointerException from BcelShadow.java:1313
From within Eclipse 3.0 (RAD 6.0.1) I get an error with the (partial) details listed below. My aspect looks like this: public aspect AAwtEventDispatcherThreadProtection { pointcut awtComponentMethod(java.awt.Component component): target(component) && call(* *.*(..)); before(java.awt.Component component): awtComponentMethod(component) { if (!SwingUtilities.isEventDispatchThread() && component.isDisplayable()) { System.err.println("AWT Component method called from another Thread than the AWT-EventDispatchThread! source: " + thisJoinPoint.getSourceLocation() + ", target: " + thisJoinPoint.toLongString()); } } } ---------------- DETAILS (shortened because the size exceeded the 65k limit): java.lang.NullPointerException at at org.aspectj.weaver.bcel.BcelShadow.ensureTargetTypeIsCorrect(BcelShadow.java:1313) at at org.aspectj.weaver.bcel.BcelShadow.initializeTargetVar(BcelShadow.java:1274) at at org.aspectj.weaver.bcel.BcelShadow.getTargetVar(BcelShadow.java:968) at at org.aspectj.weaver.patterns.ThisOrTargetPointcut.findResidueInternal(ThisOrTargetPointcut.java:185) at at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at at org.aspectj.weaver.bcel.BcelAdvice.specializeOn(BcelAdvice.java:132) at at org.aspectj.weaver.bcel.BcelShadow.prepareForMungers(BcelShadow.java:313) at at org.aspectj.weaver.Shadow.implement(Shadow.java:404) at at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public class com.sun.imageio.plugins.gif.GIFImageMetadata extends javax.imageio.metadata.IIOMetadata:
resolved wontfix
4934132
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-30T10:24:49Z
2006-01-30T00:13:20Z
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 * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ 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.ALOAD; 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.INVOKEINTERFACE; 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.ISourceLocation; 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.MemberImpl; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; 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 // SECRETAPI - for testing, this will tell us if the optimization succeeded *on the last shadow processed* public static boolean appliedLazyTjpOptimization; // Some instructions have a target type that will vary // from the signature (pr109728) (1.4 declaring type issue) private String actualInstructionTargetType; // ---- 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 instruction 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); } // Now make any jumps to the 'new', the 'dup' or the 'end' now target the nextHandle 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--) { if (sources[i] instanceof ExceptionRange) { ExceptionRange it = (ExceptionRange)sources[i]; System.err.println("..."); it.updateTarget(old,fresh,it.getBody()); } else { sources[i].updateTarget(old, fresh); } } } } // records advice that is stopping us doing the lazyTjp optimization private List badAdvice = null; public void addAdvicePreventingLazyTjp(BcelAdvice advice) { if (badAdvice == null) badAdvice = new ArrayList(); badAdvice.add(advice); } 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) { if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) deleteNewAndDup(); // no new/dup for new array construction 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); UnresolvedType 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 = true;//world.isXlazyTjp(); // lazy is default now badAdvice = null; for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.specializeOn(this); } initializeThisJoinPoint(); if (thisJoinPointVar!=null && !isThisJoinPointLazy && badAdvice!=null && badAdvice.size()>1) { // something stopped us making it a lazy tjp // can't build tjp lazily, no suitable test... int valid = 0; for (Iterator iter = badAdvice.iterator(); iter.hasNext();) { BcelAdvice element = (BcelAdvice) iter.next(); ISourceLocation sLoc = element.getSourceLocation(); if (sLoc!=null && sLoc.getLine()>0) valid++; } if (valid!=0) { ISourceLocation[] badLocs = new ISourceLocation[valid]; int i = 0; for (Iterator iter = badAdvice.iterator(); iter.hasNext();) { BcelAdvice element = (BcelAdvice) iter.next(); ISourceLocation sLoc = element.getSourceLocation(); if (sLoc!=null) badLocs[i++]=sLoc; } world.getLint().multipleAdviceStoppingLazyTjp.signal( new String[] {this.toString()}, getSourceLocation(),badLocs ); } } badAdvice=null; // 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) { if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) { 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 UnresolvedType 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.makeJoinPointSignature(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.makeJoinPointSignature(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(); UnresolvedType catchType = exceptionRange.getCatchType(); UnresolvedType inType = enclosingMethod.getEnclosingClass().getType(); ResolvedMemberImpl sig = MemberImpl.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) { // this call marks the instruction list as changed constructor.getBody(); // UnresolvedType 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(); // // UnresolvedType 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) { BcelShadow ret = new BcelShadow( world, Initialization, world.makeJoinPointSignature(constructor), constructor, null); if (constructor.getEffectiveSignature() != null) { ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature()); } return ret; } public static BcelShadow makeUnfinishedPreinitialization( BcelWorld world, LazyMethodGen constructor) { BcelShadow ret = new BcelShadow( world, PreInitialization, world.makeJoinPointSignature(constructor), constructor, null); // ret.fallsThrough = true; if (constructor.getEffectiveSignature() != null) { ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature()); } 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.makeJoinPointSignatureFromMethod(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 = world.makeJoinPointSignatureForMethodInvocation( 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 makeArrayConstructorCall(BcelWorld world,LazyMethodGen enclosingMethod,InstructionHandle arrayInstruction,BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); Member sig = world.makeJoinPointSignatureForArrayConstruction(enclosingMethod.getEnclosingClass(),arrayInstruction); BcelShadow s = new BcelShadow( world, ConstructorCall, sig, enclosingMethod, enclosingShadow); ShadowRange r = new ShadowRange(body); r.associateWithShadow(s); r.associateWithTargets( Range.genStart(body, arrayInstruction), Range.genEnd(body, arrayInstruction)); retargetAllBranches(arrayInstruction, r.getStart()); return s; } // see pr77166 // public static BcelShadow makeArrayLoadCall( // BcelWorld world, // LazyMethodGen enclosingMethod, // InstructionHandle arrayInstruction, // BcelShadow enclosingShadow) // { // final InstructionList body = enclosingMethod.getBody(); // Member sig = world.makeJoinPointSignatureForArrayLoad(enclosingMethod.getEnclosingClass(),arrayInstruction); // BcelShadow s = // new BcelShadow( // world, // MethodCall, // sig, // enclosingMethod, // enclosingShadow); // ShadowRange r = new ShadowRange(body); // r.associateWithShadow(s); // r.associateWithTargets( // Range.genStart(body, arrayInstruction), // Range.genEnd(body, arrayInstruction)); // retargetAllBranches(arrayInstruction, 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, world.makeJoinPointSignatureForMethodInvocation( 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, ResolvedMember field, LazyMethodGen enclosingMethod, InstructionHandle getHandle, BcelShadow enclosingShadow) { final InstructionList body = enclosingMethod.getBody(); BcelShadow s = new BcelShadow( world, FieldGet, field, // 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.makeFieldJoinPointSignature( 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/*<UnresolvedType,BcelVar>*/ kindedAnnotationVars = null; private Map/*<UnresolvedType,BcelVar>*/ thisAnnotationVars = null; private Map/*<UnresolvedType,BcelVar>*/ targetAnnotationVars = null; private Map/*<UnresolvedType,BcelVar>*/[] argAnnotationVars = null; private Map/*<UnresolvedType,BcelVar>*/ withinAnnotationVars = null; private Map/*<UnresolvedType,BcelVar>*/ withincodeAnnotationVars = null; public Var getThisVar() { if (!hasThis()) { throw new IllegalStateException("no this"); } initializeThisVar(); return thisVar; } public Var getThisAnnotationVar(UnresolvedType 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(UnresolvedType 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,UnresolvedType 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(UnresolvedType forAnnotationType) { initializeKindedAnnotationVars(); return (Var) kindedAnnotationVars.get(forAnnotationType); } public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) { initializeWithinAnnotationVars(); return (Var) withinAnnotationVars.get(forAnnotationType); } public Var getWithinCodeAnnotationVar(UnresolvedType 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, boolean isAround) { if (!isAround){ if (!hasGuardTest) { isThisJoinPointLazy = false; } else { lazyTjpConsumers++; } } // if (!hasGuardTest) { // isThisJoinPointLazy = false; // } else { // lazyTjpConsumers++; // } if (thisJoinPointVar == null) { thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint")); } } public Var getThisJoinPointVar() { requireThisJoinPoint(false,false); return thisJoinPointVar; } void initializeThisJoinPoint() { if (thisJoinPointVar == null) return; if (isThisJoinPointLazy) { isThisJoinPointLazy = checkLazyTjp(); } if (isThisJoinPointLazy) { appliedLazyTjpOptimization = true; 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 { appliedLazyTjpOptimization = false; 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) { if (munger.getSourceLocation()!=null) { // do we know enough to bother reporting? 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) { // If we're lazy, build the join point right here. il.append(createThisJoinPoint()); // Does someone else need it? If so, store it for later retrieval 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 { // If not lazy, its already been built and stored, just retrieve it 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(ResolvedType.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(ResolvedType.OBJECT)); ((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.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; } /** * Get the Var for the jpStaticPart * @return */ public BcelVar getThisJoinPointStaticPartBcelVar() { return getThisJoinPointStaticPartBcelVar(false); } /** * Get the Var for the xxxxJpStaticPart, xxx = this or enclosing * @param isEnclosingJp true to have the enclosingJpStaticPart * @return */ public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) { if (thisJoinPointStaticPartVar == null) { Field field = getEnclosingClass().getTjpField(this, isEnclosingJp); ResolvedType sjpType = null; if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2 sjpType = world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart")); } else { sjpType = isEnclosingJp? world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$EnclosingStaticPart")): world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart")); } thisJoinPointStaticPartVar = new BcelFieldRef( sjpType, getEnclosingClass().getClassName(), field.getName()); // getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation()); } return thisJoinPointStaticPartVar; } /** * Get the Var for the enclosingJpStaticPart * @return */ public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() { if (enclosingShadow == null) { // the enclosing of an execution is itself return getThisJoinPointStaticPartBcelVar(true); } else { return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(true); } } //??? 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(UnresolvedType.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 UnresolvedType 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 UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) { if (tx.equals(ResolvedType.OBJECT) && getKind() == MethodCall && getSignature().getReturnType().equals(ResolvedType.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--) { UnresolvedType 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++) { UnresolvedType 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(); ResolvedType[] 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++) { ResolvedType 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...) } } protected Member getRelevantMember(Member foundMember, Member relevantMember, ResolvedType relevantType){ if (foundMember != null){ return foundMember; } foundMember = getSignature().resolve(world); if (foundMember == null && relevantMember != null) { foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember); } // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); if (fakerm.getName().equals(getSignature().getName()) && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())){ if (foundMember.getKind()==ResolvedMember.CONSTRUCTOR){ foundMember = AjcMemberMaker.interConstructor( relevantType, (ResolvedMember)foundMember, typeMunger.getAspectType()); } else { foundMember = AjcMemberMaker.interMethod((ResolvedMember)foundMember, typeMunger.getAspectType(), false); } // in the above.. what about if it's on an Interface? Can that happen? // then the last arg of the above should be true return foundMember; } } } return foundMember; } protected ResolvedType [] getAnnotations(Member foundMember, Member relevantMember, ResolvedType relevantType){ if (foundMember == null){ // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); //if (fakerm.hasAnnotations()) ResolvedMember ajcMethod = (getSignature().getKind()==ResolvedMember.CONSTRUCTOR? AjcMemberMaker.postIntroducedConstructor(typeMunger.getAspectType(),fakerm.getDeclaringType(),fakerm.getParameterTypes()): AjcMemberMaker.interMethodDispatcher(fakerm,typeMunger.getAspectType())); //AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType())); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); if (fakerm.getName().equals(getSignature().getName()) && fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) { relevantType = typeMunger.getAspectType(); foundMember = rmm; return foundMember.getAnnotationTypes(); } } } // didn't find in ITDs, look in supers foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember); if (foundMember == null) { throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType); } } return foundMember.getAnnotationTypes(); } 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 (UnresolvedType). // FIXME asc Refactor this code, there is duplication ResolvedType[] annotations = null; Member relevantMember = getSignature(); ResolvedType relevantType = relevantMember.getDeclaringType().resolve(world); if (getKind() == Shadow.StaticInitialization) { annotations = relevantType.resolve(world).getAnnotationTypes(); } else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) { Member foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(),getSignature()); annotations = getAnnotations(foundMember, relevantMember, relevantType); relevantMember = getRelevantMember(foundMember,relevantMember,relevantType); relevantType = relevantMember.getDeclaringType().resolve(world); } else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) { relevantMember = findField(relevantType.getDeclaredFields(),getSignature()); if (relevantMember==null) { // check the ITD'd dooberries List mungers = relevantType.resolve(world).getInterTypeMungers(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next(); if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); //if (fakerm.hasAnnotations()) ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType()); ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod); if (fakerm.equals(getSignature())) { relevantType = typeMunger.getAspectType(); relevantMember = rmm; } } } } annotations = relevantMember.getAnnotationTypes(); } else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution || getKind() == Shadow.AdviceExecution) { //ResolvedMember rm[] = relevantType.getDeclaredMethods(); Member foundMember = findMethod2(relevantType.getDeclaredMethods(),getSignature()); annotations = getAnnotations(foundMember, relevantMember,relevantType); relevantMember = foundMember; relevantMember = getRelevantMember(foundMember, relevantMember,relevantType); } else if (getKind() == Shadow.ExceptionHandler) { relevantType = getSignature().getParameterTypes()[0].resolve(world); annotations = relevantType.getAnnotationTypes(); } else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) { ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(),getSignature()); 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("Couldn't discover annotations for shadow: "+getKind()); } for (int i = 0; i < annotations.length; i++) { ResolvedType aTX = annotations[i]; KindedAnnotationAccessVar kaav = new KindedAnnotationAccessVar(getKind(),aTX.resolve(world),relevantType,relevantMember); kindedAnnotationVars.put(aTX,kaav); } } //FIXME asc whats the real diff between this one and the version in findMethod()? ResolvedMember findMethod2(ResolvedMember rm[], Member sig) { 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().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature())) found = member; } return found; } private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); for (int i = 0; i < decMethods.length; i++) { ResolvedMember member = decMethods[i]; if (member.equals(ajcMethod)) return member; } return null; } private ResolvedMember findField(ResolvedMember[] members,Member lookingFor) { for (int i = 0; i < members.length; i++) { ResolvedMember member = members[i]; if ( member.getName().equals(getSignature().getName()) && member.getType().equals(getSignature().getType())) { return member; } } return null; } public void initializeWithinAnnotationVars() { if (withinAnnotationVars != null) return; withinAnnotationVars = new HashMap(); ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { ResolvedType 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. ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes(); for (int i = 0; i < annotations.length; i++) { ResolvedType 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, UnresolvedType.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()) { UnresolvedType tempVarType = getReturnType(); if (tempVarType.equals(ResolvedType.VOID)) { tempVar = genTempVar(UnresolvedType.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, UnresolvedType 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>")) { ResolvedType 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, UnresolvedType 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,UnresolvedType t) { if (t.resolve(world).isInterface()) return; // Don't initialize statics in final InstructionFactory fact = getFactory(); InstructionList entryInstructions = new InstructionList(); InstructionList entrySuccessInstructions = new InstructionList(); 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(ResolvedType.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(false); 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(UnresolvedType.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(false).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(); //Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type if (mungerSig instanceof ResolvedMember) { ResolvedMember rm = (ResolvedMember)mungerSig; if (rm.hasBackingGenericMember()) mungerSig = rm.getBackingGenericMember(); } ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(),true); if (declaringType.isMissing()) { world.getLint().cantFindType.signal( new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName())}, getSourceLocation(), new ISourceLocation[]{ munger.getSourceLocation()} ); // 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.isParameterizedType()?declaringType.getGenericType():declaringType)); LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig); if (!adviceMethod.getCanInline()) { weaveAroundClosure(munger, hasDynamicTest); return; } // specific test for @AJ proceedInInners if (munger.getConcreteAspect().isAnnotationStyleAspect()) { // if we can't find one proceed() // we suspect that the call is happening in an inner class // so we don't inline it. // Note: for code style, this is done at Aspect compilation time. boolean canSeeProceedPassedToOther = false; InstructionHandle curr = adviceMethod.getBody().getStart(); InstructionHandle end = adviceMethod.getBody().getEnd(); ConstantPoolGen cpg = adviceMethod.getEnclosingClass().getConstantPoolGen(); while (curr != end) { InstructionHandle next = curr.getNext(); Instruction inst = curr.getInstruction(); if ((inst instanceof InvokeInstruction) && ((InvokeInstruction)inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) { // we may want to refine to exclude stuff returning jp ? // does code style skip inline if i write dump(thisJoinPoint) ? canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous break; } curr = next; } if (canSeeProceedPassedToOther) { // remember this decision to avoid re-analysis adviceMethod.setCanInline(false); 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, BcelWorld.makeBcelType(mungerSig.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, (munger.getConcreteAspect().isAnnotationStyleAspect() && munger.getDeclaringAspect()!=null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect())? this.loadThisJoinPoint(): new InstructionList(InstructionConstants.ACONST_NULL))); // adviceMethodInvocation = advice.append( Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature())); advice.append( Utility.createConversion( getFactory(), BcelWorld.makeBcelType(mungerSig.getReturnType()), extractedMethod.getReturnType(),world.isInJava5Mode())); 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. // inlining support for code style aspects if (!munger.getConcreteAspect().isAnnotationStyleAspect()) { 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. } else { //ATAJ inlining support for @AJ aspects // [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body] 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 INVOKEINTERFACE) && "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) { final boolean isProceedWithArgs; if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) { // proceed with args as a boxed Object[] isProceedWithArgs = true; } else { isProceedWithArgs = false; } InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle( fact, extractedMethod, munger, localAdviceMethod, proceedVarList, isProceedWithArgs ); localAdviceMethod.getBody().append(curr, insteadProceedIl); Utility.deleteInstruction(curr, localAdviceMethod); } curr = next; } } } 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(true); IntMap proceedMap = makeProceedArgumentMap(adviceVars); // System.out.println(proceedMap + " for " + this); // System.out.println(argVarList); ResolvedType[] proceedParamTypes = world.resolve(munger.getSignature().getParameterTypes()); // remove this*JoinPoint* as arguments to proceed if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) { int len = munger.getBaseParameterCount()+1; ResolvedType[] newTypes = new ResolvedType[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]; ResolvedType 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; } /** * ATAJ Handle the inlining for @AJ aspects * * @param fact * @param callbackMethod * @param munger * @param localAdviceMethod * @param argVarList * @param isProceedWithArgs * @return */ private InstructionList getRedoneProceedCallForAnnotationStyle( InstructionFactory fact, LazyMethodGen callbackMethod, BcelAdvice munger, LazyMethodGen localAdviceMethod, List argVarList, boolean isProceedWithArgs) { // Notes: // proceedingjp is on stack (since user was calling pjp.proceed(...) // the boxed args to proceed() are on stack as well (Object[]) unless // the call is to pjp.proceed(<noarg>) // new Object[]{new Integer(argAdvice1-1)};// arg of proceed // call to proceed(..) is NOT made // instead we do // itar callback args i // get from array i, convert it to the callback arg i // if ask for JP, push the one we got on the stack // invoke callback, create conversion back to Object/Integer // rest of method -- (hence all those conversions) // intValue() from original code // int res = .. from original code //Note: we just don't care about the proceed map etc InstructionList ret = new InstructionList(); // store the Object[] array on stack if proceed with args if (isProceedWithArgs) { Type objectArrayType = Type.getType("[Ljava/lang/Object;"); int localProceedArgArray = localAdviceMethod.allocateLocal(objectArrayType); ret.append(InstructionFactory.createStore(objectArrayType, localProceedArgArray)); Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;"); int localJp = localAdviceMethod.allocateLocal(proceedingJpType); ret.append(InstructionFactory.createStore(proceedingJpType, localJp)); // push on stack each element of the object array // that is assumed to be consistent with the callback argument (ie munger args) // TODO do we want to try catch ClassCast and AOOBE exception ? // special logic when withincode is static or not int startIndex = 0; if (thisVar != null) { startIndex = 1; //TODO this logic is actually depending on target as well - test me ret.append(new ALOAD(0));//thisVar } for (int i = startIndex, len=callbackMethod.getArgumentTypes().length; i < len; i++) { Type stateType = callbackMethod.getArgumentTypes()[i]; BcelWorld.fromBcel(stateType).resolve(world); if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { ret.append(new ALOAD(localJp));// from localAdvice signature } else { ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray)); ret.append(Utility.createConstant(fact, i-startIndex)); ret.append(InstructionFactory.createArrayLoad(Type.OBJECT)); ret.append(Utility.createConversion( fact, Type.OBJECT, stateType )); } } } else { Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;"); int localJp = localAdviceMethod.allocateLocal(proceedingJpType); ret.append(InstructionFactory.createStore(proceedingJpType, localJp)); for (int i = 0, len=callbackMethod.getArgumentTypes().length; i < len; i++) { Type stateType = callbackMethod.getArgumentTypes()[i]; /*ResolvedType stateTypeX =*/ BcelWorld.fromBcel(stateType).resolve(world); if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { ret.append(new ALOAD(localJp));// from localAdvice signature // } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) { // //FIXME ALEX? // ret.append(new ALOAD(localJp));// from localAdvice signature //// ret.append(fact.createCheckCast( //// (ReferenceType) BcelWorld.makeBcelType(stateTypeX) //// )); // // cast ? // } else { ret.append(InstructionFactory.createLoad(stateType, i)); } } } // do the callback invoke ret.append(Utility.createInvoke(fact, callbackMethod)); // box it again. Handles cases where around advice does return something else than Object if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) { ret.append(Utility.createConversion( fact, callbackMethod.getReturnType(), Type.OBJECT )); } ret.append(Utility.createConversion( fact, callbackMethod.getReturnType(), BcelWorld.makeBcelType(munger.getSignature().getReturnType()) )); return ret; // // // // if (proceedMap.hasKey(i)) { // ret.append(new ALOAD(i)); // //throw new RuntimeException("unimplemented"); // //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX); // } else { // //((BcelVar) argVarList.get(i)).appendLoad(ret, fact); // //ret.append(new ALOAD(i)); // if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) { // ret.append(new ALOAD(i)); // } else { // ret.append(new ALOAD(i)); // } // } // } // // ret.append(Utility.createInvoke(fact, callbackMethod)); // ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(), // BcelWorld.makeBcelType(munger.getSignature().getReturnType()))); // // //ret.append(new ACONST_NULL());//will be POPed // if (true) return ret; // // // // // 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); // // ResolvedType[] proceedParamTypes = // world.resolve(munger.getSignature().getParameterTypes()); // // remove this*JoinPoint* as arguments to proceed // if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) { // int len = munger.getBaseParameterCount()+1; // ResolvedType[] newTypes = new ResolvedType[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]; // ResolvedType 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(true); String closureClassName = NameMangler.makeClosureClassName( getEnclosingClass().getType(), getEnclosingClass().getNewGeneratedNameTag()); Member constructorSig = new MemberImpl(Member.CONSTRUCTOR, UnresolvedType.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(UnresolvedType.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++) { UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]); ResolvedType stateRTX = world.resolve(bcelTX,true); if (stateRTX.isMissing()) { world.getLint().cantFindType.signal( new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName())}, getSourceLocation(), new ISourceLocation[]{ munger.getSourceLocation()} ); // 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(),world.isInJava5Mode()); if (!isFallsThrough()) { returnConversionCode.append( InstructionFactory.createReturn(callbackMethod.getReturnType())); } } // ATAJ for @AJ aspect we need to link the closure with the joinpoint instance if (munger.getConcreteAspect()!=null && munger.getConcreteAspect().isAnnotationStyleAspect() && munger.getDeclaringAspect()!=null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) { closureInstantiation.append(Utility.createInvoke( getFactory(), getWorld(), new MemberImpl( Member.METHOD, UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"), Modifier.PUBLIC, "linkClosureAndJoinPoint", "()Lorg/aspectj/lang/ProceedingJoinPoint;" ) )); } InstructionList advice = new InstructionList(); advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation)); // invoke the advice 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(UnresolvedType.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[] {}, getWorld()); 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(UnresolvedType.OBJECTARRAY.resolve(world), 1); // int proceedVarIndex = 1; BcelVar stateVar = new BcelVar(UnresolvedType.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]; ResolvedType 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("Attempt to extract method from a shadow kind that does not support this operation (" + getKind() + ")"); 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(UnresolvedType.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++) { UnresolvedType 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) { UnresolvedType targetType = getTargetType(); targetType = ensureTargetTypeIsCorrect(targetType); // see pr109728 - this fixes the case when the declaring class is sometype 'X' but the getfield // in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally // mentioned in the fieldget instruction as the method parameter and *not* the type upon which the // field is declared because when the instructions are extracted into the new around body, // they will still refer to the subtype. if (getKind()==FieldGet && getActualTargetType()!=null && !getActualTargetType().equals(targetType.getName())) { targetType = UnresolvedType.forName(getActualTargetType()).resolve(world); } ResolvedMember resolvedMember = getSignature().resolve(world); if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) && !samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) && !resolvedMember.getName().equals("clone")) { if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) { throw new BCException("bad bytecode"); } targetType = getThisType(); } parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes); } if (thisVar != null) { UnresolvedType 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); //FIXME ALEX? which one //parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes); } UnresolvedType returnType; if (getKind() == PreInitialization) { returnType = UnresolvedType.OBJECTARRAY; } else { returnType = getReturnType(); } return new LazyMethodGen( modifiers, BcelWorld.makeBcelType(returnType), newMethodName, parameterTypes, new String[0], // XXX again, we need to look up methods! // UnresolvedType.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(UnresolvedType typeX) { return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize())); } // public static final boolean CREATE_TEMP_NAMES = true; public BcelVar genTempVar(UnresolvedType 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 { // For staticinitialization, if we have a nice offset, don't build a new source loc if (getKind()==Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset()!=0) { return getEnclosingClass().getType().getSourceLocation(); } else { int offset = 0; Kind kind = getKind(); if ( (kind == MethodExecution) || (kind == ConstructorExecution) || (kind == AdviceExecution) || (kind == StaticInitialization) || (kind == PreInitialization) || (kind == Initialization)) { if (getEnclosingMethod().hasDeclaredLineNumberInfo()) { offset = getEnclosingMethod().getDeclarationOffset(); } } return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset); } } } public Shadow getEnclosingShadow() { return enclosingShadow; } public LazyMethodGen getEnclosingMethod() { return enclosingMethod; } public boolean isFallsThrough() { return !terminatesWithReturn(); //fallsThrough; } public void setActualTargetType(String className) { this.actualInstructionTargetType = className; } public String getActualTargetType() { return actualInstructionTargetType; } }
125,809
Bug 125809 AjTypeDeclaration in the dom shouldn't have the properties of it's subtype AspectDeclaration
The AjTypeDeclaration should not have the properties 'privileged' and 'perClause' which it's subtype AspectDeclaration has. This was shown up whilst building an aspectj for ajdt and a failure in one of the visitor tests.
resolved fixed
eec4990
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-31T12:53:10Z
2006-01-31T12:20:00Z
org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjTypeDeclaration.java
/******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.org.eclipse.jdt.core.dom; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This subtype of TypeDeclaration allows for the extensions that AspectJ * has for types - they might be aspects and pointcuts may exist in * classes. This type does not represent an aspect, that is represented * by AspectDeclaration, a further subtype of AjTypeDeclaration. */ public class AjTypeDeclaration extends TypeDeclaration { /** * The "aspect" structural property of this node type. * @since 3.0 */ public static final SimplePropertyDescriptor ASPECT_PROPERTY = new SimplePropertyDescriptor(TypeDeclaration.class, "aspect", boolean.class, MANDATORY); //$NON-NLS-1$ // Need to fix up the property lists created during the super's static initializer static { // Need to fix up the property lists created during the super's static initializer List temporary = new ArrayList(); createPropertyList(TypeDeclaration.class, temporary); temporary.addAll(PROPERTY_DESCRIPTORS_2_0); addProperty(ASPECT_PROPERTY, temporary); PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(temporary); temporary.clear(); createPropertyList(TypeDeclaration.class, temporary); temporary.addAll(PROPERTY_DESCRIPTORS_3_0); addProperty(ASPECT_PROPERTY, temporary); PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(temporary); } /** * <code>true</code> for an aspect, <code>false</code> for a class or interface. * Defaults to class. */ private boolean isAspect = false; /** * Creates a new AST node for a type declaration owned by the given * AST. By default, the type declaration is for a class of an * unspecified, but legal, name; no modifiers; no javadoc; * no type parameters; no superclass or superinterfaces; and an empty list * of body declarations. * <p> * N.B. This constructor is package-private; all subclasses must be * declared in the same package; clients are unable to declare * additional subclasses. * </p> * * @param ast the AST that is to own this node */ public AjTypeDeclaration(AST ast) { super(ast); } /* (omit javadoc for this method) * Method declared on ASTNode. */ boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) { if (property == ASPECT_PROPERTY) { if (get) { return isAspect(); } else { setAspect(value); return false; } } // allow default implementation to flag the error return super.internalGetSetBooleanProperty(property, get, value); } /** * Returns whether this type declaration declares a class or an * aspect. * * @return <code>true</code> if this is an aspect declaration, * and <code>false</code> if this is a class or interface declaration */ public boolean isAspect() { return this.isAspect; } /** * Sets whether this type declaration declares a class or an * aspect. * * @param isAspect <code>true</code> if this is an aspect * declaration, and <code>false</code> if this is a class or interface * declaration */ public void setAspect(boolean isAspect) { preValueChange(ASPECT_PROPERTY); this.isAspect = isAspect; postValueChange(ASPECT_PROPERTY); } public PointcutDeclaration[] getPointcuts() { // ajh02: method added, currently returning none :-/ List bd = bodyDeclarations(); // ajh02: 0 bodyDeclarations :-/ int pointcutCount = 0; for (Iterator it = bd.listIterator(); it.hasNext(); ) { if (it.next() instanceof PointcutDeclaration) { pointcutCount++; } } PointcutDeclaration[] pointcuts = new PointcutDeclaration[pointcutCount]; int next = 0; for (Iterator it = bd.listIterator(); it.hasNext(); ) { Object decl = it.next(); if (decl instanceof PointcutDeclaration) { pointcuts[next++] = (PointcutDeclaration) decl; } } return pointcuts; } public ASTNode.NodeList getSuperInterfaceNames() { return superInterfaceNames; } public ASTNode.NodeList getTypeParameters() { return typeParameters; } }
125,809
Bug 125809 AjTypeDeclaration in the dom shouldn't have the properties of it's subtype AspectDeclaration
The AjTypeDeclaration should not have the properties 'privileged' and 'perClause' which it's subtype AspectDeclaration has. This was shown up whilst building an aspectj for ajdt and a failure in one of the visitor tests.
resolved fixed
eec4990
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-31T12:53:10Z
2006-01-31T12:20:00Z
org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AspectDeclaration.java
/******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.org.eclipse.jdt.core.dom; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * AspectDeclaration DOM AST node. * * Has everything an AjTypeDeclaration has plus: * an ASTNode called 'perClause' * a boolean called 'privileged' * * @author ajh02 * */ public class AspectDeclaration extends AjTypeDeclaration { public static final ChildPropertyDescriptor PERCLAUSE_PROPERTY = new ChildPropertyDescriptor(AspectDeclaration.class, "perClause", ASTNode.class, OPTIONAL, NO_CYCLE_RISK); //$NON-NLS-1$ public static final SimplePropertyDescriptor PRIVILEGED_PROPERTY = new SimplePropertyDescriptor(AspectDeclaration.class, "privileged", boolean.class, MANDATORY); //$NON-NLS-1$ static { List temporary = new ArrayList(); createPropertyList(AspectDeclaration.class, temporary); temporary.addAll(PROPERTY_DESCRIPTORS_2_0); addProperty(PERCLAUSE_PROPERTY, temporary); addProperty(PRIVILEGED_PROPERTY, temporary); PROPERTY_DESCRIPTORS_2_0 = reapPropertyList(temporary); temporary.clear(); createPropertyList(AspectDeclaration.class, temporary); temporary.addAll(PROPERTY_DESCRIPTORS_3_0); addProperty(PERCLAUSE_PROPERTY, temporary); addProperty(PRIVILEGED_PROPERTY, temporary); PROPERTY_DESCRIPTORS_3_0 = reapPropertyList(temporary); } protected ASTNode perClause = null; // stays null if the aspect is an _implicit_ persingleton() /** * <code>true</code> for a privileged aspect, <code>false</code> otherwise. * Defaults to not privileged. */ private boolean isPrivileged = false; AspectDeclaration(AST ast) { super(ast); } AspectDeclaration(AST ast, ASTNode perClause) { this(ast); this.perClause = perClause; setAspect(true); } AspectDeclaration(AST ast, ASTNode perClause, boolean isPrivileged) { this(ast, perClause); this.isPrivileged = isPrivileged; } /* (omit javadoc for this method) * Method declared on ASTNode. */ ASTNode clone0(AST target) { AspectDeclaration result = new AspectDeclaration(target, perClause); result.setSourceRange(this.getStartPosition(), this.getLength()); result.setJavadoc( (Javadoc) ASTNode.copySubtree(target, getJavadoc())); if (this.ast.apiLevel == AST.JLS2_INTERNAL) { result.internalSetModifiers(getModifiers()); result.setSuperclass( (Name) ASTNode.copySubtree(target, getSuperclass())); result.superInterfaces().addAll( ASTNode.copySubtrees(target, superInterfaces())); } result.setInterface(isInterface()); result.setAspect(isAspect()); result.setPrivileged(isPrivileged()); result.setName((SimpleName) getName().clone(target)); if (this.ast.apiLevel >= AST.JLS3) { result.modifiers().addAll(ASTNode.copySubtrees(target, modifiers())); result.typeParameters().addAll( ASTNode.copySubtrees(target, typeParameters())); result.setSuperclassType( (Type) ASTNode.copySubtree(target, getSuperclassType())); result.superInterfaceTypes().addAll( ASTNode.copySubtrees(target, superInterfaceTypes())); } result.bodyDeclarations().addAll( ASTNode.copySubtrees(target, bodyDeclarations())); result.setPerClause((ASTNode)getPerClause().clone(target)); return result; } /* (omit javadoc for this method) * Method declared on ASTNode. */ void accept0(ASTVisitor visitor) { boolean visitChildren = visitor.visit(this); if (visitChildren) { // visit children in normal left to right reading order if (this.ast.apiLevel == AST.JLS2_INTERNAL) { acceptChild(visitor, getJavadoc()); acceptChild(visitor, getName()); acceptChild(visitor, getSuperclass()); acceptChildren(visitor, this.superInterfaceNames); acceptChild(visitor, this.perClause); acceptChildren(visitor, this.bodyDeclarations); } if (this.ast.apiLevel >= AST.JLS3) { acceptChild(visitor, getJavadoc()); acceptChildren(visitor, this.modifiers); acceptChild(visitor, getName()); acceptChildren(visitor, this.typeParameters); acceptChild(visitor, getSuperclassType()); acceptChildren(visitor, this.superInterfaceTypes); acceptChild(visitor, this.perClause); acceptChildren(visitor, this.bodyDeclarations); } } visitor.endVisit(this); } /* (omit javadoc for this method) * Method declared on ASTNode and AjTypeDeclaration. */ final boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) { if (property == PRIVILEGED_PROPERTY) { if (get) { return isPrivileged(); } else { setPrivileged(value); return false; } } // allow default implementation to flag the error return super.internalGetSetBooleanProperty(property, get, value); } /* * (omit javadoc for this method) * Method declared on ASTNode. */ final ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property,boolean get, ASTNode child) { if (property == PERCLAUSE_PROPERTY) { if (get) { return getPerClause(); } else { setPerClause((ASTNode) child); return null; } } return super.internalGetSetChildProperty(property,get,child); } public ASTNode getPerClause(){ return perClause; } public void setPerClause(ASTNode perClause) { if (perClause == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.perClause; preReplaceChild(oldChild, perClause, PERCLAUSE_PROPERTY); this.perClause = perClause; postReplaceChild(oldChild, perClause, PERCLAUSE_PROPERTY); } /** * Returns whether this aspect is a privileged one. * * @return <code>true</code> if this is a privileged aspect * declaration, and <code>false</code> otherwise. */ public boolean isPrivileged() { return this.isPrivileged; } /** * Sets whether this aspect is a privileged one * * @param isPrivileged <code>true</code> if this is a privileged aspect * declaration, and <code>false</code> otherwise. */ public void setPrivileged(boolean isPrivileged) { preValueChange(PRIVILEGED_PROPERTY); this.isPrivileged = isPrivileged; postValueChange(PRIVILEGED_PROPERTY); } public List getAdvice() { // ajh02: method added List bd = bodyDeclarations(); List advice = new ArrayList(); for (Iterator it = bd.listIterator(); it.hasNext(); ) { Object decl = it.next(); if (decl instanceof AdviceDeclaration) { advice.add(decl); } } return advice; } // public PointcutDeclaration[] getPointcuts() { // // ajh02: method added, currently returning none :-/ // List bd = bodyDeclarations(); // // ajh02: 0 bodyDeclarations :-/ // int pointcutCount = 0; // for (Iterator it = bd.listIterator(); it.hasNext(); ) { // if (it.next() instanceof PointcutDeclaration) { // pointcutCount++; // } // } // PointcutDeclaration[] pointcuts = new PointcutDeclaration[pointcutCount]; // int next = 0; // for (Iterator it = bd.listIterator(); it.hasNext(); ) { // Object decl = it.next(); // if (decl instanceof PointcutDeclaration) { // pointcuts[next++] = (PointcutDeclaration) decl; // } // } // return pointcuts; // } }
125,809
Bug 125809 AjTypeDeclaration in the dom shouldn't have the properties of it's subtype AspectDeclaration
The AjTypeDeclaration should not have the properties 'privileged' and 'perClause' which it's subtype AspectDeclaration has. This was shown up whilst building an aspectj for ajdt and a failure in one of the visitor tests.
resolved fixed
eec4990
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-01-31T12:53:10Z
2006-01-31T12:20:00Z
org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/AjASTTest.java
/******************************************************************** * Copyright (c) 2006 Contributors. All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation * Helen Hawkins - iniital version *******************************************************************/ package org.aspectj.tools.ajc; import java.util.HashMap; import java.util.Iterator; import java.util.List; import junit.framework.TestCase; import org.aspectj.org.eclipse.jdt.core.dom.AST; import org.aspectj.org.eclipse.jdt.core.dom.ASTNode; import org.aspectj.org.eclipse.jdt.core.dom.ASTParser; import org.aspectj.org.eclipse.jdt.core.dom.AfterAdviceDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.AfterReturningAdviceDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.AfterThrowingAdviceDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.AjAST; import org.aspectj.org.eclipse.jdt.core.dom.AjASTVisitor; import org.aspectj.org.eclipse.jdt.core.dom.AjTypeDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.AndPointcut; import org.aspectj.org.eclipse.jdt.core.dom.AroundAdviceDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.AspectDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.BeforeAdviceDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.Block; import org.aspectj.org.eclipse.jdt.core.dom.CflowPointcut; import org.aspectj.org.eclipse.jdt.core.dom.ChildListPropertyDescriptor; import org.aspectj.org.eclipse.jdt.core.dom.ChildPropertyDescriptor; import org.aspectj.org.eclipse.jdt.core.dom.CompilationUnit; import org.aspectj.org.eclipse.jdt.core.dom.DeclareAtConstructorDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.DeclareAtFieldDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.DeclareAtMethodDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.DeclareAtTypeDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.DeclareErrorDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.DeclareParentsDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.DeclarePrecedenceDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.DeclareSoftDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.DeclareWarningDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.DefaultPointcut; import org.aspectj.org.eclipse.jdt.core.dom.DefaultTypePattern; import org.aspectj.org.eclipse.jdt.core.dom.InterTypeFieldDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.InterTypeMethodDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.NotPointcut; import org.aspectj.org.eclipse.jdt.core.dom.OrPointcut; import org.aspectj.org.eclipse.jdt.core.dom.PerCflow; import org.aspectj.org.eclipse.jdt.core.dom.PerObject; import org.aspectj.org.eclipse.jdt.core.dom.PerTypeWithin; import org.aspectj.org.eclipse.jdt.core.dom.PointcutDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.PrimitiveType; import org.aspectj.org.eclipse.jdt.core.dom.ReferencePointcut; import org.aspectj.org.eclipse.jdt.core.dom.SignaturePattern; import org.aspectj.org.eclipse.jdt.core.dom.SimpleName; import org.aspectj.org.eclipse.jdt.core.dom.SimplePropertyDescriptor; import org.aspectj.org.eclipse.jdt.core.dom.SimpleType; import org.aspectj.org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.aspectj.org.eclipse.jdt.core.dom.StringLiteral; import org.aspectj.org.eclipse.jdt.core.dom.Type; import org.aspectj.org.eclipse.jdt.core.dom.TypePattern; /** * For each AspectJ ASTNode there is a test for: * * - that a new instance can be created via ajast.newXXX() * - that the property descriptors have been set correctly * - that the get/set methods for the different properties * work as expected * - that the clone0 method sets the correct properties * - that the internalStructuralPropertiesForType(int) and * internalGetSetXXXProperty(..) methods have been implemented * correctly * * These are all that is required for an ASTNode, except an * implementation of the accept0() method which is tested * in ASTVisitorTest. */ public class AjASTTest extends TestCase { // -------------- DefaultPointcut tests --------------- public void testNewDefaultPointcut() { AjAST ajast = createAjAST(); DefaultPointcut p = ajast.newDefaultPointcut(); assertNotNull("a new DefaultPointcut should have been created",p); } public void testGetAndSetDetail() { AjAST ajast = createAjAST(); DefaultPointcut p = ajast.newDefaultPointcut(); assertEquals("The default detail should be the empty string","",p.getDetail()); p.setDetail("some detail"); assertEquals("The detail should now be 'some detail'","some detail",p.getDetail()); } // -------------- ReferencePointcut tests --------------- public void testNewReferencePointcut() { AjAST ajast = createAjAST(); ReferencePointcut p = ajast.newReferencePointcut(); assertNotNull("a new ReferencePointcut should have been created",p); } /** * ReferencePointcut's have a name property - tests * the getting and setting of this property */ public void testGetAndSetRefPointcutName() { AjAST ajast = createAjAST(); ReferencePointcut p = ajast.newReferencePointcut(); assertEquals("the default reference pointcut name should be MISSING", "MISSING",p.getName().getFullyQualifiedName()); p.setName(ajast.newSimpleName("refPointcutName")); assertEquals("the pointcut name should now be set to 'refPointcutName'", "refPointcutName",p.getName().getFullyQualifiedName()); } public void testNewAndPointcut() { AjAST ajast = createAjAST(); AndPointcut p = ajast.newAndPointcut(); assertNotNull("a new AndPointcut should have been created",p); } // -------------- AndPointcut tests --------------- /** * AndPointcut's have a left property - test the getting * and setting of this property */ public void testGetAndSetLeftOfAndPointcut() { AjAST ajast = createAjAST(); AndPointcut ap = ajast.newAndPointcut(); assertNull("by default the left side of an AndPointcut should be null", ap.getLeft()); ReferencePointcut p = ajast.newReferencePointcut(); ap.setLeft(p); assertEquals("the left side of the AndPointcut should now be the" + " ReferencePointcut",p,ap.getLeft()); } /** * AndPointcut's have a right property - test the getting * and setting of this property */ public void testGetAndSetRightOfAndPointcut() { AjAST ajast = createAjAST(); AndPointcut ap = ajast.newAndPointcut(); assertNull("by default the right side of an AndPointcut should be null", ap.getRight()); ReferencePointcut p = ajast.newReferencePointcut(); ap.setRight(p); assertEquals("the right side of the AndPointcut should now be the" + " ReferencePointcut",p,ap.getRight()); } // -------------- CflowPointcut tests --------------- public void testNewCflowPointcut() { AjAST ajast = createAjAST(); CflowPointcut p = ajast.newCflowPointcut(); assertNotNull("a new CflowPointcut should have been created",p); } /** * CflowPointcut's have a body property - test the getting * and setting of this property */ public void testGetAndSetBodyOfCflowPointcut() { AjAST ajast = createAjAST(); CflowPointcut p = ajast.newCflowPointcut(); assertNull("by default a CflowPointcut should have a null body",p.getBody()); ReferencePointcut rp = ajast.newReferencePointcut(); p.setBody(rp); assertEquals("the body of the CflowPointcut should now be a " + "ReferencePointcut", rp, p.getBody()); } // -------------- NotPointcut tests --------------- public void testNewNotPointcut() { AjAST ajast = createAjAST(); NotPointcut p = ajast.newNotPointcut(); assertNotNull("a new NotPointcut should have been created",p); } /** * NotPointcut's have a body property - test the getting * and setting of this property */ public void testGetAndSetBodyOfNotPointcut() { AjAST ajast = createAjAST(); NotPointcut p = ajast.newNotPointcut(); assertNull("by default a NotPointcut should have a null body",p.getBody()); ReferencePointcut rp = ajast.newReferencePointcut(); p.setBody(rp); assertEquals("the body of the NotPointcut should now be a " + "ReferencePointcut", rp, p.getBody()); } // -------------- OrPointcut tests --------------- public void testNewOrPointcut() { AjAST ajast = createAjAST(); OrPointcut p = ajast.newOrPointcut(); assertNotNull("a new OrPointcut should have been created",p); } /** * OrPointcut's have a left property - test the getting * and setting of this property */ public void testGetAndSetLeftOfOrPointcut() { AjAST ajast = createAjAST(); OrPointcut op = ajast.newOrPointcut(); assertNull("by default the left side of an OrPointcut should be null", op.getLeft()); ReferencePointcut p = ajast.newReferencePointcut(); op.setLeft(p); assertEquals("the left side of the OrPointcut should now be the" + " ReferencePointcut",p,op.getLeft()); } /** * OrPointcut's have a right property - test the getting * and setting of this property */ public void testGetAndSetRightOfOrPointcut() { AjAST ajast = createAjAST(); OrPointcut op = ajast.newOrPointcut(); assertNull("by default the right side of an OrPointcut should be null", op.getRight()); ReferencePointcut p = ajast.newReferencePointcut(); op.setRight(p); assertEquals("the right side of the OrPointcut should now be the" + " ReferencePointcut",p,op.getRight()); } // -------------- PerCflow tests --------------- public void testNewPerCflow() { AjAST ajast = createAjAST(); PerCflow p = ajast.newPerCflow(); assertNotNull("a new PerCflow should have been created",p); } /** * PerCflow's have a body property - test the getting * and setting of this property */ public void testGetAndSetBodyOfPerCflow() { AjAST ajast = createAjAST(); PerCflow p = ajast.newPerCflow(); assertNull("by default a PerCflow should have a null body",p.getBody()); ReferencePointcut rp = ajast.newReferencePointcut(); p.setBody(rp); assertEquals("the body of the PerCflow should now be a " + "ReferencePointcut", rp, p.getBody()); } // -------------- PerObject tests --------------- public void testNewPerObject() { AjAST ajast = createAjAST(); PerObject p = ajast.newPerObject(); assertNotNull("a new PerObject should have been created",p); } /** * PerObject's have a body property - test the getting * and setting of this property */ public void testGetAndSetBodyOfPerObject() { AjAST ajast = createAjAST(); PerObject p = ajast.newPerObject(); assertNull("by default a PerObject should have a null body",p.getBody()); ReferencePointcut rp = ajast.newReferencePointcut(); p.setBody(rp); assertEquals("the body of the PerObject should now be a " + "ReferencePointcut", rp, p.getBody()); } // -------------- PerTypeWithin tests --------------- public void testNewPerTypeWithin() { AjAST ajast = createAjAST(); PerTypeWithin p = ajast.newPerTypeWithin(); assertNotNull("a new PerTypeWithin should have been created",p); } // -------------- DefaultTypePattern tests --------------- public void testNewDefaultTypePattern() { AjAST ajast = createAjAST(); DefaultTypePattern p = ajast.newDefaultTypePattern(); assertNotNull("a new DefaultTypePattern should have been created",p); } public void testGetAndSetDetailInDefaultTypePattern() { AjAST ajast = createAjAST(); DefaultTypePattern p = ajast.newDefaultTypePattern(); assertEquals("The default detail should be the empty string","",p.getDetail()); p.setDetail("some detail"); assertEquals("The detail should now be 'some detail'","some detail",p.getDetail()); } public void testPropertyDescriptorsForDefaultTypePattern() { AjAST ajast = createAjAST(); DefaultTypePattern d = ajast.newDefaultTypePattern(); List props = DefaultTypePattern.propertyDescriptors(AST.JLS3); assertEquals("there should be no properties for the DefaultTypePattern", 0,props.size()); } public void testCloneDefaultTypePattern() { AjAST ajast = createAjAST(); DefaultTypePattern d = ajast.newDefaultTypePattern(); d.setDetail("new detail"); DefaultTypePattern copy = (DefaultTypePattern)ASTNode.copySubtree(ajast,d); assertEquals("the copy should have detail 'new detail'","new detail",copy.getDetail()); } // -------------- SignaturePattern tests --------------- public void testNewSignaturePattern() { AjAST ajast = createAjAST(); SignaturePattern p = ajast.newSignaturePattern(); assertNotNull("a new SignaturePattern should have been created",p); } public void testGetAndSetDetailInSignaturePattern() { AjAST ajast = createAjAST(); SignaturePattern p = ajast.newSignaturePattern(); assertEquals("The default detail should be the empty string","",p.getDetail()); p.setDetail("some detail"); assertEquals("The detail should now be 'some detail'","some detail",p.getDetail()); } public void testPropertyDescriptorsForSignaturePattern() { AjAST ajast = createAjAST(); SignaturePattern p = ajast.newSignaturePattern(); List props = SignaturePattern.propertyDescriptors(AST.JLS3); assertEquals("there should be no properties for the DefaultTypePattern", 0,props.size()); } public void testCloneDefaultSignaturePattern() { AjAST ajast = createAjAST(); SignaturePattern p = ajast.newSignaturePattern(); p.setDetail("new detail"); SignaturePattern copy = (SignaturePattern)ASTNode.copySubtree(ajast,p); assertEquals("the copy should have detail 'new detail'","new detail",copy.getDetail()); } // -------------- PointcutDeclaration tests --------------- public void testNewPointcutDeclaration() { AjAST ajast = createAjAST(); PointcutDeclaration pd = ajast.newPointcutDeclaration(); assertNotNull("a new PointcutDeclaration should have been created",pd); } /** * PointcutDeclarations's have a name property - test the getting * and setting of this property */ public void testGetAndSetPointcutName() { AjAST ajast = createAjAST(); PointcutDeclaration pd = ajast.newPointcutDeclaration(); assertEquals("the default pointcut name should be MISSING", "MISSING",pd.getName().getFullyQualifiedName()); pd.setName(ajast.newSimpleName("p")); assertEquals("the pointcut name should now be set to 'p'", "p",pd.getName().getFullyQualifiedName()); } /** * PointcutDeclarations's have a designator property - test the getting * and setting of this property */ public void testGetAndSetPointcutDesignator() { AjAST ajast = createAjAST(); PointcutDeclaration pd = ajast.newPointcutDeclaration(); assertNull("by default the pointcut designator is null",pd.getDesignator()); ReferencePointcut rp = ajast.newReferencePointcut(); pd.setDesignator(rp); assertEquals("should have set the pointcut designator to be " + "the ReferencePointcut",rp,pd.getDesignator()); } // -------------- AspectDeclaration tests --------------- public void testNewAspectDeclaration() { AjAST ajast = createAjAST(); AspectDeclaration ad = ajast.newAspectDeclaration(); assertNotNull("a new AspectDeclaration should have been created",ad); } public void testPropertyDescriptorsForAspectDeclaration() { AjAST ajast = createAjAST(); AspectDeclaration d = ajast.newAspectDeclaration(); List props = AspectDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundPerClause = false; boolean foundIsPrivileged = false; for (Iterator iter = props.iterator(); iter.hasNext();) { Object o = iter.next(); if ((o instanceof ChildPropertyDescriptor)) { ChildPropertyDescriptor element = (ChildPropertyDescriptor)o; String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; } else if (id.equals("perClause")) { foundPerClause = true; } } else if ((o instanceof SimplePropertyDescriptor) && ((SimplePropertyDescriptor)o).getId().equals("privileged")) { foundIsPrivileged = true; } } assertTrue("AspectDeclaration should have a javadoc PropertyDescriptor",foundJavadoc); assertTrue("AspectDeclaration should have a perClause PropertyDescriptor",foundPerClause); assertTrue("AspectDeclaration should have an isPrivileged PropertyDescriptor",foundIsPrivileged); } public void testCloneAspectDeclaration() { AjAST ajast = createAjAST(); AspectDeclaration d = ajast.newAspectDeclaration(); d.setPerClause(ajast.newPerTypeWithin()); d.setPrivileged(true); AspectDeclaration copy = (AspectDeclaration)ASTNode.copySubtree(ajast,d); assertNotNull("the AspectDeclaration clone should have a perClause set", copy.getPerClause()); assertTrue("the AspectDeclaration clone should be a 'privileged'", copy.isPrivileged()); } public void testInternalAspectDeclaration() { AjAST ajast = createAjAST(); AspectDeclaration d = ajast.newAspectDeclaration(); List props = AspectDeclaration.propertyDescriptors(AST.JLS3); for (Iterator iter = props.iterator(); iter.hasNext();) { Object o = iter.next(); if (o instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor element = (ChildPropertyDescriptor)o; if (element.getId().equals("perClause")) { assertNull("AspectDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet", d.getStructuralProperty(element)); } } else if (o instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor element = (SimplePropertyDescriptor)o; assertNotNull("AspectDeclaration's " + element.getId() + " property" + "should not be null since it is a boolean", d.getStructuralProperty(element)); } } for (Iterator iter = props.iterator(); iter.hasNext();) { Object o = iter.next(); if (o instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("perClause")) { PerTypeWithin ptw = ajast.newPerTypeWithin(); d.setStructuralProperty(element,ptw); assertEquals("AspectDeclaration's perClause property should" + " now be a perTypeWithin",ptw,d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc } } else if (o instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor element = (SimplePropertyDescriptor)o; if (element.getId().equals("privileged")) { Boolean b = new Boolean(true); d.setStructuralProperty(element,b); assertEquals("AspectDeclaration's isPrivileged property should" + " now be a boolean",b,d.getStructuralProperty(element)); } } } } /** * AsepctDeclarations's have a perClause property - test the getting * and setting of this property */ public void testSetPerClauseInAspectDeclaration() { AjAST ajast = createAjAST(); AspectDeclaration ad = ajast.newAspectDeclaration(); assertNull("by default the perClause should be null",ad.getPerClause()); PerCflow pcf = ajast.newPerCflow(); ad.setPerClause(pcf); assertEquals("should have set the perClause to be a PerCflow", pcf,ad.getPerClause()); } /** * AsepctDeclarations's have a isPrivileged property - test the getting * and setting of this property */ public void testSetPrivilegedInAspectDeclaration() { AjAST ajast = createAjAST(); AspectDeclaration ad = ajast.newAspectDeclaration(); assertFalse("by default the aspect should not be privileged",ad.isPrivileged()); ad.setPrivileged(true); assertTrue("the aspect should now privileged",ad.isPrivileged()); } // -------------- AfterAdviceDeclaration tests --------------- public void testNewAfterAdviceDeclaration() { AjAST ajast = createAjAST(); AfterAdviceDeclaration ad = ajast.newAfterAdviceDeclaration(); assertNotNull("a new AfterAdviceDeclaration should have been created",ad); } // -------------- BeforeAdviceDeclaration tests --------------- public void testNewBeforeAdviceDeclaration() { AjAST ajast = createAjAST(); BeforeAdviceDeclaration bd = ajast.newBeforeAdviceDeclaration(); assertNotNull("a new BeforeAdviceDeclaration should have been created",bd); } /** * AdviceDeclarations's have a pointcut property - test the getting * and setting of this property */ public void testGetAndSetPointcutInAdviceDeclaration() { AjAST ajast = createAjAST(); BeforeAdviceDeclaration bd = ajast.newBeforeAdviceDeclaration(); assertNull("by default there should be no pointcut associated with" + " the advice",bd.getPointcut()); AndPointcut p = ajast.newAndPointcut(); bd.setPointcut(p); assertEquals("there should now be an AndPointcut associated with" + " the advice",p,bd.getPointcut()); } /** * AdviceDeclarations's have a body property - test the getting * and setting of this property */ public void testGetAndSetBodyInAdviceDeclaration() { AjAST ajast = createAjAST(); BeforeAdviceDeclaration bd = ajast.newBeforeAdviceDeclaration(); assertNull("by default there should be no body associated with" + " the advice",bd.getBody()); Block b = ajast.newBlock(); bd.setBody(b); assertEquals("there should now be a body associated with" + " the advice",b,bd.getBody()); } // -------------- AfterReturningAdviceDeclaration tests --------------- public void testNewAfterReturningAdviceDeclaration() { AjAST ajast = createAjAST(); AfterReturningAdviceDeclaration d = ajast.newAfterReturningAdviceDeclaration(); assertNotNull("should have created an AfterReturningAdviceDeclaration",d); } /** * AfterReturningAdviceDeclarations's have a returning property - * test the getting and setting of this property */ public void testGetAndSetReturning() { AjAST ajast = createAjAST(); AfterReturningAdviceDeclaration d = ajast.newAfterReturningAdviceDeclaration(); assertNull("by default there should be no returning property associated with" + " the AfterReturningAdviceDeclaration",d.getReturning()); SingleVariableDeclaration s = ajast.newSingleVariableDeclaration(); d.setReturning(s); assertEquals("there should now be a returning property associated with" + " the AfterReturningAdviceDeclaration",s,d.getReturning()); } // -------------- AfterThrowingAdviceDeclaration tests --------------- public void testNewAfterThrowingAdviceDeclaration() { AjAST ajast = createAjAST(); AfterThrowingAdviceDeclaration d = ajast.newAfterThrowingAdviceDeclaration(); assertNotNull("should have created an AfterThrowingAdviceDeclaration",d); } /** * AfterThrowingAdviceDeclaration's have a throwing property - * test the getting and setting of this property */ public void testGetAndSetThrowing() { AjAST ajast = createAjAST(); AfterThrowingAdviceDeclaration d = ajast.newAfterThrowingAdviceDeclaration(); assertNull("by default there should be no throwing property associated with" + " the AfterThrowingAdviceDeclaration",d.getThrowing()); SingleVariableDeclaration s = ajast.newSingleVariableDeclaration(); d.setThrowing(s); assertEquals("there should now be a throwing property associated with" + " the AfterThrowingAdviceDeclaration",s,d.getThrowing()); } // -------------- AroundAdviceDeclaration tests --------------- public void testNewAroundAdviceDeclaration() { AjAST ajast = createAjAST(); AroundAdviceDeclaration d = ajast.newAroundAdviceDeclaration(); assertNotNull("should have created an AroundAdviceDeclaration",d); } /** * AroundAdviceDeclaration's have a return type property - * test the getting and setting of this property (different * implementation for JLS2 and JLS3) */ public void testGetAndSetReturnTypeJLS2() { AjAST ajast = createAjAST(AST.JLS2); AroundAdviceDeclaration d = ajast.newAroundAdviceDeclaration(); Type t = d.getReturnType(); assertTrue("by default the return type associated with the" + " AroundAdviceDeclaration should be a PrimitiveType", t instanceof PrimitiveType); assertEquals("by default there should be the PrimitiveType.VOID return " + "type associated with the AroundAdviceDeclaration", PrimitiveType.VOID.toString(),((PrimitiveType)t).toString()); SimpleType s = ajast.newSimpleType(ajast.newSimpleName("name")); d.setReturnType(s); assertEquals("there should now be a SimpleType return type associated with" + " the AroundAdviceDeclaration",s,d.getReturnType()); } /** * AroundAdviceDeclaration's have a return type property - * test the getting and setting of this property (different * implementation for JLS2 and JLS3) */ public void testGetAndSetReturnTypeJLS3() { AjAST ajast = createAjAST(); AroundAdviceDeclaration d = ajast.newAroundAdviceDeclaration(); Type t = d.getReturnType2(); assertTrue("by default the return type associated with the" + " AroundAdviceDeclaration should be a PrimitiveType", t instanceof PrimitiveType); assertEquals("by default there should be the PrimitiveType.VOID return " + "type associated with the AroundAdviceDeclaration", PrimitiveType.VOID.toString(),((PrimitiveType)t).toString()); SimpleType s = ajast.newSimpleType(ajast.newSimpleName("name")); d.setReturnType2(s); assertEquals("there should now be a SimpleType return type associated with" + " the AroundAdviceDeclaration",s,d.getReturnType2()); } // -------------- InterTypeFieldDeclaration tests --------------- public void testNewITDFieldDeclaration() { AjAST ajast = createAjAST(); InterTypeFieldDeclaration d = ajast.newInterTypeFieldDeclaration(); assertNotNull("should have created an InterTypeFieldDeclaration",d); } // -------------- InterTypeMethodDeclaration tests --------------- public void testNewITDMethodDeclaration() { AjAST ajast = createAjAST(); InterTypeMethodDeclaration d = ajast.newInterTypeMethodDeclaration(); assertNotNull("should have created an InterTypeMethodDeclaration",d); } // -------------- AjTypeDeclaration tests --------------- public void testNewAjTypeDeclaration() { AjAST ajast = createAjAST(); AjTypeDeclaration d = ajast.newAjTypeDeclaration(); assertNotNull("should have created an AjTypeDeclaration",d); } /** * AjTypeDeclaration's have an isAspect property - * test the getting and setting of this property */ public void testGetAndSetIsAspect() { AjAST ajast = createAjAST(); AjTypeDeclaration d = ajast.newAjTypeDeclaration(); assertFalse("by default an AjTypeDeclaration should be a class",d.isAspect()); d.setAspect(true); assertTrue("AjTypeDeclaration should now be an aspect",d.isAspect()); d.setAspect(false); assertFalse("AjTypeDeclaration should now be a class",d.isAspect()); } // -------------- DeclareAtFieldDeclaration tests --------------- public void testNewDeclareAtFieldDeclaration() { AjAST ajast = createAjAST(); DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration(); assertNotNull("should have created a DeclareAtFieldDeclaration",d); } public void testPropertyDescriptorsForDeclareAtField() { AjAST ajast = createAjAST(); DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration(); List props = DeclareAtFieldDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundPattern = false; boolean foundAnnotationName = false; for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor)iter.next(); String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; } else if (id.equals("pattern")) { foundPattern = true; } else if (id.equals("annotationName")) { foundAnnotationName = true; } else { fail("unknown PropertyDescriptor associated with DeclareAtFieldDeclaration: " + element.getId()); } } assertTrue("DeclareAtFieldDeclaration should have a javadoc PropertyDescriptor",foundJavadoc); assertTrue("DeclareAtFieldDeclaration should have a attern PropertyDescriptor",foundPattern); assertTrue("DeclareAtFieldDeclaration should have a annotationName PropertyDescriptor",foundAnnotationName); } public void testGetAndSetPatternNodeInDeclareAtField() { AjAST ajast = createAjAST(); DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration(); assertNull("by default there should be no typePattern associated with" + " the declare @field annotation",d.getPatternNode()); SignaturePattern p = ajast.newSignaturePattern(); d.setPatternNode(p); assertEquals("there should now be a DefaultTypePattern associated with" + " the declare @field annotation",p,d.getPatternNode()); } public void testGetAndSetAnnNameInDeclareAtField() { AjAST ajast = createAjAST(); DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration(); assertEquals("the default annotation name should be MISSING", "MISSING",d.getAnnotationName().getFullyQualifiedName()); d.setAnnotationName(ajast.newSimpleName("MyAnnotation")); assertEquals("the annotation name should now be set to 'MyAnnotation'", "MyAnnotation",d.getAnnotationName().getFullyQualifiedName()); } public void testCloneDeclareAtField() { AjAST ajast = createAjAST(); DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration(); d.setPatternNode(ajast.newSignaturePattern()); d.setAnnotationName(ajast.newSimpleName("MyAnnotation")); DeclareAtFieldDeclaration copy = (DeclareAtFieldDeclaration)ASTNode.copySubtree(ajast,d); assertNotNull("the DeclareAtFieldDeclaration clone should have a TypePattern set", copy.getPatternNode()); assertNotNull("the DeclareAtFieldDeclaration clone should have a Annotation name set", copy.getAnnotationName()); } public void testInternalDeclareAtField() { AjAST ajast = createAjAST(); DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration(); List props = DeclareAtFieldDeclaration.propertyDescriptors(AST.JLS3); for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("annotationName")) { assertNotNull("DeclareAtFieldDeclaration's " + element.getId() + " property" + " should not be null since it is lazily created", d.getStructuralProperty(element)); } else { assertNull("DeclareAtFieldDeclaration's " + element.getId() + " property" + " should be null since we haven't set it yet", d.getStructuralProperty(element)); } } for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("pattern")) { SignaturePattern p = ajast.newSignaturePattern(); d.setStructuralProperty(element,p); assertEquals("DeclareAtFieldDeclaration's pattern property should" + " now be a SignaturePattern",p,d.getStructuralProperty(element)); } else if (element.getId().equals("annotationName")) { SimpleName s = ajast.newSimpleName("MyAnnotation"); d.setStructuralProperty(element,s); assertEquals("DeclareAtFieldDeclaration's annotationName property should" + " now be a SimpleName",s,d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc } else { fail("unknown property for DeclareAtFieldDeclaration"); } } } // -------------- DeclareAtMethodDeclaration tests --------------- public void testNewDeclareAtMethodDeclaration() { AjAST ajast = createAjAST(); DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration(); assertNotNull("should have created a DeclareAtMethodDeclaration",d); } public void testPropertyDescriptorsForDeclareAtMethod() { AjAST ajast = createAjAST(); DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration(); List props = DeclareAtMethodDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundPattern = false; boolean foundAnnotationName = false; for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor)iter.next(); String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; } else if (id.equals("pattern")) { foundPattern = true; } else if (id.equals("annotationName")) { foundAnnotationName = true; } else { fail("unknown PropertyDescriptor associated with DeclareAtMethodDeclaration: " + element.getId()); } } assertTrue("DeclareAtMethodDeclaration should have a javadoc PropertyDescriptor",foundJavadoc); assertTrue("DeclareAtMethodDeclaration should have a attern PropertyDescriptor",foundPattern); assertTrue("DeclareAtMethodDeclaration should have a annotationName PropertyDescriptor",foundAnnotationName); } public void testGetAndSetPatternNodeInDeclareAtMethod() { AjAST ajast = createAjAST(); DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration(); assertNull("by default there should be no typePattern associated with" + " the declare @method annotation",d.getPatternNode()); SignaturePattern p = ajast.newSignaturePattern(); d.setPatternNode(p); assertEquals("there should now be a DefaultTypePattern associated with" + " the declare @method annotation",p,d.getPatternNode()); } public void testGetAndSetAnnNameInDeclareAtMethod() { AjAST ajast = createAjAST(); DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration(); assertEquals("the default annotation name should be MISSING", "MISSING",d.getAnnotationName().getFullyQualifiedName()); d.setAnnotationName(ajast.newSimpleName("MyAnnotation")); assertEquals("the annotation name should now be set to 'MyAnnotation'", "MyAnnotation",d.getAnnotationName().getFullyQualifiedName()); } public void testCloneDeclareAtMethod() { AjAST ajast = createAjAST(); DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration(); d.setPatternNode(ajast.newSignaturePattern()); d.setAnnotationName(ajast.newSimpleName("MyAnnotation")); DeclareAtMethodDeclaration copy = (DeclareAtMethodDeclaration)ASTNode.copySubtree(ajast,d); assertNotNull("the DeclareAtMethodDeclaration clone should have a TypePattern set", copy.getPatternNode()); assertNotNull("the DeclareAtMethodDeclaration clone should have a Annotation name set", copy.getAnnotationName()); } public void testInternalDeclareAtMethod() { AjAST ajast = createAjAST(); DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration(); List props = DeclareAtMethodDeclaration.propertyDescriptors(AST.JLS3); for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("annotationName")) { assertNotNull("DeclareAtMethodDeclaration's " + element.getId() + " property" + " should not be null since it is lazily created", d.getStructuralProperty(element)); } else { assertNull("DeclareAtMethodDeclaration's " + element.getId() + " property" + " should be null since we haven't set it yet", d.getStructuralProperty(element)); } } for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("pattern")) { SignaturePattern p = ajast.newSignaturePattern(); d.setStructuralProperty(element,p); assertEquals("DeclareAtMethodDeclaration's pattern property should" + " now be a SignaturePattern",p,d.getStructuralProperty(element)); } else if (element.getId().equals("annotationName")) { SimpleName s = ajast.newSimpleName("MyAnnotation"); d.setStructuralProperty(element,s); assertEquals("DeclareAtMethodDeclaration's annotationName property should" + " now be a SimpleName",s,d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc } else { fail("unknown property for DeclareAtMethodDeclaration"); } } } // -------------- DeclareAtConstructorDeclaration tests --------------- public void testNewDeclareAtConstructorDeclaration() { AjAST ajast = createAjAST(); DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration(); assertNotNull("should have created a DeclareAtConstructorDeclaration",d); } public void testPropertyDescriptorsForDeclareAtConstructor() { AjAST ajast = createAjAST(); DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration(); List props = DeclareAtConstructorDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundPattern = false; boolean foundAnnotationName = false; for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor)iter.next(); String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; } else if (id.equals("pattern")) { foundPattern = true; } else if (id.equals("annotationName")) { foundAnnotationName = true; } else { fail("unknown PropertyDescriptor associated with DeclareAtConstructorDeclaration: " + element.getId()); } } assertTrue("DeclareAtConstructorDeclaration should have a javadoc PropertyDescriptor",foundJavadoc); assertTrue("DeclareAtConstructorDeclaration should have a attern PropertyDescriptor",foundPattern); assertTrue("DeclareAtConstructorDeclaration should have a annotationName PropertyDescriptor",foundAnnotationName); } public void testGetAndSetPatternNodeInDeclareAtConstructor() { AjAST ajast = createAjAST(); DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration(); assertNull("by default there should be no typePattern associated with" + " the declare @constructor annotation",d.getPatternNode()); SignaturePattern p = ajast.newSignaturePattern(); d.setPatternNode(p); assertEquals("there should now be a DefaultTypePattern associated with" + " the declare @constructor annotation",p,d.getPatternNode()); } public void testGetAndSetAnnNameInDeclareAtConstructor() { AjAST ajast = createAjAST(); DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration(); assertEquals("the default annotation name should be MISSING", "MISSING",d.getAnnotationName().getFullyQualifiedName()); d.setAnnotationName(ajast.newSimpleName("MyAnnotation")); assertEquals("the annotation name should now be set to 'MyAnnotation'", "MyAnnotation",d.getAnnotationName().getFullyQualifiedName()); } public void testCloneDeclareAtConstructor() { AjAST ajast = createAjAST(); DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration(); d.setPatternNode(ajast.newSignaturePattern()); d.setAnnotationName(ajast.newSimpleName("MyAnnotation")); DeclareAtConstructorDeclaration copy = (DeclareAtConstructorDeclaration)ASTNode.copySubtree(ajast,d); assertNotNull("the DeclareAtConstructorDeclaration clone should have a SignaturePattern set", copy.getPatternNode()); assertNotNull("the DeclareAtConstructorDeclaration clone should have a Annotation name set", copy.getAnnotationName()); } public void testInternalDeclareAtConstructor() { AjAST ajast = createAjAST(); DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration(); List props = DeclareAtConstructorDeclaration.propertyDescriptors(AST.JLS3); for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("annotationName")) { assertNotNull("DeclareAtConstructorDeclaration's " + element.getId() + " property" + " should not be null since it is lazily created", d.getStructuralProperty(element)); } else { assertNull("DeclareAtConstructorDeclaration's " + element.getId() + " property" + " should be null since we haven't set it yet", d.getStructuralProperty(element)); } } for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("pattern")) { SignaturePattern p = ajast.newSignaturePattern(); d.setStructuralProperty(element,p); assertEquals("DeclareAtConstructorDeclaration's pattern property should" + " now be a SignaturePattern",p,d.getStructuralProperty(element)); } else if (element.getId().equals("annotationName")) { SimpleName s = ajast.newSimpleName("MyAnnotation"); d.setStructuralProperty(element,s); assertEquals("DeclareAtConstructorDeclaration's annotationName property should" + " now be a SimpleName",s,d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc } else { fail("unknown property for DeclareAtConstructorDeclaration"); } } } // -------------- DeclareAtTypeDeclaration tests --------------- public void testNewDeclareAtTypeDeclaration() { AjAST ajast = createAjAST(); DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration(); assertNotNull("should have created a DeclareAtTypeDeclaration",d); } public void testPropertyDescriptorsForDeclareAtType() { AjAST ajast = createAjAST(); DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration(); List props = DeclareAtTypeDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundPattern = false; boolean foundAnnotationName = false; for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor)iter.next(); String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; } else if (id.equals("pattern")) { foundPattern = true; } else if (id.equals("annotationName")) { foundAnnotationName = true; } else { fail("unknown PropertyDescriptor associated with DeclareAtTypeDeclaration: " + element.getId()); } } assertTrue("DeclareAtTypeDeclaration should have a javadoc PropertyDescriptor",foundJavadoc); assertTrue("DeclareAtTypeDeclaration should have a attern PropertyDescriptor",foundPattern); assertTrue("DeclareAtTypeDeclaration should have a annotationName PropertyDescriptor",foundAnnotationName); } public void testGetAndSetPatternNodeInDeclareAtType() { AjAST ajast = createAjAST(); DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration(); assertNull("by default there should be no typePattern associated with" + " the declare @type annotation",d.getPatternNode()); DefaultTypePattern dtp = ajast.newDefaultTypePattern(); d.setPatternNode(dtp); assertEquals("there should now be a DefaultTypePattern associated with" + " the declare @type annotation",dtp,d.getPatternNode()); } public void testGetAndSetAnnNameInDeclareAtType() { AjAST ajast = createAjAST(); DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration(); assertEquals("the default annotation name should be MISSING", "MISSING",d.getAnnotationName().getFullyQualifiedName()); d.setAnnotationName(ajast.newSimpleName("MyAnnotation")); assertEquals("the annotation name should now be set to 'MyAnnotation'", "MyAnnotation",d.getAnnotationName().getFullyQualifiedName()); } public void testCloneDeclareAtType() { AjAST ajast = createAjAST(); DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration(); d.setPatternNode(ajast.newDefaultTypePattern()); d.setAnnotationName(ajast.newSimpleName("MyAnnotation")); DeclareAtTypeDeclaration copy = (DeclareAtTypeDeclaration)ASTNode.copySubtree(ajast,d); assertNotNull("the DeclareAtTypeDeclaration clone should have a TypePattern set", copy.getPatternNode()); assertNotNull("the DeclareAtTypeDeclaration clone should have a Annotation name set", copy.getAnnotationName()); } public void testInternalDeclareAtType() { AjAST ajast = createAjAST(); DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration(); List props = DeclareAtTypeDeclaration.propertyDescriptors(AST.JLS3); for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("annotationName")) { assertNotNull("DeclareAtTypeDeclaration's " + element.getId() + " property" + " should not be null since it is lazily created", d.getStructuralProperty(element)); } else { assertNull("DeclareAtTypeDeclaration's " + element.getId() + " property" + " should be null since we haven't set it yet", d.getStructuralProperty(element)); } } for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("pattern")) { DefaultTypePattern p = ajast.newDefaultTypePattern(); d.setStructuralProperty(element,p); assertEquals("DeclareAtTypeDeclaration's pattern property should" + " now be a DefaultTypePattern",p,d.getStructuralProperty(element)); } else if (element.getId().equals("annotationName")) { SimpleName s = ajast.newSimpleName("MyAnnotation"); d.setStructuralProperty(element,s); assertEquals("DeclareAtTypeDeclaration's annotationName property should" + " now be a SimpleName",s,d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc } else { fail("unknown property for DeclareAtTypeDeclaration"); } } } // -------------- DeclareErrorDeclaration tests --------------- public void testNewDeclareErrorDeclaration() { AjAST ajast = createAjAST(); DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration(); assertNotNull("should have created a DeclareErrorDeclaration",d); } public void testPropertyDescriptorsForDeclareErrorDeclaration() { AjAST ajast = createAjAST(); DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration(); List props = DeclareErrorDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundPointcut = false; boolean foundMessage = false; for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; } else if (id.equals("pointcut")) { foundPointcut = true; } else if (id.equals("message")) { foundMessage = true; } else { fail("unknown PropertyDescriptor associated with DeclareErrorDeclaration"); } } assertTrue("DeclareErrorDeclaration should have a javadoc PropertyDescriptor",foundJavadoc); assertTrue("DeclareErrorDeclaration should have a pointcut PropertyDescriptor",foundPointcut); assertTrue("DeclareErrorDeclaration should have a message PropertyDescriptor",foundMessage); } public void testGetAndSetPointcutInErrorDeclaration() { AjAST ajast = createAjAST(); DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration(); assertNull("by default there should be no pointcut associated with" + " the declare error",d.getPointcut()); AndPointcut p = ajast.newAndPointcut(); d.setPointcut(p); assertEquals("there should now be an AndPointcut associated with" + " the declare error",p,d.getPointcut()); } public void testGetAndSetMessageInErrorDeclaration() { AjAST ajast = createAjAST(); DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration(); assertNull("by default there should be no message associated with" + " the declare error",d.getMessage()); StringLiteral s = ajast.newStringLiteral(); d.setMessage(s); assertEquals("there should now be a StringLiteral message associated with" + " the declare error",s,d.getMessage()); } public void testCloneDeclareErrorDeclaration() { AjAST ajast = createAjAST(); DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration(); d.setPointcut(ajast.newAndPointcut()); d.setMessage(ajast.newStringLiteral()); DeclareErrorDeclaration copy = (DeclareErrorDeclaration)ASTNode.copySubtree(ajast,d); assertNotNull("the DeclareErrorDeclaration clone should have a pointcut set", copy.getPointcut()); assertNotNull("the DeclareErrorDeclaration clone should have a message set", copy.getMessage()); } public void testInternalDeclareErrorDeclaration() { AjAST ajast = createAjAST(); DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration(); List props = DeclareErrorDeclaration.propertyDescriptors(AST.JLS3); for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); assertNull("DeclareErrorDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet", d.getStructuralProperty(element)); } for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("pointcut")) { AndPointcut p = ajast.newAndPointcut(); d.setStructuralProperty(element,p); assertEquals("DeclareErrorDeclaration's pointcut property should" + " now be an AndPointcut",p,d.getStructuralProperty(element)); } else if (element.getId().equals("message")) { StringLiteral s = ajast.newStringLiteral(); d.setStructuralProperty(element,s); assertEquals("DeclareErrorDeclaration's message property should" + " now be an AndPointcut",s,d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc } else { fail("unknown property for DeclareErrorDeclaration"); } } } // -------------- DeclareParentsDeclaration tests --------------- public void testNewDeclareParentsDeclaration() { AjAST ajast = createAjAST(); DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration(); assertNotNull("should have created a DeclareParentsDeclaration",d); } public void testPropertyDescriptorsForDeclareParentsDeclaration() { AjAST ajast = createAjAST(); DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration(); List props = DeclareParentsDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundTypePattern = false; boolean foundIsExtends = false; boolean foundTypePatternList = false; for (Iterator iter = props.iterator(); iter.hasNext();) { Object o = iter.next(); if ((o instanceof ChildPropertyDescriptor)) { ChildPropertyDescriptor element = (ChildPropertyDescriptor)o; String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; } else if (id.equals("childTypePattern")) { foundTypePattern = true; } else { fail("unknown PropertyDescriptor associated with DeclareParentsDeclaration: " + element.getId()); } } else if ((o instanceof ChildListPropertyDescriptor) && ((ChildListPropertyDescriptor)o).getId().equals("typePatternsList")) { foundTypePatternList= true; } else if ((o instanceof SimplePropertyDescriptor) && ((SimplePropertyDescriptor)o).getId().equals("isExtends")) { foundIsExtends = true; } else { fail("unknown PropertyDescriptor associated with DeclareErrorDeclaration: " + o); } } assertTrue("DeclareParentsDeclaration should have a javadoc PropertyDescriptor",foundJavadoc); assertTrue("DeclareParentsDeclaration should have a typePattern PropertyDescriptor",foundTypePattern); assertTrue("DeclareParentsDeclaration should have an isExtends PropertyDescriptor",foundIsExtends); assertTrue("DeclareParentsDeclaration should have a typePatternList PropertyDescriptor",foundTypePatternList); } public void testGetAndSetTypePatternInDeclareParentsDeclaration() { AjAST ajast = createAjAST(); DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration(); assertNull("by default there should be no TypePattern associated with" + " the declare parents",d.getChildTypePattern()); DefaultTypePattern dtp = ajast.newDefaultTypePattern(); d.setChildTypePattern(dtp); assertEquals("there should now be a DefaultTypePattern associated with" + " the declare parents",dtp,d.getChildTypePattern()); } public void testGetAndSetIsExtendsInDeclareParentsDeclaration() { AjAST ajast = createAjAST(); DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration(); assertFalse("by default the declare parents should not be 'extends'",d.isExtends()); d.setExtends(true); assertTrue("the declare parents should now be 'extends'",d.isExtends()); } public void testTypePatternsInDeclareParents() { AjAST ajast = createAjAST(); DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration(); List l = d.parentTypePatterns(); assertEquals("there shouldn't be any type patterns associated with" + "the declare parents yet",0,l.size()); DefaultTypePattern dtp = ajast.newDefaultTypePattern(); l.add(dtp); assertEquals("there should be one type patterns associated with" + "the declare parents",1,l.size()); assertEquals("there should be a DefaultTypePattern associated with" + "the declare parents",dtp,l.get(0)); } public void testCloneDeclareParentsDeclaration() { AjAST ajast = createAjAST(); DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration(); d.setChildTypePattern(ajast.newDefaultTypePattern()); d.setExtends(true); d.parentTypePatterns().add(ajast.newDefaultTypePattern()); DeclareParentsDeclaration copy = (DeclareParentsDeclaration)ASTNode.copySubtree(ajast,d); assertEquals("there should be one type patterns associated with" + "the declare parents copy",1,copy.parentTypePatterns().size()); assertNotNull("the DeclareParentsDeclaration clone should have a typePattern set", copy.getChildTypePattern()); assertTrue("the DeclareParentsDeclaration clone should be an 'extends'", copy.isExtends()); } public void testInternalDeclareParentsDeclaration() { AjAST ajast = createAjAST(); DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration(); List props = DeclareParentsDeclaration.propertyDescriptors(AST.JLS3); for (Iterator iter = props.iterator(); iter.hasNext();) { Object o = iter.next(); if (o instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor element = (ChildPropertyDescriptor)o; assertNull("DeclareParentsDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet", d.getStructuralProperty(element)); } else if (o instanceof ChildListPropertyDescriptor) { ChildListPropertyDescriptor element = (ChildListPropertyDescriptor)o; assertNotNull("DeclareParentsDeclaration's " + element.getId() + " property" + "should not be null since it is a list", d.getStructuralProperty(element)); assertEquals("should only be able to put TypePattern's into the list", TypePattern.class,element.getElementType()); } else if (o instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor element = (SimplePropertyDescriptor)o; assertNotNull("DeclareParentsDeclaration's " + element.getId() + " property" + "should not be null since it is a boolean", d.getStructuralProperty(element)); } else { fail("unknown PropertyDescriptor associated with DeclareParentsDeclaration: " + o); } } for (Iterator iter = props.iterator(); iter.hasNext();) { Object o = iter.next(); if (o instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("childTypePattern")) { DefaultTypePattern dtp = ajast.newDefaultTypePattern(); d.setStructuralProperty(element,dtp); assertEquals("DeclareParentsDeclaration's typePattern property should" + " now be a DefaultTypePattern",dtp,d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc } else { fail("unknown property for DeclareParentsDeclaration"); } } else if (o instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor element = (SimplePropertyDescriptor)o; if (element.getId().equals("isExtends")) { Boolean b = new Boolean(true); d.setStructuralProperty(element,b); assertEquals("DeclareParentsDeclaration's isExtends property should" + " now be a boolean",b,d.getStructuralProperty(element)); } } } } // -------------- DeclarePrecedenceDeclaration tests --------------- public void testNewDeclarePrecedenceDeclaration() { AjAST ajast = createAjAST(); DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration(); assertNotNull("should have created a DeclarePrecedenceDeclaration",d); } public void testPropertyDescriptorsForDeclarePrecedence() { AjAST ajast = createAjAST(); DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration(); List props = DeclarePrecedenceDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundTypePatterns = false; for (Iterator iter = props.iterator(); iter.hasNext();) { Object o = iter.next(); if ((o instanceof ChildPropertyDescriptor) && ((ChildPropertyDescriptor)o).getId().equals("javadoc")) { foundJavadoc = true; } else if ((o instanceof ChildListPropertyDescriptor) && ((ChildListPropertyDescriptor)o).getId().equals("parentTypePatterns")) { foundTypePatterns = true; } else { fail("unknown PropertyDescriptor associated with DeclareErrorDeclaration: " + o); } } assertTrue("DeclareErrorDeclaration should have a javadoc PropertyDescriptor",foundJavadoc); assertTrue("DeclareErrorDeclaration should have a pointcut PropertyDescriptor",foundTypePatterns); } public void testTypePatternsInDeclarePrecedence() { AjAST ajast = createAjAST(); DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration(); List l = d.typePatterns(); assertEquals("there shouldn't be any type patterns associated with" + "the declare precedence yet",0,l.size()); DefaultTypePattern dtp = ajast.newDefaultTypePattern(); l.add(dtp); assertEquals("there should be one type patterns associated with" + "the declare precedence",1,l.size()); assertEquals("there should be a DefaultTypePattern associated with" + "the declare precedence",dtp,l.get(0)); } public void testCloneDeclarePrecedenceDeclaration() { AjAST ajast = createAjAST(); DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration(); d.typePatterns().add(ajast.newDefaultTypePattern()); DeclarePrecedenceDeclaration copy = (DeclarePrecedenceDeclaration)ASTNode.copySubtree(ajast,d); assertEquals("there should be one type patterns associated with" + "the declare precedence copy",1,copy.typePatterns().size()); } public void testInternalDeclarePrecedenceDeclaration() { AjAST ajast = createAjAST(); DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration(); List props = DeclarePrecedenceDeclaration.propertyDescriptors(AST.JLS3); for (Iterator iter = props.iterator(); iter.hasNext();) { Object o = iter.next(); if (o instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor element = (ChildPropertyDescriptor)o; assertNull("DeclareErrorDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet", d.getStructuralProperty(element)); } else if (o instanceof ChildListPropertyDescriptor) { ChildListPropertyDescriptor element = (ChildListPropertyDescriptor)o; assertNotNull("DeclareErrorDeclaration's " + element.getId() + " property" + "should not be null since it is a list", d.getStructuralProperty(element)); assertEquals("should only be able to put TypePattern's into the list", TypePattern.class,element.getElementType()); } else { fail("unknown PropertyDescriptor associated with DeclareErrorDeclaration: " + o); } } } // -------------- DeclareSoftDeclaration tests --------------- public void testNewDeclareSoftDeclaration() { AjAST ajast = createAjAST(); DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration(); assertNotNull("should have created a DeclareSoftDeclaration",d); } public void testPropertyDescriptorsForDeclareSoftDeclaration() { AjAST ajast = createAjAST(); DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration(); List props = DeclareSoftDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundPointcut = false; boolean foundTypePattern = false; for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; } else if (id.equals("pointcut")) { foundPointcut = true; } else if (id.equals("typePattern")) { foundTypePattern = true; } else { fail("unknown PropertyDescriptor associated with " + "DeclareSoftDeclaration: " + element.getId()); } } assertTrue("DeclareSoftDeclaration should have a javadoc PropertyDescriptor",foundJavadoc); assertTrue("DeclareSoftDeclaration should have a pointcut PropertyDescriptor",foundPointcut); assertTrue("DeclareSoftDeclaration should have a type PropertyDescriptor",foundTypePattern); } public void testGetAndSetPointcutInSoftDeclaration() { AjAST ajast = createAjAST(); DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration(); assertNull("by default there should be no pointcut associated with" + " the declare soft",d.getPointcut()); AndPointcut p = ajast.newAndPointcut(); d.setPointcut(p); assertEquals("there should now be an AndPointcut associated with" + " the declare soft",p,d.getPointcut()); } public void testGetAndSetTypePatternInSoftDeclaration() { AjAST ajast = createAjAST(); DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration(); assertNull("by default there should be no TypePattern associated with" + " the declare soft",d.getTypePattern()); DefaultTypePattern dtp = ajast.newDefaultTypePattern(); d.setTypePattern(dtp); assertEquals("there should now be a DefaultTypePattern associated with" + " the declare soft",dtp,d.getTypePattern()); } public void testCloneDeclareSoftDeclaration() { AjAST ajast = createAjAST(); DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration(); d.setPointcut(ajast.newAndPointcut()); d.setTypePattern(ajast.newDefaultTypePattern()); DeclareSoftDeclaration copy = (DeclareSoftDeclaration)ASTNode.copySubtree(ajast,d); assertNotNull("the DeclareSoftDeclaration clone should have a pointcut set", copy.getPointcut()); assertNotNull("the DeclareSoftDeclaration clone should have a typePattern set", copy.getTypePattern()); } public void testInternalDeclareSoftDeclaration() { AjAST ajast = createAjAST(); DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration(); List props = DeclareSoftDeclaration.propertyDescriptors(AST.JLS3); for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); assertNull("DeclareSoftDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet", d.getStructuralProperty(element)); } for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("pointcut")) { AndPointcut p = ajast.newAndPointcut(); d.setStructuralProperty(element,p); assertEquals("DeclareSoftDeclaration's pointcut property should" + " now be an AndPointcut",p,d.getStructuralProperty(element)); } else if (element.getId().equals("typePattern")) { DefaultTypePattern dtp = ajast.newDefaultTypePattern(); d.setStructuralProperty(element,dtp); assertEquals("DeclareSoftDeclaration's typePattern property should" + " now be an DefaultTypePattern",dtp,d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc } else { fail("unknown property for DeclareSoftDeclaration: " + element.getId()); } } } // -------------- DeclareWarningDeclaration tests --------------- public void testNewDeclareWarningDeclaration() { AjAST ajast = createAjAST(); DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration(); assertNotNull("should have created a DeclareWarningDeclaration",d); } public void testPropertyDescriptorsForDeclareWarningDeclaration() { AjAST ajast = createAjAST(); DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration(); List props = DeclareWarningDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundPointcut = false; boolean foundMessage = false; for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; } else if (id.equals("pointcut")) { foundPointcut = true; } else if (id.equals("message")) { foundMessage = true; } else { fail("unknown PropertyDescriptor associated with DeclareWarningDeclaration"); } } assertTrue("DeclareWarningDeclaration should have a javadoc PropertyDescriptor",foundJavadoc); assertTrue("DeclareWarningDeclaration should have a pointcut PropertyDescriptor",foundPointcut); assertTrue("DeclareWarningDeclaration should have a message PropertyDescriptor",foundMessage); } public void testGetAndSetPointcutInWarningDeclaration() { AjAST ajast = createAjAST(); DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration(); assertNull("by default there should be no pointcut associated with" + " the declare warning",d.getPointcut()); AndPointcut p = ajast.newAndPointcut(); d.setPointcut(p); assertEquals("there should now be an AndPointcut associated with" + " the declare warning",p,d.getPointcut()); } public void testGetAndSetMessageInWarningDeclaration() { AjAST ajast = createAjAST(); DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration(); assertNull("by default there should be no message associated with" + " the declare warning",d.getMessage()); StringLiteral s = ajast.newStringLiteral(); d.setMessage(s); assertEquals("there should now be a StringLiteral message associated with" + " the declare warning",s,d.getMessage()); } public void testCloneDeclareWarningDeclaration() { AjAST ajast = createAjAST(); DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration(); d.setPointcut(ajast.newAndPointcut()); d.setMessage(ajast.newStringLiteral()); DeclareWarningDeclaration copy = (DeclareWarningDeclaration)ASTNode.copySubtree(ajast,d); assertNotNull("the DeclareWarningDeclaration clone should have a pointcut set", copy.getPointcut()); assertNotNull("the DeclareWarningDeclaration clone should have a message set", copy.getMessage()); } public void testInternalDeclareWarningDeclaration() { AjAST ajast = createAjAST(); DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration(); List props = DeclareWarningDeclaration.propertyDescriptors(AST.JLS3); for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); assertNull("DeclareWarningDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet", d.getStructuralProperty(element)); } for (Iterator iter = props.iterator(); iter.hasNext();) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); if (element.getId().equals("pointcut")) { AndPointcut p = ajast.newAndPointcut(); d.setStructuralProperty(element,p); assertEquals("DeclareWarningDeclaration's pointcut property should" + " now be an AndPointcut",p,d.getStructuralProperty(element)); } else if (element.getId().equals("message")) { StringLiteral s = ajast.newStringLiteral(); d.setStructuralProperty(element,s); assertEquals("DeclareWarningDeclaration's message property should" + " now be an AndPointcut",s,d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc } else { fail("unknown property for DeclareWarningDeclaration"); } } } // --------- testing that the source ranges have been set correctly --------- public void testDeclareAnnotationType(){ checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @type: C : @MyAnnotation;}", 43,33); } public void testDeclareAnnotationMethod(){ checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @method:public * C.*(..) : @MyAnnotation;}", 43,49); } public void testDeclareAnnotationField(){ checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @field: * C+.* : @MyAnnotation;}", 43,39); } public void testDeclareAnnotationConstructor(){ checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @constructor: C+.new(..) : @MyAnnotation;}", 43,49); } public void testDeclareParents(){ checkJLS3("class A{}class B{}aspect C {declare parents : A extends B;}", 28,29); } public void testDeclareWarning(){ checkJLS3("aspect A {pointcut a();declare warning: a(): \"error\";}", 23,30); } public void testDeclareError(){ checkJLS3("aspect A {pointcut a();declare error: a(): \"error\";}", 23,28); } public void testDeclareSoft(){ checkJLS3("aspect A {pointcut a();declare soft: Exception+: a();}", 23,29); } public void testDeclarePrecedence(){ checkJLS3("aspect A{}aspect B{declare precedence: B,A;}", 19,23); } // --------- Helper methods ---------- private AjAST createAjAST() { return createAjAST(AST.JLS3); } private AjAST createAjAST(int astlevel) { if (astlevel != AST.JLS2 && astlevel != AST.JLS3) { fail("need to pass AST.JLS2 or AST.JLS3 as an argument"); } String source = ""; ASTParser parser = ASTParser.newParser(astlevel); parser.setSource(source.toCharArray()); parser.setCompilerOptions(new HashMap()); CompilationUnit cu = (CompilationUnit) parser.createAST(null); AST ast = cu.getAST(); assertTrue("the ast should be an instance of AjAST",ast instanceof AjAST); return (AjAST)ast; } private void checkJLS3(String source, int start, int length) { ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setCompilerOptions(new HashMap()); parser.setSource(source.toCharArray()); CompilationUnit cu2 = (CompilationUnit) parser.createAST(null); SourceRangeVisitor visitor = new SourceRangeVisitor(); cu2.accept(visitor); int s = visitor.getStart(); int l = visitor.getLength(); assertTrue("Expected start position: "+ start + ", Actual:" + s, start == s); assertTrue("Expected length: "+ length + ", Actual:" + l, length == l); } } class SourceRangeVisitor extends AjASTVisitor { boolean visitTheKids = true; boolean visitDocTags; int start, length; SourceRangeVisitor() { this(false); } SourceRangeVisitor(boolean visitDocTags) { super(visitDocTags); this.visitDocTags = visitDocTags; } public boolean isVisitingChildren() { return visitTheKids; } public void setVisitingChildren(boolean visitChildren) { visitTheKids = visitChildren; } public int getStart() { return start; } public int getLength() { return length; } public boolean visit(DeclareAtTypeDeclaration node) { start = node.getStartPosition(); length = node.getLength(); return isVisitingChildren(); } public boolean visit(DeclareAtMethodDeclaration node) { start = node.getStartPosition(); length = node.getLength(); return isVisitingChildren(); } public boolean visit(DeclareAtConstructorDeclaration node) { start = node.getStartPosition(); length = node.getLength(); return isVisitingChildren(); } public boolean visit(DeclareAtFieldDeclaration node) { start = node.getStartPosition(); length = node.getLength(); return isVisitingChildren(); } public boolean visit(DeclareWarningDeclaration node) { start = node.getStartPosition(); length = node.getLength(); return isVisitingChildren(); } public boolean visit(DeclareErrorDeclaration node) { start = node.getStartPosition(); length = node.getLength(); return isVisitingChildren(); } public boolean visit(DeclareParentsDeclaration node) { start = node.getStartPosition(); length = node.getLength(); return isVisitingChildren(); } public boolean visit(DeclarePrecedenceDeclaration node) { start = node.getStartPosition(); length = node.getLength(); return isVisitingChildren(); } public boolean visit(DeclareSoftDeclaration node) { start = node.getStartPosition(); length = node.getLength(); return isVisitingChildren(); } }
123,212
Bug 123212 Skip subversion resources when copying files from input to output folders
Exception when compile a project under svn. java.io.FileNotFoundException at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:179) at java.io.FileOutputStream.<init>(FileOutputStream.java:131) at org.aspectj.util.FileUtil.makeOutputStream(FileUtil.java:1258) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.writeResource(AjBuildManager.java:466) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesFromFile(AjBuildManager.java:444) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.copyResourcesToDestination(AjBuildManager.java:386) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:298) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) FileNotFoundException thrown: /home/chomats/Fede/svn/fede-repos/Tool.Product.ProductServer/classes/.svn/format (Permission non accordee)
resolved fixed
d856e4f
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-10T07:55:32Z
2006-01-10T08:00:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.ICompilerAdapter; import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.CountingMessageHandler; import org.aspectj.bridge.ILifecycleAware; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.Version; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextFormatter; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathDirectory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.util.FileUtil; import org.aspectj.weaver.Dump; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.core.runtime.OperationCanceledException; //import org.aspectj.org.eclipse.jdt.internal.compiler.util.HashtableOfObject; public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory { private static final String CROSSREFS_FILE_NAME = "build.lst"; private static final String CANT_WRITE_RESULT = "unable to write compilation result"; private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; static final boolean COPY_INPATH_DIR_RESOURCES = false; static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false; private static final FileFilter binarySourceFilter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".class"); }}; /** * This builder is static so that it can be subclassed and reset. However, note * that there is only one builder present, so if two extendsion reset it, only * the latter will get used. */ private static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder(); static { CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter()); CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter()); } private IProgressListener progressListener = null; private int compiledCount; private int sourceFileCount; private JarOutputStream zos; private boolean batchCompile = true; private INameEnvironment environment; private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap(); // FIXME asc should this really be in here? private IHierarchy structureModel; public AjBuildConfig buildConfig; private List aspectNames = new LinkedList(); AjState state = new AjState(this); public BcelWeaver getWeaver() { return state.getWeaver();} public BcelWorld getBcelWorld() { return state.getBcelWorld();} public CountingMessageHandler handler; public AjBuildManager(IMessageHandler holder) { super(); this.handler = CountingMessageHandler.makeCountingMessageHandler(holder); } /** @return true if we should generate a model as a side-effect */ public boolean doGenerateModel() { return buildConfig.isGenerateModelMode(); } public boolean batchBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, true); } public boolean incrementalBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, false); } /** @throws AbortException if check for runtime fails */ protected boolean doBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler, boolean batch) throws IOException, AbortException { boolean ret = true; batchCompile = batch; if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware)baseHandler).buildStarting(!batch); } int phase = batch ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD; ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase ,buildConfig); try { if (batch) { this.state = new AjState(this); } boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !batch) { // retry as batch? CompilationAndWeavingContext.leavingPhase(ct); return doBuild(buildConfig, baseHandler, true); } this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler); // XXX duplicate, no? remove? String check = checkRtJar(buildConfig); if (check != null) { if (FAIL_IF_RUNTIME_NOT_FOUND) { MessageUtil.error(handler, check); CompilationAndWeavingContext.leavingPhase(ct); return false; } else { MessageUtil.warn(handler, check); } } // if (batch) { setBuildConfig(buildConfig); //} if (batch || !AsmManager.attemptIncrementalModelRepairs) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(buildConfig); // } } if (batch) { initBcelWorld(handler); } if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } } if (batch) { // System.err.println("XXXX batch: " + buildConfig.getFiles()); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { getWorld().setModel(AsmManager.getDefault().getHierarchy()); // in incremental build, only get updated model? } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); performCompilation(buildConfig.getFiles()); if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After a batch build"); } else { // done already? // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { // bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel()); // } // System.err.println("XXXX start inc "); binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); List files = state.getFilesToCompile(true); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles()); boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); for (int i = 0; (i < 5) && hereWeGoAgain; i++) { // System.err.println("XXXX inc: " + files); performCompilation(files); if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false); files = state.getFilesToCompile(false); hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); // TODO Andy - Needs some thought here... // I think here we might want to pass empty addedFiles/deletedFiles as they were // dealt with on the first call to processDelta - we are going through this loop // again because in compiling something we found something else we needed to // rebuild. But what case causes this? if (hereWeGoAgain) { if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles()); } } if (!files.isEmpty()) { CompilationAndWeavingContext.leavingPhase(ct); return batchBuild(buildConfig, baseHandler); } else { if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After an incremental build"); } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(); } // for bug 113554: support ajsym file generation for command line builds if (buildConfig.isGenerateCrossRefsMode()) { String configFileProxy = buildConfig.getOutputDir().getAbsolutePath() + File.separator + CROSSREFS_FILE_NAME; AsmManager.getDefault().writeStructureModel(configFileProxy); } // have to tell state we succeeded or next is not incremental state.successfulCompile(buildConfig,batch); copyResourcesToDestination(); if (buildConfig.getOutxmlName() != null) { writeOutxmlFile(); } /*boolean weaved = *///weaveAndGenerateClassFiles(); // if not weaved, then no-op build, no model changes // but always returns true // XXX weaved not in Mik's incremental if (buildConfig.isGenerateModelMode()) { AsmManager.getDefault().fireModelUpdated(); } CompilationAndWeavingContext.leavingPhase(ct); } finally { if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware)baseHandler).buildFinished(!batch); } if (zos != null) { closeOutputStream(buildConfig.getOutputJar()); } ret = !handler.hasErrors(); if (getBcelWorld()!=null) getBcelWorld().tidyUp(); // bug 59895, don't release reference to handler as may be needed by a nested call //handler = null; } return ret; } private boolean openOutputStream(File outJar) { try { OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar()); zos = new JarOutputStream(os,getWeaver().getManifest(true)); } catch (IOException ex) { IMessage message = new Message("Unable to open outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); return false; } return true; } private void closeOutputStream(File outJar) { try { if (zos != null) zos.close(); zos = null; /* Ensure we don't write an incomplete JAR bug-71339 */ if (handler.hasErrors()) { outJar.delete(); } } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); } } private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); copyResourcesFromJarFile(inJar); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (inPathElement.isDirectory()) { copyResourcesFromDirectory(inPathElement); } else { copyResourcesFromJarFile(inPathElement); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) { String resource = (String)i.next(); File from = (File)buildConfig.getSourcePathResources().get(resource); copyResourcesFromFile(from,resource,from); } } writeManifest(); } private void copyResourcesFromJarFile(File jarFile) throws IOException { JarInputStream inStream = null; try { inStream = new JarInputStream(new FileInputStream(jarFile)); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; String filename = entry.getName(); // System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'"); if (!entry.isDirectory() && acceptResource(filename)) { byte[] bytes = FileUtil.readAsByteArray(inStream); writeResource(filename,bytes,jarFile); } inStream.closeEntry(); } } finally { if (inStream != null) inStream.close(); } } private void copyResourcesFromDirectory(File dir) throws IOException { if (!COPY_INPATH_DIR_RESOURCES) return; // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(dir,new FileFilter() { public boolean accept(File f) { boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ; return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = files[i].getAbsolutePath().substring( dir.getAbsolutePath().length()+1); copyResourcesFromFile(files[i],filename,dir); } } private void copyResourcesFromFile(File f,String filename,File src) throws IOException { if (!acceptResource(filename)) return; FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); writeResource(filename,bytes,src); } finally { if (fis != null) fis.close(); } } private void writeResource(String filename, byte[] content, File srcLocation) throws IOException { if (state.hasResource(filename)) { IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); return; } if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(content); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename)); fos.write(content); fos.close(); } state.recordResource(filename); } /* * If we are writing to an output directory copy the manifest but only * if we already have one */ private void writeManifest () throws IOException { Manifest manifest = getWeaver().getManifest(false); if (manifest != null && zos == null) { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME)); manifest.write(fos); fos.close(); } } private boolean acceptResource(String resourceName) { if ( (resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS")) || (resourceName.endsWith(".class")) || (resourceName.toUpperCase().equals(MANIFEST_NAME)) ) { return false; } else { return true; } } private void writeOutxmlFile () throws IOException { String filename = buildConfig.getOutxmlName(); // System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename); // System.err.println("? AjBuildManager.writeOutxmlFile() outputDir=" + buildConfig.getOutputDir()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ps.println("<aspectj>"); ps.println("<aspects>"); for (Iterator i = aspectNames.iterator(); i.hasNext();) { String name = (String)i.next(); ps.println("<aspect name=\"" + name + "\"/>"); } ps.println("</aspects>"); ps.println("</aspectj>"); ps.println(); ps.close(); if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); zos.putNextEntry(newEntry); zos.write(baos.toByteArray()); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename)); fos.write(baos.toByteArray()); fos.close(); } } // public static void dumprels() { // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); // int ctr = 1; // Set entries = irm.getEntries(); // for (Iterator iter = entries.iterator(); iter.hasNext();) { // String hid = (String) iter.next(); // List rels = irm.get(hid); // for (Iterator iterator = rels.iterator(); iterator.hasNext();) { // IRelationship ir = (IRelationship) iterator.next(); // List targets = ir.getTargets(); // for (Iterator iterator2 = targets.iterator(); // iterator2.hasNext(); // ) { // String thid = (String) iterator2.next(); // System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid); // } // } // } // } /** * Responsible for managing the ASM model between builds. Contains the policy for * maintaining the persistance of elements in the model. * * This code is driven before each 'fresh' (batch) build to create * a new model. */ private void setupModel(AjBuildConfig config) { AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode()); if (!AsmManager.isCreatingModel()) return; AsmManager.getDefault().createNewASM(); // AsmManager.getDefault().getRelationshipMap().clear(); IHierarchy model = AsmManager.getDefault().getHierarchy(); String rootLabel = "<root>"; IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA; if (buildConfig.getConfigFile() != null) { rootLabel = buildConfig.getConfigFile().getName(); model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath()); kind = IProgramElement.Kind.FILE_LST; } model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList())); model.setFileMap(new HashMap()); setStructureModel(model); state.setStructureModel(model); state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap()); } // // private void dumplist(List l) { // System.err.println("---- "+l.size()); // for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i)); // } // private void accumulateFileNodes(IProgramElement ipe,List store) { // if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA || // ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) { // if (!ipe.getName().equals("<root>")) { // store.add(ipe); // return; // } // } // for (Iterator i = ipe.getChildren().iterator();i.hasNext();) { // accumulateFileNodes((IProgramElement)i.next(),store); // } // } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { List cp = buildConfig.getBootclasspath(); cp.addAll(buildConfig.getClasspath()); BcelWorld bcelWorld = new BcelWorld(cp, handler, null); bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way()); bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel()); bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints()); bcelWorld.setXnoInline(buildConfig.isXnoInline()); bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp()); bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled()); bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint()); BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld); state.setWorld(bcelWorld); state.setWeaver(bcelWeaver); state.clearBinarySourceFiles(); for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) { File f = (File) i.next(); if (!f.exists()) { IMessage message = new Message("invalid aspectpath entry: "+f.getName(),null,true); handler.handleMessage(message); } else { bcelWeaver.addLibraryJarFile(f); } } // String lintMode = buildConfig.getLintMode(); if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) { bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(buildConfig.getLintMode()); } if (buildConfig.getLintSpecFile() != null) { bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile()); } //??? incremental issues for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false); state.recordBinarySource(inJar.getPath(), unwovenClasses); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory()) { // its a jar file on the inpath // the weaver method can actually handle dirs, but we don't call it, see next block List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true); state.recordBinarySource(inPathElement.getPath(),unwovenClasses); } else { // add each class file in an in-dir individually, this gives us the best error reporting // (they are like 'source' files then), and enables a cleaner incremental treatment of // class file changes in indirs. File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter); for (int j = 0; j < binSrcs.length; j++) { UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, buildConfig.getOutputDir()); List ucfl = new ArrayList(); ucfl.add(ucf); state.recordBinarySource(binSrcs[j].getPath(),ucfl); } } } bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable()); //check for org.aspectj.runtime.JoinPoint ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint"); if (joinPoint.isMissing()) { IMessage message = new Message("classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)", null, true); handler.handleMessage(message); } } public World getWorld() { return getBcelWorld(); } void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException { for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); getWeaver().addClassFile(classFile); } } // public boolean weaveAndGenerateClassFiles() throws IOException { // handler.handleMessage(MessageUtil.info("weaving")); // if (progressListener != null) progressListener.setText("weaving aspects"); // bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size()); // //!!! doesn't provide intermediate progress during weaving // // XXX add all aspects even during incremental builds? // addAspectClassFilesToWeaver(state.addedClassFiles); // if (buildConfig.isNoWeave()) { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.dumpUnwoven(buildConfig.getOutputJar()); // } else { // bcelWeaver.dumpUnwoven(); // bcelWeaver.dumpResourcesToOutPath(); // } // } else { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.weave(buildConfig.getOutputJar()); // } else { // bcelWeaver.weave(); // bcelWeaver.dumpResourcesToOutPath(); // } // } // if (progressListener != null) progressListener.setProgress(1.0); // return true; // //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors(); // } public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) { String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ // Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every // element of the classpath is likely to be a directory. If we ensure every element of the array is set to // only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build // a classpathDirectory object that will attempt to look for source when it can't find binary. int[] classpathModes = new int[classpaths.length]; for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY; return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes); } public IProblemFactory getProblemFactory() { return new DefaultProblemFactory(Locale.getDefault()); } /* * Build the set of compilation source units */ public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) { int fileCount = filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; // HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ for (int i = 0; i < fileCount; i++) { String encoding = encodings[i]; if (encoding == null) encoding = defaultEncoding; units[i] = new CompilationUnit(null, filenames[i], encoding); } return units; } public String extractDestinationPathFromSourceFile(CompilationResult result) { ICompilationUnit compilationUnit = result.compilationUnit; if (compilationUnit != null) { char[] fileName = compilationUnit.getFileName(); int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName); if (lastIndex == -1) { return System.getProperty("user.dir"); //$NON-NLS-1$ } return new String(CharOperation.subarray(fileName, 0, lastIndex)); } return System.getProperty("user.dir"); //$NON-NLS-1$ } public void performCompilation(List files) { if (progressListener != null) { compiledCount=0; sourceFileCount = files.size(); progressListener.setText("compiling source files"); } //System.err.println("got files: " + files); String[] filenames = new String[files.size()]; String[] encodings = new String[files.size()]; //System.err.println("filename: " + this.filenames); for (int i=0; i < files.size(); i++) { filenames[i] = ((File)files.get(i)).getPath(); } List cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i=0; i < cps.size(); i++) { classpaths[i] = (String)cps.get(i); } //System.out.println("compiling"); environment = getLibraryAccess(classpaths, filenames); if (!state.getClassNameToUCFMap().isEmpty()) { environment = new StatefulNameEnvironment(environment, state.getClassNameToUCFMap()); } org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this); org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(), getBatchRequestor(), getProblemFactory()); CompilerOptions options = compiler.options; options.produceReferenceInfo = true; //TODO turn off when not needed try { compiler.compile(getCompilationUnits(filenames, encodings)); } catch (OperationCanceledException oce) { handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null)); } // cleanup environment.cleanup(); environment = null; } /* * Answer the component to which will be handed back compilation results from the compiler */ public IIntermediateResultsRequestor getInterimResultRequestor() { return new IIntermediateResultsRequestor() { public void acceptResult(InterimCompilationResult result) { if (progressListener != null) { compiledCount++; progressListener.setProgress((compiledCount/2.0)/sourceFileCount); progressListener.setText("compiled: " + result.fileName()); } state.noteResult(result); if (progressListener!=null && progressListener.isCancelledRequested()) { throw new AbortCompilation(true, new OperationCanceledException("Compilation cancelled as requested")); } } }; } public ICompilerRequestor getBatchRequestor() { return new ICompilerRequestor() { public void acceptResult(CompilationResult unitResult) { // end of compile, must now write the results to the output destination // this is either a jar file or a file in a directory if (!(unitResult.hasErrors() && !proceedOnError())) { Collection classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile classFile = (ClassFile) iter.next(); String filename = new String(classFile.fileName()); String classname = filename.replace('/', '.'); filename = filename.replace('/', File.separatorChar) + ".class"; try { if (buildConfig.getOutputJar() == null) { writeDirectoryEntry(unitResult, classFile,filename); } else { writeZipEntry(classFile,filename); } if (shouldAddAspectName) addAspectName(classname); } catch (IOException ex) { IMessage message = EclipseAdapterUtils.makeErrorMessage( new String(unitResult.fileName), CANT_WRITE_RESULT, ex); handler.handleMessage(message); } } } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); for (int i=0; i < problems.length; i++) { IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i]); handler.handleMessage(message); } } } private void writeDirectoryEntry( CompilationResult unitResult, ClassFile classFile, String filename) throws IOException { File destinationPath = buildConfig.getOutputDir(); String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); } private void writeZipEntry(ClassFile classFile, String name) throws IOException { name = name.replace(File.separatorChar,'/'); ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(classFile.getBytes()); zos.closeEntry(); } private void addAspectName (String name) { BcelWorld world = getBcelWorld(); ResolvedType type = world.resolve(name); // System.err.println("? writeAspectName() type=" + type); if (type.isAspect()) { aspectNames.add(name); } } }; } protected boolean proceedOnError() { return buildConfig.getProceedOnError(); } // public void noteClassFiles(AjCompiler.InterimResult result) { // if (result == null) return; // CompilationResult unitResult = result.result; // String sourceFileName = result.fileName(); // if (!(unitResult.hasErrors() && !proceedOnError())) { // List unwovenClassFiles = new ArrayList(); // Enumeration classFiles = unitResult.compiledTypes.elements(); // while (classFiles.hasMoreElements()) { // ClassFile classFile = (ClassFile) classFiles.nextElement(); // String filename = new String(classFile.fileName()); // filename = filename.replace('/', File.separatorChar) + ".class"; // // File destinationPath = buildConfig.getOutputDir(); // if (destinationPath == null) { // filename = new File(filename).getName(); // filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath(); // } else { // filename = new File(destinationPath, filename).getPath(); // } // // //System.out.println("classfile: " + filename); // unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes())); // } // state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles); //// System.out.println("file: " + sourceFileName); //// for (int i=0; i < unitResult.simpleNameReferences.length; i++) { //// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i])); //// } //// for (int i=0; i < unitResult.qualifiedReferences.length; i++) { //// System.out.println("qualified: " + //// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/'))); //// } // } else { // state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST); // } // } // private void setBuildConfig(AjBuildConfig buildConfig) { this.buildConfig = buildConfig; handler.reset(); } String makeClasspathString(AjBuildConfig buildConfig) { if (buildConfig == null || buildConfig.getFullClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. * Otherwise it will return a string message indicating the problem. */ public String checkRtJar(AjBuildConfig buildConfig) { // omitting dev info if (Version.text.equals(Version.DEVELOPMENT)) { // in the development version we can't do this test usefully // MessageUtil.info(holder, "running development version of aspectj compiler"); return null; } if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified"; String ret = null; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { File p = new File( (String)it.next() ); // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) { try { String version = null; Manifest manifest = new JarFile(p).getManifest(); if (manifest == null) { ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text; continue; } Attributes attr = manifest.getAttributes("org/aspectj/lang/"); if (null != attr) { version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (null != version) { version = version.trim(); } } // assume that users of development aspectjrt.jar know what they're doing if (Version.DEVELOPMENT.equals(version)) { // MessageUtil.info(holder, // "running with development version of aspectjrt.jar in " + // p.getAbsolutePath()); return null; } else if (!Version.text.equals(version)) { ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found " + version; continue; } } catch (IOException ioe) { ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; } return null; // this is the "OK" return value! } else { // might want to catch other classpath errors } } if (ret != null) return ret; // last error found in potentially matching jars... return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("AjBuildManager("); buf.append(")"); return buf.toString(); } public void setStructureModel(IHierarchy structureModel) { this.structureModel = structureModel; } /** * Returns null if there is no structure model */ public IHierarchy getStructureModel() { return structureModel; } public IProgressListener getProgressListener() { return progressListener; } public void setProgressListener(IProgressListener progressListener) { this.progressListener = progressListener; } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[]) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { String filename = new String(eclipseClassFileName); filename = filename.replace('/', File.separatorChar) + ".class"; File destinationPath = buildConfig.getOutputDir(); String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } return outFile; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, getProblemFactory()); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment); EclipseFactory factory = new EclipseFactory(le,this); le.factory = factory; pr.factory = factory; forCompiler.lookupEnvironment = le; forCompiler.parser = new Parser( pr, forCompiler.options.parseLiteralExpressionsAsConstants); return new AjCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), state.getResultSetToUseForFullWeave(), buildConfig.isNoWeave(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing()); } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return binarySourcesForTheNextCompile; } public static AsmHierarchyBuilder getAsmHierarchyBuilder() { return asmHierarchyBuilder; } /** * Override the the default hierarchy builder. */ public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) { asmHierarchyBuilder = newBuilder; } public AjState getState() { return state; } public void setState(AjState buildState) { state = buildState; } private static class AjBuildContexFormatter implements ContextFormatter { public String formatEntry(int phaseId, Object data) { StringBuffer sb = new StringBuffer(); if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) { sb.append("batch building "); } else { sb.append("incrementally building "); } AjBuildConfig config = (AjBuildConfig) data; List classpath = config.getClasspath(); sb.append("with classpath: "); for (Iterator iter = classpath.iterator(); iter.hasNext();) { sb.append(iter.next().toString()); sb.append(File.pathSeparator); } return sb.toString(); } } }
120,356
Bug 120356 @AJ decl err/warn does not show cross structure view
Perhaps an issue in the ASM struct for DEOW since cross struct. is empty in AJDT , despite error / warning gutter and message is ok.
resolved fixed
f743fb2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-10T11:25:44Z
2005-12-12T12:20:00Z
tests/bugs151/pr120356/A.java
120,356
Bug 120356 @AJ decl err/warn does not show cross structure view
Perhaps an issue in the ASM struct for DEOW since cross struct. is empty in AJDT , despite error / warning gutter and message is ok.
resolved fixed
f743fb2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-10T11:25:44Z
2005-12-12T12:20:00Z
tests/bugs151/pr120356/C.java
120,356
Bug 120356 @AJ decl err/warn does not show cross structure view
Perhaps an issue in the ASM struct for DEOW since cross struct. is empty in AJDT , despite error / warning gutter and message is ok.
resolved fixed
f743fb2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-10T11:25:44Z
2005-12-12T12:20:00Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.systemtest.ajc150.GenericsTests; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");} public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");} public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");} public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");} public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");} //public void testExposingWithintype_enh123423() { runTest("exposing withintype");} public void testMixingNumbersOfTypeParameters_pr125080() { runTest("mixing numbers of type parameters"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;"); } public void testMixingNumbersOfTypeParameters_pr125080_2() { runTest("mixing numbers of type parameters - 2"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;"); } public void testIProgramElementMethods_pr125295() { runTest("new IProgramElement methods"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForType("pkg","foo"); assertNotNull("Couldn't find 'foo' element in the tree",pe); // check that the defaults return the fully qualified arg assertEquals("foo(int, java.lang.Object)",pe.toLabelString()); assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString()); assertEquals("foo(int, java.lang.Object)",pe.toSignatureString()); // check that can get hold of the non qualified args assertEquals("foo(int, Object)",pe.toLabelString(false)); assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false)); assertEquals("foo(int, Object)",pe.toSignatureString(false)); IProgramElement pe2 = top.findElementForType("pkg","printParameters"); assertNotNull("Couldn't find 'printParameters' element in the tree",pe2); // the argument is org.aspectj.lang.JoinPoint, check that this is added assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty()); } public void testParameterizedEnum_pr126316() { runTest("E extends Enum(E) again"); } /* * @AspectJ bugs and enhancements */ // public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { // runTest("inherit adivce with this() and thisJoinPoint"); // } public void testAtAspectInheritsAbstractPointcut_pr125810 () { runTest("warning when inherited pointcut not made concrete"); } /* * Load-time weaving bugs and enhancements */ public void testEmptyPointcutInAtAspectJ_pr125475 () { runTest("define empty pointcut using an annotation"); } public void testEmptyPointcutInAtAspectJ_pr125475_2() { runTest("define empty pointcut using an annotation - 2"); } public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () { runTest("define empty pointcut using aop.xml"); } public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () { runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent"); } ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
120,356
Bug 120356 @AJ decl err/warn does not show cross structure view
Perhaps an issue in the ASM struct for DEOW since cross struct. is empty in AJDT , despite error / warning gutter and message is ok.
resolved fixed
f743fb2
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-10T11:25:44Z
2005-12-12T12:20:00Z
weaver/src/org/aspectj/weaver/bcel/AtAjAttributes.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * initial implementation Alexandre Vasseur *******************************************************************************/ package org.aspectj.weaver.bcel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.Constant; import org.aspectj.apache.bcel.classfile.ConstantUtf8; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.LocalVariable; import org.aspectj.apache.bcel.classfile.LocalVariableTable; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.classfile.annotation.ClassElementValue; import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePair; import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnotations; import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisibleAnnotations; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.IHasPosition; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.MethodDelegateTypeMunger; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.DeclareErrorOrWarning; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.DeclarePrecedence; import org.aspectj.weaver.patterns.ExactTypePattern; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.IScope; import org.aspectj.weaver.patterns.IdentityPointcutVisitor; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.PerCflow; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.PerFromSuper; import org.aspectj.weaver.patterns.PerObject; import org.aspectj.weaver.patterns.PerSingleton; import org.aspectj.weaver.patterns.PerTypeWithin; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.SimpleScope; import org.aspectj.weaver.patterns.TypePattern; /** * Annotation defined aspect reader. * <p/> * It reads the Java 5 annotations and turns them into AjAttributes * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class AtAjAttributes { private final static List EMPTY_LIST = new ArrayList(); private final static String[] EMPTY_STRINGS = new String[0]; private final static String VALUE = "value"; private final static String POINTCUT = "pointcut"; private final static String THROWING = "throwing"; private final static String RETURNING = "returning"; private final static String STRING_DESC = "Ljava/lang/String;"; /** * A struct that allows to add extra arguments without always breaking the API * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ private static class AjAttributeStruct { /** * The list of AjAttribute.XXX that we are populating from the @AJ read */ List ajAttributes = new ArrayList(); /** * The resolved type (class) for which we are reading @AJ for (be it class, method, field annotations) */ final ResolvedType enclosingType; final ISourceContext context; final IMessageHandler handler; public AjAttributeStruct(ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) { enclosingType = type; context = sourceContext; handler = messageHandler; } } /** * A struct when we read @AJ on method * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ private static class AjAttributeMethodStruct extends AjAttributeStruct { /** * Argument names as they appear in the SOURCE code, ordered, and lazyly populated * Used to do formal binding */ private String[] m_argumentNamesLazy = null; final Method method; final BcelMethod bMethod; public AjAttributeMethodStruct(Method method, BcelMethod bMethod, ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) { super(type, sourceContext, messageHandler); this.method = method; this.bMethod = bMethod; } public String[] getArgumentNames() { if (m_argumentNamesLazy == null) { m_argumentNamesLazy = getMethodArgumentNamesAsInSource(method); } return m_argumentNamesLazy; } } /** * A struct when we read @AJ on field * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ private static class AjAttributeFieldStruct extends AjAttributeStruct { final Field field; final BcelField bField; public AjAttributeFieldStruct(Field field, BcelField bField, ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) { super(type, sourceContext, messageHandler); this.field = field; this.bField = bField; } } /** * Annotations are RuntimeVisible only. This allow us to not visit RuntimeInvisible ones. * * @param attribute * @return true if runtime visible annotation */ public static boolean acceptAttribute(Attribute attribute) { return (attribute instanceof RuntimeVisibleAnnotations); } /** * Extract class level annotations and turn them into AjAttributes. * * @param javaClass * @param type * @param context * @param msgHandler * @return list of AjAttributes */ public static List readAj5ClassAttributes(JavaClass javaClass, ReferenceType type, ISourceContext context, IMessageHandler msgHandler, boolean isCodeStyleAspect) { //FIXME AV - 1.5 feature limitation, kick after implemented try { Constant[] cpool = javaClass.getConstantPool().getConstantPool(); for (int i = 0; i < cpool.length; i++) { Constant constant = cpool[i]; if (constant != null && constant.getTag() == Constants.CONSTANT_Utf8) { if (!javaClass.getClassName().startsWith("org.aspectj.lang.annotation")) { ConstantUtf8 constantUtf8 = (ConstantUtf8) constant; if ("Lorg/aspectj/lang/annotation/DeclareAnnotation;".equals(constantUtf8.getBytes())) { msgHandler.handleMessage( new Message( "Found @DeclareAnnotation while current release does not support it (see '" + type.getName() + "')", IMessage.WARNING, null, type.getSourceLocation() ) ); } } } } } catch (Throwable t) { ; } AjAttributeStruct struct = new AjAttributeStruct(type, context, msgHandler); Attribute[] attributes = javaClass.getAttributes(); boolean hasAtAspectAnnotation = false; boolean hasAtPrecedenceAnnotation = false; for (int i = 0; i < attributes.length; i++) { Attribute attribute = attributes[i]; if (acceptAttribute(attribute)) { RuntimeAnnotations rvs = (RuntimeAnnotations) attribute; // we don't need to look for several attribute occurence since it cannot happen as per JSR175 if (!isCodeStyleAspect && !javaClass.isInterface()) { hasAtAspectAnnotation = handleAspectAnnotation(rvs, struct); //TODO AV - if put outside the if isCodeStyleAspect then we would enable mix style hasAtPrecedenceAnnotation = handlePrecedenceAnnotation(rvs, struct); } // there can only be one RuntimeVisible bytecode attribute break; } } // basic semantic check if (hasAtPrecedenceAnnotation && !hasAtAspectAnnotation) { msgHandler.handleMessage( new Message( "Found @DeclarePrecedence on a non @Aspect type '" + type.getName() + "'", IMessage.WARNING, null, type.getSourceLocation() ) ); // bypass what we have read return EMPTY_LIST; } // the following block will not detect @Pointcut in non @Aspect types for optimization purpose if (!hasAtAspectAnnotation) { return EMPTY_LIST; } //FIXME AV - turn on when ajcMightHaveAspect // if (hasAtAspectAnnotation && type.isInterface()) { // msgHandler.handleMessage( // new Message( // "Found @Aspect on an interface type '" + type.getName() + "'", // IMessage.WARNING, // null, // type.getSourceLocation() // ) // ); // // bypass what we have read // return EMPTY_LIST; // } // semantic check: @Aspect must be public // FIXME AV - do we really want to enforce that? // if (hasAtAspectAnnotation && !javaClass.isPublic()) { // msgHandler.handleMessage( // new Message( // "Found @Aspect annotation on a non public class '" + javaClass.getClassName() + "'", // IMessage.ERROR, // null, // type.getSourceLocation() // ) // ); // return EMPTY_LIST; // } // code style pointcuts are class attributes // we need to gather the @AJ pointcut right now and not at method level annotation extraction time // in order to be able to resolve the pointcut references later on // we don't need to look in super class, the pointcut reference in the grammar will do it for (int i = 0; i < javaClass.getMethods().length; i++) { Method method = javaClass.getMethods()[i]; if (method.getName().startsWith(NameMangler.PREFIX)) continue; // already dealt with by ajc... //FIXME alex optimize, this method struct will gets recreated for advice extraction AjAttributeMethodStruct mstruct = new AjAttributeMethodStruct(method, null, type, context, msgHandler);//FIXME AVASM Attribute[] mattributes = method.getAttributes(); for (int j = 0; j < mattributes.length; j++) { Attribute mattribute = mattributes[j]; if (acceptAttribute(mattribute)) { RuntimeAnnotations mrvs = (RuntimeAnnotations) mattribute; handlePointcutAnnotation(mrvs, mstruct); // there can only be one RuntimeVisible bytecode attribute break; } } // FIXME asc should check we aren't adding multiple versions... will do once I get the tests passing again... struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); struct.ajAttributes.addAll(mstruct.ajAttributes); } // code style declare error / warning / implements / parents are field attributes for (int i = 0; i < javaClass.getFields().length; i++) { Field field = javaClass.getFields()[i]; if (field.getName().startsWith(NameMangler.PREFIX)) continue; // already dealt with by ajc... //FIXME alex optimize, this method struct will gets recreated for advice extraction AjAttributeFieldStruct fstruct = new AjAttributeFieldStruct(field, null, type, context, msgHandler); Attribute[] fattributes = field.getAttributes(); for (int j = 0; j < fattributes.length; j++) { Attribute fattribute = fattributes[j]; if (acceptAttribute(fattribute)) { RuntimeAnnotations frvs = (RuntimeAnnotations) fattribute; if (handleDeclareErrorOrWarningAnnotation(frvs, fstruct) || handleDeclareParentsAnnotation(frvs, fstruct)) { // semantic check - must be in an @Aspect [remove if previous block bypassed in advance] if (!type.isAnnotationStyleAspect()) { msgHandler.handleMessage( new Message( "Found @AspectJ annotations in a non @Aspect type '" + type.getName() + "'", IMessage.WARNING, null, type.getSourceLocation() ) ); ;// go ahead } } // there can only be one RuntimeVisible bytecode attribute break; } } struct.ajAttributes.addAll(fstruct.ajAttributes); } return struct.ajAttributes; } /** * Extract method level annotations and turn them into AjAttributes. * * @param method * @param type * @param context * @param msgHandler * @return list of AjAttributes */ public static List readAj5MethodAttributes(Method method, BcelMethod bMethod, ResolvedType type, ResolvedPointcutDefinition preResolvedPointcut, ISourceContext context, IMessageHandler msgHandler) { if (method.getName().startsWith(NameMangler.PREFIX)) return Collections.EMPTY_LIST; // already dealt with by ajc... AjAttributeMethodStruct struct = new AjAttributeMethodStruct(method, bMethod, type, context, msgHandler); Attribute[] attributes = method.getAttributes(); // we remember if we found one @AJ annotation for minimal semantic error reporting // the real reporting beeing done thru AJDT and the compiler mapping @AJ to AjAtttribute // or thru APT // // Note: we could actually skip the whole thing if type is not itself an @Aspect // but then we would not see any warning. We do bypass for pointcut but not for advice since it would // be too silent. boolean hasAtAspectJAnnotation = false; boolean hasAtAspectJAnnotationMustReturnVoid = false; for (int i = 0; i < attributes.length; i++) { Attribute attribute = attributes[i]; try { if (acceptAttribute(attribute)) { RuntimeAnnotations rvs = (RuntimeAnnotations) attribute; hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleBeforeAnnotation( rvs, struct, preResolvedPointcut ); hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterAnnotation( rvs, struct, preResolvedPointcut ); hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterReturningAnnotation( rvs, struct, preResolvedPointcut, bMethod ); hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterThrowingAnnotation( rvs, struct, preResolvedPointcut, bMethod ); hasAtAspectJAnnotation = hasAtAspectJAnnotation || handleAroundAnnotation( rvs, struct, preResolvedPointcut ); // there can only be one RuntimeVisible bytecode attribute break; } } catch (ReturningFormalNotDeclaredInAdviceSignatureException e) { msgHandler.handleMessage( new Message( WeaverMessages.format(WeaverMessages.RETURNING_FORMAL_NOT_DECLARED_IN_ADVICE,e.getFormalName()), IMessage.ERROR, null, bMethod.getSourceLocation()) ); } catch (ThrownFormalNotDeclaredInAdviceSignatureException e) { msgHandler.handleMessage( new Message( WeaverMessages.format(WeaverMessages.THROWN_FORMAL_NOT_DECLARED_IN_ADVICE,e.getFormalName()), IMessage.ERROR, null, bMethod.getSourceLocation()) ); } } hasAtAspectJAnnotation = hasAtAspectJAnnotation || hasAtAspectJAnnotationMustReturnVoid; // semantic check - must be in an @Aspect [remove if previous block bypassed in advance] if (hasAtAspectJAnnotation && !type.isAnnotationStyleAspect()) { msgHandler.handleMessage( new Message( "Found @AspectJ annotations in a non @Aspect type '" + type.getName() + "'", IMessage.WARNING, null, type.getSourceLocation() ) ); ;// go ahead } // semantic check - advice must be public if (hasAtAspectJAnnotation && !struct.method.isPublic()) { msgHandler.handleMessage( new Message( "Found @AspectJ annotation on a non public advice '" + methodToString(struct.method) + "'", IMessage.ERROR, null, type.getSourceLocation() ) ); ;// go ahead } // semantic check for non around advice must return void if (hasAtAspectJAnnotationMustReturnVoid && !Type.VOID.equals(struct.method.getReturnType())) { msgHandler.handleMessage( new Message( "Found @AspectJ annotation on a non around advice not returning void '" + methodToString( struct.method ) + "'", IMessage.ERROR, null, type.getSourceLocation() ) ); ;// go ahead } return struct.ajAttributes; } /** * Extract field level annotations and turn them into AjAttributes. * * @param field * @param type * @param context * @param msgHandler * @return list of AjAttributes, always empty for now */ public static List readAj5FieldAttributes(Field field, BcelField bField, ResolvedType type, ISourceContext context, IMessageHandler msgHandler) { // Note: field annotation are for ITD and DEOW - processed at class level directly return Collections.EMPTY_LIST; } /** * Read @Aspect * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAspectAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeStruct struct) { Annotation aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION); if (aspect != null) { // semantic check for inheritance (only one level up) boolean extendsAspect = false; if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) { if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) { reportError("cannot extend a concrete aspect", struct); return false; } extendsAspect = struct.enclosingType.getSuperclass().isAspect(); } ElementNameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE); final PerClause perClause; if (aspectPerClause == null) { // empty value means singleton unless inherited if (!extendsAspect) { perClause = new PerSingleton(); } else { perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind()); } } else { String perX = aspectPerClause.getValue().stringifyValue(); if (perX == null || perX.length() <= 0) { perClause = new PerSingleton(); } else { perClause = parsePerClausePointcut(perX, struct); } } if (perClause == null) { // could not parse it, ignore the aspect return false; } else { perClause.setLocation(struct.context, struct.context.getOffset(), struct.context.getOffset()+1);//FIXME AVASM // FIXME asc see related comment way about about the version... struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo()); AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause); struct.ajAttributes.add(aspectAttribute); FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; final IScope binding; binding = new BindingScope( struct.enclosingType, struct.context, bindings ); // // we can't resolve here since the perclause typically refers to pointcuts // // defined in the aspect that we haven't told the BcelObjectType about yet. // // perClause.resolve(binding); // so we prepare to do it later... aspectAttribute.setResolutionScope(binding); return true; } } return false; } /** * Read a perClause, returns null on failure and issue messages * * @param perClauseString like "pertarget(.....)" * @param struct for which we are parsing the per clause * @return a PerClause instance */ private static PerClause parsePerClausePointcut(String perClauseString, AjAttributeStruct struct) { final String pointcutString; Pointcut pointcut = null; TypePattern typePattern = null; final PerClause perClause; if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOW.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERCFLOW.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerCflow(pointcut, false); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOWBELOW.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERCFLOWBELOW.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerCflow(pointcut, true); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTARGET.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERTARGET.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerObject(pointcut, false); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTHIS.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERTHIS.extractPointcut(perClauseString); pointcut = parsePointcut(pointcutString, struct, false); perClause = new PerObject(pointcut, true); } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTYPEWITHIN.getName())) { pointcutString = PerClause.KindAnnotationPrefix.PERTYPEWITHIN.extractPointcut(perClauseString); typePattern = parseTypePattern(pointcutString, struct); perClause = new PerTypeWithin(typePattern); } else if (perClauseString.equalsIgnoreCase(PerClause.SINGLETON.getName() + "()")) { perClause = new PerSingleton(); } else { // could not parse the @AJ perclause - fallback to singleton and issue an error reportError("@Aspect per clause cannot be read '" + perClauseString + "'", struct); return null; } if (!PerClause.SINGLETON.equals(perClause.getKind()) && !PerClause.PERTYPEWITHIN.equals(perClause.getKind()) && pointcut == null) { // we could not parse the pointcut return null; } if (PerClause.PERTYPEWITHIN.equals(perClause.getKind()) && typePattern == null) { // we could not parse the type pattern return null; } return perClause; } /** * Read @DeclarePrecedence * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handlePrecedenceAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeStruct struct) { Annotation aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREPRECEDENCE_ANNOTATION); if (aspect != null) { ElementNameValuePair precedence = getAnnotationElement(aspect, VALUE); if (precedence != null) { String precedencePattern = precedence.getValue().stringifyValue(); PatternParser parser = new PatternParser(precedencePattern); DeclarePrecedence ajPrecedence = parser.parseDominates(); struct.ajAttributes.add(new AjAttribute.DeclareAttribute(ajPrecedence)); return true; } } return false; } // /** // * Read @DeclareImplements // * // * @param runtimeAnnotations // * @param struct // * @return true if found // */ // private static boolean handleDeclareImplementsAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeFieldStruct struct) {//, ResolvedPointcutDefinition preResolvedPointcut) { // Annotation deci = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREIMPLEMENTS_ANNOTATION); // if (deci != null) { // ElementNameValuePair deciPatternNVP = getAnnotationElement(deci, VALUE); // String deciPattern = deciPatternNVP.getValue().stringifyValue(); // if (deciPattern != null) { // TypePattern typePattern = parseTypePattern(deciPattern, struct); // ResolvedType fieldType = UnresolvedType.forSignature(struct.field.getSignature()).resolve(struct.enclosingType.getWorld()); // if (fieldType.isPrimitiveType()) { // return false; // } else if (fieldType.isInterface()) { // TypePattern parent = new ExactTypePattern(UnresolvedType.forSignature(struct.field.getSignature()), false, false); // parent.resolve(struct.enclosingType.getWorld()); // List parents = new ArrayList(1); // parents.add(parent); // //TODO kick ISourceLocation sl = struct.bField.getSourceLocation(); ?? // struct.ajAttributes.add( // new AjAttribute.DeclareAttribute( // new DeclareParents( // typePattern, // parents, // false // ) // ) // ); // return true; // } else { // reportError("@DeclareImplements: can only be used on field whose type is an interface", struct); // return false; // } // } // } // return false; // } /** * Read @DeclareParents * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleDeclareParentsAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeFieldStruct struct) {//, ResolvedPointcutDefinition preResolvedPointcut) { Annotation decp = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREPARENTS_ANNOTATION); if (decp != null) { ElementNameValuePair decpPatternNVP = getAnnotationElement(decp, VALUE); String decpPattern = decpPatternNVP.getValue().stringifyValue(); if (decpPattern != null) { TypePattern typePattern = parseTypePattern(decpPattern, struct); ResolvedType fieldType = UnresolvedType.forSignature(struct.field.getSignature()).resolve(struct.enclosingType.getWorld()); if (fieldType.isInterface()) { TypePattern parent = new ExactTypePattern(UnresolvedType.forSignature(struct.field.getSignature()), false, false); parent.resolve(struct.enclosingType.getWorld()); // first add the declare implements like List parents = new ArrayList(1); parents.add(parent); DeclareParents dp = new DeclareParents( typePattern, parents, false ); //TODO kick ISourceLocation sl = struct.bField.getSourceLocation(); ?? dp.setLocation(struct.context,0,0); // not ideal... struct.ajAttributes.add( new AjAttribute.DeclareAttribute( dp ) ); // do we have a defaultImpl=xxx.class (ie implementation) String defaultImplClassName = null; ElementNameValuePair defaultImplNVP = getAnnotationElement(decp, "defaultImpl"); if (defaultImplNVP != null) { ClassElementValue defaultImpl = (ClassElementValue) defaultImplNVP.getValue(); defaultImplClassName = UnresolvedType.forSignature(defaultImpl.getClassString()).getName(); if (defaultImplClassName.equals("org.aspectj.lang.annotation.DeclareParents")) { defaultImplClassName = null; } else { // check public no arg ctor ResolvedType impl = struct.enclosingType.getWorld().resolve( defaultImplClassName, false ); ResolvedMember[] mm = impl.getDeclaredMethods(); boolean hasNoCtorOrANoArgOne = true; for (int i = 0; i < mm.length; i++) { ResolvedMember resolvedMember = mm[i]; if (resolvedMember.getName().equals("<init>")) { hasNoCtorOrANoArgOne = false; if (resolvedMember.getParameterTypes().length == 0 && resolvedMember.isPublic()) { hasNoCtorOrANoArgOne = true; } } if (hasNoCtorOrANoArgOne) { break; } } if (!hasNoCtorOrANoArgOne) { reportError("@DeclareParents: defaultImpl=\"" + defaultImplClassName + "\" has no public no-arg constructor", struct); } } } // then iterate on field interface hierarchy (not object) boolean hasAtLeastOneMethod = false; ResolvedMember[] methods = (ResolvedMember[])fieldType.getMethodsWithoutIterator(true, false).toArray(new ResolvedMember[0]); for (int i = 0; i < methods.length; i++) { ResolvedMember method = (ResolvedMember)methods[i]; if (method.isAbstract()) { if (defaultImplClassName == null) { // non marker interface with no default impl provided reportError("@DeclareParents: used with a non marker interface and no defaultImpl=\"...\" provided", struct); return false; } hasAtLeastOneMethod = true; struct.ajAttributes.add( new AjAttribute.TypeMunger( new MethodDelegateTypeMunger( method, struct.enclosingType, defaultImplClassName, typePattern ) ) ); } } // successfull so far, we thus need a bcel type munger to have // a field hosting the mixin in the target type if (hasAtLeastOneMethod) { struct.ajAttributes.add( new AjAttribute.TypeMunger( new MethodDelegateTypeMunger.FieldHostTypeMunger( AjcMemberMaker.itdAtDeclareParentsField( null,//prototyped fieldType, struct.enclosingType ), struct.enclosingType, typePattern ) ) ); } return true; } else { reportError("@DeclareParents: can only be used on a field whose type is an interface", struct); return false; } } } return false; } /** * Read @Before * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleBeforeAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) { Annotation before = getAnnotation(runtimeAnnotations, AjcMemberMaker.BEFORE_ANNOTATION); if (before != null) { ElementNameValuePair beforeAdvice = getAnnotationElement(before, VALUE); if (beforeAdvice != null) { // this/target/args binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = extractBindings(struct); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope( struct.enclosingType, struct.context, bindings ); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); //pc.resolve(binding); } else { pc = parsePointcut(beforeAdvice.getValue().stringifyValue(), struct, false); if (pc == null) return false;//parse error pc = pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod.getDeclarationOffset()); struct.ajAttributes.add( new AjAttribute.AdviceAttribute( AdviceKind.Before, pc, extraArgument, sl.getOffset(), sl.getOffset()+1,//FIXME AVASM struct.context ) ); return true; } } return false; } /** * Read @After * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAfterAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) { Annotation after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTER_ANNOTATION); if (after != null) { ElementNameValuePair afterAdvice = getAnnotationElement(after, VALUE); if (afterAdvice != null) { // this/target/args binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = extractBindings(struct); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope( struct.enclosingType, struct.context, bindings ); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(afterAdvice.getValue().stringifyValue(), struct, false); if (pc == null) return false;//parse error pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod.getDeclarationOffset()); struct.ajAttributes.add( new AjAttribute.AdviceAttribute( AdviceKind.After, pc, extraArgument, sl.getOffset(), sl.getOffset()+1,//FIXME AVASM struct.context ) ); return true; } } return false; } /** * Read @AfterReturning * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAfterReturningAnnotation( RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut, BcelMethod owningMethod) throws ReturningFormalNotDeclaredInAdviceSignatureException { Annotation after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERRETURNING_ANNOTATION); if (after != null) { ElementNameValuePair annValue = getAnnotationElement(after, VALUE); ElementNameValuePair annPointcut = getAnnotationElement(after, POINTCUT); ElementNameValuePair annReturned = getAnnotationElement(after, RETURNING); // extract the pointcut and returned type/binding - do some checks String pointcut = null; String returned = null; if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) { reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annValue != null) { pointcut = annValue.getValue().stringifyValue(); } else { pointcut = annPointcut.getValue().stringifyValue(); } if (isNullOrEmpty(pointcut)) { reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annReturned != null) { returned = annReturned.getValue().stringifyValue(); if (isNullOrEmpty(returned)) { returned = null; } else { // check that thrownFormal exists as the last parameter in the advice String[] pNames = owningMethod.getParameterNames(); if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(returned)) { throw new ReturningFormalNotDeclaredInAdviceSignatureException(returned); } } } // this/target/args binding // exclude the return binding from the pointcut binding since it is an extraArg binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = (returned == null ? extractBindings(struct) : extractBindings(struct, returned)); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope( struct.enclosingType, struct.context, bindings ); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); // return binding if (returned != null) { extraArgument |= Advice.ExtraArgument; } Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(pointcut, struct, false); if (pc == null) return false;//parse error pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod.getDeclarationOffset()); struct.ajAttributes.add( new AjAttribute.AdviceAttribute( AdviceKind.AfterReturning, pc, extraArgument, sl.getOffset(), sl.getOffset()+1,//FIXME AVASM struct.context ) ); return true; } return false; } /** * Read @AfterThrowing * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAfterThrowingAnnotation( RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut, BcelMethod owningMethod) throws ThrownFormalNotDeclaredInAdviceSignatureException { Annotation after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERTHROWING_ANNOTATION); if (after != null) { ElementNameValuePair annValue = getAnnotationElement(after, VALUE); ElementNameValuePair annPointcut = getAnnotationElement(after, POINTCUT); ElementNameValuePair annThrown = getAnnotationElement(after, THROWING); // extract the pointcut and throwned type/binding - do some checks String pointcut = null; String thrownFormal = null; if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) { reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annValue != null) { pointcut = annValue.getValue().stringifyValue(); } else { pointcut = annPointcut.getValue().stringifyValue(); } if (isNullOrEmpty(pointcut)) { reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct); return false; } if (annThrown != null) { thrownFormal = annThrown.getValue().stringifyValue(); if (isNullOrEmpty(thrownFormal)) { thrownFormal = null; } else { // check that thrownFormal exists as the last parameter in the advice String[] pNames = owningMethod.getParameterNames(); if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(thrownFormal)) { throw new ThrownFormalNotDeclaredInAdviceSignatureException(thrownFormal); } } } // this/target/args binding // exclude the throwned binding from the pointcut binding since it is an extraArg binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = (thrownFormal == null ? extractBindings(struct) : extractBindings(struct, thrownFormal)); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope( struct.enclosingType, struct.context, bindings ); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); // return binding if (thrownFormal != null) { extraArgument |= Advice.ExtraArgument; } Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(pointcut, struct, false); if (pc == null) return false;//parse error pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod.getDeclarationOffset()); struct.ajAttributes.add( new AjAttribute.AdviceAttribute( AdviceKind.AfterThrowing, pc, extraArgument, sl.getOffset(), sl.getOffset()+1,//FIXME AVASM struct.context ) ); return true; } return false; } /** * Read @Around * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleAroundAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) { Annotation around = getAnnotation(runtimeAnnotations, AjcMemberMaker.AROUND_ANNOTATION); if (around != null) { ElementNameValuePair aroundAdvice = getAnnotationElement(around, VALUE); if (aroundAdvice != null) { // this/target/args binding FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; try { bindings = extractBindings(struct); } catch (UnreadableDebugInfoException unreadableDebugInfoException) { return false; } IScope binding = new BindingScope( struct.enclosingType, struct.context, bindings ); // joinpoint, staticJoinpoint binding int extraArgument = extractExtraArgument(struct.method); Pointcut pc = null; if (preResolvedPointcut != null) { pc = preResolvedPointcut.getPointcut(); } else { pc = parsePointcut(aroundAdvice.getValue().stringifyValue(), struct, false); if (pc == null) return false;//parse error pc.resolve(binding); } setIgnoreUnboundBindingNames(pc, bindings); ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod.getDeclarationOffset()); struct.ajAttributes.add( new AjAttribute.AdviceAttribute( AdviceKind.Around, pc, extraArgument, sl.getOffset(), sl.getOffset()+1,//FIXME AVASM struct.context ) ); return true; } } return false; } /** * Read @Pointcut and handle the resolving in a lazy way to deal with pointcut references * * @param runtimeAnnotations * @param struct */ private static void handlePointcutAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct) { Annotation pointcut = getAnnotation(runtimeAnnotations, AjcMemberMaker.POINTCUT_ANNOTATION); if (pointcut != null) { ElementNameValuePair pointcutExpr = getAnnotationElement(pointcut, VALUE); // semantic check: the method must return void, or be "public static boolean" for if() support if (!(Type.VOID.equals(struct.method.getReturnType()) || (Type.BOOLEAN.equals(struct.method.getReturnType()) && struct.method.isStatic() && struct.method.isPublic()))) { reportWarning("Found @Pointcut on a method not returning 'void' or not 'public static boolean'", struct); ;//no need to stop } // semantic check: the method must not throw anything if (struct.method.getExceptionTable() != null) { reportWarning("Found @Pointcut on a method throwing exception", struct); ;// no need to stop } // this/target/args binding final IScope binding; try { binding = new BindingScope( struct.enclosingType, struct.context, extractBindings(struct) ); } catch (UnreadableDebugInfoException e) { return; } UnresolvedType[] argumentTypes = new UnresolvedType[struct.method.getArgumentTypes().length]; for (int i = 0; i < argumentTypes.length; i++) { argumentTypes[i] = UnresolvedType.forSignature(struct.method.getArgumentTypes()[i].getSignature()); } Pointcut pc = null; if (struct.method.isAbstract()) { if ((pointcutExpr != null && isNullOrEmpty(pointcutExpr.getValue().stringifyValue())) || pointcutExpr == null) { // abstract pointcut // leave pc = null } else { reportError("Found defined @Pointcut on an abstract method", struct); return;//stop } } else { if (pointcutExpr==null || (pointcutExpr != null && isNullOrEmpty(pointcutExpr.getValue().stringifyValue()))) { // the matches nothing pointcut (125475/125480) - perhaps not as cleanly supported as it could be. } else { if (pointcutExpr != null) { // use a LazyResolvedPointcutDefinition so that the pointcut is resolved lazily // since for it to be resolved, we will need other pointcuts to be registered as well pc = parsePointcut(pointcutExpr.getValue().stringifyValue(), struct, true); if (pc == null) return;//parse error pc.setLocation(struct.context, -1, -1);//FIXME AVASM !! bMethod is null here.. } else { reportError("Found undefined @Pointcut on a non-abstract method", struct); return; } } } // do not resolve binding now but lazily struct.ajAttributes.add( new AjAttribute.PointcutDeclarationAttribute( new LazyResolvedPointcutDefinition( struct.enclosingType, struct.method.getModifiers(), struct.method.getName(), argumentTypes, UnresolvedType.forSignature(struct.method.getReturnType().getSignature()), pc,//can be null for abstract pointcut binding ) ) ); } } /** * Read @DeclareError, @DeclareWarning * * @param runtimeAnnotations * @param struct * @return true if found */ private static boolean handleDeclareErrorOrWarningAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeFieldStruct struct) { Annotation error = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREERROR_ANNOTATION); boolean hasError = false; if (error != null) { ElementNameValuePair declareError = getAnnotationElement(error, VALUE); if (declareError != null) { if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) { reportError("@DeclareError used on a non String constant field", struct); return false; } FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; IScope binding = new BindingScope( struct.enclosingType, struct.context, bindings ); Pointcut pc = parsePointcut(declareError.getValue().stringifyValue(), struct, false); if (pc == null) { hasError = false;//cannot parse pointcut } else { pc .resolve(binding); DeclareErrorOrWarning deow = new DeclareErrorOrWarning(true, pc, struct.field.getConstantValue().toString()); deow.setLocation(struct.context, -1, -1); struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow)); hasError = true; } } } Annotation warning = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREWARNING_ANNOTATION); boolean hasWarning = false; if (warning != null) { ElementNameValuePair declareWarning = getAnnotationElement(warning, VALUE); if (declareWarning != null) { if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) { reportError("@DeclareWarning used on a non String constant field", struct); return false; } FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; IScope binding = new BindingScope( struct.enclosingType, struct.context, bindings ); Pointcut pc = parsePointcut(declareWarning.getValue().stringifyValue(), struct, false); if (pc == null) { hasWarning = false;//cannot parse pointcut } else { pc.resolve(binding); DeclareErrorOrWarning deow = new DeclareErrorOrWarning(false, pc, struct.field.getConstantValue().toString()); deow.setLocation(struct.context, -1, -1); struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow)); return hasWarning = true; } } } return hasError || hasWarning; } /** * Returns a readable representation of a method. * Method.toString() is not suitable. * * @param method * @return a readable representation of a method */ private static String methodToString(Method method) { StringBuffer sb = new StringBuffer(); sb.append(method.getName()); sb.append(method.getSignature()); return sb.toString(); } /** * Returns a readable representation of a field. * Field.toString() is not suitable. * * @param field * @return a readable representation of a field */ private static String fieldToString(Field field) { StringBuffer sb = new StringBuffer(); sb.append(field.getName()).append(' '); sb.append(field.getSignature()); return sb.toString(); } /** * Build the bindings for a given method (pointcut / advice) * * @param struct * @return null if no debug info is available */ private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct) throws UnreadableDebugInfoException { Method method = struct.method; String[] argumentNames = struct.getArgumentNames(); // assert debug info was here if (argumentNames.length != method.getArgumentTypes().length) { reportError("Cannot read debug info for @Aspect to handle formal binding in pointcuts (please compile with 'javac -g' or '<javac debug='true'.../>' in Ant)", struct); throw new UnreadableDebugInfoException(); } List bindings = new ArrayList(); for (int i = 0; i < argumentNames.length; i++) { String argumentName = argumentNames[i]; UnresolvedType argumentType = UnresolvedType.forSignature(method.getArgumentTypes()[i].getSignature()); // do not bind JoinPoint / StaticJoinPoint / EnclosingStaticJoinPoint // TODO solve me : this means that the JP/SJP/ESJP cannot appear as binding // f.e. when applying advice on advice etc if ((AjcMemberMaker.TYPEX_JOINPOINT.equals(argumentType) || AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.equals(argumentType) || AjcMemberMaker.TYPEX_STATICJOINPOINT.equals(argumentType) || AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.equals(argumentType) || AjcMemberMaker.AROUND_CLOSURE_TYPE.equals(argumentType))) { //continue;// skip bindings.add(new FormalBinding.ImplicitFormalBinding(argumentType, argumentName, i)); } else { bindings.add(new FormalBinding(argumentType, argumentName, i)); } } return (FormalBinding[]) bindings.toArray(new FormalBinding[]{}); } //FIXME alex deal with exclude index private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct, String excludeFormal) throws UnreadableDebugInfoException { FormalBinding[] bindings = extractBindings(struct); int excludeIndex = -1; for (int i = 0; i < bindings.length; i++) { FormalBinding binding = bindings[i]; if (binding.getName().equals(excludeFormal)) { excludeIndex = i; bindings[i] = new FormalBinding.ImplicitFormalBinding( binding.getType(), binding.getName(), binding.getIndex() ); break; } } return bindings; // // if (excludeIndex >= 0) { // FormalBinding[] bindingsFiltered = new FormalBinding[bindings.length-1]; // int k = 0; // for (int i = 0; i < bindings.length; i++) { // if (i == excludeIndex) { // ; // } else { // bindingsFiltered[k] = new FormalBinding(bindings[i].getType(), bindings[i].getName(), k); // k++; // } // } // return bindingsFiltered; // } else { // return bindings; // } } /** * Compute the flag for the xxxJoinPoint extra argument * * @param method * @return extra arg flag */ private static int extractExtraArgument(Method method) { Type[] methodArgs = method.getArgumentTypes(); String[] sigs = new String[methodArgs.length]; for (int i = 0; i < methodArgs.length; i++) { sigs[i] = methodArgs[i].getSignature(); } return extractExtraArgument(sigs); } /** * Compute the flag for the xxxJoinPoint extra argument * * @param argumentSignatures * @return extra arg flag */ public static int extractExtraArgument(String[] argumentSignatures) { int extraArgument = 0; for (int i = 0; i < argumentSignatures.length; i++) { if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisJoinPoint; } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisJoinPoint; } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisJoinPointStaticPart; } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argumentSignatures[i])) { extraArgument |= Advice.ThisEnclosingJoinPointStaticPart; } } return extraArgument; } /** * Returns the runtime (RV/RIV) annotation of type annotationType or null if no such annotation * * @param rvs * @param annotationType * @return annotation */ private static Annotation getAnnotation(RuntimeAnnotations rvs, UnresolvedType annotationType) { final String annotationTypeName = annotationType.getName(); for (Iterator iterator = rvs.getAnnotations().iterator(); iterator.hasNext();) { Annotation rv = (Annotation) iterator.next(); if (annotationTypeName.equals(rv.getTypeName())) { return rv; } } return null; } /** * Returns the value of a given element of an annotation or null if not found * Caution: Does not handles default value. * * @param annotation * @param elementName * @return annotation NVP */ private static ElementNameValuePair getAnnotationElement(Annotation annotation, String elementName) { for (Iterator iterator1 = annotation.getValues().iterator(); iterator1.hasNext();) { ElementNameValuePair element = (ElementNameValuePair) iterator1.next(); if (elementName.equals(element.getNameString())) { return element; } } return null; } /** * Extract the method argument names as in source from debug info * returns an empty array upon inconsistency * * @param method * @return method arg names as in source */ private static String[] getMethodArgumentNamesAsInSource(Method method) { if (method.getArgumentTypes().length == 0) { return EMPTY_STRINGS; } final int startAtStackIndex = method.isStatic() ? 0 : 1; final List arguments = new ArrayList(); LocalVariableTable lt = (LocalVariableTable) method.getLocalVariableTable(); if (lt != null) { for (int j = 0; j < lt.getLocalVariableTable().length; j++) { LocalVariable localVariable = lt.getLocalVariableTable()[j]; if (localVariable.getStartPC() == 0) { if (localVariable.getIndex() >= startAtStackIndex) { arguments.add(new MethodArgument(localVariable.getName(), localVariable.getIndex())); } } } } if (arguments.size() != method.getArgumentTypes().length) { return EMPTY_STRINGS; } // sort by index Collections.sort( arguments, new Comparator() { public int compare(Object o, Object o1) { MethodArgument mo = (MethodArgument) o; MethodArgument mo1 = (MethodArgument) o1; if (mo.indexOnStack == mo1.indexOnStack) { return 0; } else if (mo.indexOnStack > mo1.indexOnStack) { return 1; } else { return -1; } } } ); String[] argumentNames = new String[arguments.size()]; int i = 0; for (Iterator iterator = arguments.iterator(); iterator.hasNext(); i++) { MethodArgument methodArgument = (MethodArgument) iterator.next(); argumentNames[i] = methodArgument.name; } return argumentNames; } /** * A method argument, used for sorting by indexOnStack (ie order in signature) * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ private static class MethodArgument { String name; int indexOnStack; public MethodArgument(String name, int indexOnStack) { this.name = name; this.indexOnStack = indexOnStack; } } /** * BindingScope that knows the enclosingType, which is needed for pointcut reference resolution * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public static class BindingScope extends SimpleScope { private ResolvedType m_enclosingType; private ISourceContext m_sourceContext; public BindingScope(ResolvedType type, ISourceContext sourceContext, FormalBinding[] bindings) { super(type.getWorld(), bindings); m_enclosingType = type; m_sourceContext = sourceContext; } public ResolvedType getEnclosingType() { return m_enclosingType; } public ISourceLocation makeSourceLocation(IHasPosition location) { return m_sourceContext.makeSourceLocation(location); } } /** * LazyResolvedPointcutDefinition lazyly resolve the pointcut so that we have time to register all * pointcut referenced before pointcut resolution happens * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public static class LazyResolvedPointcutDefinition extends ResolvedPointcutDefinition { private Pointcut m_pointcutUnresolved; private IScope m_binding; private Pointcut m_lazyPointcut = null; public LazyResolvedPointcutDefinition(ResolvedType declaringType, int modifiers, String name, UnresolvedType[] parameterTypes, UnresolvedType returnType, Pointcut pointcut, IScope binding) { super(declaringType, modifiers, name, parameterTypes, returnType, null); m_pointcutUnresolved = pointcut; m_binding = binding; } public Pointcut getPointcut() { if (m_lazyPointcut == null) { m_lazyPointcut = m_pointcutUnresolved.resolve(m_binding); m_lazyPointcut.copyLocationFrom(m_pointcutUnresolved); } return m_lazyPointcut; } } /** * Helper to test empty strings * * @param s * @return true if empty or null */ private static boolean isNullOrEmpty(String s) { return (s == null || s.length() <= 0); } /** * Set the pointcut bindings for which to ignore unbound issues, so that we can implicitly bind * xxxJoinPoint for @AJ advices * * @param pointcut * @param bindings */ private static void setIgnoreUnboundBindingNames(Pointcut pointcut, FormalBinding[] bindings) { // register ImplicitBindings as to be ignored since unbound // TODO is it likely to fail in a bad way if f.e. this(jp) etc ? List ignores = new ArrayList(); for (int i = 0; i < bindings.length; i++) { FormalBinding formalBinding = bindings[i]; if (formalBinding instanceof FormalBinding.ImplicitFormalBinding) { ignores.add(formalBinding.getName()); } } pointcut.m_ignoreUnboundBindingForNames = (String[]) ignores.toArray(new String[ignores.size()]); } /** * A check exception when we cannot read debug info (needed for formal binding) */ private static class UnreadableDebugInfoException extends Exception { } /** * Report an error * * @param message * @param location */ private static void reportError(String message, AjAttributeStruct location) { if (!location.handler.isIgnoring(IMessage.ERROR)) { location.handler.handleMessage( new Message( message, location.enclosingType.getSourceLocation(), true ) ); } } /** * Report a warning * * @param message * @param location */ private static void reportWarning(String message, AjAttributeStruct location) { if (!location.handler.isIgnoring(IMessage.WARNING)) { location.handler.handleMessage( new Message( message, location.enclosingType.getSourceLocation(), false ) ); } } /** * Parse the given pointcut, return null on failure and issue an error * * @param pointcutString * @param struct * @param allowIf * @return pointcut, unresolved */ private static Pointcut parsePointcut(String pointcutString, AjAttributeStruct struct, boolean allowIf) { try { Pointcut pointcut = new PatternParser(pointcutString, struct.context).parsePointcut(); if (!allowIf && pointcutString.indexOf("if()") >= 0 && hasIf(pointcut)) { reportError("if() pointcut is not allowed at this pointcut location '" + pointcutString +"'", struct); return null; } pointcut.setLocation(struct.context, -1, -1);//FIXME -1,-1 is not good enough return pointcut; } catch (ParserException e) { reportError("Invalid pointcut '" + pointcutString + "': " + e.toString(), struct); return null; } } private static boolean hasIf(Pointcut pointcut) { IfFinder visitor = new IfFinder(); pointcut.accept(visitor, null); return visitor.hasIf; } /** * Parse the given type pattern, return null on failure and issue an error * * @param patternString * @param location * @return type pattern */ private static TypePattern parseTypePattern(String patternString, AjAttributeStruct location) { try { TypePattern typePattern = new PatternParser(patternString).parseTypePattern(); typePattern.setLocation(location.context, -1, -1);//FIXME -1,-1 is not good enough return typePattern; } catch (ParserException e) { reportError("Invalid type pattern'" + patternString + "' : " + e.getLocation(), location); return null; } } /** * Look for an if() pointcut */ private static class IfFinder extends IdentityPointcutVisitor { boolean hasIf = false; public Object visit(IfPointcut node, Object data) { if (node.alwaysFalse() || node.alwaysTrue()) { ;//IfFalse / IfTrue } else { hasIf = true; } return node; } public Object visit(AndPointcut node, Object data) { if (!hasIf) node.getLeft().accept(this, data); if (!hasIf) node.getRight().accept(this, data); return node; } public Object visit(NotPointcut node, Object data) { if (!hasIf) node.getNegatedPointcut().accept(this, data); return node; } public Object visit(OrPointcut node, Object data) { if (!hasIf) node.getLeft().accept(this, data); if (!hasIf) node.getRight().accept(this, data); return node; } } static class ThrownFormalNotDeclaredInAdviceSignatureException extends Exception { private String formalName; public ThrownFormalNotDeclaredInAdviceSignatureException(String formalName) { this.formalName = formalName; } public String getFormalName() { return formalName; } } static class ReturningFormalNotDeclaredInAdviceSignatureException extends Exception { private String formalName; public ReturningFormalNotDeclaredInAdviceSignatureException(String formalName) { this.formalName = formalName; } public String getFormalName() { return formalName; } } }
119,882
Bug 119882 BCException when deleting a java-source-file
org.aspectj.weaver.BCException at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1087) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:254) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) BCException thrown: Can't find bcel delegate for training.casino.Konto type=class org.aspectj.weaver.ReferenceType when weaving classes when weaving when incrementally building BuildConfig[C:\Documents and Settings\mheidt\workspace 3.1.1\.metadata\.plugins\org.eclipse.ajdt.core\AspJTraining.generated.lst] #Files=11 deleted a java-source-file before (but not the class-file), possibly pointed by a LogAspect. Created a new source file. Error occurs after saving the new file.
resolved fixed
0b39aa5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-13T10:51:11Z
2005-12-08T16:40:00Z
tests/multiIncremental/PR119882/base/src/pack/C1.java
119,882
Bug 119882 BCException when deleting a java-source-file
org.aspectj.weaver.BCException at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1087) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:254) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) BCException thrown: Can't find bcel delegate for training.casino.Konto type=class org.aspectj.weaver.ReferenceType when weaving classes when weaving when incrementally building BuildConfig[C:\Documents and Settings\mheidt\workspace 3.1.1\.metadata\.plugins\org.eclipse.ajdt.core\AspJTraining.generated.lst] #Files=11 deleted a java-source-file before (but not the class-file), possibly pointed by a LogAspect. Created a new source file. Error occurs after saving the new file.
resolved fixed
0b39aa5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-13T10:51:11Z
2005-12-08T16:40:00Z
tests/multiIncremental/PR119882/base/src/pack/C2.java
119,882
Bug 119882 BCException when deleting a java-source-file
org.aspectj.weaver.BCException at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1087) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:254) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) BCException thrown: Can't find bcel delegate for training.casino.Konto type=class org.aspectj.weaver.ReferenceType when weaving classes when weaving when incrementally building BuildConfig[C:\Documents and Settings\mheidt\workspace 3.1.1\.metadata\.plugins\org.eclipse.ajdt.core\AspJTraining.generated.lst] #Files=11 deleted a java-source-file before (but not the class-file), possibly pointed by a LogAspect. Created a new source file. Error occurs after saving the new file.
resolved fixed
0b39aa5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-13T10:51:11Z
2005-12-08T16:40:00Z
tests/multiIncremental/PR119882/inc1/src/pack/C1.java
119,882
Bug 119882 BCException when deleting a java-source-file
org.aspectj.weaver.BCException at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1087) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:254) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) BCException thrown: Can't find bcel delegate for training.casino.Konto type=class org.aspectj.weaver.ReferenceType when weaving classes when weaving when incrementally building BuildConfig[C:\Documents and Settings\mheidt\workspace 3.1.1\.metadata\.plugins\org.eclipse.ajdt.core\AspJTraining.generated.lst] #Files=11 deleted a java-source-file before (but not the class-file), possibly pointed by a LogAspect. Created a new source file. Error occurs after saving the new file.
resolved fixed
0b39aa5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-13T10:51:11Z
2005-12-08T16:40:00Z
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.systemtest.incremental.tools; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.ajdt.internal.core.builder.AjState; import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.IMessage; import org.aspectj.testing.util.FileUtil; /** * The superclass knows all about talking through Ajde to the compiler. * The superclass isn't in charge of knowing how to simulate overlays * for incremental builds, that is in here. As is the ability to * generate valid build configs based on a directory structure. To * support this we just need access to a sandbox directory - this * sandbox is managed by the superclass (it only assumes all builds occur * in <sandboxDir>/<projectName>/ ) * * The idea is you can initialize multiple projects in the sandbox and * they can all be built independently, hopefully exploiting * incremental compilation. Between builds you can alter the contents * of a project using the alter() method that overlays some set of * new files onto the current set (adding new files/changing existing * ones) - you can then drive a new build and check it behaves as * expected. */ public class MultiProjectIncrementalTests extends AjdeInteractionTestbed { public static boolean VERBOSE = false; protected void setUp() throws Exception { super.setUp(); AjdeInteractionTestbed.VERBOSE = VERBOSE; } // Compile a single simple project public void testTheBasics() { initialiseProject("P1"); build("P1"); // This first build will be batch build("P1"); checkWasntFullBuild(); checkCompileWeaveCount(0,0); } // source code doesnt matter, we are checking invalid path handling public void testInvalidAspectpath_pr121395() { initialiseProject("P1"); File f = new File("foo.jar"); Set s = new HashSet(); s.add(f); configureAspectPath(s); build("P1"); // This first build will be batch checkForError("invalid aspectpath entry"); } // Make simple changes to a project, adding a class public void testSimpleChanges() { initialiseProject("P1"); build("P1"); // This first build will be batch alter("P1","inc1"); // adds a single class build("P1"); checkCompileWeaveCount(1,-1); build("P1"); checkCompileWeaveCount(0,-1); } // Make simple changes to a project, adding a class and an aspect public void testAddingAnAspect() { initialiseProject("P1"); build("P1"); // build 1, weave 1 alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); // build 1, long timeTakenForFullBuildAndWeave = getTimeTakenForBuild(); checkWasFullBuild(); // it *will* be a full build under the new // "back-to-the-source strategy checkCompileWeaveCount(5,3); // we compile X and A (the delta) find out that // an aspect has changed, go back to the source // and compile X,A,C, then weave them all. build("P1"); long timeTakenForSimpleIncBuild = getTimeTakenForBuild(); // I don't think this test will have timing issues as the times should be *RADICALLY* different // On my config, first build time is 2093ms and the second is 30ms assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+ "ms second="+timeTakenForSimpleIncBuild+"ms", timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave); } public void testBuildingTwoProjectsInTurns() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); } /** * In order for this next test to run, I had to move the weaver/world pair we keep in the * AjBuildManager instance down into the state object - this makes perfect sense - otherwise * when reusing the state for another project we'd not be switching to the right weaver/world * for that project. */ public void testBuildingTwoProjectsMakingSmallChanges() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); checkWasFullBuild(); // adding an aspect makes us go back to the source } /** * Setup up two simple projects and build them in turn - check the * structure model is right after each build */ public void testBuildingTwoProjectsAndVerifyingModel() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } // Setup up two simple projects and build them in turn - check the // structure model is right after each build public void testBuildingTwoProjectsAndVerifyingStuff() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, adding a new method and check structural changes is 1. */ public void testStateManagement1() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be a state object for project P1",ajs!=null); assertTrue("Should be no structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc3"); // adds a method to the class C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Should be one structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, changing body of a method, not the structure and * check struc changes is still 0. */ public void testStateManagement2() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making // it a structural change build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be state for project P1",ajs!=null); assertTrue("Should be no struc changes as its a full build: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); } /** * Now the most complex test. Create a dependancy between two projects. Building * one may affect whether the other does an incremental or full build. The * structural information recorded in the state object should be getting used * to control whether a full build is necessary... */ public void testBuildingDependantProjects() { initialiseProject("P1"); initialiseProject("P2"); configureNewProjectDependency("P2","P1"); build("P1"); build("P2"); // now everything is consistent and compiled alter("P1","inc1"); // adds a second class build("P1"); build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :) checkWasntFullBuild(); alter("P1","inc3"); // structurally changes one of the classes build("P1"); build("P2"); // build notices the structural change checkWasFullBuild(); alter("P1","inc4"); build("P1"); build("P2"); // build sees a change but works out its not structural checkWasntFullBuild(); } public void testPr85132() { initialiseProject("PR85132"); build("PR85132"); alter("PR85132","inc1"); build("PR85132"); } // parameterization of generic aspects public void testPr125405() { initialiseProject("PR125405"); build("PR125405"); checkCompileWeaveCount(1,1); alter("PR125405","inc1"); build("PR125405"); // "only abstract aspects can have type parameters" checkForError("only abstract aspects can have type parameters"); alter("PR125405","inc2"); build("PR125405"); checkCompileWeaveCount(2,1); assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0); } public void testPr92837() { initialiseProject("PR92837"); build("PR92837"); alter("PR92837","inc1"); build("PR92837"); } public void testPr119570() { initialiseProject("PR119570"); build("PR119570"); assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0); } public void testPr119570_2() { initialiseProject("PR119570_2"); build("PR119570_2"); List l = MyTaskListManager.getWarningMessages(); assertTrue("Should be no warnings, but got "+l,l.size()==0); } // If you fiddle with the compiler options - you must manually reset the options at the end of the test public void testPr117209() { try { initialiseProject("pr117209"); configureNonStandardCompileOptions("-proceedOnError"); build("pr117209"); checkCompileWeaveCount(6,6); } finally { MyBuildOptionsAdapter.reset(); } } public void testPr114875() { initialiseProject("pr114875"); build("pr114875"); alter("pr114875","inc1"); build("pr114875"); checkWasFullBuild(); alter("pr114875","inc2"); build("pr114875"); checkWasFullBuild(); // back to the source for an aspect change } public void testPr117882() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882"); build("PR117882"); checkWasFullBuild(); alter("PR117882","inc1"); build("PR117882"); checkWasFullBuild(); // back to the source for an aspect // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr117882_2() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882_2"); build("PR117882_2"); checkWasFullBuild(); alter("PR117882_2","inc1"); build("PR117882_2"); checkWasFullBuild(); // back to the source... //checkCompileWeaveCount(1,4); //fullBuild("PR117882_2"); //checkWasFullBuild(); // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr115251() { //AjdeInteractionTestbed.VERBOSE=true; initialiseProject("PR115251"); build("PR115251"); checkWasFullBuild(); alter("PR115251","inc1"); build("PR115251"); checkWasFullBuild(); // back to the source } // public void testPr124399() { // AjdeInteractionTestbed.VERBOSE=true; // configureBuildStructureModel(true); // initialiseProject("PR124399"); // build("PR124399"); // checkWasFullBuild(); // alter("PR124399","inc1"); // build("PR124399"); // checkWasntFullBuild(); // } public void testPr121384() { // AjdeInteractionTestbed.VERBOSE=true; // AsmManager.setReporting("c:/foo.txt",true,true,true,false); MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo"); configureBuildStructureModel(true); initialiseProject("pr121384"); build("pr121384"); checkWasFullBuild(); alter("pr121384","inc1"); build("pr121384"); checkWasntFullBuild(); } /* public void testPr111779() { super.VERBOSE=true; initialiseProject("PR111779"); build("PR111779"); alter("PR111779","inc1"); build("PR111779"); } */ public void testPr93310_1() { initialiseProject("PR93310_1"); build("PR93310_1"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_1","inc1"); build("PR93310_1"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1); String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java")); } public void testPr93310_2() { initialiseProject("PR93310_2"); build("PR93310_2"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_2","inc1"); build("PR93310_2"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1); String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java")); } // Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A. // Stage2: make the field private in class A > gives compile error // Stage3: Add a new aspect whilst there is a compile error ! public void testPr113531() { initialiseProject("PR113531"); build("PR113531"); assertFalse("build should have compiled ok", MyTaskListManager.hasErrorMessages()); alter("PR113531","inc1"); build("PR113531"); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); alter("PR113531","inc2"); build("PR113531"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); } public void testPr112736() { AjdeInteractionTestbed.VERBOSE = true; initialiseProject("PR112736"); build("PR112736"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java"; (new File(fileC2)).delete(); alter("PR112736","inc1"); build("PR112736"); checkWasFullBuild(); } /** * We have problems with multiple rewrites of a pointcut across incremental builds. */ public void testPr113257() { initialiseProject("PR113257"); build("PR113257"); alter("PR113257","inc1"); build("PR113257"); checkWasFullBuild(); // back to the source alter("PR113257","inc1"); build("PR113257"); } public void testPr123612() { initialiseProject("PR123612"); build("PR123612"); alter("PR123612","inc1"); build("PR123612"); checkWasFullBuild(); // back to the source } // other possible tests: // - memory usage (freemem calls?) // - relationship map // --------------------------------------------------------------------------------------------------- /** * Check we compiled/wove the right number of files, passing '-1' indicates you don't care about * that number. */ private void checkCompileWeaveCount(int expCompile,int expWoven) { if (expCompile!=-1 && getCompiledFiles().size()!=expCompile) fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+ "\n"+printCompiledAndWovenFiles()); if (expWoven!=-1 && getWovenClasses().size()!=expWoven) fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+ "\n"+printCompiledAndWovenFiles()); } private void checkWasntFullBuild() { assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild()); } private void checkWasFullBuild() { assertTrue("Should have been a full (batch) build",wasFullBuild()); } private void checkForNode(String packageName,String typeName,boolean shouldBeFound) { IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName); if (shouldBeFound) { if (ipe==null) printModel(); assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null); } else { if (ipe!=null) printModel(); assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null); } } private void printModel() { try { AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0); } catch (IOException e) { e.printStackTrace(); } } public void build(String projectName) { constructUpToDateLstFile(projectName,"build.lst"); build(projectName,"build.lst"); if (AjdeInteractionTestbed.VERBOSE) printBuildReport(); } public void fullBuild(String projectName) { constructUpToDateLstFile(projectName,"build.lst"); fullBuild(projectName,"build.lst"); if (AjdeInteractionTestbed.VERBOSE) printBuildReport(); } private void constructUpToDateLstFile(String pname,String configname) { File projectBase = new File(sandboxDir,pname); File toConstruct = new File(projectBase,configname); List filesForCompilation = new ArrayList(); collectUpFiles(projectBase,projectBase,filesForCompilation); try { FileOutputStream fos = new FileOutputStream(toConstruct); DataOutputStream dos = new DataOutputStream(fos); for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) { String file = (String) iter.next(); dos.writeBytes(file+"\n"); } dos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } public void checkForError(String anError) { List messages = MyTaskListManager.getErrorMessages(); for (Iterator iter = messages.iterator(); iter.hasNext();) { IMessage element = (IMessage) iter.next(); if (element.getMessage().indexOf(anError)!=-1) return; } fail("Didn't find the error message:\n'"+anError+"'.\nErrors that occurred:\n"+MyTaskListManager.getErrorMessages()); } private void collectUpFiles(File location,File base,List collectionPoint) { String contents[] = location.list(); if (contents==null) return; for (int i = 0; i < contents.length; i++) { String string = contents[i]; File f = new File(location,string); if (f.isDirectory()) { collectUpFiles(f,base,collectionPoint); } else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) { String fileFound; try { fileFound = f.getCanonicalPath(); String toRemove = base.getCanonicalPath(); if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove); collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator } catch (IOException e) { e.printStackTrace(); } } } } /** * Fill in the working directory with the project base files, * from the 'base' folder. */ protected void initialiseProject(String p) { File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base"); File destination=new File(getWorkingDir(),p); if (!destination.exists()) {destination.mkdir();} copy(projectSrc,destination);//,false); } /* * Applies an overlay onto the project being tested - copying * the contents of the specified overlay directory. */ private void alter(String projectName,String overlayDirectory) { File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+ File.separatorChar+overlayDirectory); File destination=new File(getWorkingDir(),projectName); copy(projectSrc,destination); } /** * Copy the contents of some directory to another location - the * copy is recursive. */ private void copy(File from, File to) { String contents[] = from.list(); if (contents==null) return; for (int i = 0; i < contents.length; i++) { String string = contents[i]; File f = new File(from,string); File t = new File(to,string); if (f.isDirectory() && !f.getName().startsWith("inc")) { t.mkdir(); copy(f,t); } else if (f.isFile()) { StringBuffer sb = new StringBuffer(); //if (VERBOSE) System.err.println("Copying "+f+" to "+t); FileUtil.copyFile(f,t,sb); if (sb.length()!=0) { System.err.println(sb.toString());} } } } private static void log(String msg) { if (VERBOSE) System.out.println(msg); } }
119,882
Bug 119882 BCException when deleting a java-source-file
org.aspectj.weaver.BCException at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1087) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:254) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) BCException thrown: Can't find bcel delegate for training.casino.Konto type=class org.aspectj.weaver.ReferenceType when weaving classes when weaving when incrementally building BuildConfig[C:\Documents and Settings\mheidt\workspace 3.1.1\.metadata\.plugins\org.eclipse.ajdt.core\AspJTraining.generated.lst] #Files=11 deleted a java-source-file before (but not the class-file), possibly pointed by a LogAspect. Created a new source file. Error occurs after saving the new file.
resolved fixed
0b39aa5
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-13T10:51:11Z
2005-12-08T16:40: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 * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.jar.Attributes.Name; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; 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.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.BindingAnnotationTypePattern; import org.aspectj.weaver.patterns.BindingTypePattern; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.ConcreteCflowPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NameBindingPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.patterns.WithinPointcut; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; public BcelWeaver(BcelWorld world) { super(); WeaverMetrics.reset(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List lateTypeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } /** * Add the given aspect to the weaver. * The type is resolved to support DOT for static inner classes as well as DOLLAR * * @param aspectName * @return aspect */ public ResolvedType addLibraryAspect(String aspectName) { // 1 - resolve as is ResolvedType type = world.resolve(UnresolvedType.forName(aspectName), true); if (type.isMissing()) { // fallback on inner class lookup mechanism String fixedName = aspectName; int hasDot = fixedName.lastIndexOf('.'); while (hasDot > 0) { //System.out.println("BcelWeaver.addLibraryAspect " + fixedName); char[] fixedNameChars = fixedName.toCharArray(); fixedNameChars[hasDot] = '$'; fixedName = new String(fixedNameChars); hasDot = fixedName.lastIndexOf('.'); type = world.resolve(UnresolvedType.forName(fixedName), true); if (!type.isMissing()) { break; } } } //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { // Bug 119657 ensure we use the unwoven aspect WeaverStateInfo wsi = type.getWeaverState(); if (wsi != null && wsi.isReweavable()) { BcelObjectType classType = getClassType(type.getName()); classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes()))); } //TODO AV - happens to reach that a lot of time: for each type flagged reweavable X for each aspect in the weaverstate //=> mainly for nothing for LTW - pbly for something in incremental build... xcutSet.addOrReplaceAspect(type); return type; } else { // FIXME AV - better warning upon no such aspect from aop.xml throw new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName); } } /** * * @param inFile File path to class directory or zip/jar class archive * @throws IOException */ public void addLibraryJarFile(File inFile) throws IOException { List addedAspects = null; if (inFile.isDirectory()) { addedAspects = addAspectsFromDirectory(inFile); } else { addedAspects = addAspectsFromJarFile(inFile); } for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedType aspectX = (ResolvedType) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } // FIXME ASC performance? of this alternative soln. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); return addedAspects; } private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{ List addedAspects = new ArrayList(); File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){ public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }); for (int i = 0; i < classFiles.length; i++) { FileInputStream fis = new FileInputStream(classFiles[i]); byte[] bytes = FileUtil.readAsByteArray(fis); addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects); } return addedAspects; } private void addIfAspect(byte[] bytes, String name, List toList) throws IOException { ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name); JavaClass jc = parser.parse(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { toList.add(type); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarFile inJar = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inJar = new JarFile(inFile); addManifest(inJar.getManifest()); Enumeration entries = inJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); InputStream inStream = inJar.getInputStream(entry); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); // System.out.println("? addJarFile() filename='" + filename + "'"); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.close(); } inJar.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inJar != null) { try {inJar.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(UnresolvedType.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void prepareForWeave() { needToReweaveWorld = false; CflowPointcut.clearCaches(); // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(UnresolvedType.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); rewritePointcuts(shadowMungerList); // Sometimes an error occurs during rewriting pointcuts (for example, if ambiguous bindings // are detected) - we ought to fail the prepare when this happens because continuing with // inconsistent pointcuts could lead to problems typeMungerList = xcutSet.getTypeMungers(); lateTypeMungerList = xcutSet.getLateTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); // The ordering here used to be based on a string compare on toString() for the two mungers - // that breaks for the @AJ style where advice names aren't programmatically generated. So we // have changed the sorting to be based on source location in the file - this is reliable, in // the case of source locations missing, we assume they are 'sorted' - i.e. the order in // which they were added to the collection is correct, this enables the @AJ stuff to work properly. // When @AJ processing starts filling in source locations for mungers, this code may need // a bit of alteration... Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { ShadowMunger sm1 = (ShadowMunger)o1; ShadowMunger sm2 = (ShadowMunger)o2; if (sm1.getSourceLocation()==null) return (sm2.getSourceLocation()==null?0:1); if (sm2.getSourceLocation()==null) return -1; return (sm2.getSourceLocation().getOffset()-sm1.getSourceLocation().getOffset()); } }); } /* * Rewrite all of the pointcuts in the world into their most efficient * form for subsequent matching. Also ensure that if pc1.equals(pc2) * then pc1 == pc2 (for non-binding pcds) by making references all * point to the same instance. * Since pointcuts remember their match decision on the last shadow, * this makes matching faster when many pointcuts share common elements, * or even when one single pointcut has one common element (which can * be a side-effect of DNF rewriting). */ private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) { PointcutRewriter rewriter = new PointcutRewriter(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = rewriter.rewrite(p); // validateBindings now whilst we still have around the pointcut // that resembles what the user actually wrote in their program // text. if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getSignature() != null) { final int numFormals; final String names[]; //ATAJ for @AJ aspect, the formal have to be checked according to the argument number // since xxxJoinPoint presence or not have side effects if (advice.getConcreteAspect().isAnnotationStyleAspect()) { numFormals = advice.getBaseParameterCount(); int numArgs = advice.getSignature().getParameterTypes().length; if (numFormals > 0) { names = advice.getSignature().getParameterNames(world); validateBindings(newP,p,numArgs,names); } } else { numFormals = advice.getBaseParameterCount(); if (numFormals > 0) { names = advice.getBaseParameterNames(world); validateBindings(newP,p,numFormals,names); } } } } munger.setPointcut(newP); } // now that we have optimized individual pointcuts, optimize // across the set of pointcuts.... // Use a map from key based on pc equality, to value based on // pc identity. Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); munger.setPointcut(shareEntriesFromMap(p,pcMap)); } } private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) { // some things cant be shared... if (p instanceof NameBindingPointcut) return p; if (p instanceof IfPointcut) return p; if (p instanceof ConcreteCflowPointcut) return p; if (p instanceof AndPointcut) { AndPointcut apc = (AndPointcut) p; Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap); return new AndPointcut(left,right); } else if (p instanceof OrPointcut) { OrPointcut opc = (OrPointcut) p; Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap); return new OrPointcut(left,right); } else if (p instanceof NotPointcut) { NotPointcut npc = (NotPointcut) p; Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap); return new NotPointcut(not); } else { // primitive pcd if (pcMap.containsKey(p)) { // based on equality return (Pointcut) pcMap.get(p); // same instance (identity) } else { pcMap.put(p,p); return p; } } } // userPointcut is the pointcut that the user wrote in the program text. // dnfPointcut is the same pointcut rewritten in DNF // numFormals is the number of formal parameters in the pointcut // if numFormals > 0 then every branch of a disjunction must bind each formal once and only once. // in addition, the left and right branches of a disjunction must hold on join point kinds in // common. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) { if (numFormals == 0) return; // nothing to check if (dnfPointcut.couldMatchKinds().isEmpty()) return; // cant have problems if you dont match! if (dnfPointcut instanceof OrPointcut) { OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut; Pointcut[] leftBindings = new Pointcut[numFormals]; Pointcut[] rightBindings = new Pointcut[numFormals]; validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings); } else { Pointcut[] bindings = new Pointcut[numFormals]; validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings); } } private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) { Pointcut left = pc.getLeft(); Pointcut right = pc.getRight(); if (left instanceof OrPointcut) { Pointcut[] newRightBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings); } else { if (left.couldMatchKinds().size() > 0) validateSingleBranch(left, userPointcut, numFormals, names, leftBindings); } if (right instanceof OrPointcut) { Pointcut[] newLeftBindings = new Pointcut[numFormals]; validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings); } else { if (right.couldMatchKinds().size() > 0) validateSingleBranch(right, userPointcut, numFormals, names, rightBindings); } Set kindsInCommon = left.couldMatchKinds(); kindsInCommon.retainAll(right.couldMatchKinds()); if (!kindsInCommon.isEmpty() && couldEverMatchSameJoinPoints(left,right)) { // we know that every branch binds every formal, so there is no ambiguity // if each branch binds it in exactly the same way... List ambiguousNames = new ArrayList(); for (int i = 0; i < numFormals; i++) { if (!leftBindings[i].equals(rightBindings[i])) { ambiguousNames.add(names[i]); } } if (!ambiguousNames.isEmpty()) raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames); } } // pc is a pointcut that does not contain any disjunctions // check that every formal is bound (negation doesn't count). // we know that numFormals > 0 or else we would not be called private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) { boolean[] foundFormals = new boolean[numFormals]; for (int i = 0; i < foundFormals.length; i++) { foundFormals[i] = false; } validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings); for (int i = 0; i < foundFormals.length; i++) { if (!foundFormals[i]) { boolean ignore = false; // ATAJ soften the unbound error for implicit bindings like JoinPoint in @AJ style for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) { if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) { ignore = true; break; } } if (!ignore) { raiseUnboundFormalError(names[i],userPointcut); } } } } // each formal must appear exactly once private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) { if (pc instanceof NotPointcut) { // nots can only appear at leaves in DNF NotPointcut not = (NotPointcut) pc; if (not.getNegatedPointcut() instanceof NameBindingPointcut) { NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut(); if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) raiseNegationBindingError(userPointcut); } } else if (pc instanceof AndPointcut) { AndPointcut and = (AndPointcut) pc; validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings); validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings); } else if (pc instanceof NameBindingPointcut) { List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns(); for (Iterator iter = btps.iterator(); iter.hasNext();) { BindingTypePattern btp = (BindingTypePattern) iter.next(); int index = btp.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns(); for (Iterator iter = baps.iterator(); iter.hasNext();) { BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next(); int index = bap.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); for (int i = 0; i < slots.length; i++) { bindings[slots[i]] = cfp; if (foundFormals[slots[i]]) { raiseAmbiguousBindingError(names[slots[i]],userPointcut); } else { foundFormals[slots[i]] = true; } } } } // By returning false from this method, we are allowing binding of the same // variable on either side of an or. // Be conservative :- have to consider overriding, varargs, autoboxing, // the effects of itds (on within for example), interfaces, the fact that // join points can have multiple signatures and so on. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) { if (left instanceof OrPointcut) { OrPointcut leftOrPointcut = (OrPointcut)left; if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(),right)) return true; if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(),right)) return true; return false; } if (right instanceof OrPointcut) { OrPointcut rightOrPointcut = (OrPointcut)right; if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getLeft())) return true; if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getRight())) return true; return false; } // look for withins WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class); WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class); if ((leftWithin != null) && (rightWithin != null)) { if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false; } // look for kinded KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class); KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class); if ((leftKind != null) && (rightKind != null)) { if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false; } return true; } private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) { if (toSearch instanceof NotPointcut) return null; if (toLookFor.isInstance(toSearch)) return toSearch; if (toSearch instanceof AndPointcut) { AndPointcut apc = (AndPointcut) toSearch; Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor); if (left != null) return left; return findFirstPointcutIn(apc.getRight(),toLookFor); } return null; } /** * @param userPointcut */ private void raiseNegationBindingError(Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param userPointcut */ private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) { StringBuffer formalNames = new StringBuffer(names.get(0).toString()); for (int i = 1; i < names.size(); i++) { formalNames.append(", "); formalNames.append(names.get(i)); } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseUnboundFormalError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public boolean isApplyAtAspectJMungersOnly() { return false; } public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, ""); Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); // special case for AtAspectJMungerOnly - see #113587 if (input.isApplyAtAspectJMungersOnly()) { ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, ""); requestor.weavingAspects(); ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType.isAnnotationStyleAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } LazyClassGen clazz = classType.getLazyClassGen(); BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind()); selfMunger.forceMunge(clazz, true); classType.finishedWith(); UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int news = 0; news < newClasses.length; news++) { requestor.acceptResult(newClasses[news]); } wovenClassNames.add(classFile.getClassName()); } } requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly); return wovenClassNames; } requestor.processingReweavableState(); ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE,""); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); // null return from getClassType() means the delegate is an eclipse source type - so // there *cant* be any reweavable state... (he bravely claimed...) if (classType !=null) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className); processReweavableStateIfPresent(className, classType); CompilationAndWeavingContext.leavingPhase(tok); } } CompilationAndWeavingContext.leavingPhase(reweaveToken); ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,""); requestor.addingTypeMungers(); // We process type mungers in two groups, first mungers that change the type // hierarchy, then 'normal' ITD type mungers. // Process the types in a predictable order (rather than the order encountered). // For class A, the order is superclasses of A then superinterfaces of A // (and this mechanism is applied recursively) List typesToProcess = new ArrayList(); for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = (UnwovenClassFile) iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size()>0) { weaveParentsFor(typesToProcess,(String)typesToProcess.get(0)); } for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addNormalTypeMungers(className); } CompilationAndWeavingContext.leavingPhase(typeMungingToken); requestor.weavingAspects(); ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType.isAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { // Sometimes.. if the Bcel Delegate couldn't be found then a problem occurred at compile time - on // a previous compiler run. In this case I assert the delegate will still be an EclipseSourceType // and we can ignore the problem here (the original compile error will be reported again from // the eclipse source type) - pr113531 ReferenceTypeDelegate theDelegate = ((ReferenceType)theType).getDelegate(); if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue; throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(aspectToken); requestor.weavingClasses(); ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, ""); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (!theType.isAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(classToken); addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); warnOnUnmatchedAdvice(); requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(weaveToken); return wovenClassNames; } /** * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any * mungers that did not match anything. */ private void warnOnUnmatchedAdvice() { class AdviceLocation { private int lineNo; private UnresolvedType inAspect; public AdviceLocation(BcelAdvice advice) { this.lineNo = advice.getSourceLocation().getLine(); this.inAspect = advice.getDeclaringAspect(); } public boolean equals(Object obj) { if (!(obj instanceof AdviceLocation)) return false; AdviceLocation other = (AdviceLocation) obj; if (this.lineNo != other.lineNo) return false; if (!this.inAspect.equals(other.inAspect)) return false; return true; } public int hashCode() { return 37 + 17*lineNo + 17*inAspect.hashCode(); }; } // FIXME asc Should be factored out into Xlint code and done automatically for all xlint messages, ideally. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) { List l = world.getCrosscuttingMembersSet().getShadowMungers(); Set alreadyWarnedLocations = new HashSet(); for (Iterator iter = l.iterator(); iter.hasNext();) { ShadowMunger element = (ShadowMunger) iter.next(); if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers BcelAdvice ba = (BcelAdvice)element; if (!ba.hasMatchedSomething()) { // Because we implement some features of AJ itself by creating our own kind of mungers, you sometimes // find that ba.getSignature() is not a BcelMethod - for example it might be a cflow entry munger. if (ba.getSignature()!=null) { // check we haven't already warned on this advice and line // (cflow creates multiple mungers for the same advice) AdviceLocation loc = new AdviceLocation(ba); if (alreadyWarnedLocations.contains(loc)) { continue; } else { alreadyWarnedLocations.add(loc); } if (!(ba.getSignature() instanceof BcelMethod) || !Utility.isSuppressing((AnnotationX[])ba.getSignature().getAnnotations(),"adviceDidNotMatch")) { world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(),element.getSourceLocation()); } } } } } } } /** * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process * supertypes (classes/interfaces) of 'typeToWeave' that are in the * 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from * the 'typesForWeaving' list. * * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may * break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it * may choose to weave them in either order - but you'll probably have other problems if * you are supplying partial hierarchies like that ! */ private void weaveParentsFor(List typesForWeaving,String typeToWeave) { // Look at the supertype first ResolvedType rtx = world.resolve(typeToWeave); ResolvedType superType = rtx.getSuperclass(); if (superType!=null && typesForWeaving.contains(superType.getName())) { weaveParentsFor(typesForWeaving,superType.getName()); } // Then look at the superinterface list ResolvedType[] interfaceTypes = rtx.getDeclaredInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ResolvedType rtxI = interfaceTypes[i]; if (typesForWeaving.contains(rtxI.getName())) { weaveParentsFor(typesForWeaving,rtxI.getName()); } } ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,rtx.getName()); weaveParentTypeMungers(rtx); // Now do this type CompilationAndWeavingContext.leavingPhase(tok); typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process } public void prepareToProcessReweavableState() { if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()), null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { // keep track of them just to ensure unique missing aspect error reporting Set alreadyConfirmedReweavableState = new HashSet(); for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedType rtx = world.resolve(UnresolvedType.forName(requiredTypeName),true); boolean exists = !rtx.isMissing(); if (!exists) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className), classType.getSourceLocation(), null); } else { // weaved in aspect that are not declared in aop.xml trigger an error for now // may cause headhache for LTW and packaged lib without aop.xml in // see #104218 if(!xcutSet.containsAspect(rtx)){ world.showMessage( IMessage.ERROR, WeaverMessages.format( WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED, requiredTypeName, className ), null, 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); } } } } // old: //classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); // new: reweavable default with clever diff classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes()))); } else { classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType.getResolvedTypeX().getName()); LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } CompilationAndWeavingContext.leavingPhase(tok); } /** helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType */ public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addParentTypeMungers(String typeName) { weaveParentTypeMungers(world.resolve(typeName)); } public void addNormalTypeMungers(String typeName) { weaveNormalTypeMungers(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClassBytesIncludingReweavable(world)); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } /** * Weaves new parents and annotations onto a type ("declare parents" and "declare @type") * * Algorithm: * 1. First pass, do parents then do annotations. During this pass record: * - any parent mungers that don't match but have a non-wild annotation type pattern * - any annotation mungers that don't match * 2. Multiple subsequent passes which go over the munger lists constructed in the first * pass, repeatedly applying them until nothing changes. * FIXME asc confirm that algorithm is optimal ?? */ public void weaveParentTypeMungers(ResolvedType onType) { if (onType.isRawType()) onType = onType.getGenericType(); onType.clearInterTypeMungers(); List decpToRepeat = new ArrayList(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents decp = (DeclareParents)i.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { // Perhaps it would have matched if a 'dec @type' had modified the type if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation)i.next(); boolean typeChanged = applyDeclareAtType(decA,onType,true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List decpToRepeatNextTime = new ArrayList(); for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = (DeclareParents) iter.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA,onType,false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType,boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) { // Could put out a lint here for an already annotated type ... // 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) { AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation()); // TAG: WeavingMessage if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()), decA.getAnnotationString(), "type", decA.getAspect().toString(), Utility.beautifyLocation(decA.getSourceLocation()) })); } didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation * to be attached to the target type that matched. */ private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationX annoX,boolean outputProblems) { boolean problemReported = false; if (annoX.specifiesTarget()) { if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { if (outputProblems) { if (decA.isExactPattern()) { world.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation())); } else { if (world.getLint().invalidTargetForAnnotation.isEnabled()) { world.getLint().invalidTargetForAnnotation.signal( new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()}); } } } problemReported = true; } } return problemReported; } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType,true); if (!newParents.isEmpty()) { didSomething=true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedType newParent = (ResolvedType)j.next(); // We set it here so that the imminent matching for ITDs can succeed - we // still haven't done the necessary changes to the class file itself // (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent() classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } return didSomething; } public void weaveNormalTypeMungers(ResolvedType onType) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, onType.getName()); if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (!m.isLateMunger() && m.matches(onType)) { onType.addInterTypeMunger(m); } } CompilationAndWeavingContext.leavingPhase(tok); } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { // Don't touch synthetic classes if (dump) dumpUnchanged(classFile); return null; } List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); // Decide if we need to do actual weaving for this class boolean mightNeedToWeave = shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() || world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0; // May need bridge methods if on 1.5 and something in our hierarchy is affected by ITDs boolean mightNeedBridgeMethods = world.isInJava5Mode() && !classType.isInterface() && classType.getResolvedTypeX().getInterTypeMungersIncludingSupers().size()>0; LazyClassGen clazz = null; if (mightNeedToWeave || mightNeedBridgeMethods) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = false; if (mightNeedToWeave) isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList); if (mightNeedBridgeMethods) isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world,clazz) || isChanged; if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { String messageText = "trouble in: \n" + clazz.toLongString(); getWorld().getMessageHandler().handleMessage( new Message(messageText,IMessage.ABORT,re,null) ); } catch (Error re) { String messageText = "trouble in: \n" + clazz.toLongString(); getWorld().getMessageHandler().handleMessage( new Message(messageText,IMessage.ABORT,re,null) ); } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { // ATAJ: the class was not weaved, but since it gets there early it may have new generated inner classes // attached to it to support LTW perX aspectOf support (see BcelPerClauseAspectAdder) // that aggressively defines the inner <aspect>$mayHaveAspect interface. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) { return clazz; } return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedType type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info if (fb.maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean xNotReweavable) { inReweavableMode = !xNotReweavable; WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable,false,true); BcelClassWeaver.setReweavableMode(!xNotReweavable); } public boolean isReweavable() { return inReweavableMode; } public World getWorld() { return world; } }
121,616
Bug 121616 [@AspectJ]Lacking import for JoinPoint crahes the compiler
null
resolved fixed
d4219e1
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-16T09:33:38Z
2005-12-20T20:20:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java
/* ******************************************************************* * Copyright (c) 2005 IBM Corporation Ltd * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.lang.reflect.Modifier; import java.util.Stack; import java.util.ArrayList; import java.util.List; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope; import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.aspectj.weaver.AdviceKind; import org.aspectj.weaver.AjAttribute; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.patterns.AbstractPatternNodeVisitor; import org.aspectj.weaver.patterns.FormalBinding; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.ParserException; import org.aspectj.weaver.patterns.PatternParser; import org.aspectj.weaver.patterns.Pointcut; public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { private static final char[] beforeAdviceSig = "Lorg/aspectj/lang/annotation/Before;".toCharArray(); private static final char[] afterAdviceSig = "Lorg/aspectj/lang/annotation/After;".toCharArray(); private static final char[] afterReturningAdviceSig = "Lorg/aspectj/lang/annotation/AfterReturning;".toCharArray(); private static final char[] afterThrowingAdviceSig = "Lorg/aspectj/lang/annotation/AfterThrowing;".toCharArray(); private static final char[] aroundAdviceSig = "Lorg/aspectj/lang/annotation/Around;".toCharArray(); private static final char[] pointcutSig = "Lorg/aspectj/lang/annotation/Pointcut;".toCharArray(); private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray(); private static final char[] adviceNameSig = "Lorg/aspectj/lang/annotation/AdviceName;".toCharArray(); private static final char[] orgAspectJLangAnnotation = "org/aspectj/lang/annotation/".toCharArray(); private static final char[] voidType = "void".toCharArray(); private static final char[] booleanType = "boolean".toCharArray(); private static final char[] joinPoint = "Lorg/aspectj/lang/JoinPoint;".toCharArray(); private static final char[] joinPointStaticPart = "Lorg/aspectj/lang/JoinPoint$StaticPart;".toCharArray(); private static final char[] joinPointEnclosingStaticPart = "Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".toCharArray(); private static final char[] proceedingJoinPoint = "Lorg/aspectj/lang/ProceedingJoinPoint;".toCharArray(); private static final char[][] adviceSigs = new char[][] {beforeAdviceSig,afterAdviceSig,afterReturningAdviceSig,afterThrowingAdviceSig,aroundAdviceSig}; private CompilationUnitDeclaration unit; private Stack typeStack = new Stack(); private AspectJAnnotations ajAnnotations; public ValidateAtAspectJAnnotationsVisitor(CompilationUnitDeclaration unit) { this.unit = unit; } public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) { typeStack.push(localTypeDeclaration); ajAnnotations = new AspectJAnnotations(localTypeDeclaration.annotations); checkTypeDeclaration(localTypeDeclaration); return true; } public void endVisit(TypeDeclaration localTypeDeclaration,BlockScope scope) { typeStack.pop(); } public boolean visit(TypeDeclaration memberTypeDeclaration,ClassScope scope) { typeStack.push(memberTypeDeclaration); ajAnnotations = new AspectJAnnotations(memberTypeDeclaration.annotations); checkTypeDeclaration(memberTypeDeclaration); return true; } public void endVisit(TypeDeclaration memberTypeDeclaration,ClassScope scope) { typeStack.pop(); } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { typeStack.push(typeDeclaration); ajAnnotations = new AspectJAnnotations(typeDeclaration.annotations); checkTypeDeclaration(typeDeclaration); return true; } public void endVisit(TypeDeclaration typeDeclaration,CompilationUnitScope scope) { typeStack.pop(); } private void checkTypeDeclaration(TypeDeclaration typeDecl) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, typeDecl.name); if (!(typeDecl instanceof AspectDeclaration)) { if (ajAnnotations.hasAspectAnnotation) { validateAspectDeclaration(typeDecl); } else { // check that class doesn't extend aspect TypeReference parentRef = typeDecl.superclass; if (parentRef != null) { TypeBinding parentBinding = parentRef.resolvedType; if (parentBinding instanceof SourceTypeBinding) { SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding; if (parentSTB.scope != null) { TypeDeclaration parentDecl = parentSTB.scope.referenceContext; if (isAspect(parentDecl)) { typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"a class cannot extend an aspect"); } } } } } } else { // check that aspect doesn't have @Aspect annotation, we've already added on ourselves. if (ajAnnotations.hasMultipleAspectAnnotations) { typeDecl.scope.problemReporter().signalError( typeDecl.sourceStart, typeDecl.sourceEnd, "aspects cannot have @Aspect annotation" ); } } CompilationAndWeavingContext.leavingPhase(tok); } public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, methodDeclaration.selector); ajAnnotations = new AspectJAnnotations(methodDeclaration.annotations); if (!methodDeclaration.getClass().equals(AjMethodDeclaration.class)) { // simply test for innapropriate use of annotations on code-style members if (methodDeclaration instanceof PointcutDeclaration) { if (ajAnnotations.hasMultiplePointcutAnnotations || ajAnnotations.hasAdviceAnnotation || ajAnnotations.hasAspectAnnotation || ajAnnotations.hasAdviceNameAnnotation) { methodDeclaration.scope.problemReporter().signalError( methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "@AspectJ annotations cannot be declared on this aspect member"); } } else if (methodDeclaration instanceof AdviceDeclaration) { if (ajAnnotations.hasMultipleAdviceAnnotations || ajAnnotations.hasAspectAnnotation || ajAnnotations.hasPointcutAnnotation) { methodDeclaration.scope.problemReporter().signalError( methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "Only @AdviceName AspectJ annotation allowed on advice"); } } else { if (ajAnnotations.hasAspectJAnnotations()) { methodDeclaration.scope.problemReporter().signalError( methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "@AspectJ annotations cannot be declared on this aspect member"); } } CompilationAndWeavingContext.leavingPhase(tok); return false; } if (ajAnnotations.hasAdviceAnnotation) { validateAdvice(methodDeclaration); } else if (ajAnnotations.hasPointcutAnnotation) { convertToPointcutDeclaration(methodDeclaration,scope); } CompilationAndWeavingContext.leavingPhase(tok); return false; } private boolean isAspectJAnnotation(Annotation ann) { if (ann.resolvedType == null) return false; char[] sig = ann.resolvedType.signature(); return CharOperation.contains(orgAspectJLangAnnotation, sig); } private boolean insideAspect() { if (typeStack.empty()) return false; TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek(); return isAspect(typeDecl); } private boolean isAspect(TypeDeclaration typeDecl) { if (typeDecl instanceof AspectDeclaration) return true; return new AspectJAnnotations(typeDecl.annotations).hasAspectAnnotation; } /** * aspect must be public * nested aspect must be static * cannot extend a concrete aspect * pointcut in perclause must be good. */ private void validateAspectDeclaration(TypeDeclaration typeDecl) { if (typeStack.size() > 1) { // it's a nested aspect if (!Modifier.isStatic(typeDecl.modifiers)) { typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, "inner aspects must be static"); return; } } SourceTypeBinding binding = typeDecl.binding; if (binding != null) { if (binding.isEnum() || binding.isInterface() || binding.isAnnotationType()) { typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"only classes can have an @Aspect annotation"); } } //FIXME AV - do we really want that // if (!Modifier.isPublic(typeDecl.modifiers)) { // typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"@Aspect class must be public"); // } TypeReference parentRef = typeDecl.superclass; if (parentRef != null) { TypeBinding parentBinding = parentRef.resolvedType; if (parentBinding instanceof SourceTypeBinding) { SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding; if (parentSTB.scope!=null) { // scope is null if its a binarytypebinding (in AJ world, thats a subclass of SourceTypeBinding) TypeDeclaration parentDecl = parentSTB.scope.referenceContext; if (isAspect(parentDecl) && !Modifier.isAbstract(parentDecl.modifiers)) { typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"cannot extend a concrete aspect"); } } } } Annotation aspectAnnotation = ajAnnotations.aspectAnnotation; int[] pcLoc = new int[2]; String perClause = getStringLiteralFor("value", aspectAnnotation, pcLoc); AspectDeclaration aspectDecl = new AspectDeclaration(typeDecl.compilationResult); try { if (perClause != null && !perClause.equals("")) { ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLoc[0]); Pointcut pc = new PatternParser(perClause,context).maybeParsePerClause(); FormalBinding[] bindings = new FormalBinding[0]; if (pc != null) pc.resolve(new EclipseScope(bindings,typeDecl.scope)); } } catch(ParserException pEx) { typeDecl.scope.problemReporter().parseError( pcLoc[0] + pEx.getLocation().getStart(), pcLoc[0] + pEx.getLocation().getEnd() , -1, perClause.toCharArray(), perClause, new String[] {pEx.getMessage()}); } } /** * 1) Advice must be public * 2) Advice must have a void return type if not around advice * 3) Advice must not have any other @AspectJ annotations * 4) After throwing advice must declare the thrown formal * 5) After returning advice must declare the returning formal */ private void validateAdvice(MethodDeclaration methodDeclaration) { if (!insideAspect()) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart, methodDeclaration.sourceEnd, "Advice must be declared inside an aspect type"); } if (!Modifier.isPublic(methodDeclaration.modifiers)) { methodDeclaration.scope.problemReporter() .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"advice must be public"); } if (ajAnnotations.hasMultipleAdviceAnnotations) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.duplicateAdviceAnnotation); } if (ajAnnotations.hasPointcutAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.pointcutAnnotation); } if (ajAnnotations.hasAspectAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation); } if (ajAnnotations.hasAdviceNameAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation); } if (ajAnnotations.adviceKind != AdviceKind.Around) { ensureVoidReturnType(methodDeclaration); } if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) { int[] throwingLocation = new int[2]; String thrownFormal = getStringLiteralFor("throwing",ajAnnotations.adviceAnnotation,throwingLocation); if (thrownFormal != null) { Argument[] arguments = methodDeclaration.arguments; if (!toArgumentNames(methodDeclaration.arguments).contains(thrownFormal)) { methodDeclaration.scope.problemReporter() .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"throwing formal '" + thrownFormal + "' must be declared as a parameter in the advice signature"); } } } if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) { int[] throwingLocation = new int[2]; String returningFormal = getStringLiteralFor("returning",ajAnnotations.adviceAnnotation,throwingLocation); if (returningFormal != null) { if (!toArgumentNames(methodDeclaration.arguments).contains(returningFormal)) { methodDeclaration.scope.problemReporter() .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"returning formal '" + returningFormal + "' must be declared as a parameter in the advice signature"); } } } resolveAndSetPointcut(methodDeclaration, ajAnnotations.adviceAnnotation); } /** * Get the argument names as a string list * @param arguments * @return argument names (possibly empty) */ private List toArgumentNames(Argument[] arguments) { List names = new ArrayList(); if (arguments == null) { return names; } else { for (int i = 0; i < arguments.length; i++) { names.add(new String(arguments[i].name)); } return names; } } private void resolveAndSetPointcut(MethodDeclaration methodDeclaration, Annotation adviceAnn) { int[] pcLocation = new int[2]; String pointcutExpression = getStringLiteralFor("pointcut",adviceAnn,pcLocation); if (pointcutExpression == null) pointcutExpression = getStringLiteralFor("value",adviceAnn,pcLocation); try { ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLocation[0]); Pointcut pc = new PatternParser(pointcutExpression,context).parsePointcut(); FormalBinding[] bindings = buildFormalAdviceBindingsFrom(methodDeclaration); pc.resolve(new EclipseScope(bindings,methodDeclaration.scope)); EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(methodDeclaration.scope); // now create a ResolvedPointcutDefinition,make an attribute out of it, and add it to the method UnresolvedType[] paramTypes = new UnresolvedType[bindings.length]; for (int i = 0; i < paramTypes.length; i++) paramTypes[i] = bindings[i].getType(); ResolvedPointcutDefinition resPcutDef = new ResolvedPointcutDefinition( factory.fromBinding(((TypeDeclaration)typeStack.peek()).binding), methodDeclaration.modifiers, "anonymous", paramTypes, pc ); AjAttribute attr = new AjAttribute.PointcutDeclarationAttribute(resPcutDef); ((AjMethodDeclaration)methodDeclaration).addAttribute(new EclipseAttributeAdapter(attr)); } catch(ParserException pEx) { methodDeclaration.scope.problemReporter().parseError( pcLocation[0] + pEx.getLocation().getStart(), pcLocation[0] + pEx.getLocation().getEnd() , -1, pointcutExpression.toCharArray(), pointcutExpression, new String[] {pEx.getMessage()}); } } private void ensureVoidReturnType(MethodDeclaration methodDeclaration) { boolean returnsVoid = true; if ((methodDeclaration.returnType instanceof SingleTypeReference)) { SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType; if (!CharOperation.equals(voidType,retType.token)) { returnsVoid = false; } } else { returnsVoid = false; } if (!returnsVoid) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "This advice must return void"); } } private FormalBinding[] buildFormalAdviceBindingsFrom(MethodDeclaration mDecl) { if (mDecl.arguments == null) return new FormalBinding[0]; EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(mDecl.scope); String extraArgName = maybeGetExtraArgName(); if (extraArgName == null) extraArgName = ""; FormalBinding[] ret = new FormalBinding[mDecl.arguments.length]; for (int i = 0; i < mDecl.arguments.length; i++) { Argument arg = mDecl.arguments[i]; String name = new String(arg.name); TypeBinding argTypeBinding = mDecl.binding.parameters[i]; UnresolvedType type = factory.fromBinding(argTypeBinding); if (CharOperation.equals(joinPoint,argTypeBinding.signature()) || CharOperation.equals(joinPointStaticPart,argTypeBinding.signature()) || CharOperation.equals(joinPointEnclosingStaticPart,argTypeBinding.signature()) || CharOperation.equals(proceedingJoinPoint,argTypeBinding.signature()) || name.equals(extraArgName)) { ret[i] = new FormalBinding.ImplicitFormalBinding(type,name,i); } else { ret[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown"); } } return ret; } private String maybeGetExtraArgName() { String argName = null; if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) { argName = getStringLiteralFor("returning",ajAnnotations.adviceAnnotation,new int[2]); } else if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) { argName = getStringLiteralFor("throwing",ajAnnotations.adviceAnnotation,new int[2]); } return argName; } private String getStringLiteralFor(String memberName, Annotation inAnnotation, int[] location) { if (inAnnotation instanceof SingleMemberAnnotation && memberName.equals("value")) { SingleMemberAnnotation sma = (SingleMemberAnnotation) inAnnotation; if (sma.memberValue instanceof StringLiteral) { StringLiteral sv = (StringLiteral) sma.memberValue; location[0] = sv.sourceStart; location[1] = sv.sourceEnd; return new String(sv.source()); } } if (! (inAnnotation instanceof NormalAnnotation)) return null; NormalAnnotation ann = (NormalAnnotation) inAnnotation; MemberValuePair[] mvps = ann.memberValuePairs; if (mvps == null) return null; for (int i = 0; i < mvps.length; i++) { if (CharOperation.equals(memberName.toCharArray(),mvps[i].name)) { if (mvps[i].value instanceof StringLiteral) { StringLiteral sv = (StringLiteral) mvps[i].value; location[0] = sv.sourceStart; location[1] = sv.sourceEnd; return new String(sv.source()); } } } return null; } private void convertToPointcutDeclaration(MethodDeclaration methodDeclaration, ClassScope scope) { TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek(); if (typeDecl.binding != null) { if (!typeDecl.binding.isClass()) { methodDeclaration.scope.problemReporter() .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"pointcuts can only be declared in a class or an aspect"); } } if (methodDeclaration.thrownExceptions != null && methodDeclaration.thrownExceptions.length > 0) { methodDeclaration.scope.problemReporter() .signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"pointcuts cannot throw exceptions!"); } PointcutDeclaration pcDecl = new PointcutDeclaration(unit.compilationResult); copyAllFields(methodDeclaration,pcDecl); if (ajAnnotations.hasAdviceAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceAnnotation); } if (ajAnnotations.hasAspectAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation); } if (ajAnnotations.hasAdviceNameAnnotation) { methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation); } boolean noValueSupplied=true; boolean containsIfPcd = false; int[] pcLocation = new int[2]; String pointcutExpression = getStringLiteralFor("value",ajAnnotations.pointcutAnnotation,pcLocation); try { ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLocation[0]); Pointcut pc = null;//abstract if (pointcutExpression == null || pointcutExpression.length() == 0) { noValueSupplied=true; // matches nothing pointcut } else { noValueSupplied=false; pc = new PatternParser(pointcutExpression,context).parsePointcut(); } pcDecl.pointcutDesignator = (pc==null)?null:new PointcutDesignator(pc); pcDecl.setGenerateSyntheticPointcutMethod(); TypeDeclaration onType = (TypeDeclaration) typeStack.peek(); pcDecl.postParse(onType); // EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(methodDeclaration.scope); // int argsLength = methodDeclaration.arguments == null ? 0 : methodDeclaration.arguments.length; FormalBinding[] bindings = buildFormalAdviceBindingsFrom(methodDeclaration); // FormalBinding[] bindings = new FormalBinding[argsLength]; // for (int i = 0, len = bindings.length; i < len; i++) { // Argument arg = methodDeclaration.arguments[i]; // String name = new String(arg.name); // UnresolvedType type = factory.fromBinding(methodDeclaration.binding.parameters[i]); // bindings[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown"); // } swap(onType,methodDeclaration,pcDecl); if (pc != null) { // has an expression pc.resolve(new EclipseScope(bindings,methodDeclaration.scope)); HasIfPCDVisitor ifFinder = new HasIfPCDVisitor(); pc.traverse(ifFinder, null); containsIfPcd = ifFinder.containsIfPcd; } } catch(ParserException pEx) { methodDeclaration.scope.problemReporter().parseError( pcLocation[0] + pEx.getLocation().getStart(), pcLocation[0] + pEx.getLocation().getEnd() , -1, pointcutExpression.toCharArray(), pointcutExpression, new String[] {pEx.getMessage()}); } boolean returnsVoid = false; boolean returnsBoolean = false; if ((methodDeclaration.returnType instanceof SingleTypeReference)) { SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType; if (CharOperation.equals(voidType,retType.token)) returnsVoid = true; if (CharOperation.equals(booleanType,retType.token)) returnsBoolean = true; } if (!returnsVoid && !containsIfPcd) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "Methods annotated with @Pointcut must return void unless the pointcut contains an if() expression"); } if (!returnsBoolean && containsIfPcd) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "Methods annotated with @Pointcut must return boolean when the pointcut contains an if() expression"); } if (methodDeclaration.statements != null && methodDeclaration.statements.length > 0 && !containsIfPcd) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "Pointcuts without an if() expression should have an empty method body"); } if (pcDecl.pointcutDesignator == null) { if (Modifier.isAbstract(methodDeclaration.modifiers) || noValueSupplied // this is a matches nothing pointcut //those 2 checks makes sense for aop.xml concretization but NOT for regular abstraction of pointcut //&& returnsVoid //&& (methodDeclaration.arguments == null || methodDeclaration.arguments.length == 0)) { ) { ;//fine } else { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "Method annotated with @Pointcut() for abstract pointcut must be abstract"); } } else if (Modifier.isAbstract(methodDeclaration.modifiers)) { methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart, methodDeclaration.returnType.sourceEnd, "Method annotated with non abstract @Pointcut(\""+pointcutExpression+"\") is abstract"); } } private void copyAllFields(MethodDeclaration from, MethodDeclaration to) { to.annotations = from.annotations; to.arguments = from.arguments; to.binding = from.binding; to.bits = from.bits; to.bodyEnd = from.bodyEnd; to.bodyStart = from.bodyStart; to.declarationSourceEnd = from.declarationSourceEnd; to.declarationSourceStart = from.declarationSourceStart; to.errorInSignature = from.errorInSignature; to.explicitDeclarations = from.explicitDeclarations; to.ignoreFurtherInvestigation = from.ignoreFurtherInvestigation; to.javadoc = from.javadoc; to.modifiers = from.modifiers; to.modifiersSourceStart = from.modifiersSourceStart; to.needFreeReturn = from.needFreeReturn; to.returnType = from.returnType; to.scope = from.scope; to.selector = from.selector; to.sourceEnd = from.sourceEnd; to.sourceStart = from.sourceStart; to.statements = from.statements; to.thrownExceptions = from.thrownExceptions; to.typeParameters = from.typeParameters; } private void swap(TypeDeclaration inType, MethodDeclaration thisDeclaration, MethodDeclaration forThatDeclaration) { for (int i = 0; i < inType.methods.length; i++) { if (inType.methods[i] == thisDeclaration) { inType.methods[i] = forThatDeclaration; break; } } } private static class AspectJAnnotations { boolean hasAdviceAnnotation = false; boolean hasPointcutAnnotation = false; boolean hasAspectAnnotation = false; boolean hasAdviceNameAnnotation = false; boolean hasMultipleAdviceAnnotations = false; boolean hasMultiplePointcutAnnotations = false; boolean hasMultipleAspectAnnotations = false; AdviceKind adviceKind = null; Annotation adviceAnnotation = null; Annotation pointcutAnnotation = null; Annotation aspectAnnotation = null; Annotation adviceNameAnnotation = null; Annotation duplicateAdviceAnnotation = null; Annotation duplicatePointcutAnnotation = null; Annotation duplicateAspectAnnotation = null; public AspectJAnnotations(Annotation[] annotations) { if (annotations == null) return; for (int i = 0; i < annotations.length; i++) { if (annotations[i].resolvedType == null) continue; // user messed up annotation declaration char[] sig = annotations[i].resolvedType.signature(); if (CharOperation.equals(afterAdviceSig,sig)) { adviceKind = AdviceKind.After; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(afterReturningAdviceSig,sig)) { adviceKind = AdviceKind.AfterReturning; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(afterThrowingAdviceSig,sig)) { adviceKind = AdviceKind.AfterThrowing; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(beforeAdviceSig,sig)) { adviceKind = AdviceKind.Before; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(aroundAdviceSig,sig)) { adviceKind = AdviceKind.Around; addAdviceAnnotation(annotations[i]); } else if (CharOperation.equals(adviceNameSig,sig)) { hasAdviceNameAnnotation = true; adviceNameAnnotation = annotations[i]; } else if (CharOperation.equals(aspectSig,sig)) { if (hasAspectAnnotation) { hasMultipleAspectAnnotations = true; duplicateAspectAnnotation = annotations[i]; } else { hasAspectAnnotation = true; aspectAnnotation = annotations[i]; } } else if (CharOperation.equals(pointcutSig,sig)) { if (hasPointcutAnnotation) { hasMultiplePointcutAnnotations = true; duplicatePointcutAnnotation = annotations[i]; } else { hasPointcutAnnotation = true; pointcutAnnotation = annotations[i]; } } } } public boolean hasAspectJAnnotations() { return hasAdviceAnnotation || hasPointcutAnnotation || hasAdviceNameAnnotation || hasAspectAnnotation; } private void addAdviceAnnotation(Annotation annotation) { if (!hasAdviceAnnotation) { hasAdviceAnnotation = true; adviceAnnotation = annotation; } else { hasMultipleAdviceAnnotations = true; duplicateAdviceAnnotation = annotation; } } } private static class HasIfPCDVisitor extends AbstractPatternNodeVisitor { public boolean containsIfPcd = false; public Object visit(IfPointcut node, Object data) { containsIfPcd = true; return data; } } }
121,616
Bug 121616 [@AspectJ]Lacking import for JoinPoint crahes the compiler
null
resolved fixed
d4219e1
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-16T09:33:38Z
2005-12-20T20:20:00Z
tests/bugs151/pr121616.java
121,616
Bug 121616 [@AspectJ]Lacking import for JoinPoint crahes the compiler
null
resolved fixed
d4219e1
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-16T09:33:38Z
2005-12-20T20:20:00Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import java.util.List; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.Relationship; import org.aspectj.systemtest.ajc150.GenericsTests; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");} public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");} public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");} public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");} public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");} //public void testExposingWithintype_enh123423() { runTest("exposing withintype");} //public void testMissingImport_pr127299() { runTest("missing import gives funny message");} public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");} public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); } public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); } public void testMixingNumbersOfTypeParameters_pr125080() { runTest("mixing numbers of type parameters"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;"); } public void testMixingNumbersOfTypeParameters_pr125080_2() { runTest("mixing numbers of type parameters - 2"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;"); } public void testIProgramElementMethods_pr125295() { runTest("new IProgramElement methods"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForType("pkg","foo"); assertNotNull("Couldn't find 'foo' element in the tree",pe); // check that the defaults return the fully qualified arg assertEquals("foo(int, java.lang.Object)",pe.toLabelString()); assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString()); assertEquals("foo(int, java.lang.Object)",pe.toSignatureString()); // check that can get hold of the non qualified args assertEquals("foo(int, Object)",pe.toLabelString(false)); assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false)); assertEquals("foo(int, Object)",pe.toSignatureString(false)); IProgramElement pe2 = top.findElementForType("pkg","printParameters"); assertNotNull("Couldn't find 'printParameters' element in the tree",pe2); // the argument is org.aspectj.lang.JoinPoint, check that this is added assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty()); } public void testParameterizedEnum_pr126316() { runTest("E extends Enum(E) again"); } public void testSwallowedException() { runTest("swallowed exceptions"); } public void testSwallowedExceptionIgnored() { runTest("swallowed exceptions with xlint"); } /* * @AspectJ bugs and enhancements */ // public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { // runTest("inherit adivce with this() and thisJoinPoint"); // } public void testAtAspectInheritsAbstractPointcut_pr125810 () { runTest("warning when inherited pointcut not made concrete"); } public void testAtAspectDEOWInStructureModel_pr120356() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("@AJ deow appear correctly when structure model is generated"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // get the IProgramElements corresponding to the @DeclareWarning statement // and the method it matches. IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"warningMethod()"); assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE); IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"warning"); assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE); // check that the method has a matches declare relationship with @DeclareWarning List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE); assertNotNull("warningMethod should have some relationships but does not",matches); assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1); List matchesTargets = ((Relationship)matches.get(0)).getTargets(); assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0)); assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label " + target.toLabelString(),atDeclareWarningIPE,target); // check that the @DeclareWarning has a matches relationship with the warningMethod List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE); assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy); assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1); List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets(); assertTrue("@DeclareWarning 'matched by' relationship should have one target " + "but has " + matchedByTargets.size(), matchedByTargets.size() == 1); IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0)); assertEquals("target of relationship should be the warningMethod but is IPE with label " + matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget); // get the IProgramElements corresponding to the @DeclareError statement // and the method it matches. IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"badMethod()"); assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE); IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"error"); assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE); // check that the @DeclareError has a matches relationship with the badMethod List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE); assertNotNull("@DeclareError should have some relationships but does not",matchedByE); assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1); List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets(); assertTrue("@DeclareError 'matched by' relationship should have one target " + "but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1); IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0)); assertEquals("target of relationship should be the badMethod but is IPE with label " + matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE); } public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() { runTest("@AJ no NPE with deow when structure model isn't generated"); } /* * Load-time weaving bugs and enhancements */ public void testEmptyPointcutInAtAspectJ_pr125475 () { runTest("define empty pointcut using an annotation"); } public void testEmptyPointcutInAtAspectJ_pr125475_2() { runTest("define empty pointcut using an annotation - 2"); } public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () { runTest("define empty pointcut using aop.xml"); } public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () { runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent"); } ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
122,370
Bug 122370 [@AspectJ] @DeclareParents/declare parents not equivalent
Adding a setter to the Moody example makes it clear that the annotation style (@DeclareParents) results in different behavior than the classic (declare parents) style. Calling the setter in a "declare parents"-advised object behaves as one would expect. However, calling the setter with a "@DeclareParents"-advised object has no effect -- that is, you can call the setter (and see that it's been called) and immediately call the getter, only to find that the value didn't change. The following examples (all in "package moody;") illustrate: public enum Mood { HAPPY, JOLLY } Classic style: ------------- public aspect ClassicMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } private Mood Moody.mood = Mood.HAPPY; public Mood Moody.getMood() { return mood; } public void Moody.setMood(Mood mood) { this.mood = mood; } declare parents : moody.ClassicMoodImplementor implements Moody; } public class ClassicMoodImplementor { } Annotation style: ---------------- import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; @Aspect public class AnnotationMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } public static class MoodyImpl implements Moody { private Mood mood = Mood.HAPPY; public Mood getMood() { return mood; } public void setMood(Mood mood) { this.mood = mood; } } @DeclareParents(value="moody.AnnotationMoodImplementor",defaultImpl=MoodyImpl.class) private Moody implementedInterface; } public class AnnotationMoodImplementor { } JUnit TestCase: -------------- import junit.framework.TestCase; public class MoodTester extends TestCase { public MoodTester(String name) { super(name); } public void testClassic() { ClassicMoodImplementor cmi0 = new ClassicMoodImplementor(); ClassicMoodImplementor cmi1 = new ClassicMoodImplementor(); assertEquals("cmi0 should be HAPPY", Mood.HAPPY, cmi0.getMood()); cmi1.setMood(Mood.JOLLY); assertEquals("cmi1 should be JOLLY", Mood.JOLLY, cmi1.getMood()); assertEquals("cmi0 should be *still* be HAPPY", Mood.HAPPY, cmi0.getMood()); } public void testAnnotation() { AnnotationMoodImplementor ami0 = new AnnotationMoodImplementor(); AnnotationMoodImplementor ami1 = new AnnotationMoodImplementor(); assertEquals("ami0 should be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); ((AnnotationMoodIndicator.Moody) ami1).setMood(Mood.JOLLY); assertEquals("ami1 should be JOLLY", Mood.JOLLY, ((AnnotationMoodIndicator.Moody) ami1).getMood()); assertEquals("ami0 should be *still* be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); } } Result: ------ The test run is as follows: ..F Time: 0.021 There was 1 failure: 1) testAnnotation(moody.MoodTester)junit.framework.AssertionFailedError: ami1 should be JOLLY expected:<JOLLY> but was:<HAPPY> at moody.MoodTester.testAnnotation(MoodTester.java:27) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at moody.MoodTester.main(MoodTester.java:7) FAILURES!!! Tests run: 2, Failures: 1, Errors: 0 For classic, you can see that cmi1.setMood was successful and cmi0/cmi1 are decoupled (that is, calling setMood on cmi1 has no impact on cmi0). The annotation style, however, fails because ami1.setMood appears to have done nothing. The result should have been that ami1 is JOLLY and ami0 HAPPY (I include the second assert because both ami0 & ami1 ended up JOLLY in RC1). The current behavior makes @DeclareParents unusable for retaining field state (near as I can tell, it retains state throughout the method invocation, but not beyond it, like it is creating and discarding a backing object with each method invocation).
resolved fixed
e874581
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-16T16:50:34Z
2005-12-30T05:20:00Z
tests/bugs151/pr122370/moody/AnnotationMoodImplementor.java
122,370
Bug 122370 [@AspectJ] @DeclareParents/declare parents not equivalent
Adding a setter to the Moody example makes it clear that the annotation style (@DeclareParents) results in different behavior than the classic (declare parents) style. Calling the setter in a "declare parents"-advised object behaves as one would expect. However, calling the setter with a "@DeclareParents"-advised object has no effect -- that is, you can call the setter (and see that it's been called) and immediately call the getter, only to find that the value didn't change. The following examples (all in "package moody;") illustrate: public enum Mood { HAPPY, JOLLY } Classic style: ------------- public aspect ClassicMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } private Mood Moody.mood = Mood.HAPPY; public Mood Moody.getMood() { return mood; } public void Moody.setMood(Mood mood) { this.mood = mood; } declare parents : moody.ClassicMoodImplementor implements Moody; } public class ClassicMoodImplementor { } Annotation style: ---------------- import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; @Aspect public class AnnotationMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } public static class MoodyImpl implements Moody { private Mood mood = Mood.HAPPY; public Mood getMood() { return mood; } public void setMood(Mood mood) { this.mood = mood; } } @DeclareParents(value="moody.AnnotationMoodImplementor",defaultImpl=MoodyImpl.class) private Moody implementedInterface; } public class AnnotationMoodImplementor { } JUnit TestCase: -------------- import junit.framework.TestCase; public class MoodTester extends TestCase { public MoodTester(String name) { super(name); } public void testClassic() { ClassicMoodImplementor cmi0 = new ClassicMoodImplementor(); ClassicMoodImplementor cmi1 = new ClassicMoodImplementor(); assertEquals("cmi0 should be HAPPY", Mood.HAPPY, cmi0.getMood()); cmi1.setMood(Mood.JOLLY); assertEquals("cmi1 should be JOLLY", Mood.JOLLY, cmi1.getMood()); assertEquals("cmi0 should be *still* be HAPPY", Mood.HAPPY, cmi0.getMood()); } public void testAnnotation() { AnnotationMoodImplementor ami0 = new AnnotationMoodImplementor(); AnnotationMoodImplementor ami1 = new AnnotationMoodImplementor(); assertEquals("ami0 should be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); ((AnnotationMoodIndicator.Moody) ami1).setMood(Mood.JOLLY); assertEquals("ami1 should be JOLLY", Mood.JOLLY, ((AnnotationMoodIndicator.Moody) ami1).getMood()); assertEquals("ami0 should be *still* be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); } } Result: ------ The test run is as follows: ..F Time: 0.021 There was 1 failure: 1) testAnnotation(moody.MoodTester)junit.framework.AssertionFailedError: ami1 should be JOLLY expected:<JOLLY> but was:<HAPPY> at moody.MoodTester.testAnnotation(MoodTester.java:27) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at moody.MoodTester.main(MoodTester.java:7) FAILURES!!! Tests run: 2, Failures: 1, Errors: 0 For classic, you can see that cmi1.setMood was successful and cmi0/cmi1 are decoupled (that is, calling setMood on cmi1 has no impact on cmi0). The annotation style, however, fails because ami1.setMood appears to have done nothing. The result should have been that ami1 is JOLLY and ami0 HAPPY (I include the second assert because both ami0 & ami1 ended up JOLLY in RC1). The current behavior makes @DeclareParents unusable for retaining field state (near as I can tell, it retains state throughout the method invocation, but not beyond it, like it is creating and discarding a backing object with each method invocation).
resolved fixed
e874581
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-16T16:50:34Z
2005-12-30T05:20:00Z
tests/bugs151/pr122370/moody/AnnotationMoodIndicator.java
122,370
Bug 122370 [@AspectJ] @DeclareParents/declare parents not equivalent
Adding a setter to the Moody example makes it clear that the annotation style (@DeclareParents) results in different behavior than the classic (declare parents) style. Calling the setter in a "declare parents"-advised object behaves as one would expect. However, calling the setter with a "@DeclareParents"-advised object has no effect -- that is, you can call the setter (and see that it's been called) and immediately call the getter, only to find that the value didn't change. The following examples (all in "package moody;") illustrate: public enum Mood { HAPPY, JOLLY } Classic style: ------------- public aspect ClassicMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } private Mood Moody.mood = Mood.HAPPY; public Mood Moody.getMood() { return mood; } public void Moody.setMood(Mood mood) { this.mood = mood; } declare parents : moody.ClassicMoodImplementor implements Moody; } public class ClassicMoodImplementor { } Annotation style: ---------------- import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; @Aspect public class AnnotationMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } public static class MoodyImpl implements Moody { private Mood mood = Mood.HAPPY; public Mood getMood() { return mood; } public void setMood(Mood mood) { this.mood = mood; } } @DeclareParents(value="moody.AnnotationMoodImplementor",defaultImpl=MoodyImpl.class) private Moody implementedInterface; } public class AnnotationMoodImplementor { } JUnit TestCase: -------------- import junit.framework.TestCase; public class MoodTester extends TestCase { public MoodTester(String name) { super(name); } public void testClassic() { ClassicMoodImplementor cmi0 = new ClassicMoodImplementor(); ClassicMoodImplementor cmi1 = new ClassicMoodImplementor(); assertEquals("cmi0 should be HAPPY", Mood.HAPPY, cmi0.getMood()); cmi1.setMood(Mood.JOLLY); assertEquals("cmi1 should be JOLLY", Mood.JOLLY, cmi1.getMood()); assertEquals("cmi0 should be *still* be HAPPY", Mood.HAPPY, cmi0.getMood()); } public void testAnnotation() { AnnotationMoodImplementor ami0 = new AnnotationMoodImplementor(); AnnotationMoodImplementor ami1 = new AnnotationMoodImplementor(); assertEquals("ami0 should be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); ((AnnotationMoodIndicator.Moody) ami1).setMood(Mood.JOLLY); assertEquals("ami1 should be JOLLY", Mood.JOLLY, ((AnnotationMoodIndicator.Moody) ami1).getMood()); assertEquals("ami0 should be *still* be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); } } Result: ------ The test run is as follows: ..F Time: 0.021 There was 1 failure: 1) testAnnotation(moody.MoodTester)junit.framework.AssertionFailedError: ami1 should be JOLLY expected:<JOLLY> but was:<HAPPY> at moody.MoodTester.testAnnotation(MoodTester.java:27) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at moody.MoodTester.main(MoodTester.java:7) FAILURES!!! Tests run: 2, Failures: 1, Errors: 0 For classic, you can see that cmi1.setMood was successful and cmi0/cmi1 are decoupled (that is, calling setMood on cmi1 has no impact on cmi0). The annotation style, however, fails because ami1.setMood appears to have done nothing. The result should have been that ami1 is JOLLY and ami0 HAPPY (I include the second assert because both ami0 & ami1 ended up JOLLY in RC1). The current behavior makes @DeclareParents unusable for retaining field state (near as I can tell, it retains state throughout the method invocation, but not beyond it, like it is creating and discarding a backing object with each method invocation).
resolved fixed
e874581
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-16T16:50:34Z
2005-12-30T05:20:00Z
tests/bugs151/pr122370/moody/MainClass.java
122,370
Bug 122370 [@AspectJ] @DeclareParents/declare parents not equivalent
Adding a setter to the Moody example makes it clear that the annotation style (@DeclareParents) results in different behavior than the classic (declare parents) style. Calling the setter in a "declare parents"-advised object behaves as one would expect. However, calling the setter with a "@DeclareParents"-advised object has no effect -- that is, you can call the setter (and see that it's been called) and immediately call the getter, only to find that the value didn't change. The following examples (all in "package moody;") illustrate: public enum Mood { HAPPY, JOLLY } Classic style: ------------- public aspect ClassicMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } private Mood Moody.mood = Mood.HAPPY; public Mood Moody.getMood() { return mood; } public void Moody.setMood(Mood mood) { this.mood = mood; } declare parents : moody.ClassicMoodImplementor implements Moody; } public class ClassicMoodImplementor { } Annotation style: ---------------- import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; @Aspect public class AnnotationMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } public static class MoodyImpl implements Moody { private Mood mood = Mood.HAPPY; public Mood getMood() { return mood; } public void setMood(Mood mood) { this.mood = mood; } } @DeclareParents(value="moody.AnnotationMoodImplementor",defaultImpl=MoodyImpl.class) private Moody implementedInterface; } public class AnnotationMoodImplementor { } JUnit TestCase: -------------- import junit.framework.TestCase; public class MoodTester extends TestCase { public MoodTester(String name) { super(name); } public void testClassic() { ClassicMoodImplementor cmi0 = new ClassicMoodImplementor(); ClassicMoodImplementor cmi1 = new ClassicMoodImplementor(); assertEquals("cmi0 should be HAPPY", Mood.HAPPY, cmi0.getMood()); cmi1.setMood(Mood.JOLLY); assertEquals("cmi1 should be JOLLY", Mood.JOLLY, cmi1.getMood()); assertEquals("cmi0 should be *still* be HAPPY", Mood.HAPPY, cmi0.getMood()); } public void testAnnotation() { AnnotationMoodImplementor ami0 = new AnnotationMoodImplementor(); AnnotationMoodImplementor ami1 = new AnnotationMoodImplementor(); assertEquals("ami0 should be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); ((AnnotationMoodIndicator.Moody) ami1).setMood(Mood.JOLLY); assertEquals("ami1 should be JOLLY", Mood.JOLLY, ((AnnotationMoodIndicator.Moody) ami1).getMood()); assertEquals("ami0 should be *still* be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); } } Result: ------ The test run is as follows: ..F Time: 0.021 There was 1 failure: 1) testAnnotation(moody.MoodTester)junit.framework.AssertionFailedError: ami1 should be JOLLY expected:<JOLLY> but was:<HAPPY> at moody.MoodTester.testAnnotation(MoodTester.java:27) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at moody.MoodTester.main(MoodTester.java:7) FAILURES!!! Tests run: 2, Failures: 1, Errors: 0 For classic, you can see that cmi1.setMood was successful and cmi0/cmi1 are decoupled (that is, calling setMood on cmi1 has no impact on cmi0). The annotation style, however, fails because ami1.setMood appears to have done nothing. The result should have been that ami1 is JOLLY and ami0 HAPPY (I include the second assert because both ami0 & ami1 ended up JOLLY in RC1). The current behavior makes @DeclareParents unusable for retaining field state (near as I can tell, it retains state throughout the method invocation, but not beyond it, like it is creating and discarding a backing object with each method invocation).
resolved fixed
e874581
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-16T16:50:34Z
2005-12-30T05:20:00Z
tests/bugs151/pr122370/moody/Mood.java
122,370
Bug 122370 [@AspectJ] @DeclareParents/declare parents not equivalent
Adding a setter to the Moody example makes it clear that the annotation style (@DeclareParents) results in different behavior than the classic (declare parents) style. Calling the setter in a "declare parents"-advised object behaves as one would expect. However, calling the setter with a "@DeclareParents"-advised object has no effect -- that is, you can call the setter (and see that it's been called) and immediately call the getter, only to find that the value didn't change. The following examples (all in "package moody;") illustrate: public enum Mood { HAPPY, JOLLY } Classic style: ------------- public aspect ClassicMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } private Mood Moody.mood = Mood.HAPPY; public Mood Moody.getMood() { return mood; } public void Moody.setMood(Mood mood) { this.mood = mood; } declare parents : moody.ClassicMoodImplementor implements Moody; } public class ClassicMoodImplementor { } Annotation style: ---------------- import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; @Aspect public class AnnotationMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } public static class MoodyImpl implements Moody { private Mood mood = Mood.HAPPY; public Mood getMood() { return mood; } public void setMood(Mood mood) { this.mood = mood; } } @DeclareParents(value="moody.AnnotationMoodImplementor",defaultImpl=MoodyImpl.class) private Moody implementedInterface; } public class AnnotationMoodImplementor { } JUnit TestCase: -------------- import junit.framework.TestCase; public class MoodTester extends TestCase { public MoodTester(String name) { super(name); } public void testClassic() { ClassicMoodImplementor cmi0 = new ClassicMoodImplementor(); ClassicMoodImplementor cmi1 = new ClassicMoodImplementor(); assertEquals("cmi0 should be HAPPY", Mood.HAPPY, cmi0.getMood()); cmi1.setMood(Mood.JOLLY); assertEquals("cmi1 should be JOLLY", Mood.JOLLY, cmi1.getMood()); assertEquals("cmi0 should be *still* be HAPPY", Mood.HAPPY, cmi0.getMood()); } public void testAnnotation() { AnnotationMoodImplementor ami0 = new AnnotationMoodImplementor(); AnnotationMoodImplementor ami1 = new AnnotationMoodImplementor(); assertEquals("ami0 should be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); ((AnnotationMoodIndicator.Moody) ami1).setMood(Mood.JOLLY); assertEquals("ami1 should be JOLLY", Mood.JOLLY, ((AnnotationMoodIndicator.Moody) ami1).getMood()); assertEquals("ami0 should be *still* be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); } } Result: ------ The test run is as follows: ..F Time: 0.021 There was 1 failure: 1) testAnnotation(moody.MoodTester)junit.framework.AssertionFailedError: ami1 should be JOLLY expected:<JOLLY> but was:<HAPPY> at moody.MoodTester.testAnnotation(MoodTester.java:27) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at moody.MoodTester.main(MoodTester.java:7) FAILURES!!! Tests run: 2, Failures: 1, Errors: 0 For classic, you can see that cmi1.setMood was successful and cmi0/cmi1 are decoupled (that is, calling setMood on cmi1 has no impact on cmi0). The annotation style, however, fails because ami1.setMood appears to have done nothing. The result should have been that ami1 is JOLLY and ami0 HAPPY (I include the second assert because both ami0 & ami1 ended up JOLLY in RC1). The current behavior makes @DeclareParents unusable for retaining field state (near as I can tell, it retains state throughout the method invocation, but not beyond it, like it is creating and discarding a backing object with each method invocation).
resolved fixed
e874581
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-16T16:50:34Z
2005-12-30T05:20:00Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import java.util.List; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.Relationship; import org.aspectj.systemtest.ajc150.GenericsTests; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");} public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");} public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");} public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");} public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");} //public void testExposingWithintype_enh123423() { runTest("exposing withintype");} //public void testMissingImport_pr127299() { runTest("missing import gives funny message");} public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");} public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); } public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); } public void testMixingNumbersOfTypeParameters_pr125080() { runTest("mixing numbers of type parameters"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;"); } public void testMixingNumbersOfTypeParameters_pr125080_2() { runTest("mixing numbers of type parameters - 2"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;"); } public void testIProgramElementMethods_pr125295() { runTest("new IProgramElement methods"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForType("pkg","foo"); assertNotNull("Couldn't find 'foo' element in the tree",pe); // check that the defaults return the fully qualified arg assertEquals("foo(int, java.lang.Object)",pe.toLabelString()); assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString()); assertEquals("foo(int, java.lang.Object)",pe.toSignatureString()); // check that can get hold of the non qualified args assertEquals("foo(int, Object)",pe.toLabelString(false)); assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false)); assertEquals("foo(int, Object)",pe.toSignatureString(false)); IProgramElement pe2 = top.findElementForType("pkg","printParameters"); assertNotNull("Couldn't find 'printParameters' element in the tree",pe2); // the argument is org.aspectj.lang.JoinPoint, check that this is added assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty()); } public void testParameterizedEnum_pr126316() { runTest("E extends Enum(E) again"); } public void testSwallowedException() { runTest("swallowed exceptions"); } public void testSwallowedExceptionIgnored() { runTest("swallowed exceptions with xlint"); } /* * @AspectJ bugs and enhancements */ // public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { // runTest("inherit adivce with this() and thisJoinPoint"); // } public void testAtAspectInheritsAbstractPointcut_pr125810 () { runTest("warning when inherited pointcut not made concrete"); } public void testAtAspectDEOWInStructureModel_pr120356() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("@AJ deow appear correctly when structure model is generated"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // get the IProgramElements corresponding to the @DeclareWarning statement // and the method it matches. IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"warningMethod()"); assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE); IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"warning"); assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE); // check that the method has a matches declare relationship with @DeclareWarning List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE); assertNotNull("warningMethod should have some relationships but does not",matches); assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1); List matchesTargets = ((Relationship)matches.get(0)).getTargets(); assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0)); assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label " + target.toLabelString(),atDeclareWarningIPE,target); // check that the @DeclareWarning has a matches relationship with the warningMethod List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE); assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy); assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1); List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets(); assertTrue("@DeclareWarning 'matched by' relationship should have one target " + "but has " + matchedByTargets.size(), matchedByTargets.size() == 1); IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0)); assertEquals("target of relationship should be the warningMethod but is IPE with label " + matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget); // get the IProgramElements corresponding to the @DeclareError statement // and the method it matches. IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"badMethod()"); assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE); IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"error"); assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE); // check that the @DeclareError has a matches relationship with the badMethod List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE); assertNotNull("@DeclareError should have some relationships but does not",matchedByE); assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1); List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets(); assertTrue("@DeclareError 'matched by' relationship should have one target " + "but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1); IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0)); assertEquals("target of relationship should be the badMethod but is IPE with label " + matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE); } public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() { runTest("@AJ no NPE with deow when structure model isn't generated"); } public void testAtAspectWithoutJoinPointImport_pr121616() { runTest("@AJ without JoinPoint import"); } /* * Load-time weaving bugs and enhancements */ public void testEmptyPointcutInAtAspectJ_pr125475 () { runTest("define empty pointcut using an annotation"); } public void testEmptyPointcutInAtAspectJ_pr125475_2() { runTest("define empty pointcut using an annotation - 2"); } public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () { runTest("define empty pointcut using aop.xml"); } public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () { runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent"); } ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
122,370
Bug 122370 [@AspectJ] @DeclareParents/declare parents not equivalent
Adding a setter to the Moody example makes it clear that the annotation style (@DeclareParents) results in different behavior than the classic (declare parents) style. Calling the setter in a "declare parents"-advised object behaves as one would expect. However, calling the setter with a "@DeclareParents"-advised object has no effect -- that is, you can call the setter (and see that it's been called) and immediately call the getter, only to find that the value didn't change. The following examples (all in "package moody;") illustrate: public enum Mood { HAPPY, JOLLY } Classic style: ------------- public aspect ClassicMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } private Mood Moody.mood = Mood.HAPPY; public Mood Moody.getMood() { return mood; } public void Moody.setMood(Mood mood) { this.mood = mood; } declare parents : moody.ClassicMoodImplementor implements Moody; } public class ClassicMoodImplementor { } Annotation style: ---------------- import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; @Aspect public class AnnotationMoodIndicator { public interface Moody { Mood getMood(); void setMood(Mood mood); } public static class MoodyImpl implements Moody { private Mood mood = Mood.HAPPY; public Mood getMood() { return mood; } public void setMood(Mood mood) { this.mood = mood; } } @DeclareParents(value="moody.AnnotationMoodImplementor",defaultImpl=MoodyImpl.class) private Moody implementedInterface; } public class AnnotationMoodImplementor { } JUnit TestCase: -------------- import junit.framework.TestCase; public class MoodTester extends TestCase { public MoodTester(String name) { super(name); } public void testClassic() { ClassicMoodImplementor cmi0 = new ClassicMoodImplementor(); ClassicMoodImplementor cmi1 = new ClassicMoodImplementor(); assertEquals("cmi0 should be HAPPY", Mood.HAPPY, cmi0.getMood()); cmi1.setMood(Mood.JOLLY); assertEquals("cmi1 should be JOLLY", Mood.JOLLY, cmi1.getMood()); assertEquals("cmi0 should be *still* be HAPPY", Mood.HAPPY, cmi0.getMood()); } public void testAnnotation() { AnnotationMoodImplementor ami0 = new AnnotationMoodImplementor(); AnnotationMoodImplementor ami1 = new AnnotationMoodImplementor(); assertEquals("ami0 should be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); ((AnnotationMoodIndicator.Moody) ami1).setMood(Mood.JOLLY); assertEquals("ami1 should be JOLLY", Mood.JOLLY, ((AnnotationMoodIndicator.Moody) ami1).getMood()); assertEquals("ami0 should be *still* be HAPPY", Mood.HAPPY, ((AnnotationMoodIndicator.Moody) ami0).getMood()); } } Result: ------ The test run is as follows: ..F Time: 0.021 There was 1 failure: 1) testAnnotation(moody.MoodTester)junit.framework.AssertionFailedError: ami1 should be JOLLY expected:<JOLLY> but was:<HAPPY> at moody.MoodTester.testAnnotation(MoodTester.java:27) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at moody.MoodTester.main(MoodTester.java:7) FAILURES!!! Tests run: 2, Failures: 1, Errors: 0 For classic, you can see that cmi1.setMood was successful and cmi0/cmi1 are decoupled (that is, calling setMood on cmi1 has no impact on cmi0). The annotation style, however, fails because ami1.setMood appears to have done nothing. The result should have been that ami1 is JOLLY and ami0 HAPPY (I include the second assert because both ami0 & ami1 ended up JOLLY in RC1). The current behavior makes @DeclareParents unusable for retaining field state (near as I can tell, it retains state throughout the method invocation, but not beyond it, like it is creating and discarding a backing object with each method invocation).
resolved fixed
e874581
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-16T16:50:34Z
2005-12-30T05:20:00Z
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur @AspectJ ITDs * ******************************************************************/ package org.aspectj.weaver.bcel; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.generic.BranchInstruction; import org.aspectj.apache.bcel.generic.ConstantPoolGen; import org.aspectj.apache.bcel.generic.FieldGen; import org.aspectj.apache.bcel.generic.INVOKESPECIAL; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionFactory; import org.aspectj.apache.bcel.generic.InstructionHandle; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.weaver.AjcMemberMaker; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.MethodDelegateTypeMunger; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.NewConstructorTypeMunger; import org.aspectj.weaver.NewFieldTypeMunger; import org.aspectj.weaver.NewMethodTypeMunger; import org.aspectj.weaver.NewParentTypeMunger; import org.aspectj.weaver.PerObjectInterfaceTypeMunger; import org.aspectj.weaver.PrivilegedAccessMunger; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.Pointcut; //XXX addLazyMethodGen is probably bad everywhere public class BcelTypeMunger extends ConcreteTypeMunger { public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { super(munger, aspectType); } public String toString() { return "(BcelTypeMunger " + getMunger() + ")"; } public boolean munge(BcelClassWeaver weaver) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MUNGING_WITH, this); boolean changed = false; boolean worthReporting = true; if (munger.getKind() == ResolvedTypeMunger.Field) { changed = mungeNewField(weaver, (NewFieldTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Method) { changed = mungeNewMethod(weaver, (NewMethodTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.MethodDelegate) { changed = mungeMethodDelegate(weaver, (MethodDelegateTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.FieldHost) { changed = mungeFieldHost(weaver, (MethodDelegateTypeMunger.FieldHostTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) { changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) { // PTWIMPL Transform the target type (add the aspect instance field) changed = mungePerTypeWithinTransformer(weaver); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) { changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger)munger); worthReporting = false; } else if (munger.getKind() == ResolvedTypeMunger.Constructor) { changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.Parent) { changed = mungeNewParent(weaver, (NewParentTypeMunger)munger); } else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) { changed = mungeNewAnnotationOnType(weaver,(AnnotationOnTypeMunger)munger); worthReporting=false; } else { throw new RuntimeException("unimplemented"); } if (changed && munger.changesPublicSignature()) { WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(BcelClassWeaver.getReweavableMode()); info.addConcreteMunger(this); } if (changed && worthReporting) { if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } else { AsmRelationshipProvider.getDefault().addRelationship(weaver.getLazyClassGen().getType(), munger,getAspectType()); } } // TAG: WeavingMessage if (changed && worthReporting && munger!=null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) { String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName(); if (tName.indexOf("no debug info available")!=-1) tName = "no debug info available"; else tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath()); String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath()); if (munger.getKind().equals(ResolvedTypeMunger.Parent)) { // This message could come out of AjLookupEnvironment.addParent if doing parents // munging at compile time only... NewParentTypeMunger parentTM = (NewParentTypeMunger)munger; if (parentTM.getNewParent().isInterface()) { weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName}, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } else { weaver.getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS, new String[]{weaver.getLazyClassGen().getType().getName(), tName,parentTM.getNewParent().getName(),fName })); // TAG: WeavingMessage DECLARE PARENTS: EXTENDS // reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent); } } else if (munger.getKind().equals(ResolvedTypeMunger.FieldHost)) { ;//hidden } else { ResolvedMember declaredSig = munger.getDeclaredSignature(); if (declaredSig==null) declaredSig= munger.getSignature(); weaver.getWorld().getMessageHandler().handleMessage(WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[]{weaver.getLazyClassGen().getType().getName(), tName,munger.getKind().toString().toLowerCase(), getAspectType().getName(), fName+":'"+declaredSig+"'"}, weaver.getLazyClassGen().getClassName(), getAspectType().getName())); } } CompilationAndWeavingContext.leavingPhase(tok); return changed; } private String getShortname(String path) { int takefrom = path.lastIndexOf('/'); if (takefrom == -1) { takefrom = path.lastIndexOf('\\'); } return path.substring(takefrom+1); } private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver,AnnotationOnTypeMunger munger) { // FIXME asc this has already been done up front, need to do it here too? weaver.getLazyClassGen().addAnnotation(munger.getNewAnnotation().getBcelAnnotation()); return true; } /** * For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted * but could do with more testing! */ private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger munger) { LazyClassGen newParentTarget = weaver.getLazyClassGen(); ResolvedType newParent = munger.getNewParent(); boolean cont = true; // Set to false when we error, so we don't actually *do* the munge cont = enforceDecpRule1_abstractMethodsImplemented(weaver, munger.getSourceLocation(),newParentTarget, newParent); cont = enforceDecpRule2_cantExtendFinalClass(weaver,munger.getSourceLocation(),newParentTarget,newParent) && cont; List methods = newParent.getMethodsWithoutIterator(false,true); for (Iterator iter = methods.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (!superMethod.getName().equals("<init>")) { LazyMethodGen subMethod = findMatchingMethod(newParentTarget, superMethod); if (subMethod!=null && !subMethod.isBridgeMethod()) { // FIXME asc is this safe for all bridge methods? cont = enforceDecpRule3_visibilityChanges(weaver, newParent, superMethod, subMethod) && cont; cont = enforceDecpRule4_compatibleReturnTypes(weaver, superMethod, subMethod) && cont; cont = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver,munger.getSourceLocation(),superMethod,subMethod) && cont; } } } if (!cont) return false; // A rule was violated and an error message already reported if (newParent.isClass()) { // Changing the supertype if (!attemptToModifySuperCalls(weaver,newParentTarget,newParent)) return false; newParentTarget.setSuperClass(newParent); } else { // Adding a new interface newParentTarget.addInterface(newParent,getSourceLocation()); } return true; } /** * Rule 1: For the declare parents to be allowed, the target type must override and implement * inherited abstract methods (if the type is not declared abstract) */ private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc,LazyClassGen newParentTarget, ResolvedType newParent) { boolean ruleCheckingSucceeded = true; if (!(newParentTarget.isAbstract() || newParentTarget.isInterface())) { // Ignore abstract classes or interfaces List methods = newParent.getMethodsWithoutIterator(false,true); for (Iterator i = methods.iterator(); i.hasNext();) { ResolvedMember o = (ResolvedMember)i.next(); if (o.isAbstract() && !o.getName().startsWith("ajc$interField")) { // Ignore abstract methods of ajc$interField prefixed methods ResolvedMember discoveredImpl = null; List newParentTargetMethods = newParentTarget.getType().getMethodsWithoutIterator(false,true); for (Iterator ii = newParentTargetMethods.iterator(); ii.hasNext() && discoveredImpl==null;) { ResolvedMember gen2 = (ResolvedMember) ii.next(); if (gen2.getName().equals(o.getName()) && gen2.getParameterSignature().equals(o.getParameterSignature()) && !gen2.isAbstract()) { discoveredImpl = gen2; // Found a valid implementation ! } } if (discoveredImpl == null) { // didnt find a valid implementation, lets check the ITDs on this type to see if they satisfy it boolean satisfiedByITD = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next(); if (m.getMunger().getKind() == ResolvedTypeMunger.Method) { ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { // If the ITD shares a type variable with some target type, we need to tailor it for that // type if (m.isTargetTypeParameterized()) { ResolvedType genericOnType = getWorld().resolve(sig.getDeclaringType()).getGenericType(); m = m.parameterizedFor(newParent.discoverActualOccurrenceOfTypeInHierarchy(genericOnType)); sig = m.getSignature(); // possible sig change when type parameters filled in } if (ResolvedType .matches( AjcMemberMaker.interMethod( sig,m.getAspectType(),sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()),o)) { satisfiedByITD = true; } } } else if (m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate) { satisfiedByITD = true;//AV - that should be enough, no need to check more } } if (!satisfiedByITD) { error(weaver, "The type " + newParentTarget.getName() + " must implement the inherited abstract method "+o.getDeclaringType()+"."+o.getName()+o.getParameterSignature(), newParentTarget.getType().getSourceLocation(),new ISourceLocation[]{o.getSourceLocation(),mungerLoc}); ruleCheckingSucceeded=false; } } } } } return ruleCheckingSucceeded; } /** * Rule 2. Can't extend final types */ private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation mungerLoc, LazyClassGen newParentTarget, ResolvedType newParent) { if (newParent.isFinal()) { error(weaver,"Cannot make type "+newParentTarget.getName()+" extend final class "+newParent.getName(), newParentTarget.getType().getSourceLocation(), new ISourceLocation[]{mungerLoc}); return false; } return true; } /** * Rule 3. Can't narrow visibility of methods when overriding */ private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; if (superMethod.isPublic()) { if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } else if (superMethod.isProtected()) { if (subMethod.isDefault() || subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } else if (superMethod.isDefault()) { if (subMethod.isPrivate()) { weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Cannot reduce the visibility of the inherited method '"+superMethod+"' from "+newParent.getName(), superMethod.getSourceLocation())); cont=false; } } return cont; } /** * Rule 4. Can't have incompatible return types */ private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod, LazyMethodGen subMethod) { boolean cont = true; String superReturnTypeSig = superMethod.getReturnType().getSignature(); String subReturnTypeSig = subMethod.getReturnType().getSignature(); if (!superReturnTypeSig.equals(subReturnTypeSig)) { // Allow for covariance - wish I could test this (need Java5...) ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType()); ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType()); if (!superType.isAssignableFrom(subType)) { ISourceLocation sloc = subMethod.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "The return type is incompatible with "+superMethod.getDeclaringType()+"."+superMethod.getName()+superMethod.getParameterSignature(), subMethod.getSourceLocation())); cont=false; } } return cont; } /** * Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance * method static or override and make a static method an instance method. */ private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver,ISourceLocation mungerLoc,ResolvedMember superMethod, LazyMethodGen subMethod ) { if (superMethod.isStatic() && !subMethod.isStatic()) { error(weaver,"This instance method "+subMethod.getName()+subMethod.getParameterSignature()+ " cannot override the static method from "+superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc}); return false; } else if (!superMethod.isStatic() && subMethod.isStatic()) { error(weaver,"The static method "+subMethod.getName()+subMethod.getParameterSignature()+ " cannot hide the instance method from "+superMethod.getDeclaringType().getName(), subMethod.getSourceLocation(),new ISourceLocation[]{mungerLoc}); return false; } return true; } public void error(BcelClassWeaver weaver,String text,ISourceLocation primaryLoc,ISourceLocation[] extraLocs) { IMessage msg = new Message(text, primaryLoc, true, extraLocs); weaver.getWorld().getMessageHandler().handleMessage(msg); } private LazyMethodGen findMatchingMethod(LazyClassGen newParentTarget, ResolvedMember m) { LazyMethodGen found = null; // Search the type for methods overriding super methods (methods that come from the new parent) // Don't use the return value in the comparison as overriding doesnt for (Iterator i = newParentTarget.getMethodGens().iterator(); i.hasNext() && found==null;) { LazyMethodGen gen = (LazyMethodGen) i.next(); if (gen.getName().equals(m.getName()) && gen.getParameterSignature().equals(m.getParameterSignature())) { found = gen; } } return found; } /** * The main part of implementing declare parents extends. Modify super ctor calls to target the new type. */ public boolean attemptToModifySuperCalls(BcelClassWeaver weaver,LazyClassGen newParentTarget, ResolvedType newParent) { String currentParent = newParentTarget.getSuperClassname(); if (newParent.getGenericType()!=null) newParent = newParent.getGenericType(); // target new super calls at the generic type if its raw or parameterized List mgs = newParentTarget.getMethodGens(); // Look for ctors to modify for (Iterator iter = mgs.iterator(); iter.hasNext();) { LazyMethodGen aMethod = (LazyMethodGen) iter.next(); if (aMethod.getName().equals("<init>")) { InstructionList insList = aMethod.getBody(); InstructionHandle handle = insList.getStart(); while (handle!= null) { if (handle.getInstruction() instanceof INVOKESPECIAL) { ConstantPoolGen cpg = newParentTarget.getConstantPoolGen(); INVOKESPECIAL invokeSpecial = (INVOKESPECIAL)handle.getInstruction(); if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) { // System.err.println("Transforming super call '<init>"+sp.getSignature(cpg)+"'"); // 1. Check there is a ctor in the new parent with the same signature ResolvedMember newCtor = getConstructorWithSignature(newParent,invokeSpecial.getSignature(cpg)); if (newCtor == null) { // 2. Check ITDCs to see if the necessary ctor is provided that way boolean satisfiedByITDC = false; for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC; ) { ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next(); if (m.getMunger() instanceof NewConstructorTypeMunger) { if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) { satisfiedByITDC = true; } } } if (!satisfiedByITDC) { String csig = createReadableCtorSig(newParent, cpg, invokeSpecial); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( "Unable to modify hierarchy for "+newParentTarget.getClassName()+" - the constructor "+ csig+" is missing",this.getSourceLocation())); return false; } } int idx = cpg.addMethodref(newParent.getName(), invokeSpecial.getMethodName(cpg), invokeSpecial.getSignature(cpg)); invokeSpecial.setIndex(idx); } } handle = handle.getNext(); } } } return true; } /** * Creates a nice signature for the ctor, something like "(int,Integer,String)" */ private String createReadableCtorSig(ResolvedType newParent, ConstantPoolGen cpg, INVOKESPECIAL invokeSpecial) { StringBuffer sb = new StringBuffer(); Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg); sb.append(newParent.getClassName()); sb.append("("); for (int i = 0; i < ctorArgs.length; i++) { String argtype = ctorArgs[i].toString(); if (argtype.lastIndexOf(".")!=-1) sb.append(argtype.substring(argtype.lastIndexOf(".")+1)); else sb.append(argtype); if (i+1<ctorArgs.length) sb.append(","); } sb.append(")"); return sb.toString(); } private ResolvedMember getConstructorWithSignature(ResolvedType tx,String signature) { ResolvedMember[] mems = tx.getDeclaredJavaMethods(); for (int i = 0; i < mems.length; i++) { ResolvedMember rm = mems[i]; if (rm.getName().equals("<init>")) { if (rm.getSignature().equals(signature)) return rm; } } return null; } private boolean mungePrivilegedAccess( BcelClassWeaver weaver, PrivilegedAccessMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember member = munger.getMember(); ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); //System.out.println("munging: " + gen + " with " + member); if (onType.equals(gen.getType())) { if (member.getKind() == Member.FIELD) { //System.out.println("matched: " + gen); addFieldGetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member)); addFieldSetter(gen, member, AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member)); return true; } else if (member.getKind() == Member.METHOD) { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { for (Iterator i = gen.getMethodGens().iterator(); i.hasNext(); ) { LazyMethodGen m = (LazyMethodGen)i.next(); if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); //return true; } } return true; //throw new BCException("no match for " + member + " in " + gen); } else if (member.getKind() == Member.STATIC_INITIALIZATION) { gen.forcePublic(); return true; } else { throw new RuntimeException("unimplemented"); } } return false; } private void addFieldGetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType()))); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addFieldSetter( LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); Type fieldType = BcelWorld.makeBcelType(field.getType()); if (field.isStatic()) { il.append(InstructionFactory.createLoad(fieldType, 0)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(InstructionFactory.createLoad(fieldType, 1)); il.append(fact.createFieldAccess( gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD)); } il.append(InstructionFactory.createReturn(Type.VOID)); mg.getBody().insert(il); gen.addMethodGen(mg,getSignature().getSourceLocation()); } private void addMethodDispatch( LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) { LazyMethodGen mg = makeMethodGen(gen, accessMethod); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); //Type fieldType = BcelWorld.makeBcelType(field.getType()); Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes()); int pos = 0; if (!method.isStatic()) { il.append(InstructionConstants.ALOAD_0); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; il.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } il.append(Utility.createInvoke(fact, (BcelWorld)aspectType.getWorld(), method)); il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType()))); mg.getBody().insert(il); gen.addMethodGen(mg); } protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) { LazyMethodGen ret = new LazyMethodGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen); // 43972 : Static crosscutting makes interfaces unusable for javac // ret.makeSynthetic(); return ret; } protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) { return new FieldGen( member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(), gen.getConstantPoolGen()); } private boolean mungePerObjectInterface( BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) { //System.err.println("Munging perobject ["+munger+"] onto "+weaver.getLazyClassGen().getClassName()); LazyClassGen gen = weaver.getLazyClassGen(); if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType), new Type[0], new String[0], gen); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); LazyMethodGen mg1 = new LazyMethodGen( Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType), new Type[]{fieldType,}, new String[0], gen); InstructionList il1 = new InstructionList(); il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); gen.addInterface(munger.getInterfaceType(),getSourceLocation()); return true; } else { return false; } } // PTWIMPL Add field to hold aspect instance and an accessor private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) { LazyClassGen gen = weaver.getLazyClassGen(); // if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) { // Add (to the target type) the field that will hold the aspect instance // e.g ajc$com_blah_SecurityAspect$ptwAspectInstance FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType)); gen.addField(fg.getField(),getSourceLocation()); // Add an accessor for this new field, the ajc$<aspectname>$localAspectOf() method // e.g. "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()" Type fieldType = BcelWorld.makeBcelType(aspectType); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC | Modifier.STATIC,fieldType, NameMangler.perTypeWithinLocalAspectOf(aspectType), new Type[0], new String[0],gen); InstructionList il = new InstructionList(); //PTWIMPL ?? Should check if it is null and throw NoAspectBoundException InstructionFactory fact = gen.getFactory(); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); return true; // } else { // return false; // } } // ??? Why do we have this method? I thought by now we would know if it matched or not private boolean couldMatch( BcelObjectType bcelObjectType, Pointcut pointcut) { return !bcelObjectType.isInterface(); } private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) { World w = weaver.getWorld(); // Resolving it will sort out the tvars ResolvedMember unMangledInterMethod = munger.getSignature().resolve(w); // do matching on the unMangled one, but actually add them to the mangled method ResolvedMember interMethodBody = munger.getDeclaredInterMethodBody(aspectType,w); ResolvedMember interMethodDispatcher = munger.getDeclaredInterMethodDispatcher(aspectType,w); ResolvedMember memberHoldingAnyAnnotations = interMethodDispatcher; ResolvedType onType = weaver.getWorld().resolve(unMangledInterMethod.getDeclaringType(),munger.getSourceLocation()); LazyClassGen gen = weaver.getLazyClassGen(); boolean mungingInterface = gen.isInterface(); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); // Simple checks, can't ITD on annotations or enums if (onType.isAnnotation()) { signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (onInterface && gen.getLazyMethodGen(unMangledInterMethod.getName(), unMangledInterMethod.getSignature(),true) != null) { // this is ok, we could be providing the default implementation of a method // that the target has already declared return false; } // If we are processing the intended ITD target type (might be an interface) if (onType.equals(gen.getType())) { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface); LazyMethodGen newMethod = makeMethodGen(gen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all *implementors* of the // interface, but the method itself we add to the interface must be public abstract newMethod.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ AnnotationX annotationsOnRealMember[] = null; ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,memberHoldingAnyAnnotations,false); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ memberHoldingAnyAnnotations+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); newMethod.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();){ DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(unMangledInterMethod,weaver.getWorld()) && newMethod.getEnclosingClass().getType() == aspectType) { newMethod.addAnnotation(decaMC.getAnnotationX()); } } } // If it doesn't target an interface and there is a body (i.e. it isnt abstract) if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) { InstructionList body = newMethod.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); body.append( InstructionFactory.createReturn( BcelWorld.makeBcelType(mangledInterMethod.getReturnType()))); if (weaver.getWorld().isInJava5Mode()) { // Don't need bridge methods if not in 1.5 mode. createAnyBridgeMethodsForCovariance(weaver, munger, unMangledInterMethod, onType, gen, paramTypes); } } else { //??? this is okay //if (!(mg.getBody() == null)) throw new RuntimeException("bas"); } // XXX make sure to check that we set exceptions properly on this guy. weaver.addLazyMethodGen(newMethod); weaver.getLazyClassGen().warnOnAddedMethod(newMethod.getMethod(),getSignature().getSourceLocation()); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); return true; } else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) { // This means the 'gen' should be the top most implementor // - if it is *not* then something went wrong after we worked // out that it was the top most implementor (see pr49657) if (!gen.getType().isTopmostImplementor(onType)) { ResolvedType rtx = gen.getType().getTopmostImplementor(onType); if (!rtx.isExposedToWeaver()) { ISourceLocation sLoc = munger.getSourceLocation(); weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR,rtx,getAspectType().getName()), (sLoc==null?getAspectType().getSourceLocation():sLoc))); } else { // XXX what does this state mean? // We have incorrectly identified what is the top most implementor and its not because // a type wasn't exposed to the weaver } return false; } else { ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false); LazyMethodGen mg = makeMethodGen(gen, mangledInterMethod); if (mungingInterface) { // we want the modifiers of the ITD to be used for all *implementors* of the // interface, but the method itself we add to the interface must be public abstract mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT); } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType()); InstructionList body = mg.getBody(); InstructionFactory fact = gen.getFactory(); int pos = 0; if (!mangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), interMethodBody)); Type t= BcelWorld.makeBcelType(interMethodBody.getReturnType()); if (!t.equals(returnType)) { body.append(fact.createCast(t,returnType)); } body.append(InstructionFactory.createReturn(returnType)); mg.definingType = onType; weaver.addOrReplaceLazyMethodGen(mg); addNeededSuperCallMethods(weaver, onType, munger.getSuperMethodsCalled()); // Work out if we need a bridge method for the new method added to the topmostimplementor. if (munger.getDeclaredSignature()!=null) { // Check if the munger being processed is a parameterized form of some original munger. boolean needsbridging = false; ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,munger.getSignature().getDeclaringType().resolve(getWorld()),false,munger.getTypeVariableAliases()); if (!toBridgeTo.getReturnType().getErasureSignature().equals(munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true; UnresolvedType[] originalParams = toBridgeTo.getParameterTypes(); UnresolvedType[] newParams = munger.getSignature().getParameterTypes(); for (int ii = 0;ii<originalParams.length;ii++) { if (!originalParams[ii].getErasureSignature().equals(newParams[ii].getErasureSignature())) needsbridging=true; } if (toBridgeTo!=null && needsbridging) { ResolvedMember bridgerMethod = AjcMemberMaker.bridgerToInterMethod(unMangledInterMethod,gen.getType()); ResolvedMember bridgingSetter = AjcMemberMaker.interMethod(toBridgeTo, aspectType, false); // FIXME asc ----------------8<---------------- extract method LazyMethodGen bridgeMethod = makeMethodGen(gen,bridgingSetter); paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(unMangledInterMethod.getParameterTypes()); returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); body = bridgeMethod.getBody(); fact = gen.getFactory(); pos = 0; if (!bridgingSetter.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(unMangledInterMethod.getParameterTypes()[i].getErasureSignature()) ) { // System.err.println("Putting in cast from "+paramType+" to "+bridgingToParms[i]); body.append(fact.createCast(paramType,bridgingToParms[i])); } pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), bridgerMethod)); body.append(InstructionFactory.createReturn(returnType)); gen.addMethodGen(bridgeMethod); // mg.definingType = onType; // FIXME asc (see above) ---------------------8<--------------- extract method } } return true; } } else { return false; } } /** * Create any bridge method required because of covariant returns being used. This method is used in the case * where an ITD is applied to some type and it may be in an override relationship with a method from the supertype - but * due to covariance there is a mismatch in return values. * Example of when required: Super defines: Object m(String s) Sub defines: String m(String s) then we need a bridge method in Sub called 'Object m(String s)' that forwards to 'String m(String s)' */ private void createAnyBridgeMethodsForCovariance(BcelClassWeaver weaver, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, ResolvedType onType, LazyClassGen gen, Type[] paramTypes) { // PERFORMANCE BOTTLENECK? Might need investigating, method analysis between types in a hierarchy just seems expensive... // COVARIANCE BRIDGING // Algorithm: Step1. Check in this type - has someone already created the bridge method? // Step2. Look above us - do we 'override' a method and yet differ in return type (i.e. covariance) // Step3. Create a forwarding bridge method ResolvedType superclass = onType.getSuperclass(); boolean quitRightNow = false; String localMethodName = unMangledInterMethod.getName(); String localParameterSig = unMangledInterMethod.getParameterSignature(); String localReturnTypeESig = unMangledInterMethod.getReturnType().getErasureSignature(); // Step1 boolean alreadyDone = false; // Compiler might have done it ResolvedMember[] localMethods = onType.getDeclaredMethods(); for (int i = 0; i < localMethods.length; i++) { ResolvedMember member = localMethods[i]; if (member.getName().equals(localMethodName)) { // Check the params if (member.getParameterSignature().equals(localParameterSig)) alreadyDone = true; } } // Step2 if (!alreadyDone) { // Use the iterator form of 'getMethods()' so we do as little work as necessary for (Iterator iter = onType.getSuperclass().getMethods();iter.hasNext() && !quitRightNow;) { ResolvedMember aMethod = (ResolvedMember) iter.next(); if (aMethod.getName().equals(localMethodName) && aMethod.getParameterSignature().equals(localParameterSig)) { // check the return types, if they are different we need a bridging method. if (!aMethod.getReturnType().getErasureSignature().equals(localReturnTypeESig) && !Modifier.isPrivate(aMethod.getModifiers())) { // Step3 createBridgeMethod(weaver.getWorld(), munger, unMangledInterMethod, gen, paramTypes, aMethod); quitRightNow = true; } } } } } /** * Create a bridge method for a particular munger. * @param world * @param munger * @param unMangledInterMethod the method to bridge 'to' that we have already created in the 'subtype' * @param clazz the class in which to put the bridge method * @param paramTypes Parameter types for the bridge method, passed in as an optimization since the caller is likely to have already created them. * @param theBridgeMethod */ private void createBridgeMethod(BcelWorld world, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod, LazyClassGen clazz, Type[] paramTypes, ResolvedMember theBridgeMethod) { InstructionList body; InstructionFactory fact; int pos = 0; LazyMethodGen bridgeMethod = makeMethodGen(clazz,theBridgeMethod); // The bridge method in this type will have the same signature as the one in the supertype bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /*BRIDGE = 0x00000040*/ ); UnresolvedType[] newParams = munger.getSignature().getParameterTypes(); Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType()); body = bridgeMethod.getBody(); fact = clazz.getFactory(); if (!unMangledInterMethod.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); // if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(unMangledInterMethod.getParameterTypes()[i].getErasureSignature())) { // System.err.println("Putting in cast from "+paramType+" to "+bridgingToParms[i]); // body.append(fact.createCast(paramType,bridgingToParms[i])); // } pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, world,unMangledInterMethod)); body.append(InstructionFactory.createReturn(returnType)); clazz.addMethodGen(bridgeMethod); } private boolean mungeMethodDelegate(BcelClassWeaver weaver, MethodDelegateTypeMunger munger) { ResolvedMember introduced = munger.getSignature(); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedType fromType = weaver.getWorld().resolve(introduced.getDeclaringType(),munger.getSourceLocation()); if (fromType.isRawType()) fromType = fromType.getGenericType(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type pattern return false; } boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); if (shouldApply) { LazyMethodGen mg = new LazyMethodGen( introduced.getModifiers() - Modifier.ABSTRACT, BcelWorld.makeBcelType(introduced.getReturnType()), introduced.getName(), BcelWorld.makeBcelTypes(introduced.getParameterTypes()), BcelWorld.makeBcelTypesAsClassNames(introduced.getExceptions()), gen ); //annotation copy from annotation on ITD interface if (weaver.getWorld().isInJava5Mode()){ AnnotationX annotationsOnRealMember[] = null; ResolvedType toLookOn = weaver.getWorld().lookupOrCreateName(introduced.getDeclaringType()); if (fromType.isRawType()) toLookOn = fromType.getGenericType(); // lookup the method ResolvedMember[] ms = toLookOn.getDeclaredJavaMethods(); for (int i = 0; i < ms.length; i++) { ResolvedMember m = ms[i]; if (introduced.getName().equals(m.getName()) && introduced.getSignature().equals(m.getSignature())) { annotationsOnRealMember = m.getAnnotations(); } } if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } } InstructionList body = new InstructionList(); InstructionFactory fact = gen.getFactory(); // getfield body.append(InstructionConstants.ALOAD_0); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); BranchInstruction ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNULL, null); body.append(ifNonNull); InstructionHandle ifNonNullElse = body.append(InstructionConstants.ALOAD_0); body.append(fact.createNew(munger.getImplClassName())); body.append(InstructionConstants.DUP); body.append(fact.createInvoke(munger.getImplClassName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); ifNonNull.setTarget(ifNonNullElse); body.append(InstructionConstants.ALOAD_0); body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType()))); //args int pos = 0; if (!introduced.isStatic()) { // skip 'this' (?? can this really happen) //body.append(InstructionFactory.createThis()); pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes()); for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, Constants.INVOKEINTERFACE, introduced)); body.append( InstructionFactory.createReturn( BcelWorld.makeBcelType(introduced.getReturnType()) ) ); mg.getBody().append(body); // XXX make sure to check that we set exceptions properly on this guy. weaver.addLazyMethodGen(mg); weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(),getSignature().getSourceLocation()); return true; } return false; } private boolean mungeFieldHost(BcelClassWeaver weaver, MethodDelegateTypeMunger.FieldHostTypeMunger munger) { LazyClassGen gen = weaver.getLazyClassGen(); if (gen.getType().isAnnotation() || gen.getType().isEnum()) { // don't signal error as it could be a consequence of a wild type pattern return false; } boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType); ResolvedMember host = AjcMemberMaker.itdAtDeclareParentsField( weaver.getLazyClassGen().getType(), munger.getSignature().getType(), aspectType); weaver.getLazyClassGen().addField(makeFieldGen( weaver.getLazyClassGen(), host).getField(), null); return true; } private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType,ResolvedMember lookingFor,boolean isCtorRelated) { World world = aspectType.getWorld(); boolean debug = false; if (debug) { System.err.println("Searching for a member on type: "+aspectType); System.err.println("Member we are looking for: "+lookingFor); } ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods(); UnresolvedType [] lookingForParams = lookingFor.getParameterTypes(); ResolvedMember realMember = null; for (int i = 0; realMember==null && i < aspectMethods.length; i++) { ResolvedMember member = aspectMethods[i]; if (member.getName().equals(lookingFor.getName())){ UnresolvedType [] memberParams = member.getGenericParameterTypes(); if (memberParams.length == lookingForParams.length){ if (debug) System.err.println("Reviewing potential candidates: "+member); boolean matchOK = true; // If not related to a ctor ITD then the name is enough to confirm we have the // right one. If it is ctor related we need to check the params all match, although // only the erasure. if (isCtorRelated) { for (int j = 0; j < memberParams.length && matchOK; j++){ ResolvedType pMember = memberParams[j].resolve(world); ResolvedType pLookingFor = lookingForParams[j].resolve(world); if (pMember.isTypeVariableReference()) pMember = ((TypeVariableReference)pMember).getTypeVariable().getFirstBound().resolve(world); if (pMember.isParameterizedType() || pMember.isGenericType()) pMember = pMember.getRawType().resolve(aspectType.getWorld()); if (pLookingFor.isTypeVariableReference()) pLookingFor = ((TypeVariableReference)pLookingFor).getTypeVariable().getFirstBound().resolve(world); if (pLookingFor.isParameterizedType() || pLookingFor.isGenericType()) pLookingFor = pLookingFor.getRawType().resolve(world); if (debug) System.err.println("Comparing parameter "+j+" member="+pMember+" lookingFor="+pLookingFor); if (!pMember.equals(pLookingFor)){ matchOK=false; } } } if (matchOK) realMember = member; } } } if (debug && realMember==null) System.err.println("Didn't find a match"); return realMember; } private void addNeededSuperCallMethods( BcelClassWeaver weaver, ResolvedType onType, Set neededSuperCalls) { LazyClassGen gen = weaver.getLazyClassGen(); for (Iterator iter = neededSuperCalls.iterator(); iter.hasNext();) { ResolvedMember superMethod = (ResolvedMember) iter.next(); if (weaver.addDispatchTarget(superMethod)) { //System.err.println("super type: " + superMethod.getDeclaringType() + ", " + gen.getType()); boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType()); String dispatchName; if (isSuper) dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName()); else dispatchName = NameMangler.protectedDispatchMethod( onType, superMethod.getName()); LazyMethodGen dispatcher = makeDispatcher( gen, dispatchName, superMethod, weaver.getWorld(), isSuper); weaver.addLazyMethodGen(dispatcher); } } } private void signalError(String msgid,BcelClassWeaver weaver,UnresolvedType onType) { IMessage msg = MessageUtil.error( WeaverMessages.format(msgid,onType.getName()),getSourceLocation()); weaver.getWorld().getMessageHandler().handleMessage(msg); } private boolean mungeNewConstructor( BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) { final LazyClassGen currentClass = weaver.getLazyClassGen(); final InstructionFactory fact = currentClass.getFactory(); ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor(); ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld()); if (onType.isRawType()) onType = onType.getGenericType(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } if (! onType.equals(currentClass.getType())) return false; ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor(); //int declaredParameterCount = newConstructorTypeMunger.getDeclaredParameterCount(); LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember); mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(),Shadow.ConstructorExecution,true); // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ ResolvedMember interMethodDispatcher =AjcMemberMaker.postIntroducedConstructor(aspectType,onType,newConstructorTypeMunger.getSignature().getParameterTypes()); AnnotationX annotationsOnRealMember[] = null; ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType,interMethodDispatcher,true); if (realMember==null) throw new BCException("Couldn't find ITD holder member '"+ interMethodDispatcher+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); mg.addAnnotation(new AnnotationX(ag.getAnnotation(),weaver.getWorld())); } } // the below loop fixes the very special (and very stupid) // case where an aspect declares an annotation // on an ITD it declared on itself. List allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); for (Iterator i = allDecams.iterator(); i.hasNext();){ DeclareAnnotation decaMC = (DeclareAnnotation) i.next(); if (decaMC.matches(explicitConstructor,weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotationX()); } } } currentClass.addMethodGen(mg); //weaver.addLazyMethodGen(freshConstructor); InstructionList body = mg.getBody(); // add to body: push arts for call to pre, from actual args starting at 1 (skipping this), going to // declared argcount + 1 UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes(); Type[] paramTypes = mg.getArgumentTypes(); int frameIndex = 1; for (int i = 0, len = declaredParams.length; i < len; i++) { body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex)); frameIndex += paramTypes[i].getSize(); } // do call to pre Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams); body.append(Utility.createInvoke(fact, null, preMethod)); // create a local, and store return pre stuff into it. int arraySlot = mg.allocateLocal(1); body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot)); // put this on the stack body.append(InstructionConstants.ALOAD_0); // unpack pre args onto stack UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes(); for (int i = 0, len = superParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, i)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i]))); } // call super/this body.append(Utility.createInvoke(fact, null, explicitConstructor)); // put this back on the stack body.append(InstructionConstants.ALOAD_0); // unpack params onto stack Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams); UnresolvedType[] postParamTypes = postMethod.getParameterTypes(); for (int i = 1, len = postParamTypes.length; i < len; i++) { body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot)); body.append(Utility.createConstant(fact, superParamTypes.length + i-1)); body.append(InstructionFactory.createArrayLoad(Type.OBJECT)); body.append( Utility.createConversion( fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i]))); } // call post body.append(Utility.createInvoke(fact, null, postMethod)); // don't forget to return!! body.append(InstructionConstants.RETURN); return true; } private static LazyMethodGen makeDispatcher( LazyClassGen onGen, String dispatchName, ResolvedMember superMethod, BcelWorld world, boolean isSuper) { Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType()); int modifiers = Modifier.PUBLIC; if (onGen.isInterface()) modifiers |= Modifier.ABSTRACT; LazyMethodGen mg = new LazyMethodGen( modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod.getExceptions()), onGen); InstructionList body = mg.getBody(); if (onGen.isInterface()) return mg; // assert (!superMethod.isStatic()) InstructionFactory fact = onGen.getFactory(); int pos = 0; body.append(InstructionFactory.createThis()); pos++; for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); pos+=paramType.getSize(); } if (isSuper) { body.append(Utility.createSuperInvoke(fact, world, superMethod)); } else { body.append(Utility.createInvoke(fact, world, superMethod)); } body.append(InstructionFactory.createReturn(returnType)); return mg; } private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) { /*ResolvedMember initMethod = */munger.getInitMethod(aspectType); LazyClassGen gen = weaver.getLazyClassGen(); ResolvedMember field = munger.getSignature(); ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(),munger.getSourceLocation()); if (onType.isRawType()) onType = onType.getGenericType(); boolean onInterface = onType.isInterface(); if (onType.isAnnotation()) { signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED,weaver,onType); return false; } if (onType.isEnum()) { signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED,weaver,onType); return false; } ResolvedMember interMethodBody = munger.getInitMethod(aspectType); AnnotationX annotationsOnRealMember[] = null; // pr98901 // For copying the annotations across, we have to discover the real member in the aspect // which is holding them. if (weaver.getWorld().isInJava5Mode()){ // the below line just gets the method with the same name in aspectType.getDeclaredMethods(); ResolvedType toLookOn = aspectType; if (aspectType.isRawType()) toLookOn = aspectType.getGenericType(); ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn,interMethodBody,false); if (realMember==null) throw new BCException("Couldn't find ITD init member '"+ interMethodBody+"' on aspect "+aspectType); annotationsOnRealMember = realMember.getAnnotations(); } if (onType.equals(gen.getType())) { if (onInterface) { ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); gen.addMethodGen(mg); LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType)); gen.addMethodGen(mg1); } else { weaver.addInitializer(this); FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldClassField(field, aspectType)); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); fg.addAnnotation(ag); } } gen.addField(fg.getField(),getSourceLocation()); } return true; } else if (onInterface && gen.getType().isTopmostImplementor(onType)) { // wew know that we can't be static since we don't allow statics on interfaces if (field.isStatic()) throw new RuntimeException("unimplemented"); weaver.addInitializer(this); //System.err.println("impl body on " + gen.getType() + " for " + munger); Type fieldType = BcelWorld.makeBcelType(field.getType()); FieldGen fg = makeFieldGen(gen,AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType)); if (annotationsOnRealMember!=null) { for (int i = 0; i < annotationsOnRealMember.length; i++) { AnnotationX annotationX = annotationsOnRealMember[i]; Annotation a = annotationX.getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a,weaver.getLazyClassGen().getConstantPoolGen(),true); fg.addAnnotation(ag); } } gen.addField(fg.getField(),getSourceLocation()); //this uses a shadow munger to add init method to constructors //weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod)); ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType()/*onType*/, aspectType); LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter); InstructionList il = new InstructionList(); InstructionFactory fact = gen.getFactory(); if (field.isStatic()) { il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC)); } else { il.append(InstructionConstants.ALOAD_0); il.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD)); } il.append(InstructionFactory.createReturn(fieldType)); mg.getBody().insert(il); gen.addMethodGen(mg); // Check if we need bridge methods for the field getter and setter if (munger.getDeclaredSignature()!=null) { // is this munger a parameterized form of some original munger? ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,munger.getSignature().getDeclaringType().resolve(getWorld()),false,munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature().equals(munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true; if (toBridgeTo!=null && needsbridging) { ResolvedMember bridgingGetter = AjcMemberMaker.interFieldInterfaceGetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver,gen,itdfieldGetter,bridgingGetter); } } ResolvedMember itdfieldSetter = AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType); LazyMethodGen mg1 = makeMethodGen(gen, itdfieldSetter); InstructionList il1 = new InstructionList(); if (field.isStatic()) { il1.append(InstructionFactory.createLoad(fieldType, 0)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTSTATIC)); } else { il1.append(InstructionConstants.ALOAD_0); il1.append(InstructionFactory.createLoad(fieldType, 1)); il1.append(fact.createFieldAccess( gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD)); } il1.append(InstructionFactory.createReturn(Type.VOID)); mg1.getBody().insert(il1); gen.addMethodGen(mg1); if (munger.getDeclaredSignature()!=null) { ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,munger.getSignature().getDeclaringType().resolve(getWorld()),false,munger.getTypeVariableAliases()); boolean needsbridging = false; if (!toBridgeTo.getReturnType().getErasureSignature().equals(munger.getSignature().getReturnType().getErasureSignature())) needsbridging = true; if (toBridgeTo!=null && needsbridging) { ResolvedMember bridgingSetter = AjcMemberMaker.interFieldInterfaceSetter(toBridgeTo, gen.getType(), aspectType); createBridgeMethodForITDF(weaver, gen, itdfieldSetter, bridgingSetter); } } return true; } else { return false; } } // FIXME asc combine with other createBridge.. method in this class, avoid the duplication... private void createBridgeMethodForITDF(BcelClassWeaver weaver, LazyClassGen gen, ResolvedMember itdfieldSetter, ResolvedMember bridgingSetter) { InstructionFactory fact; LazyMethodGen bridgeMethod = makeMethodGen(gen,bridgingSetter); Type[] paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes()); Type[] bridgingToParms = BcelWorld.makeBcelTypes(itdfieldSetter.getParameterTypes()); Type returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType()); InstructionList body = bridgeMethod.getBody(); fact = gen.getFactory(); int pos = 0; if (!bridgingSetter.isStatic()) { body.append(InstructionFactory.createThis()); pos++; } for (int i = 0, len = paramTypes.length; i < len; i++) { Type paramType = paramTypes[i]; body.append(InstructionFactory.createLoad(paramType, pos)); if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(itdfieldSetter.getParameterTypes()[i].getErasureSignature()) ) { // une cast est required System.err.println("Putting in cast from "+paramType+" to "+bridgingToParms[i]); body.append(fact.createCast(paramType,bridgingToParms[i])); } pos+=paramType.getSize(); } body.append(Utility.createInvoke(fact, weaver.getWorld(), itdfieldSetter)); body.append(InstructionFactory.createReturn(returnType)); gen.addMethodGen(bridgeMethod); } public ConcreteTypeMunger parameterizedFor(ResolvedType target) { return new BcelTypeMunger(munger.parameterizedFor(target),aspectType); } /** * Returns a list of type variable aliases used in this munger. For example, if the * ITD is 'int I<A,B>.m(List<A> las,List<B> lbs) {}' then this returns a list containing * the strings "A" and "B". */ public List /*String*/ getTypeVariableAliases() { return munger.getTypeVariableAliases(); } }
123,553
Bug 123553 Can't use named pointcut in advice decl. in generic aspect
When defining a generic aspect with a paramterized PC, using that PC in an advice declaration causes an 'incompatible type' error. Example: public abstract aspect GenericAspect<Par1> { abstract pointcut checkpoint(Par1 par1); // advice declaration causes error after(Par1 par1): checkpoint(par1) {// do something} } Using 1.3.0.20051220093604 and AspectJ 1.5.0, the compiler complains: "incompatible type, expected java.lang.Object found BindingTypePattern(TPar1;, 0). Check the type specified in your pointcut" Since it is possible to paramterize a named PC in subaspects: public abstract aspect GenericAspect<Par1> { abstract pointcut checkpoint(Par1 par1); } public aspect SubAspect1 extends GenericAspect<Main>{ pointcut checkpoint(Main main): call(void Main.test()) && target(main); after (Main main): checkpoint(main) { System.out.println("Caught by 1."); } } public aspect SubAspect2 extends GenericAspect<Main2>{ pointcut checkpoint(Main2 main): call(void Main2.test()) && target(main); after (Main2 main): checkpoint(main) { System.out.println("Caught by 2."); } } ... and since it is possible to use generic PC utilizing unnamed PCs in a generic aspect: public abstract aspect GenericAspect<Par1> { // works after(Par1 par1): call(void Par1.test()) && target(par1) {// something } } ... it seems that this is a bug.
resolved fixed
1f1ace1
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-17T19:41:52Z
2006-01-12T07:13:20Z
tests/bugs151/pr123553/A.java
123,553
Bug 123553 Can't use named pointcut in advice decl. in generic aspect
When defining a generic aspect with a paramterized PC, using that PC in an advice declaration causes an 'incompatible type' error. Example: public abstract aspect GenericAspect<Par1> { abstract pointcut checkpoint(Par1 par1); // advice declaration causes error after(Par1 par1): checkpoint(par1) {// do something} } Using 1.3.0.20051220093604 and AspectJ 1.5.0, the compiler complains: "incompatible type, expected java.lang.Object found BindingTypePattern(TPar1;, 0). Check the type specified in your pointcut" Since it is possible to paramterize a named PC in subaspects: public abstract aspect GenericAspect<Par1> { abstract pointcut checkpoint(Par1 par1); } public aspect SubAspect1 extends GenericAspect<Main>{ pointcut checkpoint(Main main): call(void Main.test()) && target(main); after (Main main): checkpoint(main) { System.out.println("Caught by 1."); } } public aspect SubAspect2 extends GenericAspect<Main2>{ pointcut checkpoint(Main2 main): call(void Main2.test()) && target(main); after (Main2 main): checkpoint(main) { System.out.println("Caught by 2."); } } ... and since it is possible to use generic PC utilizing unnamed PCs in a generic aspect: public abstract aspect GenericAspect<Par1> { // works after(Par1 par1): call(void Par1.test()) && target(par1) {// something } } ... it seems that this is a bug.
resolved fixed
1f1ace1
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-17T19:41:52Z
2006-01-12T07:13:20Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import java.util.List; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.Relationship; import org.aspectj.systemtest.ajc150.GenericsTests; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");} public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");} public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");} public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");} public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");} //public void testExposingWithintype_enh123423() { runTest("exposing withintype");} //public void testMissingImport_pr127299() { runTest("missing import gives funny message");} public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");} public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); } public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); } public void testMixingNumbersOfTypeParameters_pr125080() { runTest("mixing numbers of type parameters"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;"); } public void testMixingNumbersOfTypeParameters_pr125080_2() { runTest("mixing numbers of type parameters - 2"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;"); } public void testIProgramElementMethods_pr125295() { runTest("new IProgramElement methods"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForType("pkg","foo"); assertNotNull("Couldn't find 'foo' element in the tree",pe); // check that the defaults return the fully qualified arg assertEquals("foo(int, java.lang.Object)",pe.toLabelString()); assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString()); assertEquals("foo(int, java.lang.Object)",pe.toSignatureString()); // check that can get hold of the non qualified args assertEquals("foo(int, Object)",pe.toLabelString(false)); assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false)); assertEquals("foo(int, Object)",pe.toSignatureString(false)); IProgramElement pe2 = top.findElementForType("pkg","printParameters"); assertNotNull("Couldn't find 'printParameters' element in the tree",pe2); // the argument is org.aspectj.lang.JoinPoint, check that this is added assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty()); } public void testParameterizedEnum_pr126316() { runTest("E extends Enum(E) again"); } public void testSwallowedException() { runTest("swallowed exceptions"); } public void testSwallowedExceptionIgnored() { runTest("swallowed exceptions with xlint"); } /* * @AspectJ bugs and enhancements */ // public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { // runTest("inherit adivce with this() and thisJoinPoint"); // } public void testAtAspectInheritsAbstractPointcut_pr125810 () { runTest("warning when inherited pointcut not made concrete"); } public void testAtAspectDEOWInStructureModel_pr120356() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("@AJ deow appear correctly when structure model is generated"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // get the IProgramElements corresponding to the @DeclareWarning statement // and the method it matches. IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"warningMethod()"); assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE); IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"warning"); assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE); // check that the method has a matches declare relationship with @DeclareWarning List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE); assertNotNull("warningMethod should have some relationships but does not",matches); assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1); List matchesTargets = ((Relationship)matches.get(0)).getTargets(); assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0)); assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label " + target.toLabelString(),atDeclareWarningIPE,target); // check that the @DeclareWarning has a matches relationship with the warningMethod List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE); assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy); assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1); List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets(); assertTrue("@DeclareWarning 'matched by' relationship should have one target " + "but has " + matchedByTargets.size(), matchedByTargets.size() == 1); IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0)); assertEquals("target of relationship should be the warningMethod but is IPE with label " + matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget); // get the IProgramElements corresponding to the @DeclareError statement // and the method it matches. IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"badMethod()"); assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE); IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"error"); assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE); // check that the @DeclareError has a matches relationship with the badMethod List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE); assertNotNull("@DeclareError should have some relationships but does not",matchedByE); assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1); List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets(); assertTrue("@DeclareError 'matched by' relationship should have one target " + "but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1); IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0)); assertEquals("target of relationship should be the badMethod but is IPE with label " + matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE); } public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() { runTest("@AJ no NPE with deow when structure model isn't generated"); } public void testAtAspectWithoutJoinPointImport_pr121616() { runTest("@AJ without JoinPoint import"); } public void testAtAspectDeclareParentsRetainsFieldState_pr122370() { runTest("@AJ declare parents retains field state"); } /* * Load-time weaving bugs and enhancements */ public void testEmptyPointcutInAtAspectJ_pr125475 () { runTest("define empty pointcut using an annotation"); } public void testEmptyPointcutInAtAspectJ_pr125475_2() { runTest("define empty pointcut using an annotation - 2"); } public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () { runTest("define empty pointcut using aop.xml"); } public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () { runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent"); } ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
128,699
Bug 128699 Incorrect error on "declare" statements
The error associated with the declare construct is incorrect. The current message is: "expected one of error, warning, parents, soft, dominates" dominates should be changed to "precendence" and new annotation related declararions should be mentioned. Here is a suggestion: "expected one of error, warning, parents, soft, precedence, @type, @method, @constructor, @field"
resolved fixed
f95d2c9
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-20T19:32:59Z
2006-02-20T18:26:40Z
weaver/src/org/aspectj/weaver/patterns/PatternParser.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer many updates since.... * ******************************************************************/ package org.aspectj.weaver.patterns; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.Member; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.internal.tools.PointcutDesignatorHandlerBasedPointcut; import org.aspectj.weaver.reflect.ReflectionWorld; import org.aspectj.weaver.tools.ContextBasedMatcher; import org.aspectj.weaver.tools.PointcutDesignatorHandler; //XXX doesn't handle errors for extra tokens very well (sometimes ignores) public class PatternParser { private ITokenSource tokenSource; private ISourceContext sourceContext; /** not thread-safe, but this class is not intended to be... */ private boolean allowHasTypePatterns = false; /** extension handlers used in weaver tools API only */ private Set pointcutDesignatorHandlers = Collections.EMPTY_SET; private ReflectionWorld world; /** * Constructor for PatternParser. */ public PatternParser(ITokenSource tokenSource) { super(); this.tokenSource = tokenSource; this.sourceContext = tokenSource.getSourceContext(); } /** only used by weaver tools API */ public void setPointcutDesignatorHandlers(Set handlers, ReflectionWorld world) { this.pointcutDesignatorHandlers = handlers; this.world = world; } public PerClause maybeParsePerClause() { IToken tok = tokenSource.peek(); if (tok == IToken.EOF) return null; if (tok.isIdentifier()) { String name = tok.getString(); if (name.equals("issingleton")) { return parsePerSingleton(); } else if (name.equals("perthis")) { return parsePerObject(true); } else if (name.equals("pertarget")) { return parsePerObject(false); } else if (name.equals("percflow")) { return parsePerCflow(false); } else if (name.equals("percflowbelow")) { return parsePerCflow(true); } else if (name.equals("pertypewithin")) { // PTWIMPL Parse the pertypewithin clause return parsePerTypeWithin(); } else { return null; } } return null; } private PerClause parsePerCflow(boolean isBelow) { parseIdentifier(); eat("("); Pointcut entry = parsePointcut(); eat(")"); return new PerCflow(entry, isBelow); } private PerClause parsePerObject(boolean isThis) { parseIdentifier(); eat("("); Pointcut entry = parsePointcut(); eat(")"); return new PerObject(entry, isThis); } private PerClause parsePerTypeWithin() { parseIdentifier(); eat("("); TypePattern withinTypePattern = parseTypePattern(); eat(")"); return new PerTypeWithin(withinTypePattern); } private PerClause parsePerSingleton() { parseIdentifier(); eat("("); eat(")"); return new PerSingleton(); } public Declare parseDeclare() { int startPos = tokenSource.peek().getStart(); eatIdentifier("declare"); String kind = parseIdentifier(); Declare ret; if (kind.equals("error")) { eat(":"); ret = parseErrorOrWarning(true); } else if (kind.equals("warning")) { eat(":"); ret = parseErrorOrWarning(false); } else if (kind.equals("precedence")) { eat(":"); ret = parseDominates(); } else if (kind.equals("dominates")) { throw new ParserException("name changed to declare precedence", tokenSource.peek(-2)); } else if (kind.equals("parents")) { ret = parseParents(); } else if (kind.equals("soft")) { eat(":"); ret = parseSoft(); } else { throw new ParserException("expected one of error, warning, parents, soft, dominates", tokenSource.peek(-1)); } int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } public Declare parseDeclareAnnotation() { int startPos = tokenSource.peek().getStart(); eatIdentifier("declare"); eat("@"); String kind = parseIdentifier(); eat(":"); Declare ret; if (kind.equals("type")) { ret = parseDeclareAtType(); } else if (kind.equals("method")) { ret = parseDeclareAtMethod(true); } else if (kind.equals("field")) { ret = parseDeclareAtField(); } else if (kind.equals("constructor")) { ret = parseDeclareAtMethod(false); } else { throw new ParserException("one of type, method, field, constructor",tokenSource.peek(-1)); } eat(";"); int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } public DeclareAnnotation parseDeclareAtType() { allowHasTypePatterns = true; TypePattern p = parseTypePattern(); allowHasTypePatterns = false; return new DeclareAnnotation(DeclareAnnotation.AT_TYPE,p); } public DeclareAnnotation parseDeclareAtMethod(boolean isMethod) { SignaturePattern sp = parseMethodOrConstructorSignaturePattern(); boolean isConstructorPattern = (sp.getKind() == Member.CONSTRUCTOR); if (isMethod && isConstructorPattern) { throw new ParserException("method signature pattern",tokenSource.peek(-1)); } if (!isMethod && !isConstructorPattern) { throw new ParserException("constructor signature pattern",tokenSource.peek(-1)); } if (isConstructorPattern) return new DeclareAnnotation(DeclareAnnotation.AT_CONSTRUCTOR,sp); else return new DeclareAnnotation(DeclareAnnotation.AT_METHOD,sp); } public DeclareAnnotation parseDeclareAtField() { return new DeclareAnnotation(DeclareAnnotation.AT_FIELD,parseFieldSignaturePattern()); } public DeclarePrecedence parseDominates() { List l = new ArrayList(); do { l.add(parseTypePattern()); } while (maybeEat(",")); return new DeclarePrecedence(l); } private Declare parseParents() { /* * simplified design requires use of raw types for declare parents, no generic spec. allowed * String[] typeParameters = maybeParseSimpleTypeVariableList(); */ eat(":"); allowHasTypePatterns = true; TypePattern p = parseTypePattern(false); allowHasTypePatterns = false; IToken t = tokenSource.next(); if (!(t.getString().equals("extends") || t.getString().equals("implements"))) { throw new ParserException("extends or implements", t); } boolean isExtends = t.getString().equals("extends"); List l = new ArrayList(); do { l.add(parseTypePattern()); } while (maybeEat(",")); //XXX somewhere in the chain we need to enforce that we have only ExactTypePatterns DeclareParents decp = new DeclareParents(p, l,isExtends); return decp; } private Declare parseSoft() { TypePattern p = parseTypePattern(); eat(":"); Pointcut pointcut = parsePointcut(); return new DeclareSoft(p, pointcut); } private Declare parseErrorOrWarning(boolean isError) { Pointcut pointcut = parsePointcut(); eat(":"); String message = parsePossibleStringSequence(true); return new DeclareErrorOrWarning(isError, pointcut, message); } public Pointcut parsePointcut() { Pointcut p = parseAtomicPointcut(); if (maybeEat("&&")) { p = new AndPointcut(p, parseNotOrPointcut()); } if (maybeEat("||")) { p = new OrPointcut(p, parsePointcut()); } return p; } private Pointcut parseNotOrPointcut() { Pointcut p = parseAtomicPointcut(); if (maybeEat("&&")) { p = new AndPointcut(p, parsePointcut()); } return p; } private Pointcut parseAtomicPointcut() { if (maybeEat("!")) { int startPos = tokenSource.peek(-1).getStart(); Pointcut p = new NotPointcut(parseAtomicPointcut(), startPos); return p; } if (maybeEat("(")) { Pointcut p = parsePointcut(); eat(")"); return p; } if (maybeEat("@")) { int startPos = tokenSource.peek().getStart(); Pointcut p = parseAnnotationPointcut(); int endPos = tokenSource.peek(-1).getEnd(); p.setLocation(sourceContext, startPos, endPos); return p; } int startPos = tokenSource.peek().getStart(); Pointcut p = parseSinglePointcut(); int endPos = tokenSource.peek(-1).getEnd(); p.setLocation(sourceContext, startPos, endPos); return p; } public Pointcut parseSinglePointcut() { int start = tokenSource.getIndex(); IToken t = tokenSource.peek(); Pointcut p = t.maybeGetParsedPointcut(); if (p != null) { tokenSource.next(); return p; } String kind = parseIdentifier(); // IToken possibleTypeVariableToken = tokenSource.peek(); // String[] typeVariables = maybeParseSimpleTypeVariableList(); if (kind.equals("execution") || kind.equals("call") || kind.equals("get") || kind.equals("set")) { p = parseKindedPointcut(kind); } else if (kind.equals("args")) { p = parseArgsPointcut(); } else if (kind.equals("this")) { p = parseThisOrTargetPointcut(kind); } else if (kind.equals("target")) { p = parseThisOrTargetPointcut(kind); } else if (kind.equals("within")) { p = parseWithinPointcut(); } else if (kind.equals("withincode")) { p = parseWithinCodePointcut(); } else if (kind.equals("cflow")) { p = parseCflowPointcut(false); } else if (kind.equals("cflowbelow")) { p = parseCflowPointcut(true); } else if (kind.equals("adviceexecution")) { eat("("); eat(")"); p = new KindedPointcut(Shadow.AdviceExecution, new SignaturePattern(Member.ADVICE, ModifiersPattern.ANY, TypePattern.ANY, TypePattern.ANY, NamePattern.ANY, TypePatternList.ANY, ThrowsPattern.ANY, AnnotationTypePattern.ANY)); } else if (kind.equals("handler")) { eat("("); TypePattern typePat = parseTypePattern(false); eat(")"); p = new HandlerPointcut(typePat); } else if (kind.equals("initialization")) { eat("("); SignaturePattern sig = parseConstructorSignaturePattern(); eat(")"); p = new KindedPointcut(Shadow.Initialization, sig); } else if (kind.equals("staticinitialization")) { eat("("); TypePattern typePat = parseTypePattern(false); eat(")"); p = new KindedPointcut(Shadow.StaticInitialization, new SignaturePattern(Member.STATIC_INITIALIZATION, ModifiersPattern.ANY, TypePattern.ANY, typePat, NamePattern.ANY, TypePatternList.EMPTY, ThrowsPattern.ANY,AnnotationTypePattern.ANY)); } else if (kind.equals("preinitialization")) { eat("("); SignaturePattern sig = parseConstructorSignaturePattern(); eat(")"); p = new KindedPointcut(Shadow.PreInitialization, sig); } else if (kind.equals("if")) { // @style support allows if(), if(true), if(false) eat("("); if (maybeEatIdentifier("true")) { eat(")"); p = new IfPointcut.IfTruePointcut(); } else if (maybeEatIdentifier("false")) { eat(")"); p = new IfPointcut.IfFalsePointcut(); } else { eat(")"); // TODO - Alex has some token stuff going on here to get a readable name in place of ""... p = new IfPointcut(""); } } else { boolean matchedByExtensionDesignator = false; // see if a registered handler wants to parse it, otherwise // treat as a reference pointcut for (Iterator iter = this.pointcutDesignatorHandlers.iterator(); iter.hasNext();) { PointcutDesignatorHandler pcd = (PointcutDesignatorHandler) iter.next(); if (pcd.getDesignatorName().equals(kind)) { p = parseDesignatorPointcut(pcd); matchedByExtensionDesignator = true; } } if (!matchedByExtensionDesignator) { tokenSource.setIndex(start); p = parseReferencePointcut(); } } return p; } private void assertNoTypeVariables(String[] tvs, String errorMessage,IToken token) { if ( tvs != null ) throw new ParserException(errorMessage,token); } public Pointcut parseAnnotationPointcut() { int start = tokenSource.getIndex(); IToken t = tokenSource.peek(); String kind = parseIdentifier(); IToken possibleTypeVariableToken = tokenSource.peek(); String[] typeVariables = maybeParseSimpleTypeVariableList(); if (typeVariables != null) { String message = "("; assertNoTypeVariables(typeVariables, message, possibleTypeVariableToken); } tokenSource.setIndex(start); if (kind.equals("annotation")) { return parseAtAnnotationPointcut(); } else if (kind.equals("args")) { return parseArgsAnnotationPointcut(); } else if (kind.equals("this") || kind.equals("target")) { return parseThisOrTargetAnnotationPointcut(); } else if (kind.equals("within")) { return parseWithinAnnotationPointcut(); } else if (kind.equals("withincode")) { return parseWithinCodeAnnotationPointcut(); } throw new ParserException("pointcut name", t); } private Pointcut parseAtAnnotationPointcut() { parseIdentifier(); eat("("); if (maybeEat(")")) { throw new ParserException("@AnnotationName or parameter", tokenSource.peek()); } ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern(); eat(")"); return new AnnotationPointcut(type); } private SignaturePattern parseConstructorSignaturePattern() { SignaturePattern ret = parseMethodOrConstructorSignaturePattern(); if (ret.getKind() == Member.CONSTRUCTOR) return ret; throw new ParserException("constructor pattern required, found method pattern", ret); } private Pointcut parseWithinCodePointcut() { //parseIdentifier(); eat("("); SignaturePattern sig = parseMethodOrConstructorSignaturePattern(); eat(")"); return new WithincodePointcut(sig); } private Pointcut parseCflowPointcut(boolean isBelow) { //parseIdentifier(); eat("("); Pointcut entry = parsePointcut(); eat(")"); return new CflowPointcut(entry, isBelow, null); } /** * Method parseWithinPointcut. * @return Pointcut */ private Pointcut parseWithinPointcut() { //parseIdentifier(); eat("("); TypePattern type = parseTypePattern(); eat(")"); return new WithinPointcut(type); } /** * Method parseThisOrTargetPointcut. * @return Pointcut */ private Pointcut parseThisOrTargetPointcut(String kind) { eat("("); TypePattern type = parseTypePattern(); eat(")"); return new ThisOrTargetPointcut(kind.equals("this"), type); } private Pointcut parseThisOrTargetAnnotationPointcut() { String kind = parseIdentifier(); eat("("); if (maybeEat(")")) { throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek()); } ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern(); eat(")"); return new ThisOrTargetAnnotationPointcut(kind.equals("this"),type); } private Pointcut parseWithinAnnotationPointcut() { String kind = parseIdentifier(); eat("("); if (maybeEat(")")) { throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek()); } AnnotationTypePattern type = parseAnnotationNameOrVarTypePattern(); eat(")"); return new WithinAnnotationPointcut(type); } private Pointcut parseWithinCodeAnnotationPointcut() { String kind = parseIdentifier(); eat("("); if (maybeEat(")")) { throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek()); } ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern(); eat(")"); return new WithinCodeAnnotationPointcut(type); } /** * Method parseArgsPointcut. * @return Pointcut */ private Pointcut parseArgsPointcut() { //parseIdentifier(); TypePatternList arguments = parseArgumentsPattern(); return new ArgsPointcut(arguments); } private Pointcut parseArgsAnnotationPointcut() { parseIdentifier(); AnnotationPatternList arguments = parseArgumentsAnnotationPattern(); return new ArgsAnnotationPointcut(arguments); } private Pointcut parseReferencePointcut() { TypePattern onType = parseTypePattern(); NamePattern name = null; if (onType.typeParameters.size() > 0) { eat("."); name = parseNamePattern(); } else { name = tryToExtractName(onType); } if (name == null) { throw new ParserException("name pattern", tokenSource.peek()); } if (onType.toString().equals("")) { onType = null; } String simpleName = name.maybeGetSimpleName(); if (simpleName == null) { throw new ParserException("(",tokenSource.peek(-1)); } TypePatternList arguments = parseArgumentsPattern(); return new ReferencePointcut(onType, simpleName, arguments); } private Pointcut parseDesignatorPointcut(PointcutDesignatorHandler pcdHandler) { eat("("); int parenCount = 1; StringBuffer pointcutBody = new StringBuffer(); while (parenCount > 0) { if (maybeEat("(")) { parenCount++; pointcutBody.append("("); } else if (maybeEat(")")) { parenCount--; if (parenCount > 0) { pointcutBody.append(")"); } } else { pointcutBody.append(nextToken().getString()); } } ContextBasedMatcher pcExpr = pcdHandler.parse(pointcutBody.toString()); return new PointcutDesignatorHandlerBasedPointcut(pcExpr,world); } public List parseDottedIdentifier() { List ret = new ArrayList(); ret.add(parseIdentifier()); while (maybeEat(".")) { ret.add(parseIdentifier()); } return ret; } private KindedPointcut parseKindedPointcut(String kind) { eat("("); SignaturePattern sig; Shadow.Kind shadowKind = null; if (kind.equals("execution")) { sig = parseMethodOrConstructorSignaturePattern(); if (sig.getKind() == Member.METHOD) { shadowKind = Shadow.MethodExecution; } else if (sig.getKind() == Member.CONSTRUCTOR) { shadowKind = Shadow.ConstructorExecution; } } else if (kind.equals("call")) { sig = parseMethodOrConstructorSignaturePattern(); if (sig.getKind() == Member.METHOD) { shadowKind = Shadow.MethodCall; } else if (sig.getKind() == Member.CONSTRUCTOR) { shadowKind = Shadow.ConstructorCall; } } else if (kind.equals("get")) { sig = parseFieldSignaturePattern(); shadowKind = Shadow.FieldGet; } else if (kind.equals("set")) { sig = parseFieldSignaturePattern(); shadowKind = Shadow.FieldSet; } else { throw new ParserException("bad kind: " + kind, tokenSource.peek()); } eat(")"); return new KindedPointcut(shadowKind, sig); } public TypePattern parseTypePattern() { return parseTypePattern(false); } public TypePattern parseTypePattern(boolean insideTypeParameters) { TypePattern p = parseAtomicTypePattern(insideTypeParameters); if (maybeEat("&&")) { p = new AndTypePattern(p, parseNotOrTypePattern(insideTypeParameters)); } if (maybeEat("||")) { p = new OrTypePattern(p, parseTypePattern(insideTypeParameters)); } return p; } private TypePattern parseNotOrTypePattern(boolean insideTypeParameters) { TypePattern p = parseAtomicTypePattern(insideTypeParameters); if (maybeEat("&&")) { p = new AndTypePattern(p, parseTypePattern(insideTypeParameters)); } return p; } private TypePattern parseAtomicTypePattern(boolean insideTypeParameters) { AnnotationTypePattern ap = maybeParseAnnotationPattern(); if (maybeEat("!")) { //int startPos = tokenSource.peek(-1).getStart(); //??? we lose source location for true start of !type TypePattern p = new NotTypePattern(parseAtomicTypePattern(insideTypeParameters)); p = setAnnotationPatternForTypePattern(p,ap); return p; } if (maybeEat("(")) { TypePattern p = parseTypePattern(insideTypeParameters); p = setAnnotationPatternForTypePattern(p,ap); eat(")"); boolean isVarArgs = maybeEat("..."); if (isVarArgs) p.setIsVarArgs(isVarArgs); boolean isIncludeSubtypes = maybeEat("+"); if (isIncludeSubtypes) p.includeSubtypes = true; // need the test because (A+) should not set subtypes to false! return p; } int startPos = tokenSource.peek().getStart(); TypePattern p = parseSingleTypePattern(insideTypeParameters); int endPos = tokenSource.peek(-1).getEnd(); p = setAnnotationPatternForTypePattern(p,ap); p.setLocation(sourceContext, startPos, endPos); return p; } private TypePattern setAnnotationPatternForTypePattern(TypePattern t, AnnotationTypePattern ap) { TypePattern ret = t; if (ap != AnnotationTypePattern.ANY) { if (t == TypePattern.ANY) { ret = new WildTypePattern(new NamePattern[] {NamePattern.ANY},false,0,false,null); } if (t.annotationPattern == AnnotationTypePattern.ANY) { ret.setAnnotationTypePattern(ap); } else { ret.setAnnotationTypePattern(new AndAnnotationTypePattern(ap,t.annotationPattern)); //??? } } return ret; } public AnnotationTypePattern maybeParseAnnotationPattern() { AnnotationTypePattern ret = AnnotationTypePattern.ANY; AnnotationTypePattern nextPattern = null; while ((nextPattern = maybeParseSingleAnnotationPattern()) != null) { if (ret == AnnotationTypePattern.ANY) { ret = nextPattern; } else { ret = new AndAnnotationTypePattern(ret,nextPattern); } } return ret; } public AnnotationTypePattern maybeParseSingleAnnotationPattern() { AnnotationTypePattern ret = null; // LALR(2) - fix by making "!@" a single token int startIndex = tokenSource.getIndex(); if (maybeEat("!")) { if (maybeEat("@")) { if (maybeEat("(")) { TypePattern p = parseTypePattern(); ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p)); eat(")"); return ret; } else { TypePattern p = parseSingleTypePattern(); ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p)); return ret; } } else { tokenSource.setIndex(startIndex); // not for us! return ret; } } if (maybeEat("@")) { if (maybeEat("(")) { TypePattern p = parseTypePattern(); ret = new WildAnnotationTypePattern(p); eat(")"); return ret; } else { TypePattern p = parseSingleTypePattern(); ret = new WildAnnotationTypePattern(p); return ret; } } else { tokenSource.setIndex(startIndex); // not for us! return ret; } } public TypePattern parseSingleTypePattern() { return parseSingleTypePattern(false); } public TypePattern parseSingleTypePattern(boolean insideTypeParameters) { if (insideTypeParameters && maybeEat("?")) return parseGenericsWildcardTypePattern(); if (allowHasTypePatterns) { if (maybeEatIdentifier("hasmethod")) return parseHasMethodTypePattern(); if (maybeEatIdentifier("hasfield")) return parseHasFieldTypePattern(); } List names = parseDottedNamePattern(); int dim = 0; while (maybeEat("[")) { eat("]"); dim++; } TypePatternList typeParameters = maybeParseTypeParameterList(); int endPos = tokenSource.peek(-1).getEnd(); boolean isVarArgs = maybeEat("..."); boolean includeSubtypes = maybeEat("+"); //??? what about the source location of any's???? if (names.size() == 1 && ((NamePattern)names.get(0)).isAny() && dim == 0 && !isVarArgs && typeParameters == null ) return TypePattern.ANY; // Notice we increase the dimensions if varargs is set. this is to allow type matching to // succeed later: The actual signature at runtime of a method declared varargs is an array type of // the original declared type (so Integer... becomes Integer[] in the bytecode). So, here for the // pattern 'Integer...' we create a WildTypePattern 'Integer[]' with varargs set. If this matches // during shadow matching, we confirm that the varargs flags match up before calling it a successful // match. return new WildTypePattern(names, includeSubtypes, dim+(isVarArgs?1:0), endPos,isVarArgs,typeParameters); } public TypePattern parseHasMethodTypePattern() { int startPos = tokenSource.peek(-1).getStart(); eat("("); SignaturePattern sp = parseMethodOrConstructorSignaturePattern(); eat(")"); int endPos = tokenSource.peek(-1).getEnd(); HasMemberTypePattern ret = new HasMemberTypePattern(sp); ret.setLocation(sourceContext, startPos, endPos); return ret; } public TypePattern parseHasFieldTypePattern() { int startPos = tokenSource.peek(-1).getStart(); eat("("); SignaturePattern sp = parseFieldSignaturePattern(); eat(")"); int endPos = tokenSource.peek(-1).getEnd(); HasMemberTypePattern ret = new HasMemberTypePattern(sp); ret.setLocation(sourceContext, startPos, endPos); return ret; } public TypePattern parseGenericsWildcardTypePattern() { List names = new ArrayList(); names.add(new NamePattern("?")); TypePattern upperBound = null; TypePattern[] additionalInterfaceBounds = new TypePattern[0]; TypePattern lowerBound = null; if (maybeEatIdentifier("extends")) { upperBound = parseTypePattern(false); additionalInterfaceBounds = maybeParseAdditionalInterfaceBounds(); } if (maybeEatIdentifier("super")) { lowerBound = parseTypePattern(false); } int endPos = tokenSource.peek(-1).getEnd(); return new WildTypePattern(names,false,0,endPos,false,null,upperBound,additionalInterfaceBounds,lowerBound); } // private AnnotationTypePattern completeAnnotationPattern(AnnotationTypePattern p) { // if (maybeEat("&&")) { // return new AndAnnotationTypePattern(p,parseNotOrAnnotationPattern()); // } // if (maybeEat("||")) { // return new OrAnnotationTypePattern(p,parseAnnotationTypePattern()); // } // return p; // } // // protected AnnotationTypePattern parseAnnotationTypePattern() { // AnnotationTypePattern ap = parseAtomicAnnotationPattern(); // if (maybeEat("&&")) { // ap = new AndAnnotationTypePattern(ap, parseNotOrAnnotationPattern()); // } // // if (maybeEat("||")) { // ap = new OrAnnotationTypePattern(ap, parseAnnotationTypePattern()); // } // return ap; // } // // private AnnotationTypePattern parseNotOrAnnotationPattern() { // AnnotationTypePattern p = parseAtomicAnnotationPattern(); // if (maybeEat("&&")) { // p = new AndAnnotationTypePattern(p,parseAnnotationTypePattern()); // } // return p; // } protected ExactAnnotationTypePattern parseAnnotationNameOrVarTypePattern() { ExactAnnotationTypePattern p = null; int startPos = tokenSource.peek().getStart(); if (maybeEat("@")) { throw new ParserException("@Foo form was deprecated in AspectJ 5 M2: annotation name or var ",tokenSource.peek(-1)); } p = parseSimpleAnnotationName(); int endPos = tokenSource.peek(-1).getEnd(); p.setLocation(sourceContext,startPos,endPos); return p; } /** * @return */ private ExactAnnotationTypePattern parseSimpleAnnotationName() { // the @ has already been eaten... ExactAnnotationTypePattern p; StringBuffer annotationName = new StringBuffer(); annotationName.append(parseIdentifier()); while (maybeEat(".")) { annotationName.append('.'); annotationName.append(parseIdentifier()); } UnresolvedType type = UnresolvedType.forName(annotationName.toString()); p = new ExactAnnotationTypePattern(type); return p; } // private AnnotationTypePattern parseAtomicAnnotationPattern() { // if (maybeEat("!")) { // //int startPos = tokenSource.peek(-1).getStart(); // //??? we lose source location for true start of !type // AnnotationTypePattern p = new NotAnnotationTypePattern(parseAtomicAnnotationPattern()); // return p; // } // if (maybeEat("(")) { // AnnotationTypePattern p = parseAnnotationTypePattern(); // eat(")"); // return p; // } // int startPos = tokenSource.peek().getStart(); // eat("@"); // StringBuffer annotationName = new StringBuffer(); // annotationName.append(parseIdentifier()); // while (maybeEat(".")) { // annotationName.append('.'); // annotationName.append(parseIdentifier()); // } // UnresolvedType type = UnresolvedType.forName(annotationName.toString()); // AnnotationTypePattern p = new ExactAnnotationTypePattern(type); // int endPos = tokenSource.peek(-1).getEnd(); // p.setLocation(sourceContext, startPos, endPos); // return p; // } private boolean isAnnotationPattern(PatternNode p) { return (p instanceof AnnotationTypePattern); } public List parseDottedNamePattern() { List names = new ArrayList(); StringBuffer buf = new StringBuffer(); IToken previous = null; boolean justProcessedEllipsis = false; // Remember if we just dealt with an ellipsis (PR61536) boolean justProcessedDot = false; boolean onADot = false; while (true) { IToken tok = null; int startPos = tokenSource.peek().getStart(); String afterDot = null; while (true) { if (previous !=null && previous.getString().equals(".")) justProcessedDot = true; tok = tokenSource.peek(); onADot = (tok.getString().equals(".")); if (previous != null) { if (!isAdjacent(previous, tok)) break; } if (tok.getString() == "*" || (tok.isIdentifier() && tok.getString()!="...")) { buf.append(tok.getString()); } else if (tok.getString()=="...") { break; } else if (tok.getLiteralKind() != null) { //System.err.println("literal kind: " + tok.getString()); String s = tok.getString(); int dot = s.indexOf('.'); if (dot != -1) { buf.append(s.substring(0, dot)); afterDot = s.substring(dot+1); previous = tokenSource.next(); break; } buf.append(s); // ??? so-so } else { break; } previous = tokenSource.next(); //XXX need to handle floats and other fun stuff } int endPos = tokenSource.peek(-1).getEnd(); if (buf.length() == 0 && names.isEmpty()) { throw new ParserException("name pattern", tok); } if (buf.length() == 0 && justProcessedEllipsis) { throw new ParserException("name pattern cannot finish with ..", tok); } if (buf.length() == 0 && justProcessedDot && !onADot) { throw new ParserException("name pattern cannot finish with .", tok); } if (buf.length() == 0) { names.add(NamePattern.ELLIPSIS); justProcessedEllipsis = true; } else { checkLegalName(buf.toString(), previous); NamePattern ret = new NamePattern(buf.toString()); ret.setLocation(sourceContext, startPos, endPos); names.add(ret); justProcessedEllipsis = false; } if (afterDot == null) { buf.setLength(0); // no elipsis or dotted name part if (!maybeEat(".")) break; // go on else previous = tokenSource.peek(-1); } else { buf.setLength(0); buf.append(afterDot); afterDot = null; } } //System.err.println("parsed: " + names); return names; } public NamePattern parseNamePattern() { StringBuffer buf = new StringBuffer(); IToken previous = null; IToken tok; int startPos = tokenSource.peek().getStart(); while (true) { tok = tokenSource.peek(); if (previous != null) { if (!isAdjacent(previous, tok)) break; } if (tok.getString() == "*" || tok.isIdentifier()) { buf.append(tok.getString()); } else if (tok.getLiteralKind() != null) { //System.err.println("literal kind: " + tok.getString()); String s = tok.getString(); if (s.indexOf('.') != -1) break; buf.append(s); // ??? so-so } else { break; } previous = tokenSource.next(); //XXX need to handle floats and other fun stuff } int endPos = tokenSource.peek(-1).getEnd(); if (buf.length() == 0) { throw new ParserException("name pattern", tok); } checkLegalName(buf.toString(), previous); NamePattern ret = new NamePattern(buf.toString()); ret.setLocation(sourceContext, startPos, endPos); return ret; } private void checkLegalName(String s, IToken tok) { char ch = s.charAt(0); if (!(ch == '*' || Character.isJavaIdentifierStart(ch))) { throw new ParserException("illegal identifier start (" + ch + ")", tok); } for (int i=1, len=s.length(); i < len; i++) { ch = s.charAt(i); if (!(ch == '*' || Character.isJavaIdentifierPart(ch))) { throw new ParserException("illegal identifier character (" + ch + ")", tok); } } } private boolean isAdjacent(IToken first, IToken second) { return first.getEnd() == second.getStart()-1; } public ModifiersPattern parseModifiersPattern() { int requiredFlags = 0; int forbiddenFlags = 0; int start; while (true) { start = tokenSource.getIndex(); boolean isForbidden = false; isForbidden = maybeEat("!"); IToken t = tokenSource.next(); int flag = ModifiersPattern.getModifierFlag(t.getString()); if (flag == -1) break; if (isForbidden) forbiddenFlags |= flag; else requiredFlags |= flag; } tokenSource.setIndex(start); if (requiredFlags == 0 && forbiddenFlags == 0) { return ModifiersPattern.ANY; } else { return new ModifiersPattern(requiredFlags, forbiddenFlags); } } public TypePatternList parseArgumentsPattern() { List patterns = new ArrayList(); eat("("); if (maybeEat(")")) { return new TypePatternList(); } do { if (maybeEat(".")) { eat("."); patterns.add(TypePattern.ELLIPSIS); } else { patterns.add(parseTypePattern()); } } while (maybeEat(",")); eat(")"); return new TypePatternList(patterns); } public AnnotationPatternList parseArgumentsAnnotationPattern() { List patterns = new ArrayList(); eat("("); if (maybeEat(")")) { return new AnnotationPatternList(); } do { if (maybeEat(".")) { eat("."); patterns.add(AnnotationTypePattern.ELLIPSIS); } else if (maybeEat("*")) { patterns.add(AnnotationTypePattern.ANY); } else { patterns.add(parseAnnotationNameOrVarTypePattern()); } } while (maybeEat(",")); eat(")"); return new AnnotationPatternList(patterns); } public ThrowsPattern parseOptionalThrowsPattern() { IToken t = tokenSource.peek(); if (t.isIdentifier() && t.getString().equals("throws")) { tokenSource.next(); List required = new ArrayList(); List forbidden = new ArrayList(); do { boolean isForbidden = maybeEat("!"); //???might want an error for a second ! without a paren TypePattern p = parseTypePattern(); if (isForbidden) forbidden.add(p); else required.add(p); } while (maybeEat(",")); return new ThrowsPattern(new TypePatternList(required), new TypePatternList(forbidden)); } return ThrowsPattern.ANY; } public SignaturePattern parseMethodOrConstructorSignaturePattern() { int startPos = tokenSource.peek().getStart(); AnnotationTypePattern annotationPattern = maybeParseAnnotationPattern(); ModifiersPattern modifiers = parseModifiersPattern(); TypePattern returnType = parseTypePattern(false); TypePattern declaringType; NamePattern name = null; Member.Kind kind; // here we can check for 'new' if (maybeEatNew(returnType)) { kind = Member.CONSTRUCTOR; if (returnType.toString().length() == 0) { declaringType = TypePattern.ANY; } else { declaringType = returnType; } returnType = TypePattern.ANY; name = NamePattern.ANY; } else { kind = Member.METHOD; IToken nameToken = tokenSource.peek(); declaringType = parseTypePattern(false); if (maybeEat(".")) { nameToken = tokenSource.peek(); name = parseNamePattern(); } else { name = tryToExtractName(declaringType); if (declaringType.toString().equals("")) { declaringType = TypePattern.ANY; } } if (name == null) { throw new ParserException("name pattern", tokenSource.peek()); } String simpleName = name.maybeGetSimpleName(); //XXX should add check for any Java keywords if (simpleName != null && simpleName.equals("new")) { throw new ParserException("method name (not constructor)", nameToken); } } TypePatternList parameterTypes = parseArgumentsPattern(); ThrowsPattern throwsPattern = parseOptionalThrowsPattern(); SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType, name, parameterTypes, throwsPattern, annotationPattern); int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } private boolean maybeEatNew(TypePattern returnType) { if (returnType instanceof WildTypePattern) { WildTypePattern p = (WildTypePattern)returnType; if (p.maybeExtractName("new")) return true; } int start = tokenSource.getIndex(); if (maybeEat(".")) { String id = maybeEatIdentifier(); if (id != null && id.equals("new")) return true; tokenSource.setIndex(start); } return false; } public SignaturePattern parseFieldSignaturePattern() { int startPos = tokenSource.peek().getStart(); // TypePatternList followMe = TypePatternList.ANY; AnnotationTypePattern annotationPattern = maybeParseAnnotationPattern(); ModifiersPattern modifiers = parseModifiersPattern(); TypePattern returnType = parseTypePattern(); TypePattern declaringType = parseTypePattern(); NamePattern name; //System.err.println("parsed field: " + declaringType.toString()); if (maybeEat(".")) { name = parseNamePattern(); } else { name = tryToExtractName(declaringType); if (name == null) throw new ParserException("name pattern",tokenSource.peek()); if (declaringType.toString().equals("")) { declaringType = TypePattern.ANY; } } SignaturePattern ret = new SignaturePattern(Member.FIELD, modifiers, returnType, declaringType, name, TypePatternList.ANY, ThrowsPattern.ANY,annotationPattern); int endPos = tokenSource.peek(-1).getEnd(); ret.setLocation(sourceContext, startPos, endPos); return ret; } private NamePattern tryToExtractName(TypePattern nextType) { if (nextType == TypePattern.ANY) { return NamePattern.ANY; } else if (nextType instanceof WildTypePattern) { WildTypePattern p = (WildTypePattern)nextType; return p.extractName(); } else { return null; } } /** * Parse type variable declarations for a generic method or at the start of a signature pointcut to identify * type variable names in a generic type. * @param includeParameterizedTypes * @return */ public TypeVariablePatternList maybeParseTypeVariableList() { if (!maybeEat("<")) return null; List typeVars = new ArrayList(); TypeVariablePattern t = parseTypeVariable(); typeVars.add(t); while (maybeEat(",")) { TypeVariablePattern nextT = parseTypeVariable(); typeVars.add(nextT); } eat(">"); TypeVariablePattern[] tvs = new TypeVariablePattern[typeVars.size()]; typeVars.toArray(tvs); return new TypeVariablePatternList(tvs); } // of the form execution<T,S,V> - allows identifiers only public String[] maybeParseSimpleTypeVariableList() { if (!maybeEat("<")) return null; List typeVarNames = new ArrayList(); do { typeVarNames.add(parseIdentifier()); } while (maybeEat(",")); eat(">","',' or '>'"); String[] tvs = new String[typeVarNames.size()]; typeVarNames.toArray(tvs); return tvs; } public TypePatternList maybeParseTypeParameterList() { if (!maybeEat("<")) return null; List typePats = new ArrayList(); do { TypePattern tp = parseTypePattern(true); typePats.add(tp); } while(maybeEat(",")); eat(">"); TypePattern[] tps = new TypePattern[typePats.size()]; typePats.toArray(tps); return new TypePatternList(tps); } public TypeVariablePattern parseTypeVariable() { TypePattern upperBound = null; TypePattern[] additionalInterfaceBounds = null; TypePattern lowerBound = null; String typeVariableName = null; if (typeVariableName == null) typeVariableName = parseIdentifier(); if (maybeEatIdentifier("extends")) { upperBound = parseTypePattern(); additionalInterfaceBounds = maybeParseAdditionalInterfaceBounds(); } else if (maybeEatIdentifier("super")) { lowerBound = parseTypePattern(); } return new TypeVariablePattern(typeVariableName,upperBound,additionalInterfaceBounds,lowerBound); } private TypePattern[] maybeParseAdditionalInterfaceBounds() { List boundsList = new ArrayList(); while (maybeEat("&")) { TypePattern tp = parseTypePattern(); boundsList.add(tp); } if (boundsList.size() == 0) return null; TypePattern[] ret = new TypePattern[boundsList.size()]; boundsList.toArray(ret); return ret; } public String parsePossibleStringSequence(boolean shouldEnd) { StringBuffer result = new StringBuffer(); IToken token = tokenSource.next(); if (token.getLiteralKind()==null) { throw new ParserException("string",token); } while (token.getLiteralKind().equals("string")) { result.append(token.getString()); boolean plus = maybeEat("+"); if (!plus) break; token = tokenSource.next(); if (token.getLiteralKind()==null) { throw new ParserException("string",token); } } eatIdentifier(";"); IToken t = tokenSource.next(); if (shouldEnd && t!=IToken.EOF) { throw new ParserException("<string>;",token); } // bug 125027: since we've eaten the ";" we need to set the index // to be one less otherwise the end position isn't set correctly. int currentIndex = tokenSource.getIndex(); tokenSource.setIndex(currentIndex-1); return result.toString(); } public String parseStringLiteral() { IToken token = tokenSource.next(); String literalKind = token.getLiteralKind(); if (literalKind == "string") { return token.getString(); } throw new ParserException("string", token); } public String parseIdentifier() { IToken token = tokenSource.next(); if (token.isIdentifier()) return token.getString(); throw new ParserException("identifier", token); } public void eatIdentifier(String expectedValue) { IToken next = tokenSource.next(); if (!next.getString().equals(expectedValue)) { throw new ParserException(expectedValue, next); } } public boolean maybeEatIdentifier(String expectedValue) { IToken next = tokenSource.peek(); if (next.getString().equals(expectedValue)) { tokenSource.next(); return true; } else { return false; } } public void eat(String expectedValue) { eat(expectedValue,expectedValue); } private void eat(String expectedValue,String expectedMessage) { IToken next = nextToken(); if (next.getString() != expectedValue) { if (expectedValue.equals(">") && next.getString().startsWith(">")) { // handle problem of >> and >>> being lexed as single tokens pendingRightArrows = BasicToken.makeLiteral(next.getString().substring(1).intern(), "string", next.getStart()+1, next.getEnd()); return; } throw new ParserException(expectedMessage, next); } } private IToken pendingRightArrows; private IToken nextToken() { if (pendingRightArrows != null) { IToken ret = pendingRightArrows; pendingRightArrows = null; return ret; } else { return tokenSource.next(); } } public boolean maybeEat(String token) { IToken next = tokenSource.peek(); if (next.getString() == token) { tokenSource.next(); return true; } else { return false; } } public String maybeEatIdentifier() { IToken next = tokenSource.peek(); if (next.isIdentifier()) { tokenSource.next(); return next.getString(); } else { return null; } } public boolean peek(String token) { IToken next = tokenSource.peek(); return next.getString() == token; } public PatternParser(String data) { this(BasicTokenSource.makeTokenSource(data,null)); } public PatternParser(String data, ISourceContext context) { this(BasicTokenSource.makeTokenSource(data,context)); } }
128,744
Bug 128744 LTW doesn't work using JRE1.4 in Eclipse
LTW doesn't work using JRE1.4 in Eclipse now I want to support JRE1.4 when LTW. I defined a aop.xml file in application META-INF path, it works fine using JRE1.4 in command-line, aop.xml file is used when LTW, the command as below: "D:\work\BTM\eclipse 3.1.1\eclipse-SDK-3.1.1-win32\eclipse-1.4.2\jre\bin\java" -classpath "C:\aspectj1.5\lib\aspectjweaver.jar" "-Djava.system.class.loader=org.aspectj.weaver.loadtime.WeavingURLClassLoader" "-Daj.class.path=D:\work\BTM\eclipse 3.1.1\jre1.4.2\myTest;C:\aspectj1.5\doc\examples\armtest\jar\btm-deps-e3.1.jar;C:\aspectj1.5\doc\examples\armtest\jar\btm-rt.jar" Hello but it doesn't work in Eclipse, I added upper command to VM arguments, it can't find aop.xml, because if I changed aop.xml to be wrong, there is no any error when execute the application in Eclipse , but there will be error when execute it in command-line, based on this point, I think that aop.xml didn't be used in Eclipse, I also tried to add "-Daj.aspect.path=D:\work\BTM\eclipse 3.1.1\jre1.4.2\myTest", but it is still. so I want to confirm if AspectJ only supports command-line for JRE1.4? doesn't support Eclipse for JRE1.4? BTW, my Eclipse env: eclipse 3.1.1 + ajdt_1.3_for_eclipse_3.1 + Sun JDK 1.4.2. I also tried to use eclipse 3.1.2, but this problem is still existed.
resolved fixed
7a2087e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T15:52:36Z
2006-02-21T05:33:20Z
loadtime/src/org/aspectj/weaver/loadtime/ConcreteAspectCodeGen.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package org.aspectj.weaver.loadtime; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.generic.InstructionConstants; import org.aspectj.apache.bcel.generic.InstructionList; import org.aspectj.apache.bcel.generic.ObjectType; import org.aspectj.apache.bcel.generic.Type; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; import org.aspectj.apache.bcel.generic.annotation.ElementNameValuePairGen; import org.aspectj.apache.bcel.generic.annotation.ElementValueGen; import org.aspectj.apache.bcel.generic.annotation.SimpleElementValueGen; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.Message; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelPerClauseAspectAdder; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.LazyClassGen; import org.aspectj.weaver.bcel.LazyMethodGen; import org.aspectj.weaver.loadtime.definition.Definition; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.PerSingleton; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Generates bytecode for concrete-aspect * <p/> * The concrete aspect is @AspectJ code generated. As it is build during aop.xml definitions registration * we perform the type munging for perclause ie aspectOf artifact directly, instead of waiting for it * to go thru the weaver (that we are in the middle of configuring). * * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class ConcreteAspectCodeGen { private final static String[] EMPTY_STRINGS = new String[0]; private final static Type[] EMPTY_TYPES = new Type[0]; /** * Concrete aspect definition we build for */ private final Definition.ConcreteAspect m_concreteAspect; /** * World for which we build for */ private final World m_world; /** * Set to true when all is checks are verified */ private boolean m_isValid = false; /** * The parent aspect, not concretized */ private ResolvedType m_parent; /** * Aspect perClause, used for direct munging of aspectOf artifacts */ private PerClause m_perClause; /** * Create a new compiler for a concrete aspect * * @param concreteAspect * @param world */ ConcreteAspectCodeGen(Definition.ConcreteAspect concreteAspect, World world) { m_concreteAspect = concreteAspect; m_world = world; } /** * Checks that concrete aspect is valid * * @return true if ok, false otherwise */ public boolean validate() { if (!(m_world instanceof BcelWorld)) { reportError("Internal error: world must be of type BcelWorld"); return false; } // name must be undefined so far ResolvedType current = m_world.resolve(m_concreteAspect.name, true); if (!current.isMissing()) { reportError("Attempt to concretize but choosen aspect name already defined: " + stringify()); return false; } // it can happen that extends is null, for precedence only declaration if (m_concreteAspect.extend == null && m_concreteAspect.precedence != null) { if (m_concreteAspect.pointcuts.isEmpty()) { m_isValid = true; m_perClause = new PerSingleton(); m_parent = null; return true;// no need to checks more in that special case } else { reportError("Attempt to use nested pointcuts without extends clause: "+stringify()); return false; } } m_parent = m_world.resolve(m_concreteAspect.extend, true); // handle inner classes if (m_parent.isMissing()) { // fallback on inner class lookup mechanism String fixedName = m_concreteAspect.extend; int hasDot = fixedName.lastIndexOf('.'); while (hasDot > 0) { char[] fixedNameChars = fixedName.toCharArray(); fixedNameChars[hasDot] = '$'; fixedName = new String(fixedNameChars); hasDot = fixedName.lastIndexOf('.'); m_parent = m_world.resolve(UnresolvedType.forName(fixedName), true); if (!m_parent.isMissing()) { break; } } } if (m_parent.isMissing()) { reportError("Cannot find m_parent aspect for: " + stringify()); return false; } // extends must be abstract if (!m_parent.isAbstract()) { reportError("Attempt to concretize a non-abstract aspect: " + stringify()); return false; } // m_parent must be aspect if (!m_parent.isAspect()) { reportError("Attempt to concretize a non aspect: " + stringify()); return false; } // must have all abstractions defined List elligibleAbstractions = new ArrayList(); Iterator methods = m_parent.getMethods(); while (methods.hasNext()) { ResolvedMember method = (ResolvedMember) methods.next(); if (method.isAbstract()) { if ("()V".equals(method.getSignature())) { elligibleAbstractions.add(method.getName()); } else { reportError("Abstract method '" + method.getName() + "' cannot be concretized as a pointcut (illegal signature, must have no arguments, must return void): " + stringify()); return false; } } } List pointcutNames = new ArrayList(); for (Iterator it = m_concreteAspect.pointcuts.iterator(); it.hasNext();) { Definition.Pointcut abstractPc = (Definition.Pointcut) it.next(); pointcutNames.add(abstractPc.name); } for (Iterator it = elligibleAbstractions.iterator(); it.hasNext();) { String elligiblePc = (String) it.next(); if (!pointcutNames.contains(elligiblePc)) { reportError("Abstract pointcut '" + elligiblePc + "' not configured: " + stringify()); return false; } } m_perClause = m_parent.getPerClause(); m_isValid = true; return m_isValid; } /** * Rebuild the XML snip that defines this concrete aspect, for log error purpose * * @return string repr. */ private String stringify() { StringBuffer sb = new StringBuffer("<concrete-aspect name='"); sb.append(m_concreteAspect.name); sb.append("' extends='"); sb.append(m_concreteAspect.extend); sb.append("'/> in aop.xml"); return sb.toString(); } /** * Build the bytecode for the concrete aspect * * @return concrete aspect bytecode */ public byte[] getBytes() { if (!m_isValid) { throw new RuntimeException("Must validate first"); } //TODO AV - abstract away from BCEL... // @Aspect //inherit clause from m_parent // @DeclarePrecedence("....") // if any // public class xxxName [extends xxxExtends] { // [@Pointcut(xxxExpression-n) // public void xxxName-n() {}] // } // @Aspect public class ... LazyClassGen cg = new LazyClassGen( m_concreteAspect.name.replace('.', '/'), (m_parent==null)?"java/lang/Object":m_parent.getName().replace('.', '/'), null,//TODO AV - we could point to the aop.xml that defines it and use JSR-45 Modifier.PUBLIC + Constants.ACC_SUPER, EMPTY_STRINGS, m_world ); AnnotationGen ag = new AnnotationGen( new ObjectType("org/aspectj/lang/annotation/Aspect"), Collections.EMPTY_LIST, true, cg.getConstantPoolGen() ); cg.addAnnotation(ag.getAnnotation()); if (m_concreteAspect.precedence != null) { SimpleElementValueGen svg = new SimpleElementValueGen( ElementValueGen.STRING, cg.getConstantPoolGen(), m_concreteAspect.precedence ); List elems = new ArrayList(); elems.add(new ElementNameValuePairGen("value", svg, cg.getConstantPoolGen())); AnnotationGen agprec = new AnnotationGen( new ObjectType("org/aspectj/lang/annotation/DeclarePrecedence"), elems, true, cg.getConstantPoolGen() ); cg.addAnnotation(agprec.getAnnotation()); } // default constructor LazyMethodGen init = new LazyMethodGen( Modifier.PUBLIC, Type.VOID, "<init>", EMPTY_TYPES, EMPTY_STRINGS, cg ); InstructionList cbody = init.getBody(); cbody.append(InstructionConstants.ALOAD_0); cbody.append(cg.getFactory().createInvoke( (m_parent==null)?"java/lang/Object":m_parent.getName().replace('.', '/'), "<init>", Type.VOID, EMPTY_TYPES, Constants.INVOKESPECIAL )); cbody.append(InstructionConstants.RETURN); cg.addMethodGen(init); for (Iterator it = m_concreteAspect.pointcuts.iterator(); it.hasNext();) { Definition.Pointcut abstractPc = (Definition.Pointcut) it.next(); LazyMethodGen mg = new LazyMethodGen( Modifier.PUBLIC,//TODO AV - respect visibility instead of opening up? Type.VOID, abstractPc.name, EMPTY_TYPES, EMPTY_STRINGS, cg ); SimpleElementValueGen svg = new SimpleElementValueGen( ElementValueGen.STRING, cg.getConstantPoolGen(), abstractPc.expression ); List elems = new ArrayList(); elems.add(new ElementNameValuePairGen("value", svg, cg.getConstantPoolGen())); AnnotationGen mag = new AnnotationGen( new ObjectType("org/aspectj/lang/annotation/Pointcut"), elems, true, cg.getConstantPoolGen() ); AnnotationX max = new AnnotationX(mag.getAnnotation(), m_world); mg.addAnnotation(max); InstructionList body = mg.getBody(); body.append(InstructionConstants.RETURN); cg.addMethodGen(mg); } // handle the perClause BcelPerClauseAspectAdder perClauseMunger = new BcelPerClauseAspectAdder( ResolvedType.forName(m_concreteAspect.name).resolve(m_world), m_perClause.getKind() ); perClauseMunger.forceMunge(cg, false); //TODO AV - unsafe cast // register the fresh new class into the world repository as it does not exist on the classpath anywhere JavaClass jc = cg.getJavaClass((BcelWorld) m_world); ((BcelWorld) m_world).addSourceObjectType(jc); return jc.getBytes(); } /** * Error reporting * * @param message */ private void reportError(String message) { m_world.getMessageHandler().handleMessage(new Message(message, IMessage.ERROR, null, null)); } }
128,744
Bug 128744 LTW doesn't work using JRE1.4 in Eclipse
LTW doesn't work using JRE1.4 in Eclipse now I want to support JRE1.4 when LTW. I defined a aop.xml file in application META-INF path, it works fine using JRE1.4 in command-line, aop.xml file is used when LTW, the command as below: "D:\work\BTM\eclipse 3.1.1\eclipse-SDK-3.1.1-win32\eclipse-1.4.2\jre\bin\java" -classpath "C:\aspectj1.5\lib\aspectjweaver.jar" "-Djava.system.class.loader=org.aspectj.weaver.loadtime.WeavingURLClassLoader" "-Daj.class.path=D:\work\BTM\eclipse 3.1.1\jre1.4.2\myTest;C:\aspectj1.5\doc\examples\armtest\jar\btm-deps-e3.1.jar;C:\aspectj1.5\doc\examples\armtest\jar\btm-rt.jar" Hello but it doesn't work in Eclipse, I added upper command to VM arguments, it can't find aop.xml, because if I changed aop.xml to be wrong, there is no any error when execute the application in Eclipse , but there will be error when execute it in command-line, based on this point, I think that aop.xml didn't be used in Eclipse, I also tried to add "-Daj.aspect.path=D:\work\BTM\eclipse 3.1.1\jre1.4.2\myTest", but it is still. so I want to confirm if AspectJ only supports command-line for JRE1.4? doesn't support Eclipse for JRE1.4? BTW, my Eclipse env: eclipse 3.1.1 + ajdt_1.3_for_eclipse_3.1 + Sun JDK 1.4.2. I also tried to use eclipse 3.1.2, but this problem is still existed.
resolved fixed
7a2087e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T15:52:36Z
2006-02-21T05:33:20Z
tests/bugs151/pr128744/Hello.java
128,744
Bug 128744 LTW doesn't work using JRE1.4 in Eclipse
LTW doesn't work using JRE1.4 in Eclipse now I want to support JRE1.4 when LTW. I defined a aop.xml file in application META-INF path, it works fine using JRE1.4 in command-line, aop.xml file is used when LTW, the command as below: "D:\work\BTM\eclipse 3.1.1\eclipse-SDK-3.1.1-win32\eclipse-1.4.2\jre\bin\java" -classpath "C:\aspectj1.5\lib\aspectjweaver.jar" "-Djava.system.class.loader=org.aspectj.weaver.loadtime.WeavingURLClassLoader" "-Daj.class.path=D:\work\BTM\eclipse 3.1.1\jre1.4.2\myTest;C:\aspectj1.5\doc\examples\armtest\jar\btm-deps-e3.1.jar;C:\aspectj1.5\doc\examples\armtest\jar\btm-rt.jar" Hello but it doesn't work in Eclipse, I added upper command to VM arguments, it can't find aop.xml, because if I changed aop.xml to be wrong, there is no any error when execute the application in Eclipse , but there will be error when execute it in command-line, based on this point, I think that aop.xml didn't be used in Eclipse, I also tried to add "-Daj.aspect.path=D:\work\BTM\eclipse 3.1.1\jre1.4.2\myTest", but it is still. so I want to confirm if AspectJ only supports command-line for JRE1.4? doesn't support Eclipse for JRE1.4? BTW, my Eclipse env: eclipse 3.1.1 + ajdt_1.3_for_eclipse_3.1 + Sun JDK 1.4.2. I also tried to use eclipse 3.1.2, but this problem is still existed.
resolved fixed
7a2087e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T15:52:36Z
2006-02-21T05:33:20Z
tests/bugs151/pr128744/World.java
128,744
Bug 128744 LTW doesn't work using JRE1.4 in Eclipse
LTW doesn't work using JRE1.4 in Eclipse now I want to support JRE1.4 when LTW. I defined a aop.xml file in application META-INF path, it works fine using JRE1.4 in command-line, aop.xml file is used when LTW, the command as below: "D:\work\BTM\eclipse 3.1.1\eclipse-SDK-3.1.1-win32\eclipse-1.4.2\jre\bin\java" -classpath "C:\aspectj1.5\lib\aspectjweaver.jar" "-Djava.system.class.loader=org.aspectj.weaver.loadtime.WeavingURLClassLoader" "-Daj.class.path=D:\work\BTM\eclipse 3.1.1\jre1.4.2\myTest;C:\aspectj1.5\doc\examples\armtest\jar\btm-deps-e3.1.jar;C:\aspectj1.5\doc\examples\armtest\jar\btm-rt.jar" Hello but it doesn't work in Eclipse, I added upper command to VM arguments, it can't find aop.xml, because if I changed aop.xml to be wrong, there is no any error when execute the application in Eclipse , but there will be error when execute it in command-line, based on this point, I think that aop.xml didn't be used in Eclipse, I also tried to add "-Daj.aspect.path=D:\work\BTM\eclipse 3.1.1\jre1.4.2\myTest", but it is still. so I want to confirm if AspectJ only supports command-line for JRE1.4? doesn't support Eclipse for JRE1.4? BTW, my Eclipse env: eclipse 3.1.1 + ajdt_1.3_for_eclipse_3.1 + Sun JDK 1.4.2. I also tried to use eclipse 3.1.2, but this problem is still existed.
resolved fixed
7a2087e
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T15:52:36Z
2006-02-21T05:33:20Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import java.util.List; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.Relationship; import org.aspectj.systemtest.ajc150.GenericsTests; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testGenericAdviceParameters_pr123553() { runTest("generic advice parameters");} public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");} public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");} public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");} public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");} public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");} //public void testExposingWithintype_enh123423() { runTest("exposing withintype");} //public void testMissingImport_pr127299() { runTest("missing import gives funny message");} public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");} public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); } public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); } public void testMixingNumbersOfTypeParameters_pr125080() { runTest("mixing numbers of type parameters"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;"); } public void testMixingNumbersOfTypeParameters_pr125080_2() { runTest("mixing numbers of type parameters - 2"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;"); } public void testIProgramElementMethods_pr125295() { runTest("new IProgramElement methods"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForType("pkg","foo"); assertNotNull("Couldn't find 'foo' element in the tree",pe); // check that the defaults return the fully qualified arg assertEquals("foo(int, java.lang.Object)",pe.toLabelString()); assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString()); assertEquals("foo(int, java.lang.Object)",pe.toSignatureString()); // check that can get hold of the non qualified args assertEquals("foo(int, Object)",pe.toLabelString(false)); assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false)); assertEquals("foo(int, Object)",pe.toSignatureString(false)); IProgramElement pe2 = top.findElementForType("pkg","printParameters"); assertNotNull("Couldn't find 'printParameters' element in the tree",pe2); // the argument is org.aspectj.lang.JoinPoint, check that this is added assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty()); } public void testParameterizedEnum_pr126316() { runTest("E extends Enum(E) again"); } public void testSwallowedException() { runTest("swallowed exceptions"); } public void testSwallowedExceptionIgnored() { runTest("swallowed exceptions with xlint"); } /* * @AspectJ bugs and enhancements */ // public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { // runTest("inherit adivce with this() and thisJoinPoint"); // } public void testAtAspectInheritsAbstractPointcut_pr125810 () { runTest("warning when inherited pointcut not made concrete"); } public void testAtAspectDEOWInStructureModel_pr120356() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("@AJ deow appear correctly when structure model is generated"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // get the IProgramElements corresponding to the @DeclareWarning statement // and the method it matches. IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"warningMethod()"); assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE); IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"warning"); assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE); // check that the method has a matches declare relationship with @DeclareWarning List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE); assertNotNull("warningMethod should have some relationships but does not",matches); assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1); List matchesTargets = ((Relationship)matches.get(0)).getTargets(); assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0)); assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label " + target.toLabelString(),atDeclareWarningIPE,target); // check that the @DeclareWarning has a matches relationship with the warningMethod List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE); assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy); assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1); List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets(); assertTrue("@DeclareWarning 'matched by' relationship should have one target " + "but has " + matchedByTargets.size(), matchedByTargets.size() == 1); IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0)); assertEquals("target of relationship should be the warningMethod but is IPE with label " + matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget); // get the IProgramElements corresponding to the @DeclareError statement // and the method it matches. IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"badMethod()"); assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE); IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"error"); assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE); // check that the @DeclareError has a matches relationship with the badMethod List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE); assertNotNull("@DeclareError should have some relationships but does not",matchedByE); assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1); List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets(); assertTrue("@DeclareError 'matched by' relationship should have one target " + "but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1); IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0)); assertEquals("target of relationship should be the badMethod but is IPE with label " + matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE); } public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() { runTest("@AJ no NPE with deow when structure model isn't generated"); } public void testAtAspectWithoutJoinPointImport_pr121616() { runTest("@AJ without JoinPoint import"); } public void testAtAspectDeclareParentsRetainsFieldState_pr122370() { runTest("@AJ declare parents retains field state"); } /* * Load-time weaving bugs and enhancements */ public void testEmptyPointcutInAtAspectJ_pr125475 () { runTest("define empty pointcut using an annotation"); } public void testEmptyPointcutInAtAspectJ_pr125475_2() { runTest("define empty pointcut using an annotation - 2"); } public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () { runTest("define empty pointcut using aop.xml"); } public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () { runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent"); } ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
128,237
Bug 128237 [@AspectJ] NPE on @AJ code with pointcut which contains logical OR operation.
null
resolved fixed
ba42a09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T15:55:33Z
2006-02-16T17:13:20Z
tests/bugs151/pr128237.java
128,237
Bug 128237 [@AspectJ] NPE on @AJ code with pointcut which contains logical OR operation.
null
resolved fixed
ba42a09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T15:55:33Z
2006-02-16T17:13:20Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import java.util.List; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.Relationship; import org.aspectj.systemtest.ajc150.GenericsTests; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testGenericAdviceParameters_pr123553() { runTest("generic advice parameters");} public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");} public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");} public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");} public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");} public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");} //public void testExposingWithintype_enh123423() { runTest("exposing withintype");} //public void testMissingImport_pr127299() { runTest("missing import gives funny message");} public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");} public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); } public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); } public void testBrokenLTW_pr128744() { runTest("broken ltw"); } public void testMixingNumbersOfTypeParameters_pr125080() { runTest("mixing numbers of type parameters"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;"); } public void testMixingNumbersOfTypeParameters_pr125080_2() { runTest("mixing numbers of type parameters - 2"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;"); } public void testIProgramElementMethods_pr125295() { runTest("new IProgramElement methods"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForType("pkg","foo"); assertNotNull("Couldn't find 'foo' element in the tree",pe); // check that the defaults return the fully qualified arg assertEquals("foo(int, java.lang.Object)",pe.toLabelString()); assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString()); assertEquals("foo(int, java.lang.Object)",pe.toSignatureString()); // check that can get hold of the non qualified args assertEquals("foo(int, Object)",pe.toLabelString(false)); assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false)); assertEquals("foo(int, Object)",pe.toSignatureString(false)); IProgramElement pe2 = top.findElementForType("pkg","printParameters"); assertNotNull("Couldn't find 'printParameters' element in the tree",pe2); // the argument is org.aspectj.lang.JoinPoint, check that this is added assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty()); } public void testParameterizedEnum_pr126316() { runTest("E extends Enum(E) again"); } public void testSwallowedException() { runTest("swallowed exceptions"); } public void testSwallowedExceptionIgnored() { runTest("swallowed exceptions with xlint"); } /* * @AspectJ bugs and enhancements */ // public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { // runTest("inherit adivce with this() and thisJoinPoint"); // } public void testAtAspectInheritsAbstractPointcut_pr125810 () { runTest("warning when inherited pointcut not made concrete"); } public void testAtAspectDEOWInStructureModel_pr120356() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("@AJ deow appear correctly when structure model is generated"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // get the IProgramElements corresponding to the @DeclareWarning statement // and the method it matches. IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"warningMethod()"); assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE); IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"warning"); assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE); // check that the method has a matches declare relationship with @DeclareWarning List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE); assertNotNull("warningMethod should have some relationships but does not",matches); assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1); List matchesTargets = ((Relationship)matches.get(0)).getTargets(); assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0)); assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label " + target.toLabelString(),atDeclareWarningIPE,target); // check that the @DeclareWarning has a matches relationship with the warningMethod List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE); assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy); assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1); List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets(); assertTrue("@DeclareWarning 'matched by' relationship should have one target " + "but has " + matchedByTargets.size(), matchedByTargets.size() == 1); IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0)); assertEquals("target of relationship should be the warningMethod but is IPE with label " + matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget); // get the IProgramElements corresponding to the @DeclareError statement // and the method it matches. IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"badMethod()"); assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE); IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"error"); assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE); // check that the @DeclareError has a matches relationship with the badMethod List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE); assertNotNull("@DeclareError should have some relationships but does not",matchedByE); assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1); List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets(); assertTrue("@DeclareError 'matched by' relationship should have one target " + "but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1); IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0)); assertEquals("target of relationship should be the badMethod but is IPE with label " + matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE); } public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() { runTest("@AJ no NPE with deow when structure model isn't generated"); } public void testAtAspectWithoutJoinPointImport_pr121616() { runTest("@AJ without JoinPoint import"); } public void testAtAspectDeclareParentsRetainsFieldState_pr122370() { runTest("@AJ declare parents retains field state"); } /* * Load-time weaving bugs and enhancements */ public void testEmptyPointcutInAtAspectJ_pr125475 () { runTest("define empty pointcut using an annotation"); } public void testEmptyPointcutInAtAspectJ_pr125475_2() { runTest("define empty pointcut using an annotation - 2"); } public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () { runTest("define empty pointcut using aop.xml"); } public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () { runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent"); } ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
128,237
Bug 128237 [@AspectJ] NPE on @AJ code with pointcut which contains logical OR operation.
null
resolved fixed
ba42a09
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T15:55:33Z
2006-02-16T17:13:20Z
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Alexandre Vasseur support for @AJ aspects * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.jar.Attributes.Name; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.aspectj.apache.bcel.classfile.ClassParser; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.WeaveMessage; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.util.FileUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.Advice; import org.aspectj.weaver.AnnotationOnTypeMunger; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.AsmRelationshipProvider; import org.aspectj.weaver.BCException; 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.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.WeaverMetrics; import org.aspectj.weaver.WeaverStateInfo; import org.aspectj.weaver.World; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.BindingAnnotationTypePattern; import org.aspectj.weaver.patterns.BindingTypePattern; import org.aspectj.weaver.patterns.CflowPointcut; import org.aspectj.weaver.patterns.ConcreteCflowPointcut; import org.aspectj.weaver.patterns.DeclareAnnotation; import org.aspectj.weaver.patterns.DeclareParents; import org.aspectj.weaver.patterns.FastMatchInfo; import org.aspectj.weaver.patterns.IfPointcut; import org.aspectj.weaver.patterns.KindedPointcut; import org.aspectj.weaver.patterns.NameBindingPointcut; import org.aspectj.weaver.patterns.NotPointcut; import org.aspectj.weaver.patterns.OrPointcut; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PointcutRewriter; import org.aspectj.weaver.patterns.WithinPointcut; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; private IProgressListener progressListener = null; private double progressMade; private double progressPerClassFile; private boolean inReweavableMode = false; public BcelWeaver(BcelWorld world) { super(); WeaverMetrics.reset(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields // private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ // private Map resources = new HashMap(); /* String -> UnwovenClassFile */ private Manifest manifest = null; private boolean needToReweaveWorld = false; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private List lateTypeMungerList = null; // setup by prepareForWeave private List declareParentsList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } /** * Add the given aspect to the weaver. * The type is resolved to support DOT for static inner classes as well as DOLLAR * * @param aspectName * @return aspect */ public ResolvedType addLibraryAspect(String aspectName) { // 1 - resolve as is ResolvedType type = world.resolve(UnresolvedType.forName(aspectName), true); if (type.isMissing()) { // fallback on inner class lookup mechanism String fixedName = aspectName; int hasDot = fixedName.lastIndexOf('.'); while (hasDot > 0) { //System.out.println("BcelWeaver.addLibraryAspect " + fixedName); char[] fixedNameChars = fixedName.toCharArray(); fixedNameChars[hasDot] = '$'; fixedName = new String(fixedNameChars); hasDot = fixedName.lastIndexOf('.'); type = world.resolve(UnresolvedType.forName(fixedName), true); if (!type.isMissing()) { break; } } } //System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { // Bug 119657 ensure we use the unwoven aspect WeaverStateInfo wsi = type.getWeaverState(); if (wsi != null && wsi.isReweavable()) { BcelObjectType classType = getClassType(type.getName()); classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes()))); } //TODO AV - happens to reach that a lot of time: for each type flagged reweavable X for each aspect in the weaverstate //=> mainly for nothing for LTW - pbly for something in incremental build... xcutSet.addOrReplaceAspect(type); return type; } else { // FIXME AV - better warning upon no such aspect from aop.xml throw new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName); } } /** * * @param inFile File path to class directory or zip/jar class archive * @throws IOException */ public void addLibraryJarFile(File inFile) throws IOException { List addedAspects = null; if (inFile.isDirectory()) { addedAspects = addAspectsFromDirectory(inFile); } else { addedAspects = addAspectsFromJarFile(inFile); } for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedType aspectX = (ResolvedType) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } // FIXME ASC performance? of this alternative soln. ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); return addedAspects; } private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{ List addedAspects = new ArrayList(); File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){ public boolean accept(File pathname) { return pathname.getName().endsWith(".class"); } }); for (int i = 0; i < classFiles.length; i++) { FileInputStream fis = new FileInputStream(classFiles[i]); byte[] bytes = FileUtil.readAsByteArray(fis); addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects); } return addedAspects; } private void addIfAspect(byte[] bytes, String name, List toList) throws IOException { ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name); JavaClass jc = parser.parse(); ResolvedType type = world.addSourceObjectType(jc).getResolvedTypeX(); if (type.isAspect()) { toList.add(type); } } // // The ANT copy task should be used to copy resources across. // private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false; /** * Add any .class files in the directory to the outdir. Anything other than .class files in * the directory (or its subdirectories) are considered resources and are also copied. * */ public List addDirectoryContents(File inFile,File outDir) throws IOException { List addedClassFiles = new ArrayList(); // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(inFile,new FileFilter() { public boolean accept(File f) { boolean accept = !f.isDirectory(); return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { addedClassFiles.add(addClassFile(files[i],inFile,outDir)); } return addedClassFiles; } /** Adds all class files in the jar */ public List addJarFile(File inFile, File outDir, boolean canBeDirectory){ // System.err.println("? addJarFile(" + inFile + ", " + outDir + ")"); List addedClassFiles = new ArrayList(); needToReweaveWorld = true; JarFile inJar = null; try { // Is this a directory we are looking at? if (inFile.isDirectory() && canBeDirectory) { addedClassFiles.addAll(addDirectoryContents(inFile,outDir)); } else { inJar = new JarFile(inFile); addManifest(inJar.getManifest()); Enumeration entries = inJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); InputStream inStream = inJar.getInputStream(entry); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); // System.out.println("? addJarFile() filename='" + filename + "'"); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); if (filename.endsWith(".class")) { this.addClassFile(classFile); addedClassFiles.add(classFile); } // else if (!entry.isDirectory()) { // // /* bug-44190 Copy meta-data */ // addResource(filename,classFile); // } inStream.close(); } inJar.close(); } } catch (FileNotFoundException ex) { IMessage message = new Message( "Could not find input jar file " + inFile.getPath() + ", ignoring", new SourceLocation(inFile,0), false); world.getMessageHandler().handleMessage(message); } catch (IOException ex) { IMessage message = new Message( "Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } finally { if (inJar != null) { try {inJar.close();} catch (IOException ex) { IMessage message = new Message( "Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(inFile,0), true); world.getMessageHandler().handleMessage(message); } } } return addedClassFiles; } // public void addResource(String name, File inPath, File outDir) throws IOException { // // /* Eliminate CVS files. Relative paths use "/" */ // if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { //// System.err.println("? addResource('" + name + "')"); //// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath)); //// byte[] bytes = new byte[(int)inPath.length()]; //// inStream.read(bytes); //// inStream.close(); // byte[] bytes = FileUtil.readAsByteArray(inPath); // UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes); // addResource(name,resourceFile); // } // } public boolean needToReweaveWorld() { return needToReweaveWorld; } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); // if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) { //// throw new RuntimeException(classFile.getClassName()); // } world.addSourceObjectType(classFile.getJavaClass()); } public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException { FileInputStream fis = new FileInputStream(classFile); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = classFile.getAbsolutePath().substring( inPathDir.getAbsolutePath().length()+1); UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes); if (filename.endsWith(".class")) { // System.err.println("BCELWeaver: processing class from input directory "+classFile); this.addClassFile(ucf); } fis.close(); return ucf; } public void deleteClassFile(String typename) { deletedTypenames.add(typename); // sourceJavaClasses.remove(typename); world.deleteSourceObjectType(UnresolvedType.forName(typename)); } // public void addResource (String name, UnwovenClassFile resourceFile) { // /* bug-44190 Change error to warning and copy first resource */ // if (!resources.containsKey(name)) { // resources.put(name, resourceFile); // } // else { // world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'", // null, null); // } // } // ---- weave preparation public void prepareForWeave() { needToReweaveWorld = false; CflowPointcut.clearCaches(); // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedType type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(UnresolvedType.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); rewritePointcuts(shadowMungerList); // Sometimes an error occurs during rewriting pointcuts (for example, if ambiguous bindings // are detected) - we ought to fail the prepare when this happens because continuing with // inconsistent pointcuts could lead to problems typeMungerList = xcutSet.getTypeMungers(); lateTypeMungerList = xcutSet.getLateTypeMungers(); declareParentsList = xcutSet.getDeclareParents(); // The ordering here used to be based on a string compare on toString() for the two mungers - // that breaks for the @AJ style where advice names aren't programmatically generated. So we // have changed the sorting to be based on source location in the file - this is reliable, in // the case of source locations missing, we assume they are 'sorted' - i.e. the order in // which they were added to the collection is correct, this enables the @AJ stuff to work properly. // When @AJ processing starts filling in source locations for mungers, this code may need // a bit of alteration... Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { ShadowMunger sm1 = (ShadowMunger)o1; ShadowMunger sm2 = (ShadowMunger)o2; if (sm1.getSourceLocation()==null) return (sm2.getSourceLocation()==null?0:1); if (sm2.getSourceLocation()==null) return -1; return (sm2.getSourceLocation().getOffset()-sm1.getSourceLocation().getOffset()); } }); } /* * Rewrite all of the pointcuts in the world into their most efficient * form for subsequent matching. Also ensure that if pc1.equals(pc2) * then pc1 == pc2 (for non-binding pcds) by making references all * point to the same instance. * Since pointcuts remember their match decision on the last shadow, * this makes matching faster when many pointcuts share common elements, * or even when one single pointcut has one common element (which can * be a side-effect of DNF rewriting). */ private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) { PointcutRewriter rewriter = new PointcutRewriter(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); Pointcut newP = rewriter.rewrite(p); // validateBindings now whilst we still have around the pointcut // that resembles what the user actually wrote in their program // text. if (munger instanceof Advice) { Advice advice = (Advice) munger; if (advice.getSignature() != null) { final int numFormals; final String names[]; // If the advice is being concretized in a @AJ aspect *and* the advice was declared in // an @AJ aspect (it could have been inherited from a code style aspect) then // evaluate the alternative set of formals. pr125699 if (advice.getConcreteAspect().isAnnotationStyleAspect() && advice.getDeclaringAspect()!=null && advice.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) { numFormals = advice.getBaseParameterCount(); int numArgs = advice.getSignature().getParameterTypes().length; if (numFormals > 0) { names = advice.getSignature().getParameterNames(world); validateBindings(newP,p,numArgs,names); } } else { numFormals = advice.getBaseParameterCount(); if (numFormals > 0) { names = advice.getBaseParameterNames(world); validateBindings(newP,p,numFormals,names); } } } } munger.setPointcut(newP); } // now that we have optimized individual pointcuts, optimize // across the set of pointcuts.... // Use a map from key based on pc equality, to value based on // pc identity. Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap(); for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); Pointcut p = munger.getPointcut(); munger.setPointcut(shareEntriesFromMap(p,pcMap)); } } private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) { // some things cant be shared... if (p instanceof NameBindingPointcut) return p; if (p instanceof IfPointcut) return p; if (p instanceof ConcreteCflowPointcut) return p; if (p instanceof AndPointcut) { AndPointcut apc = (AndPointcut) p; Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap); return new AndPointcut(left,right); } else if (p instanceof OrPointcut) { OrPointcut opc = (OrPointcut) p; Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap); Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap); return new OrPointcut(left,right); } else if (p instanceof NotPointcut) { NotPointcut npc = (NotPointcut) p; Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap); return new NotPointcut(not); } else { // primitive pcd if (pcMap.containsKey(p)) { // based on equality return (Pointcut) pcMap.get(p); // same instance (identity) } else { pcMap.put(p,p); return p; } } } // userPointcut is the pointcut that the user wrote in the program text. // dnfPointcut is the same pointcut rewritten in DNF // numFormals is the number of formal parameters in the pointcut // if numFormals > 0 then every branch of a disjunction must bind each formal once and only once. // in addition, the left and right branches of a disjunction must hold on join point kinds in // common. private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) { if (numFormals == 0) return; // nothing to check if (dnfPointcut.couldMatchKinds()==Shadow.NO_SHADOW_KINDS_BITS) 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()!=Shadow.NO_SHADOW_KINDS_BITS) 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()!=Shadow.NO_SHADOW_KINDS_BITS) validateSingleBranch(right, userPointcut, numFormals, names, rightBindings); } int kindsInCommon = left.couldMatchKinds() & right.couldMatchKinds(); if (kindsInCommon!=Shadow.NO_SHADOW_KINDS_BITS && couldEverMatchSameJoinPoints(left,right)) { // we know that every branch binds every formal, so there is no ambiguity // if each branch binds it in exactly the same way... List ambiguousNames = new ArrayList(); for (int i = 0; i < numFormals; i++) { if (!leftBindings[i].equals(rightBindings[i])) { ambiguousNames.add(names[i]); } } if (!ambiguousNames.isEmpty()) raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames); } } // pc is a pointcut that does not contain any disjunctions // check that every formal is bound (negation doesn't count). // we know that numFormals > 0 or else we would not be called private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) { boolean[] foundFormals = new boolean[numFormals]; for (int i = 0; i < foundFormals.length; i++) { foundFormals[i] = false; } validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings); for (int i = 0; i < foundFormals.length; i++) { if (!foundFormals[i]) { boolean ignore = false; // ATAJ soften the unbound error for implicit bindings like JoinPoint in @AJ style for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) { if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) { ignore = true; break; } } if (!ignore) { raiseUnboundFormalError(names[i],userPointcut); } } } } // each formal must appear exactly once private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) { if (pc instanceof NotPointcut) { // nots can only appear at leaves in DNF NotPointcut not = (NotPointcut) pc; if (not.getNegatedPointcut() instanceof NameBindingPointcut) { NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut(); if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty()) raiseNegationBindingError(userPointcut); } } else if (pc instanceof AndPointcut) { AndPointcut and = (AndPointcut) pc; validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings); validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings); } else if (pc instanceof NameBindingPointcut) { List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns(); for (Iterator iter = btps.iterator(); iter.hasNext();) { BindingTypePattern btp = (BindingTypePattern) iter.next(); int index = btp.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns(); for (Iterator iter = baps.iterator(); iter.hasNext();) { BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next(); int index = bap.getFormalIndex(); bindings[index] = pc; if (foundFormals[index]) { raiseAmbiguousBindingError(names[index],userPointcut); } else { foundFormals[index] = true; } } } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); for (int i = 0; i < slots.length; i++) { bindings[slots[i]] = cfp; if (foundFormals[slots[i]]) { raiseAmbiguousBindingError(names[slots[i]],userPointcut); } else { foundFormals[slots[i]] = true; } } } } // By returning false from this method, we are allowing binding of the same // variable on either side of an or. // Be conservative :- have to consider overriding, varargs, autoboxing, // the effects of itds (on within for example), interfaces, the fact that // join points can have multiple signatures and so on. private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) { if (left instanceof OrPointcut) { OrPointcut leftOrPointcut = (OrPointcut)left; if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(),right)) return true; if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(),right)) return true; return false; } if (right instanceof OrPointcut) { OrPointcut rightOrPointcut = (OrPointcut)right; if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getLeft())) return true; if (couldEverMatchSameJoinPoints(left,rightOrPointcut.getRight())) return true; return false; } // look for withins WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class); WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class); if ((leftWithin != null) && (rightWithin != null)) { if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false; } // look for kinded KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class); KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class); if ((leftKind != null) && (rightKind != null)) { if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false; } return true; } private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) { if (toSearch instanceof NotPointcut) return null; if (toLookFor.isInstance(toSearch)) return toSearch; if (toSearch instanceof AndPointcut) { AndPointcut apc = (AndPointcut) toSearch; Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor); if (left != null) return left; return findFirstPointcutIn(apc.getRight(),toLookFor); } return null; } /** * @param userPointcut */ private void raiseNegationBindingError(Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param userPointcut */ private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) { StringBuffer formalNames = new StringBuffer(names.get(0).toString()); for (int i = 1; i < names.size(); i++) { formalNames.append(", "); formalNames.append(names.get(i)); } world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } /** * @param name * @param userPointcut */ private void raiseUnboundFormalError(String name, Pointcut userPointcut) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL, name), userPointcut.getSourceContext().makeSourceLocation(userPointcut),null); } // public void dumpUnwoven(File file) throws IOException { // BufferedOutputStream os = FileUtil.makeOutputStream(file); // this.zipOutputStream = new ZipOutputStream(os); // dumpUnwoven(); // /* BUG 40943*/ // dumpResourcesToOutJar(); // zipOutputStream.close(); //this flushes and closes the acutal file // } // // // public void dumpUnwoven() throws IOException { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // public void dumpResourcesToOutPath() throws IOException { //// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next()); // dumpUnchanged(res); // } // //resources = new HashMap(); // } // /* BUG #40943 */ // public void dumpResourcesToOutJar() throws IOException { //// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet()); // Iterator i = resources.keySet().iterator(); // while (i.hasNext()) { // String name = (String)i.next(); // UnwovenClassFile res = (UnwovenClassFile)resources.get(name); // writeZipEntry(name,res.getBytes()); // } // resources = new HashMap(); // } // // // halfway house for when the jar is managed outside of the weaver, but the resources // // to be copied are known in the weaver. // public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException { // this.zipOutputStream = zos; // dumpResourcesToOutJar(); // } public void addManifest (Manifest newManifest) { // System.out.println("? addManifest() newManifest=" + newManifest); if (manifest == null) { manifest = newManifest; } } public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; private static final String WEAVER_MANIFEST_VERSION = "1.0"; private static final Attributes.Name CREATED_BY = new Name("Created-By"); private static final String WEAVER_CREATED_BY = "AspectJ Compiler"; public Manifest getManifest (boolean shouldCreate) { if (manifest == null && shouldCreate) { manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION); attributes.put(CREATED_BY,WEAVER_CREATED_BY); } return manifest; } // ---- weaving // Used by some test cases only... public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); prepareForWeave(); Collection c = weave( new IClassFileProvider() { public boolean isApplyAtAspectJMungersOnly() { return false; } public Iterator getClassFileIterator() { return addedClasses.iterator(); } public IWeaveRequestor getRequestor() { return new IWeaveRequestor() { public void acceptResult(UnwovenClassFile result) { try { writeZipEntry(result.filename, result.bytes); } catch(IOException ex) {} } public void processingReweavableState() {} public void addingTypeMungers() {} public void weavingAspects() {} public void weavingClasses() {} public void weaveCompleted() {} }; } }); // /* BUG 40943*/ // dumpResourcesToOutJar(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } // public Collection weave() throws IOException { // prepareForWeave(); // Collection filesToWeave; // // if (needToReweaveWorld) { // filesToWeave = sourceJavaClasses.values(); // } else { // filesToWeave = addedClasses; // } // // Collection wovenClassNames = new ArrayList(); // world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + // "(world=" + needToReweaveWorld + ")", null, null); // // // //System.err.println("typeMungers: " + typeMungerList); // // prepareToProcessReweavableState(); // // clear all state from files we'll be reweaving // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = getClassType(className); // processReweavableStateIfPresent(className, classType); // } // // // // //XXX this isn't quite the right place for this... // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // addTypeMungers(className); // } // // // first weave into aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // // then weave into non-aspects // for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // String className = classFile.getClassName(); // BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className)); // if (! classType.isAspect()) { // weave(classFile, classType); // wovenClassNames.add(className); // } // } // // if (zipOutputStream != null && !needToReweaveWorld) { // Collection filesToDump = new HashSet(sourceJavaClasses.values()); // filesToDump.removeAll(filesToWeave); // for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { // UnwovenClassFile classFile = (UnwovenClassFile)i.next(); // dumpUnchanged(classFile); // } // } // // addedClasses = new ArrayList(); // deletedTypenames = new ArrayList(); // // return wovenClassNames; // } // variation of "weave" that sources class files from an external source. public Collection weave(IClassFileProvider input) throws IOException { ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, ""); Collection wovenClassNames = new ArrayList(); IWeaveRequestor requestor = input.getRequestor(); // special case for AtAspectJMungerOnly - see #113587 if (input.isApplyAtAspectJMungersOnly()) { ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, ""); requestor.weavingAspects(); ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType.isAnnotationStyleAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } LazyClassGen clazz = classType.getLazyClassGen(); BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind()); selfMunger.forceMunge(clazz, true); classType.finishedWith(); UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int news = 0; news < newClasses.length; news++) { requestor.acceptResult(newClasses[news]); } wovenClassNames.add(classFile.getClassName()); } } requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly); return wovenClassNames; } requestor.processingReweavableState(); ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE,""); prepareToProcessReweavableState(); // clear all state from files we'll be reweaving for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = getClassType(className); // null return from getClassType() means the delegate is an eclipse source type - so // there *cant* be any reweavable state... (he bravely claimed...) if (classType !=null) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className); processReweavableStateIfPresent(className, classType); CompilationAndWeavingContext.leavingPhase(tok); } } CompilationAndWeavingContext.leavingPhase(reweaveToken); ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,""); requestor.addingTypeMungers(); // We process type mungers in two groups, first mungers that change the type // hierarchy, then 'normal' ITD type mungers. // Process the types in a predictable order (rather than the order encountered). // For class A, the order is superclasses of A then superinterfaces of A // (and this mechanism is applied recursively) List typesToProcess = new ArrayList(); for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) { UnwovenClassFile clf = (UnwovenClassFile) iter.next(); typesToProcess.add(clf.getClassName()); } while (typesToProcess.size()>0) { weaveParentsFor(typesToProcess,(String)typesToProcess.get(0)); } for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); addNormalTypeMungers(className); } CompilationAndWeavingContext.leavingPhase(typeMungingToken); requestor.weavingAspects(); ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, ""); // first weave into aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (theType.isAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { // Sometimes.. if the Bcel Delegate couldn't be found then a problem occurred at compile time - on // a previous compiler run. In this case I assert the delegate will still be an EclipseSourceType // and we can ignore the problem here (the original compile error will be reported again from // the eclipse source type) - pr113531 ReferenceTypeDelegate theDelegate = ((ReferenceType)theType).getDelegate(); if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue; throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } weaveAndNotify(classFile, classType,requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(aspectToken); requestor.weavingClasses(); ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, ""); // then weave into non-aspects for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedType theType = world.resolve(className); if (!theType.isAspect()) { BcelObjectType classType = BcelWorld.getBcelObjectType(theType); if (classType==null) { // bug 119882 - see above comment for bug 113531 ReferenceTypeDelegate theDelegate = ((ReferenceType)theType).getDelegate(); if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) continue; throw new BCException("Can't find bcel delegate for "+className+" type="+theType.getClass()); } weaveAndNotify(classFile, classType, requestor); wovenClassNames.add(className); } } CompilationAndWeavingContext.leavingPhase(classToken); addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); warnOnUnmatchedAdvice(); requestor.weaveCompleted(); CompilationAndWeavingContext.leavingPhase(weaveToken); return wovenClassNames; } /** * In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any * mungers that did not match anything. */ private void warnOnUnmatchedAdvice() { class AdviceLocation { private int lineNo; private UnresolvedType inAspect; public AdviceLocation(BcelAdvice advice) { this.lineNo = advice.getSourceLocation().getLine(); this.inAspect = advice.getDeclaringAspect(); } public boolean equals(Object obj) { if (!(obj instanceof AdviceLocation)) return false; AdviceLocation other = (AdviceLocation) obj; if (this.lineNo != other.lineNo) return false; if (!this.inAspect.equals(other.inAspect)) return false; return true; } public int hashCode() { return 37 + 17*lineNo + 17*inAspect.hashCode(); }; } // FIXME asc Should be factored out into Xlint code and done automatically for all xlint messages, ideally. // if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) { List l = world.getCrosscuttingMembersSet().getShadowMungers(); Set alreadyWarnedLocations = new HashSet(); for (Iterator iter = l.iterator(); iter.hasNext();) { ShadowMunger element = (ShadowMunger) iter.next(); if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers BcelAdvice ba = (BcelAdvice)element; if (!ba.hasMatchedSomething()) { // Because we implement some features of AJ itself by creating our own kind of mungers, you sometimes // find that ba.getSignature() is not a BcelMethod - for example it might be a cflow entry munger. if (ba.getSignature()!=null) { // check we haven't already warned on this advice and line // (cflow creates multiple mungers for the same advice) AdviceLocation loc = new AdviceLocation(ba); if (alreadyWarnedLocations.contains(loc)) { continue; } else { alreadyWarnedLocations.add(loc); } if (!(ba.getSignature() instanceof BcelMethod) || !Utility.isSuppressing((AnnotationX[])ba.getSignature().getAnnotations(),"adviceDidNotMatch")) { world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(),element.getSourceLocation()); } } } } } } } /** * 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process * supertypes (classes/interfaces) of 'typeToWeave' that are in the * 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from * the 'typesForWeaving' list. * * Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may * break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it * may choose to weave them in either order - but you'll probably have other problems if * you are supplying partial hierarchies like that ! */ private void weaveParentsFor(List typesForWeaving,String typeToWeave) { // Look at the supertype first ResolvedType rtx = world.resolve(typeToWeave); ResolvedType superType = rtx.getSuperclass(); if (superType!=null && typesForWeaving.contains(superType.getName())) { weaveParentsFor(typesForWeaving,superType.getName()); } // Then look at the superinterface list ResolvedType[] interfaceTypes = rtx.getDeclaredInterfaces(); for (int i = 0; i < interfaceTypes.length; i++) { ResolvedType rtxI = interfaceTypes[i]; if (typesForWeaving.contains(rtxI.getName())) { weaveParentsFor(typesForWeaving,rtxI.getName()); } } ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,rtx.getName()); weaveParentTypeMungers(rtx); // Now do this type CompilationAndWeavingContext.leavingPhase(tok); typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process } public void prepareToProcessReweavableState() { if (inReweavableMode) world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null); } public void processReweavableStateIfPresent(String className, BcelObjectType classType) { // If the class is marked reweavable, check any aspects around when it was built are in this world WeaverStateInfo wsi = classType.getWeaverState(); if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around! world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()), null,null); Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType(); if (aspectsPreviouslyInWorld!=null) { // keep track of them just to ensure unique missing aspect error reporting Set alreadyConfirmedReweavableState = new HashSet(); for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) { String requiredTypeName = (String) iter.next(); if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) { ResolvedType rtx = world.resolve(UnresolvedType.forName(requiredTypeName),true); boolean exists = !rtx.isMissing(); if (!exists) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className), classType.getSourceLocation(), null); } else { // weaved in aspect that are not declared in aop.xml trigger an error for now // may cause headhache for LTW and packaged lib without aop.xml in // see #104218 if(!xcutSet.containsAspect(rtx)){ world.showMessage( IMessage.ERROR, WeaverMessages.format( WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED, requiredTypeName, className ), null, 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); } } } } // old: //classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData())); // new: reweavable default with clever diff classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes()))); } else { classType.resetState(); } } private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType.getResolvedTypeX().getName()); LazyClassGen clazz = weaveWithoutDump(classFile,classType); classType.finishedWith(); //clazz is null if the classfile was unchanged by weaving... if (clazz != null) { UnwovenClassFile[] newClasses = getClassFilesFor(clazz); for (int i = 0; i < newClasses.length; i++) { requestor.acceptResult(newClasses[i]); } } else { requestor.acceptResult(classFile); } CompilationAndWeavingContext.leavingPhase(tok); } /** helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType */ public BcelObjectType getClassType(String forClass) { return BcelWorld.getBcelObjectType(world.resolve(forClass)); } public void addParentTypeMungers(String typeName) { weaveParentTypeMungers(world.resolve(typeName)); } public void addNormalTypeMungers(String typeName) { weaveNormalTypeMungers(world.resolve(typeName)); } public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) { List childClasses = clazz.getChildClasses(world); UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClassBytesIncludingReweavable(world)); int index = 1; for (Iterator iter = childClasses.iterator(); iter.hasNext();) { UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next(); UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } return ret; } /** * Weaves new parents and annotations onto a type ("declare parents" and "declare @type") * * Algorithm: * 1. First pass, do parents then do annotations. During this pass record: * - any parent mungers that don't match but have a non-wild annotation type pattern * - any annotation mungers that don't match * 2. Multiple subsequent passes which go over the munger lists constructed in the first * pass, repeatedly applying them until nothing changes. * FIXME asc confirm that algorithm is optimal ?? */ public void weaveParentTypeMungers(ResolvedType onType) { if (onType.isRawType()) onType = onType.getGenericType(); onType.clearInterTypeMungers(); List decpToRepeat = new ArrayList(); boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) { DeclareParents decp = (DeclareParents)i.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { // Perhaps it would have matched if a 'dec @type' had modified the type if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp); } } // Still first pass - apply all dec @type mungers for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation)i.next(); boolean typeChanged = applyDeclareAtType(decA,onType,true); if (typeChanged) { anAnnotationChangeOccurred = true; } } while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List decpToRepeatNextTime = new ArrayList(); for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) { DeclareParents decp = (DeclareParents) iter.next(); boolean typeChanged = applyDeclareParents(decp,onType); if (typeChanged) { aParentChangeOccurred = true; } else { decpToRepeatNextTime.add(decp); } } for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) { DeclareAnnotation decA = (DeclareAnnotation) iter.next(); boolean typeChanged = applyDeclareAtType(decA,onType,false); if (typeChanged) { anAnnotationChangeOccurred = true; } } decpToRepeat = decpToRepeatNextTime; } } /** * Apply a declare @type - return true if we change the type */ private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType,boolean reportProblems) { boolean didSomething = false; if (decA.matches(onType)) { if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) { // Could put out a lint here for an already annotated type ... // 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) { AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation()); // TAG: WeavingMessage if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){ getWorld().getMessageHandler().handleMessage( WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES, new String[]{ onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()), decA.getAnnotationString(), "type", decA.getAspect().toString(), Utility.beautifyLocation(decA.getSourceLocation()) })); } didSomething = true; ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX); newAnnotationTM.setSourceLocation(decA.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world))); decA.copyAnnotationTo(onType); } } return didSomething; } /** * Checks for an @target() on the annotation and if found ensures it allows the annotation * to be attached to the target type that matched. */ private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationX annoX,boolean outputProblems) { boolean problemReported = false; if (annoX.specifiesTarget()) { if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) { if (outputProblems) { if (decA.isExactPattern()) { world.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation())); } else { if (world.getLint().invalidTargetForAnnotation.isEnabled()) { world.getLint().invalidTargetForAnnotation.signal( new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()}); } } } problemReported = true; } } return problemReported; } /** * Apply a single declare parents - return true if we change the type */ private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) { boolean didSomething = false; List newParents = p.findMatchingNewParents(onType,true); if (!newParents.isEmpty()) { didSomething=true; BcelObjectType classType = BcelWorld.getBcelObjectType(onType); //System.err.println("need to do declare parents for: " + onType); for (Iterator j = newParents.iterator(); j.hasNext(); ) { ResolvedType newParent = (ResolvedType)j.next(); // We set it here so that the imminent matching for ITDs can succeed - we // still haven't done the necessary changes to the class file itself // (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent() classType.addParent(newParent); ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent); newParentMunger.setSourceLocation(p.getSourceLocation()); onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p))); } } return didSomething; } public void weaveNormalTypeMungers(ResolvedType onType) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, onType.getName()); if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType(); for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (!m.isLateMunger() && m.matches(onType)) { onType.addInterTypeMunger(m); } } CompilationAndWeavingContext.leavingPhase(tok); } // exposed for ClassLoader dynamic weaving public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { return weave(classFile, classType, false); } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { LazyClassGen ret = weave(classFile, classType, true); if (progressListener != null) { progressMade += progressPerClassFile; progressListener.setProgress(progressMade); progressListener.setText("woven: " + classFile.getFilename()); } return ret; } private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException { if (classType.isSynthetic()) { // Don't touch synthetic classes if (dump) dumpUnchanged(classFile); return null; } List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX()); List typeMungers = classType.getResolvedTypeX().getInterTypeMungers(); classType.getResolvedTypeX().checkInterTypeMungers(); // Decide if we need to do actual weaving for this class boolean mightNeedToWeave = shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() || world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0; // May need bridge methods if on 1.5 and something in our hierarchy is affected by ITDs boolean mightNeedBridgeMethods = world.isInJava5Mode() && !classType.isInterface() && classType.getResolvedTypeX().getInterTypeMungersIncludingSupers().size()>0; LazyClassGen clazz = null; if (mightNeedToWeave || mightNeedBridgeMethods) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = false; if (mightNeedToWeave) isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList); if (mightNeedBridgeMethods) isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world,clazz) || isChanged; if (isChanged) { if (dump) dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { String messageText = "trouble in: \n" + clazz.toLongString(); getWorld().getMessageHandler().handleMessage( new Message(messageText,IMessage.ABORT,re,null) ); } catch (Error re) { String messageText = "trouble in: \n" + clazz.toLongString(); getWorld().getMessageHandler().handleMessage( new Message(messageText,IMessage.ABORT,re,null) ); } } // this is very odd return behavior trying to keep everyone happy if (dump) { dumpUnchanged(classFile); return clazz; } else { // ATAJ: the class was not weaved, but since it gets there early it may have new generated inner classes // attached to it to support LTW perX aspectOf support (see BcelPerClauseAspectAdder) // that aggressively defines the inner <aspect>$mayHaveAspect interface. if (clazz != null && !clazz.getChildClasses(world).isEmpty()) { return clazz; } return null; } } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); if (!clazz.getChildClasses(world).isEmpty()) { for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass(world).getBytes(), clazz.getChildClasses(world) ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } private List fastMatch(List list, ResolvedType type) { if (list == null) return Collections.EMPTY_LIST; // here we do the coarsest grained fast match with no kind constraints // this will remove all obvious non-matches and see if we need to do any weaving FastMatchInfo info = new FastMatchInfo(type, null); List result = new ArrayList(); Iterator iter = list.iterator(); while (iter.hasNext()) { ShadowMunger munger = (ShadowMunger)iter.next(); FuzzyBoolean fb = munger.getPointcut().fastMatch(info); WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info if (fb.maybeTrue()) { result.add(munger); } } return result; } public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) { progressListener = listener; this.progressMade = previousProgress; this.progressPerClassFile = progressPerClassFile; } public void setReweavableMode(boolean xNotReweavable) { inReweavableMode = !xNotReweavable; WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable,false,true); BcelClassWeaver.setReweavableMode(!xNotReweavable); } public boolean isReweavable() { return inReweavableMode; } public World getWorld() { return world; } }
128,618
Bug 128618 [incremental] XLint warnings in the wrong place with incremental compilation
The zip file I am about to attach contains two AspectJ project, one depending on the other. If you make a small change to MainClass.java in 'Test Project' and save you will see a strange warning in that class - "advice defined in ras.FFDC has not been applied [Xlint:adviceDidNotMatch]". If you do a full build the warning goes away. Note that the error would be on line 36 if there were 36 lines in the class, which relates to a line in the FFDC aspect that contains advice.
resolved fixed
89d66dc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T16:07:04Z
2006-02-20T12:53:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/WeaverMessageHandler.java
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.ajdt.internal.compiler; import java.util.ArrayList; import java.util.List; import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceLocation; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.IMessage.Kind; 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.Compiler; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemSeverities; /** * @author colyer * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class WeaverMessageHandler implements IMessageHandler { private IMessageHandler sink; private CompilationResult currentlyWeaving; private Compiler compiler; public WeaverMessageHandler(IMessageHandler handler, Compiler compiler) { this.sink = handler; this.compiler = compiler; } public void setCurrentResult(CompilationResult result) { currentlyWeaving = result; } public boolean handleMessage(IMessage message) throws AbortException { if (! (message.isError() || message.isWarning()) ) return sink.handleMessage(message); // we only care about warnings and errors here... ISourceLocation sLoc = message.getSourceLocation(); // See bug 62073. We should assert that the caller pass the correct primary source location. // But for AJ1.2 final we will simply do less processing of the locations if that is not the // case (By calling sink.handleMessage()) - this ensures we don't put out bogus source context info. if (sLoc instanceof EclipseSourceLocation) { EclipseSourceLocation esLoc = (EclipseSourceLocation)sLoc; if (currentlyWeaving!=null && esLoc.getCompilationResult()!=null) { if (!currentlyWeaving.equals(((EclipseSourceLocation)sLoc).getCompilationResult())) return sink.handleMessage(message); // throw new RuntimeException("Primary source location must match the file we are currently processing!"); } } CompilationResult problemSource = currentlyWeaving; if (problemSource == null) { // must be a problem found during completeTypeBindings phase of begin to compile if (sLoc instanceof EclipseSourceLocation) { problemSource = ((EclipseSourceLocation)sLoc).getCompilationResult(); } if (problemSource == null) { // XXX this is ok for ajc, will have to do better for AJDT in time... return sink.handleMessage(message); } } int startPos = getStartPos(sLoc,problemSource); int endPos = getEndPos(sLoc,problemSource); int severity = message.isError() ? ProblemSeverities.Error : ProblemSeverities.Warning; char[] filename = problemSource.fileName; boolean usedBinarySourceFileName = false; if (problemSource.isFromBinarySource()) { if (sLoc != null) { filename = sLoc.getSourceFile().getPath().toCharArray(); usedBinarySourceFileName = true; } } ReferenceContext referenceContext = findReferenceContextFor(problemSource); IProblem problem = compiler.problemReporter.createProblem( filename, IProblem.Unclassified, new String[0], new String[] {message.getMessage()}, severity, startPos, endPos, sLoc != null ? sLoc.getLine() : 0 ); IProblem[] seeAlso = buildSeeAlsoProblems(problem,message.getExtraSourceLocations(), problemSource, usedBinarySourceFileName); problem.setSeeAlsoProblems(seeAlso); StringBuffer details = new StringBuffer(); // Stick more info in supplementary message info if (message.getDetails() != null) { details.append(message.getDetails()); } // Remember if this message was due to a deow if (message.getDeclared()) { details.append("[deow=true]"); } if (details.length()!=0) { problem.setSupplementaryMessageInfo(details.toString()); } compiler.problemReporter.record(problem, problemSource, referenceContext); return true; } public boolean isIgnoring(Kind kind) { return sink.isIgnoring(kind); } /** * No-op * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) * @param kind */ public void dontIgnore(IMessage.Kind kind) { ; } private int getStartPos(ISourceLocation sLoc,CompilationResult result) { int pos = 0; if (sLoc == null) return 0; int line = sLoc.getLine(); if (sLoc instanceof EclipseSourceLocation) { pos = ((EclipseSourceLocation)sLoc).getStartPos(); } else { if (line <= 1) return 0; if (result != null) { if ((result.lineSeparatorPositions != null) && (result.lineSeparatorPositions.length >= (line-1))) { pos = result.lineSeparatorPositions[line-2] + 1; } } } return pos; } private int getEndPos(ISourceLocation sLoc,CompilationResult result) { int pos = 0; if (sLoc == null) return 0; int line = sLoc.getLine(); if (line <= 0) line = 1; if (sLoc instanceof EclipseSourceLocation) { pos = ((EclipseSourceLocation)sLoc).getEndPos(); } else { if (result != null) { if ((result.lineSeparatorPositions != null) && (result.lineSeparatorPositions.length >= line)) { pos = result.lineSeparatorPositions[line -1] -1; } } } return pos; } private ReferenceContext findReferenceContextFor(CompilationResult result) { ReferenceContext context = null; if (compiler.unitsToProcess == null) return null; for (int i = 0; i < compiler.unitsToProcess.length; i++) { if ((compiler.unitsToProcess[i] != null) && (compiler.unitsToProcess[i].compilationResult == result)) { context = compiler.unitsToProcess[i]; break; } } return context; } private IProblem[] buildSeeAlsoProblems(IProblem originalProblem,List sourceLocations, CompilationResult problemSource, boolean usedBinarySourceFileName) { List ret = new ArrayList(); for (int i = 0; i < sourceLocations.size(); i++) { ISourceLocation loc = (ISourceLocation) sourceLocations.get(i); if (loc != null ) { DefaultProblem dp = new DefaultProblem( loc.getSourceFile().getPath().toCharArray(), "see also", 0, new String[] {}, ProblemSeverities.Ignore, getStartPos(loc,null), getEndPos(loc,null), loc.getLine()); ret.add(dp); } else { System.err.println("About to abort due to null location, dumping state:"); System.err.println("> Original Problem="+problemSource.toString()); throw new RuntimeException("Internal Compiler Error: Unexpected null source location passed as 'see also' location."); } } if (usedBinarySourceFileName) { DefaultProblem dp = new DefaultProblem(problemSource.fileName,"see also",0,new String[] {}, ProblemSeverities.Ignore,0, 0,0); ret.add(dp); } IProblem[] retValue = (IProblem[])ret.toArray(new IProblem[]{}); return retValue; } }
128,618
Bug 128618 [incremental] XLint warnings in the wrong place with incremental compilation
The zip file I am about to attach contains two AspectJ project, one depending on the other. If you make a small change to MainClass.java in 'Test Project' and save you will see a strange warning in that class - "advice defined in ras.FFDC has not been applied [Xlint:adviceDidNotMatch]". If you do a full build the warning goes away. Note that the error would be on line 36 if there were 36 lines in the class, which relates to a line in the FFDC aspect that contains advice.
resolved fixed
89d66dc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T16:07:04Z
2006-02-20T12:53:20Z
tests/multiIncremental/PR128618_2/base/mainpackage/MainClass.java
128,618
Bug 128618 [incremental] XLint warnings in the wrong place with incremental compilation
The zip file I am about to attach contains two AspectJ project, one depending on the other. If you make a small change to MainClass.java in 'Test Project' and save you will see a strange warning in that class - "advice defined in ras.FFDC has not been applied [Xlint:adviceDidNotMatch]". If you do a full build the warning goes away. Note that the error would be on line 36 if there were 36 lines in the class, which relates to a line in the FFDC aspect that contains advice.
resolved fixed
89d66dc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T16:07:04Z
2006-02-20T12:53:20Z
tests/multiIncremental/PR128618_2/inc1/mainpackage/MainClass.java
128,618
Bug 128618 [incremental] XLint warnings in the wrong place with incremental compilation
The zip file I am about to attach contains two AspectJ project, one depending on the other. If you make a small change to MainClass.java in 'Test Project' and save you will see a strange warning in that class - "advice defined in ras.FFDC has not been applied [Xlint:adviceDidNotMatch]". If you do a full build the warning goes away. Note that the error would be on line 36 if there were 36 lines in the class, which relates to a line in the FFDC aspect that contains advice.
resolved fixed
89d66dc
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T16:07:04Z
2006-02-20T12:53:20Z
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Andy Clement initial implementation * ******************************************************************/ package org.aspectj.systemtest.incremental.tools; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.aspectj.ajdt.internal.core.builder.AjState; import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IProgramElement; import org.aspectj.bridge.IMessage; import org.aspectj.testing.util.FileUtil; /** * The superclass knows all about talking through Ajde to the compiler. * The superclass isn't in charge of knowing how to simulate overlays * for incremental builds, that is in here. As is the ability to * generate valid build configs based on a directory structure. To * support this we just need access to a sandbox directory - this * sandbox is managed by the superclass (it only assumes all builds occur * in <sandboxDir>/<projectName>/ ) * * The idea is you can initialize multiple projects in the sandbox and * they can all be built independently, hopefully exploiting * incremental compilation. Between builds you can alter the contents * of a project using the alter() method that overlays some set of * new files onto the current set (adding new files/changing existing * ones) - you can then drive a new build and check it behaves as * expected. */ public class MultiProjectIncrementalTests extends AjdeInteractionTestbed { public static boolean VERBOSE = false; protected void setUp() throws Exception { super.setUp(); AjdeInteractionTestbed.VERBOSE = VERBOSE; } // Compile a single simple project public void testTheBasics() { initialiseProject("P1"); build("P1"); // This first build will be batch build("P1"); checkWasntFullBuild(); checkCompileWeaveCount(0,0); } // source code doesnt matter, we are checking invalid path handling public void testInvalidAspectpath_pr121395() { initialiseProject("P1"); File f = new File("foo.jar"); Set s = new HashSet(); s.add(f); configureAspectPath(s); build("P1"); // This first build will be batch checkForError("invalid aspectpath entry"); } // Make simple changes to a project, adding a class public void testSimpleChanges() { initialiseProject("P1"); build("P1"); // This first build will be batch alter("P1","inc1"); // adds a single class build("P1"); checkCompileWeaveCount(1,-1); build("P1"); checkCompileWeaveCount(0,-1); } // Make simple changes to a project, adding a class and an aspect public void testAddingAnAspect() { initialiseProject("P1"); build("P1"); // build 1, weave 1 alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); // build 1, long timeTakenForFullBuildAndWeave = getTimeTakenForBuild(); checkWasFullBuild(); // it *will* be a full build under the new // "back-to-the-source strategy checkCompileWeaveCount(5,3); // we compile X and A (the delta) find out that // an aspect has changed, go back to the source // and compile X,A,C, then weave them all. build("P1"); long timeTakenForSimpleIncBuild = getTimeTakenForBuild(); // I don't think this test will have timing issues as the times should be *RADICALLY* different // On my config, first build time is 2093ms and the second is 30ms assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+ "ms second="+timeTakenForSimpleIncBuild+"ms", timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave); } public void testBuildingTwoProjectsInTurns() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); } /** * In order for this next test to run, I had to move the weaver/world pair we keep in the * AjBuildManager instance down into the state object - this makes perfect sense - otherwise * when reusing the state for another project we'd not be switching to the right weaver/world * for that project. */ public void testBuildingTwoProjectsMakingSmallChanges() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); build("P2"); build("P1"); checkWasntFullBuild(); build("P2"); checkWasntFullBuild(); alter("P1","inc1"); // adds a class alter("P1","inc2"); // adds an aspect build("P1"); checkWasFullBuild(); // adding an aspect makes us go back to the source } /** * Setup up two simple projects and build them in turn - check the * structure model is right after each build */ public void testBuildingTwoProjectsAndVerifyingModel() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } // Setup up two simple projects and build them in turn - check the // structure model is right after each build public void testBuildingTwoProjectsAndVerifyingStuff() { configureBuildStructureModel(true); initialiseProject("P1"); initialiseProject("P2"); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); build("P1"); checkForNode("pkg","C",true); build("P2"); checkForNode("pkg","C",false); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, adding a new method and check structural changes is 1. */ public void testStateManagement1() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be a state object for project P1",ajs!=null); assertTrue("Should be no structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc3"); // adds a method to the class C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Should be one structural changes as it was a full build but found: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1); } /** * Complex. Here we are testing that a state object records structural changes since * the last full build correctly. We build a simple project from scratch - this will * be a full build and so the structural changes since last build count should be 0. * We then alter a class, changing body of a method, not the structure and * check struc changes is still 0. */ public void testStateManagement2() { File binDirectoryForP1 = new File(getFile("P1","bin")); initialiseProject("P1"); alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making // it a structural change build("P1"); // full build AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1); assertTrue("There should be state for project P1",ajs!=null); assertTrue("Should be no struc changes as its a full build: "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java build("P1"); checkWasntFullBuild(); ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin"))); assertTrue("There should be state for project P1",ajs!=null); checkWasntFullBuild(); assertTrue("Shouldn't be any structural changes but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(), ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0); } /** * Now the most complex test. Create a dependancy between two projects. Building * one may affect whether the other does an incremental or full build. The * structural information recorded in the state object should be getting used * to control whether a full build is necessary... */ public void testBuildingDependantProjects() { initialiseProject("P1"); initialiseProject("P2"); configureNewProjectDependency("P2","P1"); build("P1"); build("P2"); // now everything is consistent and compiled alter("P1","inc1"); // adds a second class build("P1"); build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :) checkWasntFullBuild(); alter("P1","inc3"); // structurally changes one of the classes build("P1"); build("P2"); // build notices the structural change checkWasFullBuild(); alter("P1","inc4"); build("P1"); build("P2"); // build sees a change but works out its not structural checkWasntFullBuild(); } public void testPr85132() { initialiseProject("PR85132"); build("PR85132"); alter("PR85132","inc1"); build("PR85132"); } // parameterization of generic aspects public void testPr125405() { initialiseProject("PR125405"); build("PR125405"); checkCompileWeaveCount(1,1); alter("PR125405","inc1"); build("PR125405"); // "only abstract aspects can have type parameters" checkForError("only abstract aspects can have type parameters"); alter("PR125405","inc2"); build("PR125405"); checkCompileWeaveCount(2,1); assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0); } public void testPr92837() { initialiseProject("PR92837"); build("PR92837"); alter("PR92837","inc1"); build("PR92837"); } public void testPr119570() { initialiseProject("PR119570"); build("PR119570"); assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0); } public void testPr119570_2() { initialiseProject("PR119570_2"); build("PR119570_2"); List l = MyTaskListManager.getWarningMessages(); assertTrue("Should be no warnings, but got "+l,l.size()==0); } // If you fiddle with the compiler options - you must manually reset the options at the end of the test public void testPr117209() { try { initialiseProject("pr117209"); configureNonStandardCompileOptions("-proceedOnError"); build("pr117209"); checkCompileWeaveCount(6,6); } finally { MyBuildOptionsAdapter.reset(); } } public void testPr114875() { initialiseProject("pr114875"); build("pr114875"); alter("pr114875","inc1"); build("pr114875"); checkWasFullBuild(); alter("pr114875","inc2"); build("pr114875"); checkWasFullBuild(); // back to the source for an aspect change } public void testPr117882() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882"); build("PR117882"); checkWasFullBuild(); alter("PR117882","inc1"); build("PR117882"); checkWasFullBuild(); // back to the source for an aspect // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr117882_2() { // AjdeInteractionTestbed.VERBOSE=true; // AjdeInteractionTestbed.configureBuildStructureModel(true); initialiseProject("PR117882_2"); build("PR117882_2"); checkWasFullBuild(); alter("PR117882_2","inc1"); build("PR117882_2"); checkWasFullBuild(); // back to the source... //checkCompileWeaveCount(1,4); //fullBuild("PR117882_2"); //checkWasFullBuild(); // AjdeInteractionTestbed.VERBOSE=false; // AjdeInteractionTestbed.configureBuildStructureModel(false); } public void testPr115251() { //AjdeInteractionTestbed.VERBOSE=true; initialiseProject("PR115251"); build("PR115251"); checkWasFullBuild(); alter("PR115251","inc1"); build("PR115251"); checkWasFullBuild(); // back to the source } // public void testPr124399() { // AjdeInteractionTestbed.VERBOSE=true; // configureBuildStructureModel(true); // initialiseProject("PR124399"); // build("PR124399"); // checkWasFullBuild(); // alter("PR124399","inc1"); // build("PR124399"); // checkWasntFullBuild(); // } public void testPr121384() { // AjdeInteractionTestbed.VERBOSE=true; // AsmManager.setReporting("c:/foo.txt",true,true,true,false); MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo"); configureBuildStructureModel(true); initialiseProject("pr121384"); build("pr121384"); checkWasFullBuild(); alter("pr121384","inc1"); build("pr121384"); checkWasntFullBuild(); } /* public void testPr111779() { super.VERBOSE=true; initialiseProject("PR111779"); build("PR111779"); alter("PR111779","inc1"); build("PR111779"); } */ public void testPr93310_1() { initialiseProject("PR93310_1"); build("PR93310_1"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_1","inc1"); build("PR93310_1"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1); String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java")); } public void testPr93310_2() { initialiseProject("PR93310_2"); build("PR93310_2"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java"; (new File(fileC2)).delete(); alter("PR93310_2","inc1"); build("PR93310_2"); checkWasFullBuild(); int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size(); assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1); String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0); assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java")); } // Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A. // Stage2: make the field private in class A > gives compile error // Stage3: Add a new aspect whilst there is a compile error ! public void testPr113531() { initialiseProject("PR113531"); build("PR113531"); assertFalse("build should have compiled ok", MyTaskListManager.hasErrorMessages()); alter("PR113531","inc1"); build("PR113531"); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); alter("PR113531","inc2"); build("PR113531"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); assertEquals("error message should be 'foo cannot be resolved' ", "foo cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); } // Stage 1: Compile the 4 files, pack.A2 extends pack.A1 (aspects) where // A2 uses a protected field in A1 and pack.C2 extends pack.C1 (classes) // where C2 uses a protected field in C1 // Stage 2: make the field private in class C1 ==> compile errors in C2 // Stage 3: make the field private in aspect A1 whilst there's the compile // error. // There shouldn't be a BCExcpetion saying can't find delegate for pack.C2 public void testPr119882() { initialiseProject("PR119882"); build("PR119882"); assertFalse("build should have compiled ok",MyTaskListManager.hasErrorMessages()); alter("PR119882","inc1"); build("PR119882"); //fullBuild("PR119882"); assertEquals("error message should be 'i cannot be resolved' ", "i cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); alter("PR119882","inc2"); build("PR119882"); assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(), MyErrorHandler.getErrorMessages().isEmpty()); assertEquals("error message should be 'i cannot be resolved' ", "i cannot be resolved", ((IMessage)MyTaskListManager.getErrorMessages().get(0)) .getMessage()); } public void testPr112736() { // AjdeInteractionTestbed.VERBOSE = true; initialiseProject("PR112736"); build("PR112736"); checkWasFullBuild(); String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java"; (new File(fileC2)).delete(); alter("PR112736","inc1"); build("PR112736"); checkWasFullBuild(); } /** * We have problems with multiple rewrites of a pointcut across incremental builds. */ public void testPr113257() { initialiseProject("PR113257"); build("PR113257"); alter("PR113257","inc1"); build("PR113257"); checkWasFullBuild(); // back to the source alter("PR113257","inc1"); build("PR113257"); } public void testPr123612() { initialiseProject("PR123612"); build("PR123612"); alter("PR123612","inc1"); build("PR123612"); checkWasFullBuild(); // back to the source } public void testPr128655() { configureNonStandardCompileOptions("-showWeaveInfo"); initialiseProject("pr128655"); build("pr128655"); List firstBuildMessages = MyTaskListManager.getWeavingMessages(); assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0); alter("pr128655","inc1"); build("pr128655"); checkWasntFullBuild(); // back to the source List secondBuildMessages = MyTaskListManager.getWeavingMessages(); // check they are the same for (int i = 0; i < firstBuildMessages.size(); i++) { IMessage m1 = (IMessage)firstBuildMessages.get(i); IMessage m2 = (IMessage)secondBuildMessages.get(i); if (!m1.toString().equals(m2.toString())) { System.err.println("Message during first build was: "+m1); System.err.println("Message during second build was: "+m1); fail("The two messages should be the same, but are not: \n"+m1+"!="+m2); } } } // Similar to above, but now the annotation is in the default package public void testPr128655_2() { configureNonStandardCompileOptions("-showWeaveInfo"); initialiseProject("pr128655_2"); build("pr128655_2"); List firstBuildMessages = MyTaskListManager.getWeavingMessages(); assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0); alter("pr128655_2","inc1"); build("pr128655_2"); checkWasntFullBuild(); // back to the source List secondBuildMessages = MyTaskListManager.getWeavingMessages(); // check they are the same for (int i = 0; i < firstBuildMessages.size(); i++) { IMessage m1 = (IMessage)firstBuildMessages.get(i); IMessage m2 = (IMessage)secondBuildMessages.get(i); if (!m1.toString().equals(m2.toString())) { System.err.println("Message during first build was: "+m1); System.err.println("Message during second build was: "+m1); fail("The two messages should be the same, but are not: \n"+m1+"!="+m2); } } } // other possible tests: // - memory usage (freemem calls?) // - relationship map // --------------------------------------------------------------------------------------------------- /** * Check we compiled/wove the right number of files, passing '-1' indicates you don't care about * that number. */ private void checkCompileWeaveCount(int expCompile,int expWoven) { if (expCompile!=-1 && getCompiledFiles().size()!=expCompile) fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+ "\n"+printCompiledAndWovenFiles()); if (expWoven!=-1 && getWovenClasses().size()!=expWoven) fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+ "\n"+printCompiledAndWovenFiles()); } private void checkWasntFullBuild() { assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild()); } private void checkWasFullBuild() { assertTrue("Should have been a full (batch) build",wasFullBuild()); } private void checkForNode(String packageName,String typeName,boolean shouldBeFound) { IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName); if (shouldBeFound) { if (ipe==null) printModel(); assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null); } else { if (ipe!=null) printModel(); assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null); } } private void printModel() { try { AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0); } catch (IOException e) { e.printStackTrace(); } } public void build(String projectName) { constructUpToDateLstFile(projectName,"build.lst"); build(projectName,"build.lst"); if (AjdeInteractionTestbed.VERBOSE) printBuildReport(); } public void fullBuild(String projectName) { constructUpToDateLstFile(projectName,"build.lst"); fullBuild(projectName,"build.lst"); if (AjdeInteractionTestbed.VERBOSE) printBuildReport(); } private void constructUpToDateLstFile(String pname,String configname) { File projectBase = new File(sandboxDir,pname); File toConstruct = new File(projectBase,configname); List filesForCompilation = new ArrayList(); collectUpFiles(projectBase,projectBase,filesForCompilation); try { FileOutputStream fos = new FileOutputStream(toConstruct); DataOutputStream dos = new DataOutputStream(fos); for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) { String file = (String) iter.next(); dos.writeBytes(file+"\n"); } dos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } public void checkForError(String anError) { List messages = MyTaskListManager.getErrorMessages(); for (Iterator iter = messages.iterator(); iter.hasNext();) { IMessage element = (IMessage) iter.next(); if (element.getMessage().indexOf(anError)!=-1) return; } fail("Didn't find the error message:\n'"+anError+"'.\nErrors that occurred:\n"+MyTaskListManager.getErrorMessages()); } private void collectUpFiles(File location,File base,List collectionPoint) { String contents[] = location.list(); if (contents==null) return; for (int i = 0; i < contents.length; i++) { String string = contents[i]; File f = new File(location,string); if (f.isDirectory()) { collectUpFiles(f,base,collectionPoint); } else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) { String fileFound; try { fileFound = f.getCanonicalPath(); String toRemove = base.getCanonicalPath(); if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove); collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator } catch (IOException e) { e.printStackTrace(); } } } } /** * Fill in the working directory with the project base files, * from the 'base' folder. */ protected void initialiseProject(String p) { File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base"); File destination=new File(getWorkingDir(),p); if (!destination.exists()) {destination.mkdir();} copy(projectSrc,destination);//,false); } /* * Applies an overlay onto the project being tested - copying * the contents of the specified overlay directory. */ private void alter(String projectName,String overlayDirectory) { File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+ File.separatorChar+overlayDirectory); File destination=new File(getWorkingDir(),projectName); copy(projectSrc,destination); } /** * Copy the contents of some directory to another location - the * copy is recursive. */ private void copy(File from, File to) { String contents[] = from.list(); if (contents==null) return; for (int i = 0; i < contents.length; i++) { String string = contents[i]; File f = new File(from,string); File t = new File(to,string); if (f.isDirectory() && !f.getName().startsWith("inc")) { t.mkdir(); copy(f,t); } else if (f.isFile()) { StringBuffer sb = new StringBuffer(); //if (VERBOSE) System.err.println("Copying "+f+" to "+t); FileUtil.copyFile(f,t,sb); if (sb.length()!=0) { System.err.println(sb.toString());} } } } private static void log(String msg) { if (VERBOSE) System.out.println(msg); } }
122,742
Bug 122742 [@AspectJ] VerifyError with @AfterThrowing/@AfterReturning and extra JoinPoint argument
If an @AspectJ aspect advises itself using after throwing advice that itself throws an exception running the resulting program causes a VerifyError: java.lang.VerifyError: (class: A, method: stop signature: ()V) catch_type not a subclass of Throwable at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2365) at java.lang.Class.getMethod0(Class.java:2611) at java.lang.Class.getMethod(Class.java:1579) at org.aspectj.tools.ajc.AjcTestCase.run(AjcTestCase.java:608) at org.aspectj.testing.RunSpec.execute(RunSpec.java:56) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc150.Ajc150Tests.testError(Ajc150Tests.java:877) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
resolved fixed
3fa1bdd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T16:13:44Z
2006-01-05T11:20:00Z
tests/bugs151/pr122742/AfterReturningTest.java
122,742
Bug 122742 [@AspectJ] VerifyError with @AfterThrowing/@AfterReturning and extra JoinPoint argument
If an @AspectJ aspect advises itself using after throwing advice that itself throws an exception running the resulting program causes a VerifyError: java.lang.VerifyError: (class: A, method: stop signature: ()V) catch_type not a subclass of Throwable at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2365) at java.lang.Class.getMethod0(Class.java:2611) at java.lang.Class.getMethod(Class.java:1579) at org.aspectj.tools.ajc.AjcTestCase.run(AjcTestCase.java:608) at org.aspectj.testing.RunSpec.execute(RunSpec.java:56) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc150.Ajc150Tests.testError(Ajc150Tests.java:877) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
resolved fixed
3fa1bdd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T16:13:44Z
2006-01-05T11:20:00Z
tests/bugs151/pr122742/AfterThrowingTest.java
122,742
Bug 122742 [@AspectJ] VerifyError with @AfterThrowing/@AfterReturning and extra JoinPoint argument
If an @AspectJ aspect advises itself using after throwing advice that itself throws an exception running the resulting program causes a VerifyError: java.lang.VerifyError: (class: A, method: stop signature: ()V) catch_type not a subclass of Throwable at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2365) at java.lang.Class.getMethod0(Class.java:2611) at java.lang.Class.getMethod(Class.java:1579) at org.aspectj.tools.ajc.AjcTestCase.run(AjcTestCase.java:608) at org.aspectj.testing.RunSpec.execute(RunSpec.java:56) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc150.Ajc150Tests.testError(Ajc150Tests.java:877) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
resolved fixed
3fa1bdd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T16:13:44Z
2006-01-05T11:20:00Z
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
/******************************************************************************* * Copyright (c) 2006 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.ajc151; import java.io.File; import java.util.List; import junit.framework.Test; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.Relationship; import org.aspectj.systemtest.ajc150.GenericsTests; import org.aspectj.testing.XMLBasedAjcTestCase; public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public void testGenericAdviceParameters_pr123553() { runTest("generic advice parameters");} public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");} public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");} public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");} public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");} public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");} public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");} public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");} public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");} public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");} public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");} public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");} public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");} //public void testExposingWithintype_enh123423() { runTest("exposing withintype");} //public void testMissingImport_pr127299() { runTest("missing import gives funny message");} public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");} public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); } public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); } public void testBrokenLTW_pr128744() { runTest("broken ltw"); } public void testMixingNumbersOfTypeParameters_pr125080() { runTest("mixing numbers of type parameters"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;"); } public void testMixingNumbersOfTypeParameters_pr125080_2() { runTest("mixing numbers of type parameters - 2"); GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;"); GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;"); GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;"); } public void testIProgramElementMethods_pr125295() { runTest("new IProgramElement methods"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForType("pkg","foo"); assertNotNull("Couldn't find 'foo' element in the tree",pe); // check that the defaults return the fully qualified arg assertEquals("foo(int, java.lang.Object)",pe.toLabelString()); assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString()); assertEquals("foo(int, java.lang.Object)",pe.toSignatureString()); // check that can get hold of the non qualified args assertEquals("foo(int, Object)",pe.toLabelString(false)); assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false)); assertEquals("foo(int, Object)",pe.toSignatureString(false)); IProgramElement pe2 = top.findElementForType("pkg","printParameters"); assertNotNull("Couldn't find 'printParameters' element in the tree",pe2); // the argument is org.aspectj.lang.JoinPoint, check that this is added assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty()); } public void testParameterizedEnum_pr126316() { runTest("E extends Enum(E) again"); } public void testSwallowedException() { runTest("swallowed exceptions"); } public void testSwallowedExceptionIgnored() { runTest("swallowed exceptions with xlint"); } /* * @AspectJ bugs and enhancements */ // public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { // runTest("inherit adivce with this() and thisJoinPoint"); // } public void testAtAspectInheritsAbstractPointcut_pr125810 () { runTest("warning when inherited pointcut not made concrete"); } public void testAtAspectDEOWInStructureModel_pr120356() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("@AJ deow appear correctly when structure model is generated"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // get the IProgramElements corresponding to the @DeclareWarning statement // and the method it matches. IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"warningMethod()"); assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE); IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"warning"); assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE); // check that the method has a matches declare relationship with @DeclareWarning List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE); assertNotNull("warningMethod should have some relationships but does not",matches); assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1); List matchesTargets = ((Relationship)matches.get(0)).getTargets(); assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0)); assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label " + target.toLabelString(),atDeclareWarningIPE,target); // check that the @DeclareWarning has a matches relationship with the warningMethod List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE); assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy); assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1); List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets(); assertTrue("@DeclareWarning 'matched by' relationship should have one target " + "but has " + matchedByTargets.size(), matchedByTargets.size() == 1); IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0)); assertEquals("target of relationship should be the warningMethod but is IPE with label " + matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget); // get the IProgramElements corresponding to the @DeclareError statement // and the method it matches. IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"badMethod()"); assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE); IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD,"error"); assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE); // check that the @DeclareError has a matches relationship with the badMethod List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE); assertNotNull("@DeclareError should have some relationships but does not",matchedByE); assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1); List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets(); assertTrue("@DeclareError 'matched by' relationship should have one target " + "but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1); IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0)); assertEquals("target of relationship should be the badMethod but is IPE with label " + matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE); } public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() { runTest("@AJ no NPE with deow when structure model isn't generated"); } public void testAtAspectWithoutJoinPointImport_pr121616() { runTest("@AJ without JoinPoint import"); } public void testAtAspectDeclareParentsRetainsFieldState_pr122370() { runTest("@AJ declare parents retains field state"); } public void testAtAspectNoNPEWithPcdContainingOrThisAndWildcard_pr128237() { runTest("@AJ no npe with pointcut containing or, this and a wildcard"); } /* * Load-time weaving bugs and enhancements */ public void testEmptyPointcutInAtAspectJ_pr125475 () { runTest("define empty pointcut using an annotation"); } public void testEmptyPointcutInAtAspectJ_pr125475_2() { runTest("define empty pointcut using an annotation - 2"); } public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () { runTest("define empty pointcut using aop.xml"); } public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () { runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent"); } ///////////////////////////////////////// public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml"); } }
122,742
Bug 122742 [@AspectJ] VerifyError with @AfterThrowing/@AfterReturning and extra JoinPoint argument
If an @AspectJ aspect advises itself using after throwing advice that itself throws an exception running the resulting program causes a VerifyError: java.lang.VerifyError: (class: A, method: stop signature: ()V) catch_type not a subclass of Throwable at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2365) at java.lang.Class.getMethod0(Class.java:2611) at java.lang.Class.getMethod(Class.java:1579) at org.aspectj.tools.ajc.AjcTestCase.run(AjcTestCase.java:608) at org.aspectj.testing.RunSpec.execute(RunSpec.java:56) at org.aspectj.testing.AjcTest.runTest(AjcTest.java:68) at org.aspectj.testing.XMLBasedAjcTestCase.runTest(XMLBasedAjcTestCase.java:111) at org.aspectj.systemtest.ajc150.Ajc150Tests.testError(Ajc150Tests.java:877) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
resolved fixed
3fa1bdd
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-21T16:13:44Z
2006-01-05T11:20:00Z
weaver/src/org/aspectj/weaver/Advice.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.Collections; import java.util.List; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.bcel.Utility; import org.aspectj.weaver.patterns.AndPointcut; import org.aspectj.weaver.patterns.PerClause; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.TypePattern; public abstract class Advice extends ShadowMunger { protected AjAttribute.AdviceAttribute attribute; // the pointcut field is ignored protected AdviceKind kind; // alias of attribute.getKind() protected Member signature; // not necessarily declaring aspect, this is a semantics change from 1.0 protected ResolvedType concreteAspect; // null until after concretize protected List innerCflowEntries = Collections.EMPTY_LIST; // just for cflow*Entry kinds protected int nFreeVars; // just for cflow*Entry kinds protected TypePattern exceptionType; // just for Softener kind // if we are parameterized, these type may be different to the advice signature types protected UnresolvedType[] bindingParameterTypes; protected List/*Lint.Kind*/ suppressedLintKinds = null; // based on annotations on this advice public static Advice makeCflowEntry(World world, Pointcut entry, boolean isBelow, Member stackField, int nFreeVars, List innerCflowEntries, ResolvedType inAspect){ Advice ret = world.createAdviceMunger(isBelow ? AdviceKind.CflowBelowEntry : AdviceKind.CflowEntry, entry, stackField, 0, entry); //0); ret.innerCflowEntries = innerCflowEntries; ret.nFreeVars = nFreeVars; ret.concreteAspect = inAspect; return ret; } public static Advice makePerCflowEntry(World world, Pointcut entry, boolean isBelow, Member stackField, ResolvedType inAspect, List innerCflowEntries) { Advice ret = world.createAdviceMunger(isBelow ? AdviceKind.PerCflowBelowEntry : AdviceKind.PerCflowEntry, entry, stackField, 0, entry); ret.innerCflowEntries = innerCflowEntries; ret.concreteAspect = inAspect; return ret; } public static Advice makePerObjectEntry(World world, Pointcut entry, boolean isThis, ResolvedType inAspect) { Advice ret = world.createAdviceMunger(isThis ? AdviceKind.PerThisEntry : AdviceKind.PerTargetEntry, entry, null, 0, entry); ret.concreteAspect = inAspect; return ret; } // PTWIMPL per type within entry advice is what initializes the aspect instance in the matched type public static Advice makePerTypeWithinEntry(World world, Pointcut p, ResolvedType inAspect) { Advice ret = world.createAdviceMunger(AdviceKind.PerTypeWithinEntry,p,null,0,p); ret.concreteAspect = inAspect; return ret; } public static Advice makeSoftener(World world, Pointcut entry, TypePattern exceptionType,ResolvedType inAspect,IHasSourceLocation loc) { Advice ret = world.createAdviceMunger(AdviceKind.Softener, entry, null, 0, loc); ret.exceptionType = exceptionType; ret.concreteAspect = inAspect; // System.out.println("made ret: " + ret + " with " + exceptionType); return ret; } public Advice(AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature) { super(pointcut, attribute.getStart(), attribute.getEnd(), attribute.getSourceContext()); this.attribute = attribute; this.kind = attribute.getKind(); // alias this.signature = signature; if (signature != null) { this.bindingParameterTypes = signature.getParameterTypes(); } else { this.bindingParameterTypes = new UnresolvedType[0]; } } public boolean match(Shadow shadow, World world) { if (super.match(shadow, world)) { if (shadow.getKind() == Shadow.ExceptionHandler) { if (kind.isAfter() || kind == AdviceKind.Around) { world.showMessage(IMessage.WARNING, WeaverMessages.format(WeaverMessages.ONLY_BEFORE_ON_HANDLER), getSourceLocation(), shadow.getSourceLocation()); return false; } } if (hasExtraParameter() && kind == AdviceKind.AfterReturning) { ResolvedType resolvedExtraParameterType = getExtraParameterType().resolve(world); ResolvedType shadowReturnType = shadow.getReturnType().resolve(world); boolean matches = (resolvedExtraParameterType.isConvertableFrom(shadowReturnType) && shadow.getKind().hasReturnValue()); if (matches && resolvedExtraParameterType.isParameterizedType()) { maybeIssueUncheckedMatchWarning(resolvedExtraParameterType,shadowReturnType,shadow,world); } return matches; } else if (hasExtraParameter() && kind==AdviceKind.AfterThrowing) { // pr119749 ResolvedType exceptionType = getExtraParameterType().resolve(world); if (!exceptionType.isCheckedException()) return true; UnresolvedType[] shadowThrows = shadow.getSignature().getExceptions(world); boolean matches = false; for (int i = 0; i < shadowThrows.length && !matches; i++) { ResolvedType type = shadowThrows[i].resolve(world); if (exceptionType.isAssignableFrom(type)) matches=true; } return matches; } else if (kind == AdviceKind.PerTargetEntry) { return shadow.hasTarget(); } else if (kind == AdviceKind.PerThisEntry) { return shadow.hasThis(); } else if (kind == AdviceKind.Around) { if (shadow.getKind() == Shadow.PreInitialization) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AROUND_ON_PREINIT), getSourceLocation(), shadow.getSourceLocation()); return false; } else if (shadow.getKind() == Shadow.Initialization) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AROUND_ON_INIT), getSourceLocation(), shadow.getSourceLocation()); return false; } else if (shadow.getKind() == Shadow.StaticInitialization && shadow.getEnclosingType().resolve(world).isInterface()) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AROUND_ON_INTERFACE_STATICINIT,shadow.getEnclosingType().getName()), getSourceLocation(), shadow.getSourceLocation()); return false; } else { //System.err.println(getSignature().getReturnType() + " from " + shadow.getReturnType()); if (getSignature().getReturnType() == ResolvedType.VOID) { if (shadow.getReturnType() != ResolvedType.VOID) { world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NON_VOID_RETURN,shadow), getSourceLocation(), shadow.getSourceLocation()); return false; } } else if (getSignature().getReturnType().equals(UnresolvedType.OBJECT)) { return true; } else { ResolvedType shadowReturnType = shadow.getReturnType().resolve(world); ResolvedType adviceReturnType = getSignature().getGenericReturnType().resolve(world); if (shadowReturnType.isParameterizedType() && adviceReturnType.isRawType()) { // Set<Integer> and Set ResolvedType shadowReturnGenericType = shadowReturnType.getGenericType(); // Set ResolvedType adviceReturnGenericType = adviceReturnType.getGenericType(); // Set if (shadowReturnGenericType.isAssignableFrom(adviceReturnGenericType) && world.getLint().uncheckedAdviceConversion.isEnabled()) { world.getLint().uncheckedAdviceConversion.signal( new String[]{shadow.toString(),shadowReturnType.getName(),adviceReturnType.getName()}, shadow.getSourceLocation(), new ISourceLocation[]{getSourceLocation()}); } } else if(!shadowReturnType.isAssignableFrom(adviceReturnType)) { //System.err.println(this + ", " + sourceContext + ", " + start); world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.INCOMPATIBLE_RETURN_TYPE,shadow), getSourceLocation(), shadow.getSourceLocation()); return false; } } } } return true; } else { return false; } } /** * In after returning advice if we are binding the extra parameter to a parameterized * type we may not be able to do a type-safe conversion. * @param resolvedExtraParameterType the type in the after returning declaration * @param shadowReturnType the type at the shadow * @param world */ private void maybeIssueUncheckedMatchWarning(ResolvedType afterReturningType, ResolvedType shadowReturnType, Shadow shadow, World world) { boolean inDoubt = !afterReturningType.isAssignableFrom(shadowReturnType); if (inDoubt && world.getLint().uncheckedArgument.isEnabled()) { String uncheckedMatchWith = afterReturningType.getSimpleBaseName(); if (shadowReturnType.isParameterizedType() && (shadowReturnType.getRawType() == afterReturningType.getRawType())) { uncheckedMatchWith = shadowReturnType.getSimpleName(); } if (!Utility.isSuppressing(getSignature().getAnnotations(), "uncheckedArgument")) { world.getLint().uncheckedArgument.signal( new String[] { afterReturningType.getSimpleName(), uncheckedMatchWith, afterReturningType.getSimpleBaseName(), shadow.toResolvedString(world)}, getSourceLocation(), new ISourceLocation[] {shadow.getSourceLocation()}); } } } // ---- public AdviceKind getKind() { return kind; } public Member getSignature() { return signature; } // only called as part of parameterization.... public void setSignature(Member signature) { this.signature = signature; } public boolean hasExtraParameter() { return (getExtraParameterFlags() & ExtraArgument) != 0; } protected int getExtraParameterFlags() { return attribute.getExtraParameterFlags(); } protected int getExtraParameterCount() { return countOnes(getExtraParameterFlags() & ParameterMask); } public UnresolvedType[] getBindingParameterTypes() { return this.bindingParameterTypes; } public void setBindingParameterTypes(UnresolvedType[] types) { this.bindingParameterTypes = types; } public static int countOnes(int bits) { int ret = 0; while (bits != 0) { if ((bits & 1) != 0) ret += 1; bits = bits >> 1; } return ret; } public int getBaseParameterCount() { return getSignature().getParameterTypes().length - getExtraParameterCount(); } public String[] getBaseParameterNames(World world) { String[] allNames = getSignature().getParameterNames(world); int extras = getExtraParameterCount(); if (extras == 0) return allNames; String[] result = new String[getBaseParameterCount()]; for (int i = 0; i < result.length; i++) { result[i] = allNames[i]; } return result; } public UnresolvedType getExtraParameterType() { if (!hasExtraParameter()) return ResolvedType.MISSING; if (signature instanceof ResolvedMember) { return ((ResolvedMember)signature).getGenericParameterTypes()[getBaseParameterCount()]; } else { return signature.getParameterTypes()[getBaseParameterCount()]; } } public UnresolvedType getDeclaringAspect() { return getOriginalSignature().getDeclaringType(); } protected Member getOriginalSignature() { return signature; } protected String extraParametersToString() { if (getExtraParameterFlags() == 0) { return ""; } else { return "(extraFlags: " + getExtraParameterFlags() + ")"; } } public Pointcut getPointcut() { return pointcut; } // ---- /** @param fromType is guaranteed to be a non-abstract aspect * @param clause has been concretized at a higher level */ public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) { // assert !fromType.isAbstract(); Pointcut p = pointcut.concretize(fromType, getDeclaringType(), signature.getArity(), this); if (clause != null) { Pointcut oldP = p; p = new AndPointcut(clause, p); p.copyLocationFrom(oldP); p.state = Pointcut.CONCRETE; //FIXME ? ATAJ copy unbound bindings to ignore p.m_ignoreUnboundBindingForNames =oldP.m_ignoreUnboundBindingForNames; } Advice munger = world.createAdviceMunger(attribute, p, signature); munger.concreteAspect = fromType; munger.bindingParameterTypes = this.bindingParameterTypes; //System.err.println("concretizing here " + p + " with clause " + clause); return munger; } // ---- from object public String toString() { StringBuffer sb = new StringBuffer(); sb.append("(").append(getKind()).append(extraParametersToString()); sb.append(": ").append(pointcut).append("->").append(signature).append(")"); return sb.toString(); // return "(" // + getKind() // + extraParametersToString() // + ": " // + pointcut // + "->" // + signature // + ")"; } public boolean equals(Object other) { if (! (other instanceof Advice)) return false; Advice o = (Advice) other; return o.attribute.equals(attribute) && o.pointcut.equals(pointcut) && o.signature.equals(signature); } private volatile int hashCode = 0; public int hashCode() { if (hashCode == 0) { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + pointcut.hashCode(); if (signature != null) result = 37*result + signature.hashCode(); hashCode = result; } return hashCode; } // ---- fields public static final int ExtraArgument = 1; public static final int ThisJoinPoint = 2; public static final int ThisJoinPointStaticPart = 4; public static final int ThisEnclosingJoinPointStaticPart = 8; public static final int ParameterMask = 0xf; public static final int CanInline = 0x40; // for testing only public void setLexicalPosition(int lexicalPosition) { start = lexicalPosition; } public ResolvedType getConcreteAspect() { return concreteAspect; } }
121,312
Bug 121312 [performance]Contribution: Refactoring to Support LTW World with Reflection Delegates for Bootstrap Types
This patch adds an IReflectionWorld interface, changes the various places in code where casts are made to ReflectionWorld to use that interface, creates some common methods and creates an LTWWorld that implements this interface, and sets up the ClassLoaderWeavingAdaptor to use it. It's important that the LTWWorld have just one type map for performance and memory efficiency.
resolved fixed
cafdecb
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-23T11:34:16Z
2005-12-17T09:00:00Z
weaver/src/org/aspectj/weaver/ltw/LTWWorld.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.ltw; import org.aspectj.weaver.Advice; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.AdviceAttribute; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PerClause.Kind; /** * @author adrian * * For use in LT weaving * * Backed by both a BcelWorld and a ReflectionWorld * * Needs a callback when a woven class is defined * This is the trigger for us to ditch the class from * Bcel and cache it in the reflective world instead. * * Problems with classes that are loaded by delegates * of our classloader * * Create by passing in a classloader, message handler */ public class LTWWorld extends World { protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) { // TODO Auto-generated method stub return null; } public Advice createAdviceMunger(AdviceAttribute attribute, Pointcut pointcut, Member signature) { // TODO Auto-generated method stub return null; } public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) { // TODO Auto-generated method stub return null; } public ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField) { // TODO Auto-generated method stub return null; } public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, Kind kind) { // TODO Auto-generated method stub return null; } public ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { // TODO Auto-generated method stub return null; } }
121,312
Bug 121312 [performance]Contribution: Refactoring to Support LTW World with Reflection Delegates for Bootstrap Types
This patch adds an IReflectionWorld interface, changes the various places in code where casts are made to ReflectionWorld to use that interface, creates some common methods and creates an LTWWorld that implements this interface, and sets up the ClassLoaderWeavingAdaptor to use it. It's important that the LTWWorld have just one type map for performance and memory efficiency.
resolved fixed
cafdecb
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-23T11:34:16Z
2005-12-17T09:00:00Z
weaver/src/org/aspectj/weaver/reflect/IReflectionWorld.java
121,312
Bug 121312 [performance]Contribution: Refactoring to Support LTW World with Reflection Delegates for Bootstrap Types
This patch adds an IReflectionWorld interface, changes the various places in code where casts are made to ReflectionWorld to use that interface, creates some common methods and creates an LTWWorld that implements this interface, and sets up the ClassLoaderWeavingAdaptor to use it. It's important that the LTWWorld have just one type map for performance and memory efficiency.
resolved fixed
cafdecb
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-23T11:34:16Z
2005-12-17T09:00:00Z
weaver/src/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateFactory.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.aspectj.util.LangUtil; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedMemberImpl; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; /** * @author colyer * Creates the appropriate ReflectionBasedReferenceTypeDelegate according to * the VM level we are running at. Uses reflection to avoid 1.5 dependencies in * 1.4 and 1.3 code base. */ public class ReflectionBasedReferenceTypeDelegateFactory { public static ReflectionBasedReferenceTypeDelegate createDelegate(ReferenceType forReferenceType, World inWorld, ClassLoader usingClassLoader) { try { Class c = Class.forName(forReferenceType.getName(),false,usingClassLoader); if (LangUtil.is15VMOrGreater()) { ReflectionBasedReferenceTypeDelegate rbrtd = create15Delegate(forReferenceType,c,usingClassLoader,inWorld); if (rbrtd!=null) return rbrtd; // can be null if we didn't find the class the delegate logic loads } return new ReflectionBasedReferenceTypeDelegate(c,usingClassLoader,inWorld,forReferenceType); } catch (ClassNotFoundException cnfEx) { return null; } } private static ReflectionBasedReferenceTypeDelegate create15Delegate(ReferenceType forReferenceType, Class forClass, ClassLoader usingClassLoader, World inWorld) { try { Class delegateClass = Class.forName("org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate");//,false,usingClassLoader);//ReflectionBasedReferenceTypeDelegate.class.getClassLoader()); ReflectionBasedReferenceTypeDelegate ret = (ReflectionBasedReferenceTypeDelegate) delegateClass.newInstance(); ret.initialize(forReferenceType,forClass,usingClassLoader,inWorld); return ret; } catch (ClassNotFoundException cnfEx) { throw new IllegalStateException("Attempted to create Java 1.5 reflection based delegate but org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate was not found on classpath"); } catch (InstantiationException insEx) { throw new IllegalStateException("Attempted to create Java 1.5 reflection based delegate but InstantiationException: " + insEx + " occured"); } catch (IllegalAccessException illAccEx) { throw new IllegalStateException("Attempted to create Java 1.5 reflection based delegate but IllegalAccessException: " + illAccEx + " occured"); } } private static GenericSignatureInformationProvider createGenericSignatureProvider(World inWorld) { if (LangUtil.is15VMOrGreater()) { try { Class providerClass = Class.forName("org.aspectj.weaver.reflect.Java15GenericSignatureInformationProvider"); Constructor cons = providerClass.getConstructor(new Class[] {World.class}); GenericSignatureInformationProvider ret = (GenericSignatureInformationProvider) cons.newInstance(new Object[] {inWorld}); return ret; } catch (ClassNotFoundException cnfEx) { throw new IllegalStateException("Attempted to create Java 1.5 generic signature provider but org.aspectj.weaver.reflect.Java15GenericSignatureInformationProvider was not found on classpath"); } catch (NoSuchMethodException nsmEx) { throw new IllegalStateException("Attempted to create Java 1.5 generic signature provider but: " + nsmEx + " occured"); } catch (InstantiationException insEx) { throw new IllegalStateException("Attempted to create Java 1.5 generic signature provider but: " + insEx + " occured"); } catch (InvocationTargetException invEx) { throw new IllegalStateException("Attempted to create Java 1.5 generic signature provider but: " + invEx + " occured"); } catch (IllegalAccessException illAcc) { throw new IllegalStateException("Attempted to create Java 1.5 generic signature provider but: " + illAcc + " occured"); } } else { return new Java14GenericSignatureInformationProvider(); } } /** * convert a java.lang.reflect.Member into a resolved member in the world * @param reflectMember * @param inWorld * @return */ public static ResolvedMember createResolvedMember(Member reflectMember, World inWorld) { if (reflectMember instanceof Method) { return createResolvedMethod((Method)reflectMember,inWorld); } else if (reflectMember instanceof Constructor) { return createResolvedConstructor((Constructor)reflectMember,inWorld); } else { return createResolvedField((Field)reflectMember,inWorld); } } public static ResolvedMember createResolvedMethod(Method aMethod, World inWorld) { ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD, toResolvedType(aMethod.getDeclaringClass(),(ReflectionWorld)inWorld), aMethod.getModifiers(), toResolvedType(aMethod.getReturnType(),(ReflectionWorld)inWorld), aMethod.getName(), toResolvedTypeArray(aMethod.getParameterTypes(),inWorld), toResolvedTypeArray(aMethod.getExceptionTypes(),inWorld), aMethod ); if (inWorld instanceof ReflectionWorld) { ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder()); } ret.setGenericSignatureInformationProvider(createGenericSignatureProvider(inWorld)); return ret; } public static ResolvedMember createResolvedAdviceMember(Method aMethod, World inWorld) { ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.ADVICE, toResolvedType(aMethod.getDeclaringClass(),(ReflectionWorld)inWorld), aMethod.getModifiers(), toResolvedType(aMethod.getReturnType(),(ReflectionWorld)inWorld), aMethod.getName(), toResolvedTypeArray(aMethod.getParameterTypes(),inWorld), toResolvedTypeArray(aMethod.getExceptionTypes(),inWorld), aMethod ); if (inWorld instanceof ReflectionWorld) { ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder()); } ret.setGenericSignatureInformationProvider(createGenericSignatureProvider(inWorld)); return ret; } public static ResolvedMember createStaticInitMember(Class forType, World inWorld) { return new ResolvedMemberImpl(org.aspectj.weaver.Member.STATIC_INITIALIZATION, toResolvedType(forType,(ReflectionWorld)inWorld), Modifier.STATIC, ResolvedType.VOID, "<clinit>", new UnresolvedType[0], new UnresolvedType[0] ); } public static ResolvedMember createResolvedConstructor(Constructor aConstructor, World inWorld) { ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.CONSTRUCTOR, toResolvedType(aConstructor.getDeclaringClass(),(ReflectionWorld)inWorld), aConstructor.getModifiers(), // to return what BCEL returns, the return type for ctor is void ResolvedType.VOID,//toResolvedType(aConstructor.getDeclaringClass(),(ReflectionWorld)inWorld), "<init>", toResolvedTypeArray(aConstructor.getParameterTypes(),inWorld), toResolvedTypeArray(aConstructor.getExceptionTypes(),inWorld), aConstructor ); if (inWorld instanceof ReflectionWorld) { ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder()); } ret.setGenericSignatureInformationProvider(createGenericSignatureProvider(inWorld)); return ret; } public static ResolvedMember createResolvedField(Field aField, World inWorld) { ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.FIELD, toResolvedType(aField.getDeclaringClass(),(ReflectionWorld)inWorld), aField.getModifiers(), toResolvedType(aField.getType(),(ReflectionWorld)inWorld), aField.getName(), new UnresolvedType[0], aField); if (inWorld instanceof ReflectionWorld) { ret.setAnnotationFinder(((ReflectionWorld)inWorld).getAnnotationFinder()); } ret.setGenericSignatureInformationProvider(createGenericSignatureProvider(inWorld)); return ret; } public static ResolvedMember createHandlerMember(Class exceptionType, Class inType,World inWorld) { return new ResolvedMemberImpl( org.aspectj.weaver.Member.HANDLER, toResolvedType(inType,(ReflectionWorld)inWorld), Modifier.STATIC, "<catch>", "(" + inWorld.resolve(exceptionType.getName()).getSignature() + ")V"); } public static ResolvedType resolveTypeInWorld(Class aClass, World aWorld) { // classes that represent arrays return a class name that is the signature of the array type, ho-hum... String className = aClass.getName(); if (aClass.isArray()) { return aWorld.resolve(UnresolvedType.forSignature(className.replace('.','/'))); } else{ return aWorld.resolve(className); } } private static ResolvedType toResolvedType(Class aClass, ReflectionWorld aWorld) { return aWorld.resolve(aClass); } private static ResolvedType[] toResolvedTypeArray(Class[] classes, World inWorld) { ResolvedType[] ret = new ResolvedType[classes.length]; for (int i = 0; i < ret.length; i++) { ret[i] = ((ReflectionWorld)inWorld).resolve(classes[i]); } return ret; } }
121,312
Bug 121312 [performance]Contribution: Refactoring to Support LTW World with Reflection Delegates for Bootstrap Types
This patch adds an IReflectionWorld interface, changes the various places in code where casts are made to ReflectionWorld to use that interface, creates some common methods and creates an LTWWorld that implements this interface, and sets up the ClassLoaderWeavingAdaptor to use it. It's important that the LTWWorld have just one type map for performance and memory efficiency.
resolved fixed
cafdecb
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-23T11:34:16Z
2005-12-17T09:00:00Z
weaver/src/org/aspectj/weaver/reflect/ReflectionShadow.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.Member; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.tools.MatchingContext; /** * @author colyer * */ public class ReflectionShadow extends Shadow { private final World world; private final ResolvedType enclosingType; private final ResolvedMember enclosingMember; private final MatchingContext matchContext; private Var thisVar = null; private Var targetVar = null; private Var[] argsVars = null; private Var atThisVar = null; private Var atTargetVar = null; private Map atArgsVars = new HashMap(); private Map withinAnnotationVar = new HashMap(); private Map withinCodeAnnotationVar = new HashMap(); private Map annotationVar = new HashMap(); private AnnotationFinder annotationFinder; public static Shadow makeExecutionShadow(World inWorld, java.lang.reflect.Member forMethod, MatchingContext withContext) { Kind kind = (forMethod instanceof Method) ? Shadow.MethodExecution : Shadow.ConstructorExecution; Member signature = ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(forMethod, inWorld); ResolvedType enclosingType = signature.getDeclaringType().resolve(inWorld); return new ReflectionShadow(inWorld,kind,signature,null,enclosingType,null,withContext); } public static Shadow makeAdviceExecutionShadow(World inWorld, java.lang.reflect.Method forMethod, MatchingContext withContext) { Kind kind = Shadow.AdviceExecution; Member signature = ReflectionBasedReferenceTypeDelegateFactory.createResolvedAdviceMember(forMethod, inWorld); ResolvedType enclosingType = signature.getDeclaringType().resolve(inWorld); return new ReflectionShadow(inWorld,kind,signature,null,enclosingType,null,withContext); } public static Shadow makeCallShadow(World inWorld, java.lang.reflect.Member aMember, java.lang.reflect.Member withinCode, MatchingContext withContext) { Shadow enclosingShadow = makeExecutionShadow(inWorld,withinCode,withContext); Member signature = ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(aMember, inWorld); ResolvedMember enclosingMember = ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(withinCode, inWorld); ResolvedType enclosingType = enclosingMember.getDeclaringType().resolve(inWorld); Kind kind = aMember instanceof Method ? Shadow.MethodCall : Shadow.ConstructorCall; return new ReflectionShadow(inWorld,kind,signature,enclosingShadow,enclosingType,enclosingMember,withContext); } public static Shadow makeCallShadow(World inWorld, java.lang.reflect.Member aMember, Class thisClass, MatchingContext withContext) { Shadow enclosingShadow = makeStaticInitializationShadow(inWorld, thisClass,withContext); Member signature = ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(aMember, inWorld); ResolvedMember enclosingMember = ReflectionBasedReferenceTypeDelegateFactory.createStaticInitMember(thisClass, inWorld); ResolvedType enclosingType = enclosingMember.getDeclaringType().resolve(inWorld); Kind kind = aMember instanceof Method ? Shadow.MethodCall : Shadow.ConstructorCall; return new ReflectionShadow(inWorld,kind,signature,enclosingShadow,enclosingType,enclosingMember,withContext); } public static Shadow makeStaticInitializationShadow(World inWorld, Class forType, MatchingContext withContext) { Member signature = ReflectionBasedReferenceTypeDelegateFactory.createStaticInitMember(forType, inWorld); ResolvedType enclosingType = signature.getDeclaringType().resolve(inWorld); Kind kind = Shadow.StaticInitialization; return new ReflectionShadow(inWorld,kind,signature,null,enclosingType,null,withContext); } public static Shadow makePreInitializationShadow(World inWorld, Constructor forConstructor, MatchingContext withContext) { Kind kind = Shadow.PreInitialization; Member signature = ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(forConstructor, inWorld); ResolvedType enclosingType = signature.getDeclaringType().resolve(inWorld); return new ReflectionShadow(inWorld,kind,signature,null,enclosingType,null,withContext); } public static Shadow makeInitializationShadow(World inWorld, Constructor forConstructor, MatchingContext withContext) { Kind kind = Shadow.Initialization; Member signature = ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(forConstructor, inWorld); ResolvedType enclosingType = signature.getDeclaringType().resolve(inWorld); return new ReflectionShadow(inWorld,kind,signature,null,enclosingType,null,withContext); } public static Shadow makeHandlerShadow(World inWorld, Class exceptionType, Class withinType, MatchingContext withContext) { Kind kind = Shadow.ExceptionHandler; Shadow enclosingShadow = makeStaticInitializationShadow(inWorld, withinType,withContext); Member signature = ReflectionBasedReferenceTypeDelegateFactory.createHandlerMember(exceptionType, withinType, inWorld); ResolvedMember enclosingMember = ReflectionBasedReferenceTypeDelegateFactory.createStaticInitMember(withinType, inWorld); ResolvedType enclosingType = enclosingMember.getDeclaringType().resolve(inWorld); return new ReflectionShadow(inWorld,kind,signature,enclosingShadow,enclosingType,enclosingMember,withContext); } public static Shadow makeHandlerShadow(World inWorld, Class exceptionType, java.lang.reflect.Member withinCode, MatchingContext withContext) { Kind kind = Shadow.ExceptionHandler; Shadow enclosingShadow = makeExecutionShadow(inWorld, withinCode,withContext); Member signature = ReflectionBasedReferenceTypeDelegateFactory.createHandlerMember(exceptionType, withinCode.getDeclaringClass(), inWorld); ResolvedMember enclosingMember = ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(withinCode, inWorld); ResolvedType enclosingType = enclosingMember.getDeclaringType().resolve(inWorld); return new ReflectionShadow(inWorld,kind,signature,enclosingShadow,enclosingType,enclosingMember,withContext); } public static Shadow makeFieldGetShadow(World inWorld, Field forField, Class callerType, MatchingContext withContext) { Shadow enclosingShadow = makeStaticInitializationShadow(inWorld, callerType,withContext); Member signature = ReflectionBasedReferenceTypeDelegateFactory.createResolvedField(forField, inWorld); ResolvedMember enclosingMember = ReflectionBasedReferenceTypeDelegateFactory.createStaticInitMember(callerType, inWorld); ResolvedType enclosingType = enclosingMember.getDeclaringType().resolve(inWorld); Kind kind = Shadow.FieldGet; return new ReflectionShadow(inWorld,kind,signature,enclosingShadow,enclosingType,enclosingMember,withContext); } public static Shadow makeFieldGetShadow(World inWorld, Field forField, java.lang.reflect.Member inMember, MatchingContext withContext) { Shadow enclosingShadow = makeExecutionShadow(inWorld,inMember,withContext); Member signature = ReflectionBasedReferenceTypeDelegateFactory.createResolvedField(forField, inWorld); ResolvedMember enclosingMember = ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(inMember, inWorld); ResolvedType enclosingType = enclosingMember.getDeclaringType().resolve(inWorld); Kind kind = Shadow.FieldGet; return new ReflectionShadow(inWorld,kind,signature,enclosingShadow,enclosingType,enclosingMember,withContext); } public static Shadow makeFieldSetShadow(World inWorld, Field forField, Class callerType, MatchingContext withContext) { Shadow enclosingShadow = makeStaticInitializationShadow(inWorld, callerType, withContext); Member signature = ReflectionBasedReferenceTypeDelegateFactory.createResolvedField(forField, inWorld); ResolvedMember enclosingMember = ReflectionBasedReferenceTypeDelegateFactory.createStaticInitMember(callerType, inWorld); ResolvedType enclosingType = enclosingMember.getDeclaringType().resolve(inWorld); Kind kind = Shadow.FieldSet; return new ReflectionShadow(inWorld,kind,signature,enclosingShadow,enclosingType,enclosingMember,withContext); } public static Shadow makeFieldSetShadow(World inWorld, Field forField, java.lang.reflect.Member inMember, MatchingContext withContext) { Shadow enclosingShadow = makeExecutionShadow(inWorld,inMember,withContext); Member signature = ReflectionBasedReferenceTypeDelegateFactory.createResolvedField(forField, inWorld); ResolvedMember enclosingMember = ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(inMember, inWorld); ResolvedType enclosingType = enclosingMember.getDeclaringType().resolve(inWorld); Kind kind = Shadow.FieldSet; return new ReflectionShadow(inWorld,kind,signature,enclosingShadow,enclosingType,enclosingMember,withContext); } public ReflectionShadow(World world, Kind kind, Member signature, Shadow enclosingShadow, ResolvedType enclosingType, ResolvedMember enclosingMember, MatchingContext withContext) { super(kind,signature,enclosingShadow); this.world = world; this.enclosingType = enclosingType; this.enclosingMember = enclosingMember; this.matchContext = withContext; if (world instanceof ReflectionWorld) { this.annotationFinder = ((ReflectionWorld)world).getAnnotationFinder(); } } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getIWorld() */ public World getIWorld() { return world; } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getThisVar() */ public Var getThisVar() { if (thisVar == null && hasThis()) { thisVar = ReflectionVar.createThisVar(getThisType().resolve(world),this.annotationFinder); } return thisVar; } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getTargetVar() */ public Var getTargetVar() { if (targetVar == null && hasTarget()) { targetVar = ReflectionVar.createTargetVar(getThisType().resolve(world),this.annotationFinder); } return targetVar; } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getEnclosingType() */ public UnresolvedType getEnclosingType() { return this.enclosingType; } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getArgVar(int) */ public Var getArgVar(int i) { if (argsVars == null) { this.argsVars = new Var[this.getArgCount()]; for (int j = 0; j < this.argsVars.length; j++) { this.argsVars[j] = ReflectionVar.createArgsVar(getArgType(j).resolve(world), j,this.annotationFinder); } } if (i < argsVars.length) { return argsVars[i]; } else { return null; } } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getThisJoinPointVar() */ public Var getThisJoinPointVar() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getThisJoinPointStaticPartVar() */ public Var getThisJoinPointStaticPartVar() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getThisEnclosingJoinPointStaticPartVar() */ public Var getThisEnclosingJoinPointStaticPartVar() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getKindedAnnotationVar(org.aspectj.weaver.UnresolvedType) */ public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) { ResolvedType annType = forAnnotationType.resolve(world); if (annotationVar.get(annType) == null) { Var v = ReflectionVar.createAtAnnotationVar(annType,this.annotationFinder); annotationVar.put(annType,v); } return (Var) annotationVar.get(annType); } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getWithinAnnotationVar(org.aspectj.weaver.UnresolvedType) */ public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) { ResolvedType annType = forAnnotationType.resolve(world); if (withinAnnotationVar.get(annType) == null) { Var v = ReflectionVar.createWithinAnnotationVar(annType,this.annotationFinder); withinAnnotationVar.put(annType,v); } return (Var) withinAnnotationVar.get(annType); } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getWithinCodeAnnotationVar(org.aspectj.weaver.UnresolvedType) */ public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) { ResolvedType annType = forAnnotationType.resolve(world); if (withinCodeAnnotationVar.get(annType) == null) { Var v = ReflectionVar.createWithinCodeAnnotationVar(annType,this.annotationFinder); withinCodeAnnotationVar.put(annType,v); } return (Var) withinCodeAnnotationVar.get(annType); } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getThisAnnotationVar(org.aspectj.weaver.UnresolvedType) */ public Var getThisAnnotationVar(UnresolvedType forAnnotationType) { if (atThisVar == null) { atThisVar = ReflectionVar.createThisAnnotationVar(forAnnotationType.resolve(world),this.annotationFinder); } return atThisVar; } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getTargetAnnotationVar(org.aspectj.weaver.UnresolvedType) */ public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) { if (atTargetVar == null) { atTargetVar = ReflectionVar.createTargetAnnotationVar(forAnnotationType.resolve(world),this.annotationFinder); } return atTargetVar; } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getArgAnnotationVar(int, org.aspectj.weaver.UnresolvedType) */ public Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType) { ResolvedType annType = forAnnotationType.resolve(world); if (atArgsVars.get(annType) == null) { Var[] vars = new Var[getArgCount()]; atArgsVars.put(annType,vars); } Var[] vars = (Var[]) atArgsVars.get(annType); if (i > (vars.length - 1) ) return null; if (vars[i] == null) { vars[i] = ReflectionVar.createArgsAnnotationVar(annType, i,this.annotationFinder); } return vars[i]; } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getEnclosingCodeSignature() */ public Member getEnclosingCodeSignature() { // XXX this code is copied from BcelShadow with one minor change... 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 this.enclosingMember; } else { return enclosingShadow.getSignature(); } } /* (non-Javadoc) * @see org.aspectj.weaver.Shadow#getSourceLocation() */ public ISourceLocation getSourceLocation() { return null; } public MatchingContext getMatchingContext() { return this.matchContext; } }
121,312
Bug 121312 [performance]Contribution: Refactoring to Support LTW World with Reflection Delegates for Bootstrap Types
This patch adds an IReflectionWorld interface, changes the various places in code where casts are made to ReflectionWorld to use that interface, creates some common methods and creates an LTWWorld that implements this interface, and sets up the ClassLoaderWeavingAdaptor to use it. It's important that the LTWWorld have just one type map for performance and memory efficiency.
resolved fixed
cafdecb
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-23T11:34:16Z
2005-12-17T09:00:00Z
weaver/src/org/aspectj/weaver/reflect/ReflectionWorld.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.reflect; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.util.LangUtil; import org.aspectj.weaver.Advice; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ConcreteTypeMunger; import org.aspectj.weaver.Member; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ReferenceTypeDelegate; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.ResolvedTypeMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.AjAttribute.AdviceAttribute; import org.aspectj.weaver.patterns.Pointcut; import org.aspectj.weaver.patterns.PerClause.Kind; /** * A ReflectionWorld is used solely for purposes of type resolution based on * the runtime classpath (java.lang.reflect). It does not support weaving operations * (creation of mungers etc..). * */ public class ReflectionWorld extends World { private ClassLoader classLoader; private AnnotationFinder annotationFinder; private ReflectionWorld() { super(); this.setMessageHandler(new ExceptionBasedMessageHandler()); setBehaveInJava5Way(LangUtil.is15VMOrGreater()); this.classLoader = ReflectionWorld.class.getClassLoader(); if (LangUtil.is15VMOrGreater()) { initializeAnnotationFinder(this.classLoader); } } public ReflectionWorld(ClassLoader aClassLoader) { super(); this.setMessageHandler(new ExceptionBasedMessageHandler()); setBehaveInJava5Way(LangUtil.is15VMOrGreater()); this.classLoader = aClassLoader; if (LangUtil.is15VMOrGreater()) { initializeAnnotationFinder(this.classLoader); } } private void initializeAnnotationFinder(ClassLoader loader) { try { Class java15AnnotationFinder = Class.forName("org.aspectj.weaver.reflect.Java15AnnotationFinder"); this.annotationFinder = (AnnotationFinder) java15AnnotationFinder.newInstance(); this.annotationFinder.setClassLoader(loader); this.annotationFinder.setWorld(this); } catch(ClassNotFoundException ex) { // must be on 1.4 or earlier } catch(IllegalAccessException ex) { // not so good throw new BCException("AspectJ internal error",ex); } catch(InstantiationException ex) { throw new BCException("AspectJ internal error",ex); } } public ClassLoader getClassLoader() { return this.classLoader; } public AnnotationFinder getAnnotationFinder() { return this.annotationFinder; } public ResolvedType resolve(Class aClass) { // classes that represent arrays return a class name that is the signature of the array type, ho-hum... String className = aClass.getName(); if (aClass.isArray()) { return resolve(UnresolvedType.forSignature(className)); } else{ return resolve(className); } } /* (non-Javadoc) * @see org.aspectj.weaver.World#resolveDelegate(org.aspectj.weaver.ReferenceType) */ protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) { return ReflectionBasedReferenceTypeDelegateFactory.createDelegate(ty, this, this.classLoader); } /* (non-Javadoc) * @see org.aspectj.weaver.World#createAdviceMunger(org.aspectj.weaver.AjAttribute.AdviceAttribute, org.aspectj.weaver.patterns.Pointcut, org.aspectj.weaver.Member) */ public Advice createAdviceMunger(AdviceAttribute attribute, Pointcut pointcut, Member signature) { throw new UnsupportedOperationException("Cannot create advice munger in ReflectionWorld"); } /* (non-Javadoc) * @see org.aspectj.weaver.World#makeCflowStackFieldAdder(org.aspectj.weaver.ResolvedMember) */ public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) { throw new UnsupportedOperationException("Cannot create cflow stack in ReflectionWorld"); } /* (non-Javadoc) * @see org.aspectj.weaver.World#makeCflowCounterFieldAdder(org.aspectj.weaver.ResolvedMember) */ public ConcreteTypeMunger makeCflowCounterFieldAdder( ResolvedMember cflowField) { throw new UnsupportedOperationException("Cannot create cflow counter in ReflectionWorld"); } /* (non-Javadoc) * @see org.aspectj.weaver.World#makePerClauseAspect(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind) */ public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, Kind kind) { throw new UnsupportedOperationException("Cannot create per clause in ReflectionWorld"); } /* (non-Javadoc) * @see org.aspectj.weaver.World#concreteTypeMunger(org.aspectj.weaver.ResolvedTypeMunger, org.aspectj.weaver.ResolvedType) */ public ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) { throw new UnsupportedOperationException("Cannot create type munger in ReflectionWorld"); } public static class ReflectionWorldException extends RuntimeException { private static final long serialVersionUID = -3432261918302793005L; public ReflectionWorldException(String message) { super(message); } } private static class ExceptionBasedMessageHandler implements IMessageHandler { public boolean handleMessage(IMessage message) throws AbortException { throw new ReflectionWorldException(message.toString()); } public boolean isIgnoring(org.aspectj.bridge.IMessage.Kind kind) { if (kind == IMessage.INFO) { return true; } else { return false; } } public void dontIgnore(org.aspectj.bridge.IMessage.Kind kind) { // empty } } }
121,312
Bug 121312 [performance]Contribution: Refactoring to Support LTW World with Reflection Delegates for Bootstrap Types
This patch adds an IReflectionWorld interface, changes the various places in code where casts are made to ReflectionWorld to use that interface, creates some common methods and creates an LTWWorld that implements this interface, and sets up the ClassLoaderWeavingAdaptor to use it. It's important that the LTWWorld have just one type map for performance and memory efficiency.
resolved fixed
cafdecb
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-23T11:34:16Z
2005-12-17T09:00:00Z
weaver/testsrc/org/aspectj/weaver/reflect/ReflectionWorldTest.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.reflect; import junit.framework.TestCase; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; public class ReflectionWorldTest extends TestCase { public void testDelegateCreation() { World world = new ReflectionWorld(getClass().getClassLoader()); ResolvedType rt = world.resolve("java.lang.Object"); assertNotNull(rt); assertEquals("Ljava/lang/Object;",rt.getSignature()); } public void testArrayTypes() { ReflectionWorld world = new ReflectionWorld(getClass().getClassLoader()); String[] strArray = new String[1]; ResolvedType rt = world.resolve(strArray.getClass()); assertTrue(rt.isArray()); } public void testPrimitiveTypes() { ReflectionWorld world = new ReflectionWorld(getClass().getClassLoader()); assertEquals("int",ResolvedType.INT,world.resolve(int.class)); assertEquals("void",ResolvedType.VOID,world.resolve(void.class)); } }
129,298
Bug 129298 Contribution: Remove Memory Consuming Declared Signature
The code for weaver.Member#getDeclaredSignature() is never used in the weaver. My memory analysis showed this can pin several megabytes of memory in a large system. This patch removes it. YAGNI :-)
resolved fixed
a116142
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-24T12:11:15Z
2006-02-24T08:33:20Z
weaver/src/org/aspectj/weaver/JoinPointSignature.java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.AjAttribute.EffectiveSignatureAttribute; /** * @author colyer * Instances of this class are created by ResolvedMember.getSignatures() when collating * all of the signatures for a member. We need to create entries in the set for the "gaps" * in the hierarchy. For example: * * class A { * void foo(); * } * * class B extends A {} * * Join Point : call(* B.foo()) * * has signatures: * * B.foo() AND A.foo() * B.foo() will be created as a ResolvedMemberWithSubstituteDeclaringType * * Oh for a JDK 1.4 dynamic proxy.... we have to run on 1.3 :( */ public class JoinPointSignature implements ResolvedMember { private ResolvedMember realMember; private ResolvedType substituteDeclaringType; public JoinPointSignature(ResolvedMember backing, ResolvedType aType) { this.realMember = backing; this.substituteDeclaringType = aType; } public UnresolvedType getDeclaringType() { return substituteDeclaringType; } public int getModifiers(World world) { return realMember.getModifiers(world); } public int getModifiers() { return realMember.getModifiers(); } public UnresolvedType[] getExceptions(World world) { return realMember.getExceptions(world); } public UnresolvedType[] getExceptions() { return realMember.getExceptions(); } public ShadowMunger getAssociatedShadowMunger() { return realMember.getAssociatedShadowMunger(); } public boolean isAjSynthetic() { return realMember.isAjSynthetic(); } public boolean hasAnnotations() { return realMember.hasAnnotations(); } public boolean hasAnnotation(UnresolvedType ofType) { return realMember.hasAnnotation(ofType); } public ResolvedType[] getAnnotationTypes() { return realMember.getAnnotationTypes(); } public void setAnnotationTypes(UnresolvedType[] annotationtypes) { realMember.setAnnotationTypes(annotationtypes); } public void addAnnotation(AnnotationX annotation) { realMember.addAnnotation(annotation); } public boolean isBridgeMethod() { return realMember.isBridgeMethod(); } public boolean isVarargsMethod() { return realMember.isVarargsMethod(); } public boolean isSynthetic() { return realMember.isSynthetic(); } public void write(DataOutputStream s) throws IOException { realMember.write(s); } public ISourceContext getSourceContext(World world) { return realMember.getSourceContext(world); } public String[] getParameterNames() { return realMember.getParameterNames(); } public void setParameterNames(String[] names) { realMember.setParameterNames(names); } public String[] getParameterNames(World world) { return realMember.getParameterNames(world); } public EffectiveSignatureAttribute getEffectiveSignature() { return realMember.getEffectiveSignature(); } public ISourceLocation getSourceLocation() { return realMember.getSourceLocation(); } public int getEnd() { return realMember.getEnd(); } public ISourceContext getSourceContext() { return realMember.getSourceContext(); } public int getStart() { return realMember.getStart(); } public void setPosition(int sourceStart, int sourceEnd) { realMember.setPosition(sourceStart,sourceEnd); } public void setSourceContext(ISourceContext sourceContext) { realMember.setSourceContext(sourceContext); } public boolean isAbstract() { return realMember.isAbstract(); } public boolean isPublic() { return realMember.isPublic(); } public boolean isProtected() { return realMember.isProtected(); } public boolean isNative() { return realMember.isNative(); } public boolean isDefault() { return realMember.isDefault(); } public boolean isVisible(ResolvedType fromType) { return realMember.isVisible(fromType); } public void setCheckedExceptions(UnresolvedType[] checkedExceptions) { realMember.setCheckedExceptions(checkedExceptions); } public void setAnnotatedElsewhere(boolean b) { realMember.setAnnotatedElsewhere(b); } public boolean isAnnotatedElsewhere() { return realMember.isAnnotatedElsewhere(); } public UnresolvedType getGenericReturnType() { return realMember.getGenericReturnType(); } public UnresolvedType[] getGenericParameterTypes() { return realMember.getGenericParameterTypes(); } public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters, ResolvedType newDeclaringType, boolean isParameterized) { return realMember.parameterizedWith(typeParameters, newDeclaringType, isParameterized); } public ResolvedMemberImpl parameterizedWith(UnresolvedType[] typeParameters, ResolvedType newDeclaringType, boolean isParameterized,List aliases) { return realMember.parameterizedWith(typeParameters, newDeclaringType, isParameterized,aliases); } public void setTypeVariables(TypeVariable[] types) { realMember.setTypeVariables(types); } public TypeVariable[] getTypeVariables() { return realMember.getTypeVariables(); } public TypeVariable getTypeVariableNamed(String name) { return realMember.getTypeVariableNamed(name); } public ResolvedMember getErasure() { throw new UnsupportedOperationException("Adrian doesn't think you should be asking for the erasure of one of these..."); } public boolean matches(ResolvedMember aCandidateMatch) { return realMember.matches(aCandidateMatch); } public ResolvedMember resolve(World world) { return realMember.resolve(world); } public int compareTo(Object other) { return realMember.compareTo(other); } public String toLongString() { return realMember.toLongString(); } public Kind getKind() { return realMember.getKind(); } public UnresolvedType getReturnType() { return realMember.getReturnType(); } public UnresolvedType getType() { return realMember.getType(); } public String getName() { return realMember.getName(); } public UnresolvedType[] getParameterTypes() { return realMember.getParameterTypes(); } public String getSignature() { return realMember.getSignature(); } public String getDeclaredSignature() { return realMember.getDeclaredSignature(); } public int getArity() { return realMember.getArity(); } public String getParameterSignature() { return realMember.getParameterSignature(); } public boolean isCompatibleWith(Member am) { return realMember.isCompatibleWith(am); } public boolean isProtected(World world) { return realMember.isProtected(world); } public boolean isStatic(World world) { return realMember.isStatic(world); } public boolean isStrict(World world) { return realMember.isStrict(world); } public boolean isStatic() { return realMember.isStatic(); } public boolean isInterface() { return realMember.isInterface(); } public boolean isPrivate() { return realMember.isPrivate(); } public boolean canBeParameterized() { return realMember.canBeParameterized(); } public int getCallsiteModifiers() { return realMember.getCallsiteModifiers(); } public String getExtractableName() { return realMember.getExtractableName(); } public AnnotationX[] getAnnotations() { return realMember.getAnnotations(); } public Collection getDeclaringTypes(World world) { throw new UnsupportedOperationException("Adrian doesn't think you should be calling this..."); } public String getSignatureMakerName() { return realMember.getSignatureMakerName(); } public String getSignatureType() { return realMember.getSignatureType(); } public String getSignatureString(World world) { return realMember.getSignatureString(world); } public Iterator getJoinPointSignatures(World world) { return realMember.getJoinPointSignatures(world); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(getReturnType().getName()); buf.append(' '); buf.append(getDeclaringType().getName()); buf.append('.'); buf.append(getName()); if (getKind() != FIELD) { buf.append("("); UnresolvedType[] parameterTypes = getParameterTypes(); if (parameterTypes.length != 0) { buf.append(parameterTypes[0]); for (int i=1, len = parameterTypes.length; i < len; i++) { buf.append(", "); buf.append(parameterTypes[i].getName()); } } buf.append(")"); } return buf.toString(); } public String toGenericString() { return realMember.toGenericString(); } public String toDebugString() { return realMember.toDebugString(); } public void resetName(String newName) { realMember.resetName(newName); } public void resetKind(Kind newKind) { realMember.resetKind(newKind); } public void resetModifiers(int newModifiers) { realMember.resetModifiers(newModifiers); } public void resetReturnTypeToObjectArray() { realMember.resetReturnTypeToObjectArray(); } public boolean equals(Object obj) { if (! (obj instanceof JoinPointSignature)) return false; JoinPointSignature other = (JoinPointSignature) obj; if (!realMember.equals(other.realMember)) return false; if (!substituteDeclaringType.equals(other.substituteDeclaringType)) return false; return true; } public int hashCode() { return 17 + (37 * realMember.hashCode()) + (37 * substituteDeclaringType.hashCode()); } public boolean hasBackingGenericMember() { return realMember.hasBackingGenericMember(); } public ResolvedMember getBackingGenericMember() { return realMember.getBackingGenericMember(); } }
129,298
Bug 129298 Contribution: Remove Memory Consuming Declared Signature
The code for weaver.Member#getDeclaredSignature() is never used in the weaver. My memory analysis showed this can pin several megabytes of memory in a large system. This patch removes it. YAGNI :-)
resolved fixed
a116142
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-24T12:11:15Z
2006-02-24T08:33:20Z
weaver/src/org/aspectj/weaver/Member.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * AMC extracted as interface * ******************************************************************/ package org.aspectj.weaver; import java.io.DataInputStream; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import org.aspectj.util.TypeSafeEnum; public interface Member { public static class Kind extends TypeSafeEnum { public Kind(String name, int key) { super(name, key); } public static Kind read(DataInputStream s) throws IOException { int key = s.readByte(); switch(key) { case 1: return METHOD; case 2: return FIELD; case 3: return CONSTRUCTOR; case 4: return STATIC_INITIALIZATION; case 5: return POINTCUT; case 6: return ADVICE; case 7: return HANDLER; } throw new BCException("weird kind " + key); } } public static final Member[] NONE = new Member[0]; public static final Kind METHOD = new Kind("METHOD", 1); public static final Kind FIELD = new Kind("FIELD", 2); public static final Kind CONSTRUCTOR = new Kind("CONSTRUCTOR", 3); public static final Kind STATIC_INITIALIZATION = new Kind("STATIC_INITIALIZATION", 4); public static final Kind POINTCUT = new Kind("POINTCUT", 5); public static final Kind ADVICE = new Kind("ADVICE", 6); public static final Kind HANDLER = new Kind("HANDLER", 7); public ResolvedMember resolve(World world); public int compareTo(Object other); public String toLongString(); public Kind getKind(); public UnresolvedType getDeclaringType(); public UnresolvedType getReturnType(); public UnresolvedType getGenericReturnType(); public UnresolvedType getType(); public String getName(); public UnresolvedType[] getParameterTypes(); /** * Return full signature, including return type, e.g. "()LFastCar;" for a signature without the return type, * use getParameterSignature() - it is importnant to choose the right one in the face of covariance. */ public String getSignature(); /** * All the signatures that a join point with this member as its signature has. */ public Iterator getJoinPointSignatures(World world); /** TODO ASC Should return the non-erased version of the signature... untested */ public String getDeclaredSignature(); public int getArity(); /** * Return signature without return type, e.g. "()" for a signature *with* the return type, * use getSignature() - it is important to choose the right one in the face of covariance. */ public String getParameterSignature(); public boolean isCompatibleWith(Member am); public int getModifiers(World world); public int getModifiers(); public UnresolvedType[] getExceptions(World world); public boolean isProtected(World world); public boolean isStatic(World world); public boolean isStrict(World world); public boolean isStatic(); public boolean isInterface(); public boolean isPrivate(); /** * Returns true iff the member is generic (NOT parameterized) * For example, a method declared in a generic type */ public boolean canBeParameterized(); public int getCallsiteModifiers(); public String getExtractableName(); /** * If you want a sensible answer, resolve the member and call * hasAnnotation() on the ResolvedMember. */ public boolean hasAnnotation(UnresolvedType ofType); /* (non-Javadoc) * @see org.aspectj.weaver.AnnotatedElement#getAnnotationTypes() */ public ResolvedType[] getAnnotationTypes(); public AnnotationX[] getAnnotations(); public Collection/*ResolvedType*/getDeclaringTypes(World world); // ---- reflective thisJoinPoint stuff public String getSignatureMakerName(); public String getSignatureType(); public String getSignatureString(World world); public String[] getParameterNames(World world); }
129,298
Bug 129298 Contribution: Remove Memory Consuming Declared Signature
The code for weaver.Member#getDeclaredSignature() is never used in the weaver. My memory analysis showed this can pin several megabytes of memory in a large system. This patch removes it. YAGNI :-)
resolved fixed
a116142
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-02-24T12:11:15Z
2006-02-24T08:33:20Z
weaver/src/org/aspectj/weaver/MemberImpl.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; public class MemberImpl implements Comparable, AnnotatedElement,Member { protected Kind kind; protected UnresolvedType declaringType; protected int modifiers; protected UnresolvedType returnType; protected String name; protected UnresolvedType[] parameterTypes; private final String signature; private final String declaredSignature; // TODO asc Is this redundant? Is it needed for generics? private String paramSignature; /** * All the signatures that a join point with this member as its signature has. * The fact that this has to go on MemberImpl and not ResolvedMemberImpl says a lot about * how broken the Member/ResolvedMember distinction currently is. */ private JoinPointSignatureIterator joinPointSignatures = null; public MemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, String name, String signature) { this.kind = kind; this.declaringType = declaringType; this.modifiers = modifiers; this.name = name; this.signature = signature; this.declaredSignature = signature; if (kind == FIELD) { this.returnType = UnresolvedType.forSignature(signature); this.parameterTypes = UnresolvedType.NONE; } else { Object[] returnAndParams = signatureToTypes(signature,false); this.returnType = (UnresolvedType) returnAndParams[0]; this.parameterTypes = (UnresolvedType[]) returnAndParams[1]; // always safe not to do this ?!? // String oldsig=new String(signature); // signature = typesToSignature(returnType,parameterTypes,true); } } public MemberImpl( Kind kind, UnresolvedType declaringType, int modifiers, UnresolvedType returnType, String name, UnresolvedType[] parameterTypes) { super(); this.kind = kind; this.declaringType = declaringType; this.modifiers = modifiers; this.returnType = returnType; this.name = name; this.parameterTypes = parameterTypes; if (kind == FIELD) { this.signature = returnType.getErasureSignature(); this.declaredSignature = returnType.getSignature(); } else { this.signature = typesToSignature(returnType, parameterTypes,true); this.declaredSignature = typesToSignature(returnType,parameterTypes,false); } } /* (non-Javadoc) * @see org.aspectj.weaver.Member#resolve(org.aspectj.weaver.World) */ public ResolvedMember resolve(World world) { return world.resolve(this); } // ---- utility methods /** returns an Object[] pair of UnresolvedType, UnresolvedType[] representing return type, * argument types parsed from the JVM bytecode signature of a method. Yes, * this should actually return a nice statically-typed pair object, but we * don't have one of those. * * <blockquote><pre> * UnresolvedType.signatureToTypes("()[Z")[0].equals(Type.forSignature("[Z")) * UnresolvedType.signatureToTypes("(JJ)I")[1] * .equals(UnresolvedType.forSignatures(new String[] {"J", "J"})) * </pre></blockquote> * * @param signature the JVM bytecode method signature string we want to break apart * @return a pair of UnresolvedType, UnresolvedType[] representing the return types and parameter types. */ public static String typesToSignature(UnresolvedType returnType, UnresolvedType[] paramTypes, boolean useRawTypes) { StringBuffer buf = new StringBuffer(); buf.append("("); for (int i = 0, len = paramTypes.length; i < len; i++) { if (paramTypes[i].isParameterizedType() && useRawTypes) buf.append(paramTypes[i].getErasureSignature()); else if (paramTypes[i].isTypeVariableReference() && useRawTypes) buf.append(paramTypes[i].getErasureSignature()); else buf.append(paramTypes[i].getSignature()); } buf.append(")"); if (returnType.isParameterizedType() && useRawTypes) buf.append(returnType.getErasureSignature()); else if (returnType.isTypeVariableReference() && useRawTypes) buf.append(returnType.getErasureSignature()); else buf.append(returnType.getSignature()); return buf.toString(); } /** * Returns "(<signaturesOfParamTypes>,...)" - unlike the other typesToSignature * that also includes the return type, this one just deals with the parameter types. */ public static String typesToSignature(UnresolvedType[] paramTypes) { StringBuffer buf = new StringBuffer(); buf.append("("); for(int i=0;i<paramTypes.length;i++) { buf.append(paramTypes[i].getSignature()); } buf.append(")"); return buf.toString(); } /** * returns an Object[] pair of UnresolvedType, UnresolvedType[] representing return type, * argument types parsed from the JVM bytecode signature of a method. Yes, * this should actually return a nice statically-typed pair object, but we * don't have one of those. * * <blockquote><pre> * UnresolvedType.signatureToTypes("()[Z")[0].equals(Type.forSignature("[Z")) * UnresolvedType.signatureToTypes("(JJ)I")[1] * .equals(UnresolvedType.forSignatures(new String[] {"J", "J"})) * </pre></blockquote> * * @param signature the JVM bytecode method signature string we want to break apart * @return a pair of UnresolvedType, UnresolvedType[] representing the return types and parameter types. */ private static Object[] signatureToTypes(String sig,boolean keepParameterizationInfo) { List l = new ArrayList(); int i = 1; boolean hasAnyAnglies = sig.indexOf('<')!=-1; while (true) { char c = sig.charAt(i); if (c == ')') break; // break out when the hit the ')' int start = i; while (c == '[') c = sig.charAt(++i); if (c == 'L' || c == 'P') { int nextSemicolon = sig.indexOf(';',start); int firstAngly = (hasAnyAnglies?sig.indexOf('<',start):-1); if (!hasAnyAnglies || firstAngly == -1 || firstAngly>nextSemicolon) { i = nextSemicolon + 1; l.add(UnresolvedType.forSignature(sig.substring(start, i))); } else { // generics generics generics // Have to skip to the *correct* ';' boolean endOfSigReached = false; int posn = firstAngly; int genericDepth=0; while (!endOfSigReached) { switch (sig.charAt(posn)) { case '<': genericDepth++;break; case '>': genericDepth--;break; case ';': if (genericDepth==0) endOfSigReached=true;break; default: } posn++; } // posn now points to the correct nextSemicolon :) i=posn; l.add(UnresolvedType.forSignature(sig.substring(start,i))); } } else if (c=='T') { // assumed 'reference' to a type variable, so just "Tname;" int nextSemicolon = sig.indexOf(';',start); String nextbit = sig.substring(start,nextSemicolon); l.add(UnresolvedType.forSignature(nextbit)); i=nextSemicolon+1; } else { i++; l.add(UnresolvedType.forSignature(sig.substring(start, i))); } } UnresolvedType[] paramTypes = (UnresolvedType[]) l.toArray(new UnresolvedType[l.size()]); UnresolvedType returnType = UnresolvedType.forSignature(sig.substring(i+1, sig.length())); return new Object[] { returnType, paramTypes }; } // ---- factory methods public static MemberImpl field(String declaring, int mods, String name, String signature) { return field(declaring, mods, UnresolvedType.forSignature(signature), name); } public static Member field(UnresolvedType declaring, int mods, String name, UnresolvedType type) { return new MemberImpl(FIELD, declaring, mods, type, name, UnresolvedType.NONE); } public static MemberImpl method(UnresolvedType declaring, int mods, String name, String signature) { Object[] pair = signatureToTypes(signature,false); return method(declaring, mods, (UnresolvedType) pair[0], name, (UnresolvedType[]) pair[1]); } public static Member pointcut(UnresolvedType declaring, String name, String signature) { Object[] pair = signatureToTypes(signature,false); return pointcut(declaring, 0, (UnresolvedType) pair[0], name, (UnresolvedType[]) pair[1]); } private static MemberImpl field(String declaring, int mods, UnresolvedType ty, String name) { return new MemberImpl( FIELD, UnresolvedType.forName(declaring), mods, ty, name, UnresolvedType.NONE); } public static MemberImpl method(UnresolvedType declTy, int mods, UnresolvedType rTy, String name, UnresolvedType[] paramTys) { return new MemberImpl( //??? this calls <clinit> a method name.equals("<init>") ? CONSTRUCTOR : METHOD, declTy, mods, rTy, name, paramTys); } private static Member pointcut(UnresolvedType declTy, int mods, UnresolvedType rTy, String name, UnresolvedType[] paramTys) { return new MemberImpl( POINTCUT, declTy, mods, rTy, name, paramTys); } public static ResolvedMemberImpl makeExceptionHandlerSignature(UnresolvedType inType, UnresolvedType catchType) { return new ResolvedMemberImpl( HANDLER, inType, Modifier.STATIC, "<catch>", "(" + catchType.getSignature() + ")V"); } // ---- parsing methods /** Takes a string in this form: * * <blockquote><pre> * static? TypeName TypeName.Id * </pre></blockquote> * Pretty much just for testing, and as such should perhaps be moved. */ public static MemberImpl fieldFromString(String str) { str = str.trim(); final int len = str.length(); int i = 0; int mods = 0; if (str.startsWith("static", i)) { mods = Modifier.STATIC; i += 6; while (Character.isWhitespace(str.charAt(i))) i++; } int start = i; while (! Character.isWhitespace(str.charAt(i))) i++; UnresolvedType retTy = UnresolvedType.forName(str.substring(start, i)); start = i; i = str.lastIndexOf('.'); UnresolvedType declaringTy = UnresolvedType.forName(str.substring(start, i).trim()); start = ++i; String name = str.substring(start, len).trim(); return new MemberImpl( FIELD, declaringTy, mods, retTy, name, UnresolvedType.NONE); } /** Takes a string in this form: * * <blockquote><pre> * (static|interface|private)? TypeName TypeName . Id ( TypeName , ...) * </pre></blockquote> * Pretty much just for testing, and as such should perhaps be moved. */ public static Member methodFromString(String str) { str = str.trim(); // final int len = str.length(); int i = 0; int mods = 0; if (str.startsWith("static", i)) { mods = Modifier.STATIC; i += 6; } else if (str.startsWith("interface", i)) { mods = Modifier.INTERFACE; i += 9; } else if (str.startsWith("private", i)) { mods = Modifier.PRIVATE; i += 7; } while (Character.isWhitespace(str.charAt(i))) i++; int start = i; while (! Character.isWhitespace(str.charAt(i))) i++; UnresolvedType returnTy = UnresolvedType.forName(str.substring(start, i)); start = i; i = str.indexOf('(', i); i = str.lastIndexOf('.', i); UnresolvedType declaringTy = UnresolvedType.forName(str.substring(start, i).trim()); start = ++i; i = str.indexOf('(', i); String name = str.substring(start, i).trim(); start = ++i; i = str.indexOf(')', i); String[] paramTypeNames = parseIds(str.substring(start, i).trim()); return method(declaringTy, mods, returnTy, name, UnresolvedType.forNames(paramTypeNames)); } private static String[] parseIds(String str) { if (str.length() == 0) return ZERO_STRINGS; List l = new ArrayList(); int start = 0; while (true) { int i = str.indexOf(',', start); if (i == -1) { l.add(str.substring(start).trim()); break; } l.add(str.substring(start, i).trim()); start = i+1; } return (String[]) l.toArray(new String[l.size()]); } private static final String[] ZERO_STRINGS = new String[0]; // ---- things we know without resolution public boolean equals(Object other) { if (! (other instanceof Member)) return false; Member o = (Member) other; return (kind == o.getKind() && name.equals(o.getName()) && signature.equals(o.getSignature()) && declaringType.equals(o.getDeclaringType())); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#compareTo(java.lang.Object) */ public int compareTo(Object other) { Member o = (Member) other; int i = getName().compareTo(o.getName()); if (i != 0) return i; return getSignature().compareTo(o.getSignature()); } /** * Equality is checked based on the underlying signature, so the hash code * of a member is based on its kind, name, signature, and declaring type. The * algorithm for this was taken from page 38 of effective java. */ private volatile int hashCode = 0; public int hashCode() { if (hashCode == 0) { int result = 17; result = 37*result + kind.hashCode(); result = 37*result + name.hashCode(); result = 37*result + signature.hashCode(); result = 37*result + declaringType.hashCode(); hashCode = result; } return hashCode; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append(returnType.getName()); buf.append(' '); buf.append(declaringType.getName()); buf.append('.'); buf.append(name); if (kind != FIELD) { buf.append("("); if (parameterTypes.length != 0) { buf.append(parameterTypes[0]); for (int i=1, len = parameterTypes.length; i < len; i++) { buf.append(", "); buf.append(parameterTypes[i].getName()); } } buf.append(")"); } return buf.toString(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#toLongString() */ public String toLongString() { StringBuffer buf = new StringBuffer(); buf.append(kind); buf.append(' '); if (modifiers != 0) { buf.append(Modifier.toString(modifiers)); buf.append(' '); } buf.append(toString()); buf.append(" <"); buf.append(signature); buf.append(" >"); return buf.toString(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getKind() */ public Kind getKind() { return kind; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getDeclaringType() */ public UnresolvedType getDeclaringType() { return declaringType; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getReturnType() */ public UnresolvedType getReturnType() { return returnType; } public UnresolvedType getGenericReturnType() { return getReturnType(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getType() */ public UnresolvedType getType() { return returnType; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getName() */ public String getName() { return name; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getParameterTypes() */ public UnresolvedType[] getParameterTypes() { return parameterTypes; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignature() */ public String getSignature() { return signature; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getDeclaredSignature() */ public String getDeclaredSignature() { return declaredSignature;} /* (non-Javadoc) * @see org.aspectj.weaver.Member#getArity() */ public int getArity() { return parameterTypes.length; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getParameterSignature() */ public String getParameterSignature() { if (paramSignature != null) return paramSignature; StringBuffer sb = new StringBuffer(); sb.append("("); for (int i = 0; i < parameterTypes.length; i++) { UnresolvedType tx = parameterTypes[i]; sb.append(tx.getSignature()); } sb.append(")"); paramSignature = sb.toString(); return paramSignature; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isCompatibleWith(org.aspectj.weaver.Member) */ public boolean isCompatibleWith(Member am) { if (kind != METHOD || am.getKind() != METHOD) return true; if (! name.equals(am.getName())) return true; if (! equalTypes(getParameterTypes(), am.getParameterTypes())) return true; return getReturnType().equals(am.getReturnType()); } private static boolean equalTypes(UnresolvedType[] a, UnresolvedType[] b) { int len = a.length; if (len != b.length) return false; for (int i = 0; i < len; i++) { if (!a[i].equals(b[i])) return false; } return true; } // ---- things we know only with resolution /* (non-Javadoc) * @see org.aspectj.weaver.Member#getModifiers(org.aspectj.weaver.World) */ public int getModifiers(World world) { return resolve(world).getModifiers(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getExceptions(org.aspectj.weaver.World) */ public UnresolvedType[] getExceptions(World world) { return resolve(world).getExceptions(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isProtected(org.aspectj.weaver.World) */ public final boolean isProtected(World world) { return Modifier.isProtected(resolve(world).getModifiers()); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isStatic(org.aspectj.weaver.World) */ public final boolean isStatic(World world) { return Modifier.isStatic(resolve(world).getModifiers()); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isStrict(org.aspectj.weaver.World) */ public final boolean isStrict(World world) { return Modifier.isStrict(resolve(world).getModifiers()); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isStatic() */ public final boolean isStatic() { return Modifier.isStatic(modifiers); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isInterface() */ public final boolean isInterface() { return Modifier.isInterface(modifiers); // this is kinda weird } /* (non-Javadoc) * @see org.aspectj.weaver.Member#isPrivate() */ public final boolean isPrivate() { return Modifier.isPrivate(modifiers); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#canBeParameterized() */ public boolean canBeParameterized() { return false; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getCallsiteModifiers() */ public final int getCallsiteModifiers() { return modifiers & ~ Modifier.INTERFACE; } public int getModifiers() { return modifiers; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getExtractableName() */ public final String getExtractableName() { if (name.equals("<init>")) return "init$"; else if (name.equals("<clinit>")) return "clinit$"; else return name; } /* (non-Javadoc) * @see org.aspectj.weaver.Member#hasAnnotation(org.aspectj.weaver.UnresolvedType) */ public boolean hasAnnotation(UnresolvedType ofType) { throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result..."); } /* (non-Javadoc) * @see org.aspectj.weaver.AnnotatedElement#getAnnotationTypes() */ /* (non-Javadoc) * @see org.aspectj.weaver.Member#getAnnotationTypes() */ public ResolvedType[] getAnnotationTypes() { throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result..."); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getAnnotations() */ public AnnotationX[] getAnnotations() { throw new UnsupportedOperationException("You should resolve this member and call getAnnotations() on the result..."); } // ---- fields 'n' stuff /* (non-Javadoc) * @see org.aspectj.weaver.Member#getDeclaringTypes(org.aspectj.weaver.World) */ public Collection/*ResolvedType*/ getDeclaringTypes(World world) { ResolvedType myType = getDeclaringType().resolve(world); Collection ret = new HashSet(); if (kind == CONSTRUCTOR) { // this is wrong if the member doesn't exist, but that doesn't matter ret.add(myType); } else if (isStatic() || kind == FIELD) { walkUpStatic(ret, myType); } else { walkUp(ret, myType); } return ret; } private boolean walkUp(Collection acc, ResolvedType curr) { if (acc.contains(curr)) return true; boolean b = false; for (Iterator i = curr.getDirectSupertypes(); i.hasNext(); ) { b |= walkUp(acc, (ResolvedType)i.next()); } if (!b && curr.isParameterizedType()) { b = walkUp(acc,curr.getGenericType()); } if (!b) { b = curr.lookupMemberNoSupers(this) != null; } if (b) acc.add(curr); return b; } private boolean walkUpStatic(Collection acc, ResolvedType curr) { if (curr.lookupMemberNoSupers(this) != null) { acc.add(curr); return true; } else { boolean b = false; for (Iterator i = curr.getDirectSupertypes(); i.hasNext(); ) { b |= walkUpStatic(acc, (ResolvedType)i.next()); } if (!b && curr.isParameterizedType()) { b = walkUpStatic(acc,curr.getGenericType()); } if (b) acc.add(curr); return b; } } // ---- reflective thisJoinPoint stuff /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignatureMakerName() */ public String getSignatureMakerName() { if (getName().equals("<clinit>")) return "makeInitializerSig"; Kind kind = getKind(); if (kind == METHOD) { return "makeMethodSig"; } else if (kind == CONSTRUCTOR) { return "makeConstructorSig"; } else if (kind == FIELD) { return "makeFieldSig"; } else if (kind == HANDLER) { return "makeCatchClauseSig"; } else if (kind == STATIC_INITIALIZATION) { return "makeInitializerSig"; } else if (kind == ADVICE) { return "makeAdviceSig"; } else { throw new RuntimeException("unimplemented"); } } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignatureType() */ public String getSignatureType() { Kind kind = getKind(); if (getName().equals("<clinit>")) return "org.aspectj.lang.reflect.InitializerSignature"; if (kind == METHOD) { return "org.aspectj.lang.reflect.MethodSignature"; } else if (kind == CONSTRUCTOR) { return "org.aspectj.lang.reflect.ConstructorSignature"; } else if (kind == FIELD) { return "org.aspectj.lang.reflect.FieldSignature"; } else if (kind == HANDLER) { return "org.aspectj.lang.reflect.CatchClauseSignature"; } else if (kind == STATIC_INITIALIZATION) { return "org.aspectj.lang.reflect.InitializerSignature"; } else if (kind == ADVICE) { return "org.aspectj.lang.reflect.AdviceSignature"; } else { throw new RuntimeException("unimplemented"); } } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getSignatureString(org.aspectj.weaver.World) */ public String getSignatureString(World world) { if (getName().equals("<clinit>")) return getStaticInitializationSignatureString(world); Kind kind = getKind(); if (kind == METHOD) { return getMethodSignatureString(world); } else if (kind == CONSTRUCTOR) { return getConstructorSignatureString(world); } else if (kind == FIELD) { return getFieldSignatureString(world); } else if (kind == HANDLER) { return getHandlerSignatureString(world); } else if (kind == STATIC_INITIALIZATION) { return getStaticInitializationSignatureString(world); } else if (kind == ADVICE) { return getAdviceSignatureString(world); } else { throw new RuntimeException("unimplemented"); } } private String getHandlerSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(0)); buf.append('-'); //buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes()[0])); buf.append('-'); String pName = "<missing>"; String[] names = getParameterNames(world); if (names != null) pName = names[0]; buf.append(pName); buf.append('-'); return buf.toString(); } private String getStaticInitializationSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); //buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); return buf.toString(); } protected String getAdviceSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes())); buf.append('-'); buf.append(makeString(getParameterNames(world))); buf.append('-'); buf.append(makeString(getExceptions(world))); buf.append('-'); buf.append(makeString(getReturnType())); buf.append('-'); return buf.toString(); } protected String getMethodSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes())); buf.append('-'); buf.append(makeString(getParameterNames(world))); buf.append('-'); buf.append(makeString(getExceptions(world))); buf.append('-'); buf.append(makeString(getReturnType())); buf.append('-'); return buf.toString(); } protected String getConstructorSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getParameterTypes())); buf.append('-'); buf.append(makeString(getParameterNames(world))); buf.append('-'); buf.append(makeString(getExceptions(world))); buf.append('-'); return buf.toString(); } protected String getFieldSignatureString(World world) { StringBuffer buf = new StringBuffer(); buf.append(makeString(getModifiers(world))); buf.append('-'); buf.append(getName()); buf.append('-'); buf.append(makeString(getDeclaringType())); buf.append('-'); buf.append(makeString(getReturnType())); buf.append('-'); return buf.toString(); } protected String makeString(int i) { return Integer.toString(i, 16); //??? expensive } protected String makeString(UnresolvedType t) { // this is the inverse of the odd behavior for Class.forName w/ arrays if (t.isArray()) { // this behavior matches the string used by the eclipse compiler for Foo.class literals return t.getSignature().replace('/', '.'); } else { return t.getName(); } } protected String makeString(UnresolvedType[] types) { if (types == null) return ""; StringBuffer buf = new StringBuffer(); for (int i = 0, len=types.length; i < len; i++) { buf.append(makeString(types[i])); buf.append(':'); } return buf.toString(); } protected String makeString(String[] names) { if (names == null) return ""; StringBuffer buf = new StringBuffer(); for (int i = 0, len=names.length; i < len; i++) { buf.append(names[i]); buf.append(':'); } return buf.toString(); } /* (non-Javadoc) * @see org.aspectj.weaver.Member#getParameterNames(org.aspectj.weaver.World) */ public String[] getParameterNames(World world) { return resolve(world).getParameterNames(); } /** * All the signatures that a join point with this member as its signature has. */ public Iterator getJoinPointSignatures(World inAWorld) { if (joinPointSignatures == null) { joinPointSignatures = new JoinPointSignatureIterator(this,inAWorld); } joinPointSignatures.reset(); return joinPointSignatures; } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
ajde/testsrc/org/aspectj/ajde/BuildConfigurationTests.java
/********************************************************************** Copyright (c) 2003 IBM Corporation and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: Adrian Colyer - initial version ... **********************************************************************/ package org.aspectj.ajde; import java.io.File; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.TestSuite; import org.aspectj.ajde.internal.CompilerAdapter; import org.aspectj.ajde.ui.UserPreferencesAdapter; import org.aspectj.ajde.ui.internal.AjcBuildOptions; import org.aspectj.ajde.ui.internal.UserPreferencesStore; import org.aspectj.ajdt.internal.core.builder.AjBuildConfig; import org.aspectj.bridge.*; import org.aspectj.bridge.MessageHandler; import org.aspectj.util.LangUtil; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; /** * Tests that a correctly populated AjBuildConfig object is created * in reponse to the setting in BuildOptionsAdapter and * ProjectPropretiesAdapter */ public class BuildConfigurationTests extends AjdeTestCase { private CompilerAdapter compilerAdapter; private AjBuildConfig buildConfig = null; private AjcBuildOptions buildOptions = null; private UserPreferencesAdapter preferencesAdapter = null; private NullIdeProperties projectProperties = null; private MessageHandler messageHandler; private static final String configFile = AjdeTests.testDataPath("examples/figures-coverage/all.lst"); public BuildConfigurationTests( String name ) { super( name ); } public static void main(String[] args) { junit.swingui.TestRunner.run(BuildConfigurationTests.class); } public static TestSuite suite() { TestSuite result = new TestSuite(); result.addTestSuite(BuildConfigurationTests.class); return result; } // The tests... public void testCharacterEncoding() { buildOptions.setCharacterEncoding( "UTF-8" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String encoding = (String) options.get( CompilerOptions.OPTION_Encoding ); assertEquals( "character encoding", "UTF-8", encoding ); } public void testComplianceLevel() { buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_14 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); assertEquals( "compliance level", CompilerOptions.VERSION_1_4, compliance); assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel ); } public void testSourceCompatibilityLevel() { buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_13); buildOptions.setSourceCompatibilityLevel( BuildOptionsAdapter.VERSION_14); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); assertEquals( "compliance level", CompilerOptions.VERSION_1_3, compliance); assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel ); } public void testSourceIncompatibilityLevel() { // this config should "fail" and leave source level at 1.4 buildOptions.setComplianceLevel( BuildOptionsAdapter.VERSION_14); buildOptions.setSourceCompatibilityLevel( BuildOptionsAdapter.VERSION_13); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String compliance = (String) options.get(CompilerOptions.OPTION_Compliance); String sourceLevel = (String) options.get(CompilerOptions.OPTION_Source); assertEquals( "compliance level", CompilerOptions.VERSION_1_4, compliance); assertEquals( "source level", CompilerOptions.VERSION_1_4, sourceLevel ); } public void testNullWarnings() { buildOptions.setWarnings( null ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with the default warnings assertOptionEquals( "report overriding package default", options, CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, CompilerOptions.WARNING); assertOptionEquals( "report method with cons name", options, CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.WARNING); assertOptionEquals( "report deprecation", options, CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); assertOptionEquals( "report hidden catch block", options, CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.WARNING); assertOptionEquals( "report unused local", options, CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.IGNORE); assertOptionEquals( "report unused param", options, CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.IGNORE); assertOptionEquals( "report synthectic access", options, CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.IGNORE); assertOptionEquals( "report non-externalized string literal", options, CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.IGNORE); assertOptionEquals( "report assert identifer", options, CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.WARNING); } // public void testEmptyWarnings() { // buildOptions.setWarnings( new HashSet() ); // buildConfig = compilerAdapter.genBuildConfig( configFile ); // Map options = buildConfig.getJavaOptions(); // // // this should leave us with the user specifiable warnings // // turned off // assertOptionEquals( "report overriding package default", // options, // CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, // CompilerOptions.WARNING); // assertOptionEquals( "report method with cons name", // options, // CompilerOptions.OPTION_ReportMethodWithConstructorName, // CompilerOptions.WARNING); // assertOptionEquals( "report deprecation", // options, // CompilerOptions.OPTION_ReportDeprecation, // CompilerOptions.WARNING); // assertOptionEquals( "report hidden catch block", // options, // CompilerOptions.OPTION_ReportHiddenCatchBlock, // CompilerOptions.WARNING); // assertOptionEquals( "report unused local", // options, // CompilerOptions.OPTION_ReportUnusedLocal, // CompilerOptions.WARNING); // assertOptionEquals( "report unused param", // options, // CompilerOptions.OPTION_ReportUnusedParameter, // CompilerOptions.WARNING); // assertOptionEquals( "report synthectic access", // options, // CompilerOptions.OPTION_ReportSyntheticAccessEmulation, // CompilerOptions.WARNING); // assertOptionEquals( "report non-externalized string literal", // options, // CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, // CompilerOptions.WARNING); // assertOptionEquals( "report assert identifer", // options, // CompilerOptions.OPTION_ReportAssertIdentifier, // CompilerOptions.WARNING); // } public void testSetOfWarnings() { HashSet warnings = new HashSet(); warnings.add( BuildOptionsAdapter.WARN_ASSERT_IDENITIFIER ); warnings.add( BuildOptionsAdapter.WARN_CONSTRUCTOR_NAME ); warnings.add( BuildOptionsAdapter.WARN_DEPRECATION ); warnings.add( BuildOptionsAdapter.WARN_MASKED_CATCH_BLOCKS ); warnings.add( BuildOptionsAdapter.WARN_PACKAGE_DEFAULT_METHOD ); warnings.add( BuildOptionsAdapter.WARN_SYNTHETIC_ACCESS ); warnings.add( BuildOptionsAdapter.WARN_UNUSED_ARGUMENTS ); warnings.add( BuildOptionsAdapter.WARN_UNUSED_IMPORTS ); warnings.add( BuildOptionsAdapter.WARN_UNUSED_LOCALS ); warnings.add( BuildOptionsAdapter.WARN_NLS ); buildOptions.setWarnings( warnings ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with all the user specifiable warnings // turned on assertOptionEquals( "report overriding package default", options, CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, CompilerOptions.WARNING); assertOptionEquals( "report method with cons name", options, CompilerOptions.OPTION_ReportMethodWithConstructorName, CompilerOptions.WARNING); assertOptionEquals( "report deprecation", options, CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); assertOptionEquals( "report hidden catch block", options, CompilerOptions.OPTION_ReportHiddenCatchBlock, CompilerOptions.WARNING); assertOptionEquals( "report unused local", options, CompilerOptions.OPTION_ReportUnusedLocal, CompilerOptions.WARNING); assertOptionEquals( "report unused param", options, CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.WARNING); assertOptionEquals( "report synthectic access", options, CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.WARNING); assertOptionEquals( "report non-externalized string literal", options, CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, CompilerOptions.WARNING); assertOptionEquals( "report assert identifer", options, CompilerOptions.OPTION_ReportAssertIdentifier, CompilerOptions.WARNING); } public void testNoDebugOptions() { buildOptions.setDebugLevel( null ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with the default debug settings assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testEmptyDebugOptions() { buildOptions.setDebugLevel( new HashSet() ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with the default debug assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testDebugAll() { HashSet debugOpts = new HashSet(); debugOpts.add( BuildOptionsAdapter.DEBUG_ALL ); buildOptions.setDebugLevel( debugOpts ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with all debug on assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testDebugSet() { HashSet debugOpts = new HashSet(); debugOpts.add( BuildOptionsAdapter.DEBUG_SOURCE ); debugOpts.add( BuildOptionsAdapter.DEBUG_VARS ); buildOptions.setDebugLevel( debugOpts ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); // this should leave us with all debug on assertOptionEquals( "debug source", options, CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug lines", options, CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); assertOptionEquals( "debug vars", options, CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } public void testNoImport() { buildOptions.setNoImportError( true ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); // Map options = buildConfig.getJavaOptions(); // String noImport = (String) options.get( CompilerOptions.OPTION_ReportInvalidImport ); // assertEquals( "no import", CompilerOptions.WARNING, noImport ); // buildOptions.setNoImportError( false ); } public void testPreserveAllLocals() { buildOptions.setPreserveAllLocals( true ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); Map options = buildConfig.getOptions().getMap(); String preserve = (String) options.get( CompilerOptions.OPTION_PreserveUnusedLocal ); assertEquals( "preserve unused", CompilerOptions.PRESERVE, preserve ); } public void testNonStandardOptions() { buildOptions.setNonStandardOptions( "-XnoWeave" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertTrue( "XnoWeave", buildConfig.isNoWeave() ); buildOptions.setNonStandardOptions( "-XserializableAspects" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue( "XserializableAspects", buildConfig.isXserializableAspects() ); buildOptions.setNonStandardOptions( "-XnoInline" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue( "XnoInline", buildConfig.isXnoInline()); buildOptions.setNonStandardOptions( "-Xlint" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertEquals( "Xlint", AjBuildConfig.AJLINT_DEFAULT, buildConfig.getLintMode()); buildOptions.setNonStandardOptions( "-Xlint:error" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertEquals( "Xlint", AjBuildConfig.AJLINT_ERROR, buildConfig.getLintMode()); // XXX test for lintfile // buildOptions.setNonStandardOptions( "-Xlintfile testdata/AspectJBuildManagerTest/lint.properties" ); // buildConfig = compilerAdapter.genBuildConfig( configFile ); // assertEquals( "Xlintfile", new File( "testdata/AspectJBuildManagerTest/lint.properties" ).getAbsolutePath(), // buildConfig.getLintSpecFile().toString()); // and a few options thrown in at once buildOptions.setNonStandardOptions( "-Xlint -XnoInline -XserializableAspects" ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertEquals( "Xlint", AjBuildConfig.AJLINT_DEFAULT, buildConfig.getLintMode()); assertTrue( "XnoInline", buildConfig.isXnoInline()); assertTrue( "XserializableAspects", buildConfig.isXserializableAspects() ); } public void testSourceRoots() { Set roots = new HashSet(); projectProperties.setSourceRoots( roots ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List configRoots = buildConfig.getSourceRoots(); assertTrue( "no source dirs", configRoots.isEmpty() ); File f = new File( AjdeTests.testDataPath("examples/figures/figures-coverage" )); roots.add( f ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List configRoots2 = buildConfig.getSourceRoots(); assertTrue( "one source dir", configRoots2.size() == 1 ); assertTrue( "source dir", configRoots2.contains(f) ); File f2 = new File( AjdeTests.testDataPath("examples/figures/figures-demo")); roots.add( f2 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List configRoots3 = buildConfig.getSourceRoots(); assertTrue( "two source dirs", configRoots3.size() == 2 ); assertTrue( "source dir 1", configRoots3.contains(f) ); assertTrue( "source dir 2", configRoots3.contains(f2) ); } public void testInJars() { Set jars = new HashSet(); projectProperties.setInJars( jars ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List inJars = buildConfig.getInJars(); assertTrue( "no in jars", inJars.isEmpty() ); File f = new File( "jarone.jar" ); jars.add( f ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List inJars2 = buildConfig.getInJars(); assertTrue( "one in jar", inJars2.size() == 1 ); assertTrue( "in jar", inJars2.contains(f) ); File f2 = new File( "jartwo.jar" ); jars.add( f2 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); List inJars3 = buildConfig.getInJars(); assertTrue( "two in jars", inJars3.size() == 2 ); assertTrue( "in jar 1", inJars3.contains(f) ); assertTrue( "in jar 2", inJars3.contains(f2) ); } public void testAspectPath() { Set aspects = new HashSet(); projectProperties.setAspectPath( aspects ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List aPath = buildConfig.getAspectpath(); assertTrue( "no aspect path", aPath.isEmpty() ); File f = new File( "jarone.jar" ); aspects.add( f ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List aPath2 = buildConfig.getAspectpath(); assertEquals("aspectpath", 1, aPath2.size()); assertTrue( "1 aspectpath", aPath2.contains(f) ); File f2 = new File( "jartwo.jar" ); aspects.add( f2 ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); List aPath3 = buildConfig.getAspectpath(); assertTrue( "two jars in path", aPath3.size() == 2 ); assertTrue( "1 aspectpath", aPath3.contains(f) ); assertTrue( "2 aspectpath", aPath3.contains(f2) ); } public void testOutJar() { String outJar = "mybuild.jar"; projectProperties.setOutJar( outJar ); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertNotNull("output jar", buildConfig.getOutputJar()); assertEquals( "out jar", outJar, buildConfig.getOutputJar().toString() ); } public void testXHasMember() { buildOptions.setNonStandardOptions("-XhasMember"); buildConfig = compilerAdapter.genBuildConfig( configFile ); assertTrue(configFile + " failed", null != buildConfig); assertTrue( "XhasMember", buildConfig.isXHasMemberEnabled() ); } protected void setUp() throws Exception { preferencesAdapter = new UserPreferencesStore(false); buildOptions = new AjcBuildOptions(preferencesAdapter); compilerAdapter = new CompilerAdapter(); projectProperties = new NullIdeProperties( "" ); messageHandler = new MessageHandler(true); ErrorHandler handler = new ErrorHandler() { public void handleWarning(String message) { MessageUtil.warn(messageHandler, message); } public void handleError(String message) { MessageUtil.error(messageHandler, message); } public void handleError(String message, Throwable t) { IMessage m = new Message(message, IMessage.ERROR, t, null); messageHandler.handleMessage(m); } }; try { // String s = null; Ajde.init( null, null, null, projectProperties, buildOptions, null, null, handler); } catch (Throwable t) { String s = "Unable to initialize AJDE " + LangUtil.renderException(t); assertTrue(s, false); } } protected void tearDown() throws Exception { super.tearDown(); preferencesAdapter = null; buildOptions = null; compilerAdapter = null; projectProperties = null; messageHandler = null; } private void assertOptionEquals( String reason, Map options, String optionName, String value) { String mapValue = (String) options.get(optionName); assertEquals( reason, value, mapValue ); } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.ajc; import java.io.*; import java.util.*; import org.aspectj.ajdt.internal.core.builder.*; import org.aspectj.bridge.*; import org.aspectj.util.*; import org.aspectj.weaver.Constants; import org.aspectj.weaver.Dump; import org.aspectj.weaver.WeaverMessages; import org.aspectj.org.eclipse.jdt.core.compiler.InvalidInputException; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.Main; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; public class BuildArgParser extends Main { private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages"; private static boolean LOADED_BUNDLE = false; static { bundle = ResourceBundle.getBundle(BUNDLE_NAME); if (!LOADED_BUNDLE) { LOADED_BUNDLE = true; } } /** to initialize super's PrintWriter but refer to underlying StringWriter */ private static class StringPrintWriter extends PrintWriter { public final StringWriter stringWriter; StringPrintWriter(StringWriter sw) { super(sw); this.stringWriter = sw; } } /** @return multi-line String usage for the compiler */ public static String getUsage() { return Main.bind("misc.usage",Main.bind("compiler.name")); } public static String getXOptionUsage() { return Main.bind("xoption.usage",Main.bind("compiler.name")); } /** * StringWriter sink for some errors. * This only captures errors not handled by any IMessageHandler parameter * and only when no PrintWriter is set in the constructor. * XXX This relies on (Sun's) implementation of StringWriter, * which returns the actual (not copy) internal StringBuffer. */ private final StringBuffer errorSink; private IMessageHandler handler; /** * Overrides super's bundle. */ public BuildArgParser(PrintWriter writer, IMessageHandler handler) { super(writer, writer, false); if (writer instanceof StringPrintWriter) { errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer(); } else { errorSink = null; } this.handler = handler; } /** Set up to capture messages using getOtherMessages(boolean) */ public BuildArgParser(IMessageHandler handler) { this(new StringPrintWriter(new StringWriter()),handler); } /** * Generate build configuration for the input args, * passing to handler any error messages. * @param args the String[] arguments for the build configuration * @return AjBuildConfig per args, * which will be invalid unless there are no handler errors. */ public AjBuildConfig genBuildConfig(String[] args) { AjBuildConfig config = new AjBuildConfig(); populateBuildConfig(config, args, true, null); return config; } /** * Generate build configuration for the input args, * passing to handler any error messages. * @param args the String[] arguments for the build configuration * @param setClasspath determines if the classpath should be parsed and set on the build configuration * @param configFile can be null * @return AjBuildConfig per args, * which will be invalid unless there are no handler errors. */ public AjBuildConfig populateBuildConfig(AjBuildConfig buildConfig, String[] args, boolean setClasspath, File configFile) { Dump.saveCommandLine(args); buildConfig.setConfigFile(configFile); try { // sets filenames to be non-null in order to make sure that file paramters are ignored super.filenames = new String[] { "" }; AjcConfigParser parser = new AjcConfigParser(buildConfig, handler); parser.parseCommandLine(args); boolean swi = buildConfig.getShowWeavingInformation(); // Now jump through firey hoops to turn them on/off if (handler instanceof CountingMessageHandler) { IMessageHandler delegate = ((CountingMessageHandler)handler).delegate; // Without dontIgnore() on the IMessageHandler interface, we have to do this *blurgh* if (delegate instanceof MessageHandler) { if (swi) ((MessageHandler)delegate).dontIgnore(IMessage.WEAVEINFO); else ((MessageHandler)delegate).ignore(IMessage.WEAVEINFO); } } boolean incrementalMode = buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode(); List fileList = new ArrayList(); List files = parser.getFiles(); if (!LangUtil.isEmpty(files)) { if (incrementalMode) { MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots"); } else { fileList.addAll(files); } } List javaArgList = new ArrayList(); // disable all special eclipse warnings by default - why??? //??? might want to instead override getDefaultOptions() javaArgList.add("-warn:none"); // these next four lines are some nonsense to fool the eclipse batch compiler // without these it will go searching for reasonable values from properties //TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed javaArgList.add("-classpath"); javaArgList.add(System.getProperty("user.dir")); javaArgList.add("-bootclasspath"); javaArgList.add(System.getProperty("user.dir")); javaArgList.addAll(parser.getUnparsedArgs()); super.configure((String[])javaArgList.toArray(new String[javaArgList.size()])); if (!proceed) { buildConfig.doNotProceed(); return buildConfig; } if (buildConfig.getSourceRoots() != null) { for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) { fileList.addAll(collectSourceRootFiles((File)i.next())); } } buildConfig.setFiles(fileList); if (destinationPath != null) { // XXX ?? unparsed but set? buildConfig.setOutputDir(new File(destinationPath)); } if (setClasspath) { buildConfig.setClasspath(getClasspath(parser)); buildConfig.setBootclasspath(getBootclasspath(parser)); } if (incrementalMode && (0 == buildConfig.getSourceRoots().size())) { MessageUtil.error(handler, "specify a source root when in incremental mode"); } /* * Ensure we don't overwrite injars, inpath or aspectpath with outjar * bug-71339 */ File outjar = buildConfig.getOutputJar(); if (outjar != null) { /* Search injars */ for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File injar = (File)i.next(); if (injar.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } /* Search inpath */ for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory() && inPathElement.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } /* Search aspectpath */ for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext(); ) { File pathElement = (File)i.next(); if (!pathElement.isDirectory() && pathElement.equals(outjar)) { String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH); MessageUtil.error(handler,message); } } } setDebugOptions(); buildConfig.getOptions().set(options); } catch (InvalidInputException iie) { ISourceLocation location = null; if (buildConfig.getConfigFile() != null) { location = new SourceLocation(buildConfig.getConfigFile(), 0); } IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location); handler.handleMessage(m); } return buildConfig; } // from super... public void printVersion() { System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$ System.err.flush(); } public void printUsage() { System.out.println(bind("misc.usage")); //$NON-NLS-1$ System.out.flush(); } /** * Get messages not dumped to handler or any PrintWriter. * @param flush if true, empty errors * @return null if none, String otherwise * @see BuildArgParser() */ public String getOtherMessages(boolean flush) { if (null == errorSink) { return null; } String result = errorSink.toString().trim(); if (0 == result.length()) { result = null; } if (flush) { errorSink.setLength(0); } return result; } private void setDebugOptions() { options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); } private Collection collectSourceRootFiles(File dir) { return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter)); } public List getBootclasspath(AjcConfigParser parser) { List ret = new ArrayList(); if (parser.bootclasspath == null) { addClasspath(System.getProperty("sun.boot.class.path", ""), ret); } else { addClasspath(parser.bootclasspath, ret); } return ret; } /** * If the classpath is not set, we use the environment's java.class.path, but remove * the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues * (refer to bug#39959). */ public List getClasspath(AjcConfigParser parser) { List ret = new ArrayList(); // if (parser.bootclasspath == null) { // addClasspath(System.getProperty("sun.boot.class.path", ""), ret); // } else { // addClasspath(parser.bootclasspath, ret); // } String extdirs = parser.extdirs; if (extdirs == null) { extdirs = System.getProperty("java.ext.dirs", ""); } addExtDirs(extdirs, ret); if (parser.classpath == null) { addClasspath(System.getProperty("java.class.path", ""), ret); List fixedList = new ArrayList(); for (Iterator it = ret.iterator(); it.hasNext(); ) { String entry = (String)it.next(); if (!entry.endsWith("aspectjtools.jar")) { fixedList.add(entry); } } ret = fixedList; } else { addClasspath(parser.classpath, ret); } //??? eclipse seems to put outdir on the classpath //??? we're brave and believe we don't need it return ret; } private void addExtDirs(String extdirs, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator); while (tokenizer.hasMoreTokens()) { // classpathCollector.add(tokenizer.nextToken()); File dirFile = new File((String)tokenizer.nextToken()); if (dirFile.canRead() && dirFile.isDirectory()) { File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER); for (int i = 0; i < files.length; i++) { classpathCollector.add(files[i].getAbsolutePath()); } } else { // XXX alert on invalid -extdirs entries } } } private void addClasspath(String classpath, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { classpathCollector.add(tokenizer.nextToken()); } } private class AjcConfigParser extends ConfigParser { private String bootclasspath = null; private String classpath = null; private String extdirs = null; private List unparsedArgs = new ArrayList(); private AjBuildConfig buildConfig; private IMessageHandler handler; public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) { this.buildConfig = buildConfig; this.handler = handler; } public List getUnparsedArgs() { return unparsedArgs; } /** * Extract AspectJ-specific options (except for argfiles). * Caller should warn when sourceroots is empty but in * incremental mode. * Signals warnings or errors through handler set in constructor. */ public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove() int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique // trim arg? buildConfig.setXlazyTjp(true); // now default - MINOR could be pushed down and made default at a lower level if (LangUtil.isEmpty(arg)) { showWarning("empty arg found"); } else if (arg.equals("-inpath")) {; if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE); List inPath = buildConfig.getInpath(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File file = makeFile(filename); if (file.exists() && FileUtil.hasZipSuffix(filename)) { inPath.add(file); } else { if (file.isDirectory()) { inPath.add(file); } else showError("bad inpath component: " + filename); } } buildConfig.setInPath(inPath); args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-injars")) {; if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) { buildConfig.getInJars().add(jarFile); } else { File dirFile = makeFile(filename); if (dirFile.isDirectory()) { buildConfig.getInJars().add(dirFile); } else showError("bad injar: " + filename); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-aspectpath")) {; if (args.size() > nextArgIndex) { StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (jarFile.exists() && (FileUtil.hasZipSuffix(filename) || jarFile.isDirectory())) { buildConfig.getAspectpath().add(jarFile); } else { showError("bad aspectpath: " + filename); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-sourceroots")) { if (args.size() > nextArgIndex) { List sourceRoots = new ArrayList(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { File f = makeFile(st.nextToken()); if (f.isDirectory() && f.canRead()) { sourceRoots.add(f); } else { showError("bad sourceroot: " + f); } } if (0 < sourceRoots.size()) { buildConfig.setSourceRoots(sourceRoots); } args.remove(args.get(nextArgIndex)); } else { showError("-sourceroots requires list of directories"); } } else if (arg.equals("-outjar")) { if (args.size() > nextArgIndex) { // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE); File jarFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); if (FileUtil.hasZipSuffix(jarFile)) { try { if (!jarFile.exists()) { jarFile.createNewFile(); } buildConfig.setOutputJar(jarFile); } catch (IOException ioe) { showError("unable to create outjar file: " + jarFile); } } else { showError("invalid -outjar file: " + jarFile); } args.remove(args.get(nextArgIndex)); } else { showError("-outjar requires jar path argument"); } } else if (arg.equals("-outxml")) { buildConfig.setOutxmlName("META-INF/aop.xml"); } else if (arg.equals("-outxmlfile")) { if (args.size() > nextArgIndex) { String name = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); buildConfig.setOutxmlName(name); args.remove(args.get(nextArgIndex)); } else { showError("-outxmlfile requires file name argument"); } } else if (arg.equals("-log")){ // remove it as it's already been handled in org.aspectj.tools.ajc.Main args.remove(args.get(nextArgIndex)); } else if (arg.equals("-messageHolder")) { // remove it as it's already been handled in org.aspectj.tools.ajc.Main args.remove(args.get(nextArgIndex)); }else if (arg.equals("-incremental")) { buildConfig.setIncrementalMode(true); } else if (arg.equals("-XincrementalFile")) { if (args.size() > nextArgIndex) { File file = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); buildConfig.setIncrementalFile(file); if (!file.canRead()) { showError("bad -XincrementalFile : " + file); // if not created before recompile test, stop after first compile } args.remove(args.get(nextArgIndex)); } else { showError("-XincrementalFile requires file argument"); } } else if (arg.equals("-crossrefs")) { buildConfig.setGenerateCrossRefsMode(true); buildConfig.setGenerateModelMode(true); } else if (arg.equals("-emacssym")) { buildConfig.setEmacsSymMode(true); buildConfig.setGenerateModelMode(true); } else if (arg.equals("-XjavadocsInModel")) { buildConfig.setGenerateModelMode(true); buildConfig.setGenerateJavadocsInModelMode(true); } else if (arg.equals("-Xdev:NoAtAspectJProcessing")) { buildConfig.setNoAtAspectJAnnotationProcessing(true); } else if (arg.equals("-Xdev:Pinpoint")) { buildConfig.setXdevPinpointMode(true); } else if (arg.equals("-Xjoinpoints:arrayconstruction")) { buildConfig.setXJoinpoints("arrayconstruction"); } else if (arg.equals("-noweave") || arg.equals( "-XnoWeave")) { buildConfig.setNoWeave(true); } else if (arg.equals("-XserializableAspects")) { buildConfig.setXserializableAspects(true); } else if (arg.equals("-XlazyTjp")) { // do nothing as this is now on by default showWarning("-XlazyTjp should no longer be used, build tjps lazily is now the default"); } else if (arg.startsWith("-Xreweavable")) { showWarning("-Xreweavable is on by default"); if (arg.endsWith(":compress")) { showWarning("-Xreweavable:compress is no longer available - reweavable is now default"); } } else if (arg.startsWith("-Xset:")) { buildConfig.setXconfigurationInfo(arg.substring(6)); } else if (arg.startsWith("-XnotReweavable")) { buildConfig.setXnotReweavable(true); } else if (arg.equals("-XnoInline")) { buildConfig.setXnoInline(true); } else if (arg.equals("-XhasMember")) { buildConfig.setXHasMemberSupport(true); } else if (arg.startsWith("-showWeaveInfo")) { buildConfig.setShowWeavingInformation(true); } else if (arg.equals("-Xlintfile")) { if (args.size() > nextArgIndex) { File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); // XXX relax restriction on props file suffix? if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) { buildConfig.setLintSpecFile(lintSpecFile); } else { showError("bad -Xlintfile file: " + lintSpecFile); buildConfig.setLintSpecFile(null); } args.remove(args.get(nextArgIndex)); } else { showError("-Xlintfile requires .properties file argument"); } } else if (arg.equals("-Xlint")) { // buildConfig.getAjOptions().put( // AjCompilerOptions.OPTION_Xlint, // CompilerOptions.GENERATE); buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT); } else if (arg.startsWith("-Xlint:")) { if (7 < arg.length()) { buildConfig.setLintMode(arg.substring(7)); } else { showError("invalid lint option " + arg); } } else if (arg.equals("-bootclasspath")) { if (args.size() > nextArgIndex) { String bcpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer bcp = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator); while (strTok.hasMoreTokens()) { bcp.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { bcp.append(File.pathSeparator); } } bootclasspath = bcp.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-bootclasspath requires classpath entries"); } } else if (arg.equals("-classpath") || arg.equals("-cp")) { if (args.size() > nextArgIndex) { String cpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer cp = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator); while (strTok.hasMoreTokens()) { cp.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { cp.append(File.pathSeparator); } } classpath = cp.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-classpath requires classpath entries"); } } else if (arg.equals("-extdirs")) { if (args.size() > nextArgIndex) { String extdirsArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); StringBuffer ed = new StringBuffer(); StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator); while (strTok.hasMoreTokens()) { ed.append(makeFile(strTok.nextToken())); if (strTok.hasMoreTokens()) { ed.append(File.pathSeparator); } } extdirs = ed.toString(); args.remove(args.get(nextArgIndex)); } else { showError("-extdirs requires list of external directories"); } // error on directory unless -d, -{boot}classpath, or -extdirs } else if (arg.equals("-d")) { dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-classpath")) { // dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-bootclasspath")) { // dirLookahead(arg, args, nextArgIndex); // } else if (arg.equals("-extdirs")) { // dirLookahead(arg, args, nextArgIndex); } else if (arg.equals("-proceedOnError")) { buildConfig.setProceedOnError(true); } else if (new File(arg).isDirectory()) { showError("dir arg not permitted: " + arg); } else if (arg.startsWith("-Xajruntimetarget")) { if (arg.endsWith(":1.2")) { buildConfig.setTargetAspectjRuntimeLevel(Constants.RUNTIME_LEVEL_12); } else if (arg.endsWith(":1.5")) { buildConfig.setTargetAspectjRuntimeLevel(Constants.RUNTIME_LEVEL_15); } else { showError("-Xajruntimetarget:<level> only supports a target level of 1.2 or 1.5"); } } 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); } } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/core/AspectJCore.java
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.ajdt.core; import java.util.Map; import org.aspectj.ajdt.internal.core.builder.AjCompilerOptions; import org.aspectj.org.eclipse.jdt.core.JavaCore; /** * This is the plugin class for AspectJ. */ public class AspectJCore extends JavaCore { public static final String COMPILER_PB_INVALID_ABSOLUTE_TYPE_NAME = AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName; public static final String COMPILER_PB_INVALID_WILDCARD_TYPE_NAME = AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName; public static final String COMPILER_PB_UNRESOLVABLE_MEMBER = AjCompilerOptions.OPTION_ReportUnresolvableMember; public static final String COMPILER_PB_TYPE_NOT_EXPOSED_TO_WEAVER = AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver; public static final String COMPILER_PB_SHADOW_NOT_IN_STRUCTURE = AjCompilerOptions.OPTION_ReportShadowNotInStructure; public static final String COMPILER_PB_UNMATCHED_SUPERTYPE_IN_CALL = AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall; public static final String COMPILER_PB_CANNOT_IMPLEMENT_LAZY_TJP = AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP; public static final String COMPILER_PB_NEED_SERIAL_VERSION_UID = AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField; public static final String COMPILER_PB_INCOMPATIBLE_SERIAL_VERSION = AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion; public static final String COMPILER_NO_WEAVE = AjCompilerOptions.OPTION_NoWeave; public static final String COMPILER_SERIALIZABLE_ASPECTS = AjCompilerOptions.OPTION_XSerializableAspects; public static final String COMPILER_LAZY_TJP = AjCompilerOptions.OPTION_XLazyThisJoinPoint; public static final String COMPILER_NO_ADVICE_INLINE = AjCompilerOptions.OPTION_XNoInline; public static final String COMPILER_NOT_REWEAVABLE = AjCompilerOptions.OPTION_XNotReweavable; public AspectJCore() { super(); } public static AspectJCore getAspectJCore() { return (AspectJCore) getPlugin(); } /* (non-Javadoc) * @see org.eclipse.jdt.core.JavaCore#getCompilerOptions() */ protected Map getCompilerOptions() { return new AjCompilerOptions().getMap(); } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/AjCompilerAdapter.java
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.ajdt.internal.compiler; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.ajdt.internal.compiler.ast.AddAtAspectJAnnotationsVisitor; import org.aspectj.ajdt.internal.compiler.ast.ValidateAtAspectJAnnotationsVisitor; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.core.builder.AjState; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.Compiler; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.patterns.CflowPointcut; /** * @author colyer * * Adapts standard JDT Compiler to add in AspectJ specific behaviours. */ public class AjCompilerAdapter implements ICompilerAdapter { private Compiler compiler; private BcelWeaver weaver; private EclipseFactory eWorld; private boolean isBatchCompile; private boolean reportedErrors; private boolean isXNoWeave; private boolean proceedOnError; private boolean inJava5Mode; private boolean noAtAspectJAnnotationProcessing; private IIntermediateResultsRequestor intermediateResultsRequestor; private IProgressListener progressListener; private IOutputClassFileNameProvider outputFileNameProvider; private IBinarySourceProvider binarySourceProvider; private WeaverMessageHandler weaverMessageHandler; private Map /* fileName |-> List<UnwovenClassFile> */ binarySourceSetForFullWeave = new HashMap(); private ContextToken processingToken = null; private ContextToken resolvingToken = null; private ContextToken analysingToken = null; private ContextToken generatingToken = null; private AjState incrementalCompilationState; List /*InterimResult*/ resultsPendingWeave = new ArrayList(); /** * Create an adapter, and tell it everything it needs to now to drive the AspectJ * parts of a compile cycle. * @param compiler the JDT compiler that produces class files from source * @param isBatchCompile true if this is a full build (non-incremental) * @param world the bcelWorld used for type resolution during weaving * @param weaver the weaver * @param intRequestor recipient of interim compilation results from compiler (pre-weave) * @param outputFileNameProvider implementor of a strategy providing output file names for results * @param binarySourceEntries binary source that we didn't compile, but that we need to weave * @param resultSetForFullWeave if we are doing an incremental build, and the weaver determines * that we need to weave the world, this is the set of intermediate * results that will be passed to the weaver. * @param isXNoWeave */ public AjCompilerAdapter(Compiler compiler, boolean isBatchCompile, BcelWorld world, BcelWeaver weaver, EclipseFactory eFactory, IIntermediateResultsRequestor intRequestor, IProgressListener progressListener, IOutputClassFileNameProvider outputFileNameProvider, IBinarySourceProvider binarySourceProvider, Map fullBinarySourceEntries, /* fileName |-> List<UnwovenClassFile> */ boolean isXNoWeave, boolean proceedOnError, boolean noAtAspectJProcessing, AjState incrementalCompilationState) { this.compiler = compiler; this.isBatchCompile = isBatchCompile; this.weaver = weaver; this.intermediateResultsRequestor = intRequestor; this.progressListener = progressListener; this.outputFileNameProvider = outputFileNameProvider; this.binarySourceProvider = binarySourceProvider; this.isXNoWeave = isXNoWeave; this.proceedOnError = proceedOnError; this.binarySourceSetForFullWeave = fullBinarySourceEntries; this.eWorld = eFactory; this.inJava5Mode = false; this.noAtAspectJAnnotationProcessing = noAtAspectJProcessing; this.incrementalCompilationState = incrementalCompilationState; if (compiler.options.complianceLevel == CompilerOptions.JDK1_5) inJava5Mode = true; IMessageHandler msgHandler = world.getMessageHandler(); // Do we need to reset the message handler or create a new one? (This saves a ton of memory lost on incremental compiles...) if (msgHandler instanceof WeaverMessageHandler) { ((WeaverMessageHandler)msgHandler).resetCompiler(null); weaverMessageHandler = (WeaverMessageHandler)msgHandler; } else { weaverMessageHandler = new WeaverMessageHandler(msgHandler, compiler); world.setMessageHandler(weaverMessageHandler); } } // the compilation lifecycle methods below are called in order as compilation progresses... public void beforeCompiling(ICompilationUnit[] sourceUnits) { resultsPendingWeave = new ArrayList(); reportedErrors = false; } public void beforeProcessing(CompilationUnitDeclaration unit) { eWorld.showMessage(IMessage.INFO, "compiling " + new String(unit.getFileName()), null, null); processingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_COMPILATION_UNIT,unit.getFileName()); if (inJava5Mode && !noAtAspectJAnnotationProcessing) { ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.ADDING_AT_ASPECTJ_ANNOTATIONS, unit.getFileName()); AddAtAspectJAnnotationsVisitor atAspectJVisitor = new AddAtAspectJAnnotationsVisitor(unit); unit.traverse(atAspectJVisitor, unit.scope); CompilationAndWeavingContext.leavingPhase(tok); } } public void beforeResolving(CompilationUnitDeclaration unit) { resolvingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.RESOLVING_COMPILATION_UNIT, unit.getFileName()); } public void afterResolving(CompilationUnitDeclaration unit) { if (resolvingToken != null) CompilationAndWeavingContext.leavingPhase(resolvingToken); } public void beforeAnalysing(CompilationUnitDeclaration unit) { analysingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.ANALYSING_COMPILATION_UNIT, unit.getFileName()); if (inJava5Mode && !noAtAspectJAnnotationProcessing) { ValidateAtAspectJAnnotationsVisitor atAspectJVisitor = new ValidateAtAspectJAnnotationsVisitor(unit); unit.traverse(atAspectJVisitor, unit.scope); } } public void afterAnalysing(CompilationUnitDeclaration unit) { if (analysingToken != null) CompilationAndWeavingContext.leavingPhase(analysingToken); } public void beforeGenerating(CompilationUnitDeclaration unit) { generatingToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.GENERATING_UNWOVEN_CODE_FOR_COMPILATION_UNIT, unit.getFileName()); } public void afterGenerating(CompilationUnitDeclaration unit) { if (generatingToken != null) CompilationAndWeavingContext.leavingPhase(generatingToken); } public void afterCompiling(CompilationUnitDeclaration[] units) { this.eWorld.cleanup(); try { if (isXNoWeave || (reportedErrors && !proceedOnError)) { // no point weaving... just tell the requestor we're done notifyRequestor(); } else { weave(); // notification happens as weave progresses... weaver.getWorld().flush(); } } catch (IOException ex) { AbortCompilation ac = new AbortCompilation(null,ex); throw ac; } catch (RuntimeException rEx) { if (rEx instanceof AbortCompilation) throw rEx; // Don't wrap AbortCompilation exceptions! // This will be unwrapped in Compiler.handleInternalException() and the nested // RuntimeException thrown back to the original caller - which is AspectJ // which will then then log it as a compiler problem. throw new AbortCompilation(true,rEx); } } public void afterProcessing(CompilationUnitDeclaration unit, int unitIndex) { CompilationAndWeavingContext.leavingPhase(processingToken); eWorld.finishedCompilationUnit(unit); InterimCompilationResult intRes = new InterimCompilationResult(unit.compilationResult,outputFileNameProvider); if (unit.compilationResult.hasErrors()) reportedErrors = true; if (intermediateResultsRequestor != null) { intermediateResultsRequestor.acceptResult(intRes); } if (isXNoWeave) { acceptResult(unit.compilationResult); } else { resultsPendingWeave.add(intRes); } } // public void beforeResolving(CompilationUnitDeclaration unit, ICompilationUnit sourceUnit, boolean verifyMethods, boolean analyzeCode, boolean generateCode) { // resultsPendingWeave = new ArrayList(); // reportedErrors = false; // } // // public void afterResolving(CompilationUnitDeclaration unit, ICompilationUnit sourceUnit, boolean verifyMethods, boolean analyzeCode, boolean generateCode) { // InterimCompilationResult intRes = new InterimCompilationResult(unit.compilationResult,outputFileNameProvider); // if (unit.compilationResult.hasErrors()) reportedErrors = true; // if (isXNoWeave || !generateCode) { // acceptResult(unit.compilationResult); // } else if (generateCode){ // resultsPendingWeave.add(intRes); // try { // weave(); // } catch (IOException ex) { // AbortCompilation ac = new AbortCompilation(null,ex); // throw ac; // } // } // } // helper methods... // ================================================================================== /* * Called from the weaverAdapter once it has finished weaving the class files * associated with a given compilation result. */ public void acceptResult(CompilationResult result) { compiler.requestor.acceptResult(result.tagAsAccepted()); if (compiler.unitsToProcess != null) { for (int i = 0; i < compiler.unitsToProcess.length; i++) { if (compiler.unitsToProcess[i] != null) { if (compiler.unitsToProcess[i].compilationResult == result) { compiler.unitsToProcess[i] = null; } } } } } private List getBinarySourcesFrom(Map binarySourceEntries) { // Map is fileName |-> List<UnwovenClassFile> List ret = new ArrayList(); for (Iterator binIter = binarySourceEntries.keySet().iterator(); binIter.hasNext();) { String sourceFileName = (String) binIter.next(); List unwovenClassFiles = (List) binarySourceEntries.get(sourceFileName); // XXX - see bugs 57432,58679 - final parameter on next call should be "compiler.options.maxProblemsPerUnit" CompilationResult result = new CompilationResult(sourceFileName.toCharArray(),0,0,Integer.MAX_VALUE); result.noSourceAvailable(); InterimCompilationResult binarySource = new InterimCompilationResult(result,unwovenClassFiles); ret.add(binarySource); } return ret; } private void notifyRequestor() { for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) { InterimCompilationResult iresult = (InterimCompilationResult) iter.next(); compiler.requestor.acceptResult(iresult.result().tagAsAccepted()); } } private void weave() throws IOException { // ensure weaver state is set up correctly for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) { InterimCompilationResult iresult = (InterimCompilationResult) iter.next(); for (int i = 0; i < iresult.unwovenClassFiles().length; i++) { weaver.addClassFile(iresult.unwovenClassFiles()[i]); } } weaver.prepareForWeave(); if (weaver.needToReweaveWorld()) { if (!isBatchCompile) { //force full recompilation from source this.incrementalCompilationState.forceBatchBuildNextTimeAround(); return; // addAllKnownClassesToWeaveList(); // if it's batch, they're already on the list... } resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave)); } else { Map binarySourcesToAdd = binarySourceProvider.getBinarySourcesForThisWeave(); resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourcesToAdd)); } // if (isBatchCompile) { // resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave)); // // passed into the compiler, the set of classes in injars and inpath... // } else if (weaver.needToReweaveWorld()) { // addAllKnownClassesToWeaveList(); // resultsPendingWeave.addAll(getBinarySourcesFrom(binarySourceSetForFullWeave)); // } try { weaver.weave(new WeaverAdapter(this,weaverMessageHandler,progressListener)); } finally { // ???: is this the right point for this? After weaving has finished clear the caches. CflowPointcut.clearCaches(); weaver.tidyUp(); } } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * Adrian Colyer added constructor to populate javaOptions with * default settings - 01.20.2003 * Bugzilla #29768, 29769 * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.aspectj.util.FileUtil; /** * All configuration information needed to run the AspectJ compiler. * Compiler options (as opposed to path information) are held in an AjCompilerOptions instance */ public class AjBuildConfig { private boolean shouldProceed = true; public static final String AJLINT_IGNORE = "ignore"; public static final String AJLINT_WARN = "warn"; public static final String AJLINT_ERROR = "error"; public static final String AJLINT_DEFAULT = "default"; private File outputDir; private File outputJar; private String outxmlName; private List/*File*/ sourceRoots = new ArrayList(); private List/*File*/ files = new ArrayList(); private List /*File*/ binaryFiles = new ArrayList(); // .class files in indirs... private List/*File*/ inJars = new ArrayList(); private List/*File*/ inPath = new ArrayList(); private Map/*String->File*/ sourcePathResources = new HashMap(); private List/*File*/ aspectpath = new ArrayList(); private List/*String*/ classpath = new ArrayList(); private List/*String*/ bootclasspath = new ArrayList(); private File configFile; private String lintMode = AJLINT_DEFAULT; private File lintSpecFile = null; private AjCompilerOptions options; /** if true, then global values override local when joining */ private boolean override = true; // incremental variants handled by the compiler client, but parsed here private boolean incrementalMode; private File incrementalFile; public String toString() { StringBuffer sb = new StringBuffer(); sb.append("BuildConfig["+(configFile==null?"null":configFile.getAbsoluteFile().toString())+"] #Files="+files.size()); return sb.toString(); } public static class BinarySourceFile { public BinarySourceFile(File dir, File src) { this.fromInPathDirectory = dir; this.binSrc = src; } public File fromInPathDirectory; public File binSrc; public boolean equals(Object obj) { if ((obj instanceof BinarySourceFile) && (obj != null)) { BinarySourceFile other = (BinarySourceFile)obj; return(binSrc.equals(other.binSrc)); } return false; } public int hashCode() { return binSrc != null ? binSrc.hashCode() : 0; } } /** * Intialises the javaOptions Map to hold the default * JDT Compiler settings. Added by AMC 01.20.2003 in reponse * to bug #29768 and enh. 29769. * The settings here are duplicated from those set in * org.eclipse.jdt.internal.compiler.batch.Main, but I've elected to * copy them rather than refactor the JDT class since this keeps * integration with future JDT releases easier (?). */ public AjBuildConfig( ) { options = new AjCompilerOptions(); } /** * returned files includes <ul> * <li>files explicitly listed on command-line</li> * <li>files listed by reference in argument list files</li> * <li>files contained in sourceRootDir if that exists</li> * </ul> * * @return all source files that should be compiled. */ public List/*File*/ getFiles() { return files; } /** * returned files includes all .class files found in * a directory on the inpath, but does not include * .class files contained within jars. */ public List/*BinarySourceFile*/ getBinaryFiles() { return binaryFiles; } public File getOutputDir() { return outputDir; } public void setFiles(List files) { this.files = files; } public void setOutputDir(File outputDir) { this.outputDir = outputDir; } public AjCompilerOptions getOptions() { return options; } /** * This does not include -bootclasspath but includes -extdirs and -classpath */ public List getClasspath() { // XXX setters don't respect javadoc contract... return classpath; } public void setClasspath(List classpath) { this.classpath = classpath; } public List getBootclasspath() { return bootclasspath; } public void setBootclasspath(List bootclasspath) { this.bootclasspath = bootclasspath; } public File getOutputJar() { return outputJar; } public String getOutxmlName() { return outxmlName; } public List/*File*/ getInpath() { // Elements of the list are either archives (jars/zips) or directories return inPath; } public List/*File*/ getInJars() { return inJars; } public Map getSourcePathResources() { return sourcePathResources; } public void setOutputJar(File outputJar) { this.outputJar = outputJar; } public void setOutxmlName(String name) { this.outxmlName = name; } public void setInJars(List sourceJars) { this.inJars = sourceJars; } public void setInPath(List dirsOrJars) { inPath = dirsOrJars; // remember all the class files in directories on the inpath binaryFiles = new ArrayList(); FileFilter filter = new FileFilter() { public boolean accept(File pathname) { return pathname.getPath().endsWith(".class"); }}; for (Iterator iter = dirsOrJars.iterator(); iter.hasNext();) { File inpathElement = (File) iter.next(); if (inpathElement.isDirectory()) { File[] files = FileUtil.listFiles(inpathElement, filter); for (int i = 0; i < files.length; i++) { binaryFiles.add(new BinarySourceFile(inpathElement,files[i])); } } } } public List getSourceRoots() { return sourceRoots; } public void setSourceRoots(List sourceRootDir) { this.sourceRoots = sourceRootDir; } public File getConfigFile() { return configFile; } public void setConfigFile(File configFile) { this.configFile = configFile; } public void setIncrementalMode(boolean incrementalMode) { this.incrementalMode = incrementalMode; } public boolean isIncrementalMode() { return incrementalMode; } public void setIncrementalFile(File incrementalFile) { this.incrementalFile = incrementalFile; } public boolean isIncrementalFileMode() { return (null != incrementalFile); } /** * @return List (String) classpath of bootclasspath, injars, inpath, aspectpath * entries, specified classpath (extdirs, and classpath), and output dir or jar */ public List getFullClasspath() { List full = new ArrayList(); full.addAll(getBootclasspath()); // XXX Is it OK that boot classpath overrides inpath/injars/aspectpath? for (Iterator i = inJars.iterator(); i.hasNext(); ) { full.add(((File)i.next()).getAbsolutePath()); } for (Iterator i = inPath.iterator();i.hasNext();) { full.add(((File)i.next()).getAbsolutePath()); } for (Iterator i = aspectpath.iterator(); i.hasNext(); ) { full.add(((File)i.next()).getAbsolutePath()); } full.addAll(getClasspath()); // if (null != outputDir) { // full.add(outputDir.getAbsolutePath()); // } else if (null != outputJar) { // full.add(outputJar.getAbsolutePath()); // } return full; } public File getLintSpecFile() { return lintSpecFile; } public void setLintSpecFile(File lintSpecFile) { this.lintSpecFile = lintSpecFile; } public List getAspectpath() { return aspectpath; } public void setAspectpath(List aspectpath) { this.aspectpath = aspectpath; } /** @return true if any config file, sourceroots, sourcefiles, injars or inpath */ public boolean hasSources() { return ((null != configFile) || (0 < sourceRoots.size()) || (0 < files.size()) || (0 < inJars.size()) || (0 < inPath.size()) ); } // /** @return null if no errors, String errors otherwise */ // public String configErrors() { // StringBuffer result = new StringBuffer(); // // ok, permit both. sigh. //// if ((null != outputDir) && (null != outputJar)) { //// result.append("specified both outputDir and outputJar"); //// } // // incremental => only sourceroots // // // return (0 == result.length() ? null : result.toString()); // } /** * Install global values into local config * unless values conflict: * <ul> * <li>Collections are unioned</li> * <li>values takes local value unless default and global set</li> * <li>this only sets one of outputDir and outputJar as needed</li> * <ul> * This also configures super if javaOptions change. * @param global the AjBuildConfig to read globals from */ public void installGlobals(AjBuildConfig global) { // XXX relies on default values // don't join the options - they already have defaults taken care of. // Map optionsMap = options.getMap(); // join(optionsMap,global.getOptions().getMap()); // options.set(optionsMap); join(aspectpath, global.aspectpath); join(classpath, global.classpath); if (null == configFile) { configFile = global.configFile; // XXX correct? } if (!isEmacsSymMode() && global.isEmacsSymMode()) { setEmacsSymMode(true); } join(files, global.files); if (!isGenerateModelMode() && global.isGenerateModelMode()) { setGenerateModelMode(true); } if (null == incrementalFile) { incrementalFile = global.incrementalFile; } if (!incrementalMode && global.incrementalMode) { incrementalMode = true; } join(inJars, global.inJars); join(inPath, global.inPath); if ((null == lintMode) || (AJLINT_DEFAULT.equals(lintMode))) { setLintMode(global.lintMode); } if (null == lintSpecFile) { lintSpecFile = global.lintSpecFile; } if (!isNoWeave() && global.isNoWeave()) { setNoWeave(true); } if ((null == outputDir) && (null == outputJar)) { if (null != global.outputDir) { outputDir = global.outputDir; } if (null != global.outputJar) { outputJar = global.outputJar; } } join(sourceRoots, global.sourceRoots); if (!isXnoInline() && global.isXnoInline()) { setXnoInline(true); } if (!isXserializableAspects() && global.isXserializableAspects()) { setXserializableAspects(true); } if (!isXlazyTjp() && global.isXlazyTjp()) { setXlazyTjp(true); } if (!getProceedOnError() && global.getProceedOnError()) { setProceedOnError(true); } setTargetAspectjRuntimeLevel(global.getTargetAspectjRuntimeLevel()); setXJoinpoints(global.getXJoinpoints()); if (!isXHasMemberEnabled() && global.isXHasMemberEnabled()) { setXHasMemberSupport(true); } if (!isXNotReweavable() && global.isXNotReweavable()) { setXnotReweavable(true); } setXconfigurationInfo(global.getXconfigurationInfo()); } void join(Collection local, Collection global) { for (Iterator iter = global.iterator(); iter.hasNext();) { Object next = iter.next(); if (!local.contains(next)) { local.add(next); } } } void join(Map local, Map global) { for (Iterator iter = global.keySet().iterator(); iter.hasNext();) { Object key = iter.next(); if (override || (null == local.get(key))) { // Object value = global.get(key); if (null != value) { local.put(key, value); } } } } public void setSourcePathResources(Map map) { sourcePathResources = map; } /** * used to indicate whether to proceed after parsing config */ public boolean shouldProceed() { return shouldProceed; } public void doNotProceed() { shouldProceed = false; } public String getLintMode() { return lintMode; } // options... public void setLintMode(String lintMode) { this.lintMode = lintMode; String lintValue = null; if (AJLINT_IGNORE.equals(lintMode)) { lintValue = AjCompilerOptions.IGNORE; } else if (AJLINT_WARN.equals(lintMode)) { lintValue = AjCompilerOptions.WARNING; } else if (AJLINT_ERROR.equals(lintMode)) { lintValue = AjCompilerOptions.ERROR; } if (lintValue != null) { Map lintOptions = new HashMap(); lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportUnresolvableMember,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField,lintValue); lintOptions.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion,lintValue); options.set(lintOptions); } } public boolean isNoWeave() { return options.noWeave; } public void setNoWeave(boolean noWeave) { options.noWeave = noWeave; } public boolean isXserializableAspects() { return options.xSerializableAspects; } public void setXserializableAspects(boolean xserializableAspects) { options.xSerializableAspects = xserializableAspects; } public void setXJoinpoints(String jps) { options.xOptionalJoinpoints = jps; } public String getXJoinpoints() { return options.xOptionalJoinpoints; } public boolean isXnoInline() { return options.xNoInline; } public void setXnoInline(boolean xnoInline) { options.xNoInline = xnoInline; } public boolean isXlazyTjp() { return options.xLazyThisJoinPoint; } public void setXlazyTjp(boolean b) { options.xLazyThisJoinPoint = b; } public void setXnotReweavable(boolean b) { options.xNotReweavable = b; } public void setXconfigurationInfo(String info) { options.xConfigurationInfo = info; } public String getXconfigurationInfo() { return options.xConfigurationInfo; } public void setXHasMemberSupport(boolean enabled) { options.xHasMember = enabled; } public boolean isXHasMemberEnabled() { return options.xHasMember; } public void setXdevPinpointMode(boolean enabled) { options.xdevPinpoint = enabled; } public boolean isXdevPinpoint() { return options.xdevPinpoint; } public boolean isXNotReweavable() { return options.xNotReweavable; } public boolean isGenerateJavadocsInModelMode() { return options.generateJavaDocsInModel; } public void setGenerateJavadocsInModelMode( boolean generateJavadocsInModelMode) { options.generateJavaDocsInModel = generateJavadocsInModelMode; } public boolean isGenerateCrossRefsMode() { return options.generateCrossRefs; } public void setGenerateCrossRefsMode(boolean on) { options.generateCrossRefs = on; } public boolean isEmacsSymMode() { return options.generateEmacsSymFiles; } public void setEmacsSymMode(boolean emacsSymMode) { options.generateEmacsSymFiles = emacsSymMode; } public boolean isGenerateModelMode() { return options.generateModel; } public void setGenerateModelMode(boolean structureModelMode) { options.generateModel = structureModelMode; } public boolean isNoAtAspectJAnnotationProcessing() { return options.noAtAspectJProcessing; } public void setNoAtAspectJAnnotationProcessing(boolean noProcess) { options.noAtAspectJProcessing = noProcess; } public void setShowWeavingInformation(boolean b) { options.showWeavingInformation = true; } public boolean getShowWeavingInformation() { return options.showWeavingInformation; } public void setProceedOnError(boolean b) { options.proceedOnError = b; } public boolean getProceedOnError() { return options.proceedOnError; } public void setBehaveInJava5Way(boolean b) { options.behaveInJava5Way = b; } public boolean getBehaveInJava5Way() { return options.behaveInJava5Way; } public void setTargetAspectjRuntimeLevel(String level) { options.targetAspectjRuntimeLevel = level; } public String getTargetAspectjRuntimeLevel() { return options.targetAspectjRuntimeLevel; } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter; import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider; import org.aspectj.ajdt.internal.compiler.ICompilerAdapter; import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory; import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor; import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider; import org.aspectj.ajdt.internal.compiler.InterimCompilationResult; import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment; import org.aspectj.ajdt.internal.compiler.lookup.AnonymousClassPublisher; import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory; import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.internal.ProgramElement; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.CountingMessageHandler; import org.aspectj.bridge.ILifecycleAware; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IProgressListener; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.Version; import org.aspectj.bridge.context.CompilationAndWeavingContext; import org.aspectj.bridge.context.ContextFormatter; import org.aspectj.bridge.context.ContextToken; import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathDirectory; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.aspectj.util.FileUtil; import org.aspectj.weaver.Dump; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.bcel.BcelWeaver; import org.aspectj.weaver.bcel.BcelWorld; import org.aspectj.weaver.bcel.UnwovenClassFile; import org.eclipse.core.runtime.OperationCanceledException; //import org.aspectj.org.eclipse.jdt.internal.compiler.util.HashtableOfObject; public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory { private static final String CROSSREFS_FILE_NAME = "build.lst"; private static final String CANT_WRITE_RESULT = "unable to write compilation result"; private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; static final boolean COPY_INPATH_DIR_RESOURCES = false; static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false; private static final FileFilter binarySourceFilter = new FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".class"); }}; /** * This builder is static so that it can be subclassed and reset. However, note * that there is only one builder present, so if two extendsion reset it, only * the latter will get used. */ public static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder(); static { CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter()); CompilationAndWeavingContext.registerFormatter( CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter()); } private IProgressListener progressListener = null; private boolean environmentSupportsIncrementalCompilation = false; private int compiledCount; private int sourceFileCount; private JarOutputStream zos; private boolean batchCompile = true; private INameEnvironment environment; private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap(); // FIXME asc should this really be in here? private IHierarchy structureModel; public AjBuildConfig buildConfig; private List aspectNames = new LinkedList(); AjState state = new AjState(this); public BcelWeaver getWeaver() { return state.getWeaver();} public BcelWorld getBcelWorld() { return state.getBcelWorld();} public CountingMessageHandler handler; public AjBuildManager(IMessageHandler holder) { super(); this.handler = CountingMessageHandler.makeCountingMessageHandler(holder); } public void environmentSupportsIncrementalCompilation(boolean itDoes) { this.environmentSupportsIncrementalCompilation = itDoes; } /** @return true if we should generate a model as a side-effect */ public boolean doGenerateModel() { return buildConfig.isGenerateModelMode(); } public boolean batchBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, true); } public boolean incrementalBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException { return doBuild(buildConfig, baseHandler, false); } /** @throws AbortException if check for runtime fails */ protected boolean doBuild( AjBuildConfig buildConfig, IMessageHandler baseHandler, boolean batch) throws IOException, AbortException { boolean ret = true; batchCompile = batch; if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware)baseHandler).buildStarting(!batch); } CompilationAndWeavingContext.reset(); int phase = batch ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD; ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase ,buildConfig); try { if (batch) { this.state = new AjState(this); } this.state.setCouldBeSubsequentIncrementalBuild(this.environmentSupportsIncrementalCompilation); boolean canIncremental = state.prepareForNextBuild(buildConfig); if (!canIncremental && !batch) { // retry as batch? CompilationAndWeavingContext.leavingPhase(ct); return doBuild(buildConfig, baseHandler, true); } this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler); // XXX duplicate, no? remove? String check = checkRtJar(buildConfig); if (check != null) { if (FAIL_IF_RUNTIME_NOT_FOUND) { MessageUtil.error(handler, check); CompilationAndWeavingContext.leavingPhase(ct); return false; } else { MessageUtil.warn(handler, check); } } // if (batch) { setBuildConfig(buildConfig); //} if (batch || !AsmManager.attemptIncrementalModelRepairs) { // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { setupModel(buildConfig); // } } if (batch) { initBcelWorld(handler); } if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (buildConfig.getOutputJar() != null) { if (!openOutputStream(buildConfig.getOutputJar())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } } if (batch) { // System.err.println("XXXX batch: " + buildConfig.getFiles()); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { getWorld().setModel(AsmManager.getDefault().getHierarchy()); // in incremental build, only get updated model? } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); performCompilation(buildConfig.getFiles()); state.clearBinarySourceFiles(); // we don't want these hanging around... if (handler.hasErrors()) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After a batch build"); } else { // done already? // if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) { // bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel()); // } // System.err.println("XXXX start inc "); binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true); List files = state.getFilesToCompile(true); if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles()); boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); for (int i = 0; (i < 5) && hereWeGoAgain; i++) { // System.err.println("XXXX inc: " + files); performCompilation(files); if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) { CompilationAndWeavingContext.leavingPhase(ct); return false; } if (state.requiresFullBatchBuild()) { return batchBuild(buildConfig, baseHandler); } binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false); files = state.getFilesToCompile(false); hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty()); // TODO Andy - Needs some thought here... // I think here we might want to pass empty addedFiles/deletedFiles as they were // dealt with on the first call to processDelta - we are going through this loop // again because in compiling something we found something else we needed to // rebuild. But what case causes this? if (hereWeGoAgain) { if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) if (AsmManager.attemptIncrementalModelRepairs) AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles()); } } if (!files.isEmpty()) { CompilationAndWeavingContext.leavingPhase(ct); return batchBuild(buildConfig, baseHandler); } else { if (AsmManager.isReporting()) AsmManager.getDefault().reportModelInfo("After an incremental build"); } } // XXX not in Mik's incremental if (buildConfig.isEmacsSymMode()) { new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(); } // for bug 113554: support ajsym file generation for command line builds if (buildConfig.isGenerateCrossRefsMode()) { String configFileProxy = buildConfig.getOutputDir().getAbsolutePath() + File.separator + CROSSREFS_FILE_NAME; AsmManager.getDefault().writeStructureModel(configFileProxy); } // have to tell state we succeeded or next is not incremental state.successfulCompile(buildConfig,batch); copyResourcesToDestination(); if (buildConfig.getOutxmlName() != null) { writeOutxmlFile(); } /*boolean weaved = *///weaveAndGenerateClassFiles(); // if not weaved, then no-op build, no model changes // but always returns true // XXX weaved not in Mik's incremental if (buildConfig.isGenerateModelMode()) { AsmManager.getDefault().fireModelUpdated(); } CompilationAndWeavingContext.leavingPhase(ct); } finally { if (baseHandler instanceof ILifecycleAware) { ((ILifecycleAware)baseHandler).buildFinished(!batch); } if (zos != null) { closeOutputStream(buildConfig.getOutputJar()); } ret = !handler.hasErrors(); if (getBcelWorld()!=null) getBcelWorld().tidyUp(); // bug 59895, don't release reference to handler as may be needed by a nested call //handler = null; } return ret; } private boolean openOutputStream(File outJar) { try { OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar()); zos = new JarOutputStream(os,getWeaver().getManifest(true)); } catch (IOException ex) { IMessage message = new Message("Unable to open outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); return false; } return true; } private void closeOutputStream(File outJar) { try { if (zos != null) zos.close(); zos = null; /* Ensure we don't write an incomplete JAR bug-71339 */ if (handler.hasErrors()) { outJar.delete(); } } catch (IOException ex) { IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")", new SourceLocation(outJar,0), true); handler.handleMessage(message); } } private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); copyResourcesFromJarFile(inJar); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (inPathElement.isDirectory()) { copyResourcesFromDirectory(inPathElement); } else { copyResourcesFromJarFile(inPathElement); } } if (buildConfig.getSourcePathResources() != null) { for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) { String resource = (String)i.next(); File from = (File)buildConfig.getSourcePathResources().get(resource); copyResourcesFromFile(from,resource,from); } } writeManifest(); } private void copyResourcesFromJarFile(File jarFile) throws IOException { JarInputStream inStream = null; try { inStream = new JarInputStream(new FileInputStream(jarFile)); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; String filename = entry.getName(); // System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'"); if (!entry.isDirectory() && acceptResource(filename)) { byte[] bytes = FileUtil.readAsByteArray(inStream); writeResource(filename,bytes,jarFile); } inStream.closeEntry(); } } finally { if (inStream != null) inStream.close(); } } private void copyResourcesFromDirectory(File dir) throws IOException { if (!COPY_INPATH_DIR_RESOURCES) return; // Get a list of all files (i.e. everything that isnt a directory) File[] files = FileUtil.listFiles(dir,new FileFilter() { public boolean accept(File f) { boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ; return accept; } }); // For each file, add it either as a real .class file or as a resource for (int i = 0; i < files.length; i++) { // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() // or we are in trouble... String filename = files[i].getAbsolutePath().substring( dir.getAbsolutePath().length()+1); copyResourcesFromFile(files[i],filename,dir); } } private void copyResourcesFromFile(File f,String filename,File src) throws IOException { if (!acceptResource(filename)) return; FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] bytes = FileUtil.readAsByteArray(fis); // String relativePath = files[i].getPath(); writeResource(filename,bytes,src); } finally { if (fis != null) fis.close(); } } private void writeResource(String filename, byte[] content, File srcLocation) throws IOException { if (state.hasResource(filename)) { IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(srcLocation,0)); handler.handleMessage(msg); return; } if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(content); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename)); fos.write(content); fos.close(); } state.recordResource(filename); } /* * If we are writing to an output directory copy the manifest but only * if we already have one */ private void writeManifest () throws IOException { Manifest manifest = getWeaver().getManifest(false); if (manifest != null && zos == null) { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME)); manifest.write(fos); fos.close(); } } private boolean acceptResource(String resourceName) { if ( (resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS")) || (resourceName.endsWith(".class")) || (resourceName.startsWith(".svn/")) || (resourceName.indexOf("/.svn/")!=-1) || (resourceName.endsWith("/.svn")) || (resourceName.toUpperCase().equals(MANIFEST_NAME)) ) { return false; } else { return true; } } private void writeOutxmlFile () throws IOException { String filename = buildConfig.getOutxmlName(); // System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename); // System.err.println("? AjBuildManager.writeOutxmlFile() outputDir=" + buildConfig.getOutputDir()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ps.println("<aspectj>"); ps.println("<aspects>"); for (Iterator i = aspectNames.iterator(); i.hasNext();) { String name = (String)i.next(); ps.println("<aspect name=\"" + name + "\"/>"); } ps.println("</aspects>"); ps.println("</aspectj>"); ps.println(); ps.close(); if (zos != null) { ZipEntry newEntry = new ZipEntry(filename); zos.putNextEntry(newEntry); zos.write(baos.toByteArray()); zos.closeEntry(); } else { OutputStream fos = FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename)); fos.write(baos.toByteArray()); fos.close(); } } // public static void dumprels() { // IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap(); // int ctr = 1; // Set entries = irm.getEntries(); // for (Iterator iter = entries.iterator(); iter.hasNext();) { // String hid = (String) iter.next(); // List rels = irm.get(hid); // for (Iterator iterator = rels.iterator(); iterator.hasNext();) { // IRelationship ir = (IRelationship) iterator.next(); // List targets = ir.getTargets(); // for (Iterator iterator2 = targets.iterator(); // iterator2.hasNext(); // ) { // String thid = (String) iterator2.next(); // System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid); // } // } // } // } /** * Responsible for managing the ASM model between builds. Contains the policy for * maintaining the persistance of elements in the model. * * This code is driven before each 'fresh' (batch) build to create * a new model. */ private void setupModel(AjBuildConfig config) { AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode()); if (!AsmManager.isCreatingModel()) return; AsmManager.getDefault().createNewASM(); // AsmManager.getDefault().getRelationshipMap().clear(); IHierarchy model = AsmManager.getDefault().getHierarchy(); String rootLabel = "<root>"; IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA; if (buildConfig.getConfigFile() != null) { rootLabel = buildConfig.getConfigFile().getName(); model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath()); kind = IProgramElement.Kind.FILE_LST; } model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList())); model.setFileMap(new HashMap()); setStructureModel(model); state.setStructureModel(model); state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap()); } // // private void dumplist(List l) { // System.err.println("---- "+l.size()); // for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i)); // } // private void accumulateFileNodes(IProgramElement ipe,List store) { // if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA || // ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) { // if (!ipe.getName().equals("<root>")) { // store.add(ipe); // return; // } // } // for (Iterator i = ipe.getChildren().iterator();i.hasNext();) { // accumulateFileNodes((IProgramElement)i.next(),store); // } // } /** init only on initial batch compile? no file-specific options */ private void initBcelWorld(IMessageHandler handler) throws IOException { List cp = buildConfig.getBootclasspath(); cp.addAll(buildConfig.getClasspath()); BcelWorld bcelWorld = new BcelWorld(cp, handler, null); bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way()); bcelWorld.performExtraConfiguration(buildConfig.getXconfigurationInfo()); bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel()); bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints()); bcelWorld.setXnoInline(buildConfig.isXnoInline()); bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp()); bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled()); bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint()); BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld); state.setWorld(bcelWorld); state.setWeaver(bcelWeaver); state.clearBinarySourceFiles(); for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) { File f = (File) i.next(); if (!f.exists()) { IMessage message = new Message("invalid aspectpath entry: "+f.getName(),null,true); handler.handleMessage(message); } else { bcelWeaver.addLibraryJarFile(f); } } // String lintMode = buildConfig.getLintMode(); if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) { bcelWorld.getLint().loadDefaultProperties(); } else { bcelWorld.getLint().setAll(buildConfig.getLintMode()); } if (buildConfig.getLintSpecFile() != null) { bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile()); } //??? incremental issues for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) { File inJar = (File)i.next(); List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false); state.recordBinarySource(inJar.getPath(), unwovenClasses); } for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) { File inPathElement = (File)i.next(); if (!inPathElement.isDirectory()) { // its a jar file on the inpath // the weaver method can actually handle dirs, but we don't call it, see next block List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true); state.recordBinarySource(inPathElement.getPath(),unwovenClasses); } else { // add each class file in an in-dir individually, this gives us the best error reporting // (they are like 'source' files then), and enables a cleaner incremental treatment of // class file changes in indirs. File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter); for (int j = 0; j < binSrcs.length; j++) { UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, buildConfig.getOutputDir()); List ucfl = new ArrayList(); ucfl.add(ucf); state.recordBinarySource(binSrcs[j].getPath(),ucfl); } } } bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable()); //check for org.aspectj.runtime.JoinPoint ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint"); if (joinPoint.isMissing()) { IMessage message = new Message("classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)", null, true); handler.handleMessage(message); } } public World getWorld() { return getBcelWorld(); } void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException { for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile) i.next(); getWeaver().addClassFile(classFile); } } // public boolean weaveAndGenerateClassFiles() throws IOException { // handler.handleMessage(MessageUtil.info("weaving")); // if (progressListener != null) progressListener.setText("weaving aspects"); // bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size()); // //!!! doesn't provide intermediate progress during weaving // // XXX add all aspects even during incremental builds? // addAspectClassFilesToWeaver(state.addedClassFiles); // if (buildConfig.isNoWeave()) { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.dumpUnwoven(buildConfig.getOutputJar()); // } else { // bcelWeaver.dumpUnwoven(); // bcelWeaver.dumpResourcesToOutPath(); // } // } else { // if (buildConfig.getOutputJar() != null) { // bcelWeaver.weave(buildConfig.getOutputJar()); // } else { // bcelWeaver.weave(); // bcelWeaver.dumpResourcesToOutPath(); // } // } // if (progressListener != null) progressListener.setProgress(1.0); // return true; // //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors(); // } public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) { String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ // Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every // element of the classpath is likely to be a directory. If we ensure every element of the array is set to // only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build // a classpathDirectory object that will attempt to look for source when it can't find binary. int[] classpathModes = new int[classpaths.length]; for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY; return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes); } public IProblemFactory getProblemFactory() { return new DefaultProblemFactory(Locale.getDefault()); } /* * Build the set of compilation source units */ public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) { int fileCount = filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; // HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = buildConfig.getOptions().defaultEncoding; if ("".equals(defaultEncoding)) //$NON-NLS-1$ defaultEncoding = null; //$NON-NLS-1$ for (int i = 0; i < fileCount; i++) { String encoding = encodings[i]; if (encoding == null) encoding = defaultEncoding; units[i] = new CompilationUnit(null, filenames[i], encoding); } return units; } public String extractDestinationPathFromSourceFile(CompilationResult result) { ICompilationUnit compilationUnit = result.compilationUnit; if (compilationUnit != null) { char[] fileName = compilationUnit.getFileName(); int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName); if (lastIndex == -1) { return System.getProperty("user.dir"); //$NON-NLS-1$ } return new String(CharOperation.subarray(fileName, 0, lastIndex)); } return System.getProperty("user.dir"); //$NON-NLS-1$ } public void performCompilation(List files) { if (progressListener != null) { compiledCount=0; sourceFileCount = files.size(); progressListener.setText("compiling source files"); } //System.err.println("got files: " + files); String[] filenames = new String[files.size()]; String[] encodings = new String[files.size()]; //System.err.println("filename: " + this.filenames); for (int i=0; i < files.size(); i++) { filenames[i] = ((File)files.get(i)).getPath(); } List cps = buildConfig.getFullClasspath(); Dump.saveFullClasspath(cps); String[] classpaths = new String[cps.size()]; for (int i=0; i < cps.size(); i++) { classpaths[i] = (String)cps.get(i); } //System.out.println("compiling"); environment = getLibraryAccess(classpaths, filenames); if (!state.getClassNameToFileMap().isEmpty()) { environment = new StatefulNameEnvironment(environment, state.getClassNameToFileMap()); } org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this); org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(), getBatchRequestor(), getProblemFactory()); CompilerOptions options = compiler.options; options.produceReferenceInfo = true; //TODO turn off when not needed try { compiler.compile(getCompilationUnits(filenames, encodings)); } catch (OperationCanceledException oce) { handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null)); } // cleanup org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null); AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null); environment.cleanup(); environment = null; } /* * Answer the component to which will be handed back compilation results from the compiler */ public IIntermediateResultsRequestor getInterimResultRequestor() { return new IIntermediateResultsRequestor() { public void acceptResult(InterimCompilationResult result) { if (progressListener != null) { compiledCount++; progressListener.setProgress((compiledCount/2.0)/sourceFileCount); progressListener.setText("compiled: " + result.fileName()); } state.noteResult(result); if (progressListener!=null && progressListener.isCancelledRequested()) { throw new AbortCompilation(true, new OperationCanceledException("Compilation cancelled as requested")); } } }; } public ICompilerRequestor getBatchRequestor() { return new ICompilerRequestor() { public void acceptResult(CompilationResult unitResult) { // end of compile, must now write the results to the output destination // this is either a jar file or a file in a directory if (!(unitResult.hasErrors() && !proceedOnError())) { Collection classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); for (Iterator iter = classFiles.iterator(); iter.hasNext();) { ClassFile classFile = (ClassFile) iter.next(); String filename = new String(classFile.fileName()); String classname = filename.replace('/', '.'); filename = filename.replace('/', File.separatorChar) + ".class"; try { if (buildConfig.getOutputJar() == null) { writeDirectoryEntry(unitResult, classFile,filename); } else { writeZipEntry(classFile,filename); } if (shouldAddAspectName) addAspectName(classname); } catch (IOException ex) { IMessage message = EclipseAdapterUtils.makeErrorMessage( new String(unitResult.fileName), CANT_WRITE_RESULT, ex); handler.handleMessage(message); } } } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); for (int i=0; i < problems.length; i++) { IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i]); handler.handleMessage(message); } } } private void writeDirectoryEntry( CompilationResult unitResult, ClassFile classFile, String filename) throws IOException { File destinationPath = buildConfig.getOutputDir(); String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile)); os.write(classFile.getBytes()); os.close(); } private void writeZipEntry(ClassFile classFile, String name) throws IOException { name = name.replace(File.separatorChar,'/'); ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zos.putNextEntry(newEntry); zos.write(classFile.getBytes()); zos.closeEntry(); } private void addAspectName (String name) { BcelWorld world = getBcelWorld(); ResolvedType type = world.resolve(name); // System.err.println("? writeAspectName() type=" + type); if (type.isAspect()) { aspectNames.add(name); } } }; } protected boolean proceedOnError() { return buildConfig.getProceedOnError(); } // public void noteClassFiles(AjCompiler.InterimResult result) { // if (result == null) return; // CompilationResult unitResult = result.result; // String sourceFileName = result.fileName(); // if (!(unitResult.hasErrors() && !proceedOnError())) { // List unwovenClassFiles = new ArrayList(); // Enumeration classFiles = unitResult.compiledTypes.elements(); // while (classFiles.hasMoreElements()) { // ClassFile classFile = (ClassFile) classFiles.nextElement(); // String filename = new String(classFile.fileName()); // filename = filename.replace('/', File.separatorChar) + ".class"; // // File destinationPath = buildConfig.getOutputDir(); // if (destinationPath == null) { // filename = new File(filename).getName(); // filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath(); // } else { // filename = new File(destinationPath, filename).getPath(); // } // // //System.out.println("classfile: " + filename); // unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes())); // } // state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles); //// System.out.println("file: " + sourceFileName); //// for (int i=0; i < unitResult.simpleNameReferences.length; i++) { //// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i])); //// } //// for (int i=0; i < unitResult.qualifiedReferences.length; i++) { //// System.out.println("qualified: " + //// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/'))); //// } // } else { // state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST); // } // } // private void setBuildConfig(AjBuildConfig buildConfig) { this.buildConfig = buildConfig; if (!this.environmentSupportsIncrementalCompilation) { this.environmentSupportsIncrementalCompilation = (buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode()); } handler.reset(); } String makeClasspathString(AjBuildConfig buildConfig) { if (buildConfig == null || buildConfig.getFullClasspath() == null) return ""; StringBuffer buf = new StringBuffer(); boolean first = true; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { if (first) { first = false; } else { buf.append(File.pathSeparator); } buf.append(it.next().toString()); } return buf.toString(); } /** * This will return null if aspectjrt.jar is present and has the correct version. * Otherwise it will return a string message indicating the problem. */ public String checkRtJar(AjBuildConfig buildConfig) { // omitting dev info if (Version.text.equals(Version.DEVELOPMENT)) { // in the development version we can't do this test usefully // MessageUtil.info(holder, "running development version of aspectj compiler"); return null; } if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified"; String ret = null; for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) { File p = new File( (String)it.next() ); // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) { try { String version = null; Manifest manifest = new JarFile(p).getManifest(); if (manifest == null) { ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text; continue; } Attributes attr = manifest.getAttributes("org/aspectj/lang/"); if (null != attr) { version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (null != version) { version = version.trim(); } } // assume that users of development aspectjrt.jar know what they're doing if (Version.DEVELOPMENT.equals(version)) { // MessageUtil.info(holder, // "running with development version of aspectjrt.jar in " + // p.getAbsolutePath()); return null; } else if (!Version.text.equals(version)) { ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found " + version; continue; } } catch (IOException ioe) { ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; } return null; // this is the "OK" return value! } else { // might want to catch other classpath errors } } if (ret != null) return ret; // last error found in potentially matching jars... return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append("AjBuildManager("); buf.append(")"); return buf.toString(); } public void setStructureModel(IHierarchy structureModel) { this.structureModel = structureModel; } /** * Returns null if there is no structure model */ public IHierarchy getStructureModel() { return structureModel; } public IProgressListener getProgressListener() { return progressListener; } public void setProgressListener(IProgressListener progressListener) { this.progressListener = progressListener; } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[]) */ public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) { String filename = new String(eclipseClassFileName); filename = filename.replace('/', File.separatorChar) + ".class"; File destinationPath = buildConfig.getOutputDir(); String outFile; if (destinationPath == null) { outFile = new File(filename).getName(); outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath(); } else { outFile = new File(destinationPath, filename).getPath(); } return outFile; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler) */ public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { // complete compiler config and return a suitable adapter... populateCompilerOptionsFromLintSettings(forCompiler); AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options, getProblemFactory()); forCompiler.problemReporter = pr; AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment); EclipseFactory factory = new EclipseFactory(le,this); le.factory = factory; pr.factory = factory; forCompiler.lookupEnvironment = le; forCompiler.parser = new Parser( pr, forCompiler.options.parseLiteralExpressionsAsConstants); return new AjCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(), factory, getInterimResultRequestor(), progressListener, this, // IOutputFilenameProvider this, // IBinarySourceProvider state.getBinarySourceMap(), buildConfig.isNoWeave(), buildConfig.getProceedOnError(), buildConfig.isNoAtAspectJAnnotationProcessing(), state); } /** * Some AspectJ lint options need to be known about in the compiler. This is * how we pass them over... * @param forCompiler */ private void populateCompilerOptionsFromLintSettings(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) { BcelWorld world = this.state.getBcelWorld(); IMessage.Kind swallowedExceptionKind = world.getLint().swallowedExceptionInCatchBlock.getKind(); Map optionsMap = new HashMap(); optionsMap.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock, swallowedExceptionKind == null ? "ignore" : swallowedExceptionKind.toString()); forCompiler.options.set(optionsMap); } /* (non-Javadoc) * @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave() */ public Map getBinarySourcesForThisWeave() { return binarySourcesForTheNextCompile; } public static AsmHierarchyBuilder getAsmHierarchyBuilder() { return asmHierarchyBuilder; } /** * Override the the default hierarchy builder. */ public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) { asmHierarchyBuilder = newBuilder; } public AjState getState() { return state; } public void setState(AjState buildState) { state = buildState; } private static class AjBuildContexFormatter implements ContextFormatter { public String formatEntry(int phaseId, Object data) { StringBuffer sb = new StringBuffer(); if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) { sb.append("batch building "); } else { sb.append("incrementally building "); } AjBuildConfig config = (AjBuildConfig) data; List classpath = config.getClasspath(); sb.append("with classpath: "); for (Iterator iter = classpath.iterator(); iter.hasNext();) { sb.append(iter.next().toString()); sb.append(File.pathSeparator); } return sb.toString(); } } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjCompilerOptions.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.util.Map; import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.aspectj.weaver.Constants; /** * Compiler options used by Eclipse integration (AJDT) */ public class AjCompilerOptions extends CompilerOptions { // AspectJ Lint options public static final String OPTION_ReportInvalidAbsoluteTypeName = "org.aspectj.ajdt.core.compiler.lint.InvalidAbsoluteTypeName"; public static final String OPTION_ReportInvalidWildcardTypeName = "org.aspectj.ajdt.core.compiler.lint.WildcardTypeName"; public static final String OPTION_ReportUnresolvableMember = "org.aspectj.ajdt.core.compiler.lint.UnresolvableMember"; public static final String OPTION_ReportTypeNotExposedToWeaver = "org.aspectj.ajdt.core.compiler.lint.TypeNotExposedToWeaver"; public static final String OPTION_ReportShadowNotInStructure = "org.aspectj.ajdt.core.compiler.lint.ShadowNotInStructure"; public static final String OPTION_ReportUnmatchedSuperTypeInCall = "org.aspectj.ajdt.core.compiler.list.UnmatchedSuperTypeInCall"; public static final String OPTION_ReportCannotImplementLazyTJP = "org.aspectj.ajdt.core.compiler.lint.CannotImplementLazyTJP"; public static final String OPTION_ReportNeedSerialVersionUIDField = "org.aspectj.ajdt.core.compiler.lint.NeedSerialVersionUIDField"; public static final String OPTION_ReportIncompatibleSerialVersion = "org.aspectj.ajdt.core.compiler.lint.BrokeSerialVersionCompatibility"; // General AspectJ Compiler options (excludes paths etc, these are handled separately) public static final String OPTION_NoWeave = "org.aspectj.ajdt.core.compiler.weaver.NoWeave"; public static final String OPTION_XSerializableAspects = "org.aspectj.ajdt.core.compiler.weaver.XSerializableAspects"; public static final String OPTION_XLazyThisJoinPoint = "org.aspectj.ajdt.core.compiler.weaver.XLazyThisJoinPoint"; public static final String OPTION_XNoInline = "org.aspectj.ajdt.core.compiler.weaver.XNoInline"; public static final String OPTION_XNotReweavable = "org.aspectj.ajdt.core.compiler.weaver.XNotReweavable"; public static final String OPTION_XHasMember = "org.aspectj.ajdt.core.compiler.weaver.XHasMember"; public static final String OPTION_XdevPinpoint = "org.aspectj.ajdt.core.compiler.weaver.XdevPinpoint"; // these next four not exposed by IDEs public static final String OPTION_XDevNoAtAspectJProcessing = "org.aspectj.ajdt.core.compiler.ast.NoAtAspectJProcessing"; public static final String OPTION_GenerateModel = "org.aspectj.ajdt.core.compiler.model.GenerateModel"; public static final String OPTION_GenerateJavaDocsInModel = "org.aspectj.ajdt.core.compiler.model.GenerateJavaDocsInModel"; public static final String OPTION_Emacssym = "org.aspectj.ajdt.core.compiler.model.Emacssym"; // constants for irritant levels public static final long InvalidAbsoluteTypeName = ASTNode.Bit47L; public static final long InvalidWildCardTypeName = ASTNode.Bit48L; public static final long UnresolvableMember = ASTNode.Bit49L; public static final long TypeNotExposedToWeaver = ASTNode.Bit50L; public static final long ShadowNotInStructure = ASTNode.Bit51L; public static final long UnmatchedSuperTypeInCall = ASTNode.Bit52L; public static final long CannotImplementLazyTJP = ASTNode.Bit53L; public static final long NeedSerialVersionUIDField = ASTNode.Bit54L; public static final long IncompatibleSerialVersion = ASTNode.Bit55L; public boolean noWeave = false; public boolean xSerializableAspects = false; public boolean xLazyThisJoinPoint = false; public boolean xNoInline = false; public boolean xNotReweavable = false; public boolean xHasMember = false; public boolean xdevPinpoint = false; public boolean showWeavingInformation = false; public String xOptionalJoinpoints = null; // If true - autoboxing behaves differently ... public boolean behaveInJava5Way = false; // Specifies the level of the aspectjrt.jar we are targetting public String targetAspectjRuntimeLevel = Constants.RUNTIME_LEVEL_DEFAULT; public String xConfigurationInfo; // these next four not exposed by IDEs public boolean generateModel = false; public boolean generateJavaDocsInModel = false; public boolean generateEmacsSymFiles = false; public boolean noAtAspectJProcessing = false; /** * Generates a map of cross references based on information * in the structure model. */ public boolean generateCrossRefs = false; public boolean proceedOnError = false; /** * Initializing the compiler options with defaults */ public AjCompilerOptions(){ super(); setAspectJWarningDefaults(); } /** * Initializing the compiler options with external settings * @param settings */ public AjCompilerOptions(Map settings){ setAspectJWarningDefaults(); if (settings == null) return; set(settings); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.impl.CompilerOptions#getMap() */ public Map getMap() { Map map = super.getMap(); // now add AspectJ additional options map.put(OPTION_ReportInvalidAbsoluteTypeName,getSeverityString(InvalidAbsoluteTypeName)); map.put(OPTION_ReportInvalidWildcardTypeName,getSeverityString(InvalidWildCardTypeName)); map.put(OPTION_ReportUnresolvableMember,getSeverityString(UnresolvableMember)); map.put(OPTION_ReportTypeNotExposedToWeaver,getSeverityString(TypeNotExposedToWeaver)); map.put(OPTION_ReportShadowNotInStructure,getSeverityString(ShadowNotInStructure)); map.put(OPTION_ReportUnmatchedSuperTypeInCall,getSeverityString(UnmatchedSuperTypeInCall)); map.put(OPTION_ReportCannotImplementLazyTJP,getSeverityString(CannotImplementLazyTJP)); map.put(OPTION_ReportNeedSerialVersionUIDField,getSeverityString(NeedSerialVersionUIDField)); map.put(OPTION_ReportIncompatibleSerialVersion,getSeverityString(IncompatibleSerialVersion)); map.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock,getSeverityString(CompilerOptions.SwallowedExceptionInCatchBlock)); map.put(OPTION_NoWeave, this.noWeave ? ENABLED : DISABLED); map.put(OPTION_XSerializableAspects,this.xSerializableAspects ? ENABLED : DISABLED); map.put(OPTION_XLazyThisJoinPoint,this.xLazyThisJoinPoint ? ENABLED : DISABLED); map.put(OPTION_XNoInline,this.xNoInline ? ENABLED : DISABLED); map.put(OPTION_XNotReweavable,this.xNotReweavable ? ENABLED : DISABLED); map.put(OPTION_XHasMember, this.xHasMember ? ENABLED : DISABLED); map.put(OPTION_XdevPinpoint, this.xdevPinpoint ? ENABLED : DISABLED); map.put(OPTION_GenerateModel,this.generateModel ? ENABLED : DISABLED); map.put(OPTION_GenerateJavaDocsInModel,this.generateJavaDocsInModel ? ENABLED : DISABLED); map.put(OPTION_Emacssym,this.generateEmacsSymFiles ? ENABLED : DISABLED); map.put(OPTION_XDevNoAtAspectJProcessing,this.noAtAspectJProcessing ? ENABLED : DISABLED); return map; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.impl.CompilerOptions#set(java.util.Map) */ public void set(Map optionsMap) { super.set(optionsMap); Object optionValue; if ((optionValue = optionsMap.get(OPTION_ReportInvalidAbsoluteTypeName)) != null) updateSeverity(InvalidAbsoluteTypeName, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportInvalidWildcardTypeName)) != null) updateSeverity(InvalidWildCardTypeName, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportUnresolvableMember)) != null) updateSeverity(UnresolvableMember, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportTypeNotExposedToWeaver)) != null) updateSeverity(TypeNotExposedToWeaver, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportShadowNotInStructure)) != null) updateSeverity(ShadowNotInStructure, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportUnmatchedSuperTypeInCall)) != null) updateSeverity(UnmatchedSuperTypeInCall, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportCannotImplementLazyTJP)) != null) updateSeverity(CannotImplementLazyTJP, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportNeedSerialVersionUIDField)) != null) updateSeverity(NeedSerialVersionUIDField, optionValue); if ((optionValue = optionsMap.get(OPTION_ReportIncompatibleSerialVersion)) != null) updateSeverity(IncompatibleSerialVersion, optionValue); if ((optionValue = optionsMap.get(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock)) != null) updateSeverity(CompilerOptions.SwallowedExceptionInCatchBlock, optionValue); if ((optionValue = optionsMap.get(OPTION_NoWeave)) != null) { if (ENABLED.equals(optionValue)) { this.noWeave = true; } else if (DISABLED.equals(optionValue)) { this.noWeave = false; } } if ((optionValue = optionsMap.get(OPTION_XSerializableAspects)) != null) { if (ENABLED.equals(optionValue)) { this.xSerializableAspects = true; } else if (DISABLED.equals(optionValue)) { this.xSerializableAspects = false; } } if ((optionValue = optionsMap.get(OPTION_XLazyThisJoinPoint)) != null) { if (ENABLED.equals(optionValue)) { this.xLazyThisJoinPoint = true; } else if (DISABLED.equals(optionValue)) { this.xLazyThisJoinPoint = false; } } if ((optionValue = optionsMap.get(OPTION_XNoInline)) != null) { if (ENABLED.equals(optionValue)) { this.xNoInline = true; } else if (DISABLED.equals(optionValue)) { this.xNoInline = false; } } if ((optionValue = optionsMap.get(OPTION_XNotReweavable)) != null) { if (ENABLED.equals(optionValue)) { this.xNotReweavable = true; } else if (DISABLED.equals(optionValue)) { this.xNotReweavable = false; } } /* if ((optionValue = optionsMap.get(OPTION_XReweavableCompress)) != null) { if (ENABLED.equals(optionValue)) { this.xReweavableCompress = true; } else if (DISABLED.equals(optionValue)) { this.xReweavableCompress = false; } } */ if ((optionValue = optionsMap.get(OPTION_XHasMember)) != null) { if (ENABLED.equals(optionValue)) { this.xHasMember = true; } else if (DISABLED.equals(optionValue)) { this.xHasMember = false; } } if ((optionValue = optionsMap.get(OPTION_XdevPinpoint)) != null) { if (ENABLED.equals(optionValue)) { this.xdevPinpoint = true; } else if (DISABLED.equals(optionValue)) { this.xdevPinpoint = false; } } if ((optionValue = optionsMap.get(OPTION_GenerateModel)) != null) { if (ENABLED.equals(optionValue)) { this.generateModel = true; } else if (DISABLED.equals(optionValue)) { this.generateModel = false; } } if ((optionValue = optionsMap.get(OPTION_GenerateJavaDocsInModel)) != null) { if (ENABLED.equals(optionValue)) { this.generateJavaDocsInModel = true; } else if (DISABLED.equals(optionValue)) { this.generateJavaDocsInModel = false; } } if ((optionValue = optionsMap.get(OPTION_Emacssym)) != null) { if (ENABLED.equals(optionValue)) { this.generateEmacsSymFiles = true; } else if (DISABLED.equals(optionValue)) { this.generateEmacsSymFiles = false; } } if ((optionValue = optionsMap.get(OPTION_XDevNoAtAspectJProcessing)) != null) { if (ENABLED.equals(optionValue)) { this.noAtAspectJProcessing = true; } else if (DISABLED.equals(optionValue)) { this.noAtAspectJProcessing = false; } } } /** * Add these warnings to the default set... */ private void setAspectJWarningDefaults() { super.warningThreshold = super.warningThreshold | InvalidAbsoluteTypeName | UnresolvableMember | TypeNotExposedToWeaver | UnmatchedSuperTypeInCall | CannotImplementLazyTJP | CompilerOptions.SwallowedExceptionInCatchBlock; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buf = new StringBuffer( super.toString() ); // now add AspectJ additional options buf.append("\n\tAspectJ Specific Options:"); buf.append("\n\t- no weave: ").append(this.noWeave ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- no inline (X option): ").append(this.xNoInline ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate serializable aspects (X option): ").append(this.xSerializableAspects ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- lazy thisJoinPoint (X option): ").append(this.xLazyThisJoinPoint ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate non-reweavable class files (X option): ").append(this.xNotReweavable ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- has member support (X option): ").append(this.xHasMember ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate AJDE model: ").append(this.generateModel ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate Javadocs in AJDE model: ").append(this.generateJavaDocsInModel ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- generate Emacs symbol files: ").append(this.generateEmacsSymFiles ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- suppress @AspectJ processing: ").append(this.noAtAspectJProcessing ? ENABLED : DISABLED); //$NON-NLS-1$ buf.append("\n\t- invalid absolute type name (XLint): ").append(getSeverityString(InvalidAbsoluteTypeName)); //$NON-NLS-1$ buf.append("\n\t- invalid wildcard type name (XLint): ").append(getSeverityString(InvalidWildCardTypeName)); //$NON-NLS-1$ buf.append("\n\t- unresolvable member (XLint): ").append(getSeverityString(UnresolvableMember)); //$NON-NLS-1$ buf.append("\n\t- type not exposed to weaver (XLint): ").append(getSeverityString(TypeNotExposedToWeaver)); //$NON-NLS-1$ buf.append("\n\t- shadow not in structure (XLint): ").append(getSeverityString(ShadowNotInStructure)); //$NON-NLS-1$ buf.append("\n\t- unmatched super type in call (XLint): ").append(getSeverityString(UnmatchedSuperTypeInCall)); //$NON-NLS-1$ buf.append("\n\t- cannot implement lazy thisJoinPoint (XLint): ").append(getSeverityString(CannotImplementLazyTJP)); //$NON-NLS-1$ buf.append("\n\t- need serialVersionUID field (XLint): ").append(getSeverityString(NeedSerialVersionUIDField)); //$NON-NLS-1$ buf.append("\n\t- incompatible serial version (XLint): ").append(getSeverityString(IncompatibleSerialVersion)); //$NON-NLS-1$ buf.append("\n\t- swallowed exception in catch block (XLint): ").append(getSeverityString(CompilerOptions.SwallowedExceptionInCatchBlock)); //$NON-NLS-1$ return buf.toString(); } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/BcweaverJarMaker.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.batch; import java.io.File; import java.io.IOException; import java.util.*; import org.aspectj.ajdt.ajc.AjdtAjcTests; import org.aspectj.tools.ajc.AjcTests; public class BcweaverJarMaker { private static String cp = "../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path"); public BcweaverJarMaker() { super(); } public static void main(String[] args) throws IOException { makeJar0(); makeJar1(); makeJar1a(); makeJar2(); makeJarObviousNothing(); makeJarHardNothing(); makeTestJars(); makeURLWeavingClassLoaderJars(); makeDuplicateManifestTestJars(); makeOutjarTestJars(); makeAspectPathTestJars(); makeAjc11TestJars(); } public static void makeJar0() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/tracing.jar"); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath()); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/Trace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/MyTrace.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJar1() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatrace.jar"); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath()); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ExecTrace.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJarObviousNothing() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatrace0easy.jar"); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath()); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ObviousTraceNothing.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJarHardNothing() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatrace0hard.jar"); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath()); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/HardTraceNothing.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJar1a() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/megatraceNoweave.jar"); args.add("-noweave"); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath()); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ExecTrace.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeJar2() throws IOException { List args = new ArrayList(); args.add("-outjar"); args.add("../weaver/testdata/dummyAspect.jar"); args.add("-classpath"); args.add(AjcTests.aspectjrtClasspath()); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/DummyAspect.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeTestJars() throws IOException { List args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/new/options11/aspectlib1.jar"); args.add("../tests/new/options11/library1/*.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/new/options11/aspectlib2.jar"); args.add("../tests/new/options11/library2/*.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/new/options11/injar.jar"); args.add("../tests/new/options11/injar/*.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/bugs/serialVersionUID/injar.jar"); args.add("../tests/bugs/serialVersionUID/Test.java"); args.add("../tests/bugs/serialVersionUID/Util.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); // For PR55341 args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../tests/bugs/StringToString/helloworld.jar"); args.add("../tests/bugs/StringToString/HW.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); buildShowWeaveInfoTestingJars(); } public static void makeURLWeavingClassLoaderJars() throws IOException { List args = new ArrayList(); /* * Vanilla classes */ args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-classes.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWHelloWorld.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/ltw/LTWPackageTest.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Woven classes */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-XnotReweavable"); args.add("-outjar"); args.add("../weaver/testdata/ltw-woven.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWHelloWorld.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAspect.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Advice */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-aspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAspect.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Declare warning advice */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-dwaspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWDeclareWarning.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Declare error advice */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-deaspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWDeclareError.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * Around closure advice */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-acaspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAroundClosure.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * ITD */ args = new ArrayList(); args.add("-Xlint:ignore"); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-itdaspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWInterfaceITD.aj"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWFieldITD.aj"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWMethodITD.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * perXXX() */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../weaver/testdata/ltw-peraspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWPerthis.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } private static void buildJarWithClasspath(String outjar,String input,String deps,boolean nodebug) { System.out.println(" Building "+outjar); List args = new ArrayList(); if (nodebug) args.add("-g:none"); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path") + (deps!=null?File.pathSeparator + "../ajde/testdata/WeaveInfoMessagesTest/"+deps:"")); args.add("-outjar"); args.add("../ajde/testdata/WeaveInfoMessagesTest/"+outjar); args.add("../ajde/testdata/WeaveInfoMessagesTest/"+input); System.err.println(args); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } private static void buildShowWeaveInfoTestingJars() { System.out.println("For binary weave info message testing (ShowWeaveMessagesTestCase.java)"); buildJarWithClasspath("Simple.jar","Simple.java",null,false); // Build with javac and jar // buildJarWithClasspath("Simple_nodebug.jar","Simple.java",null,true); buildJarWithClasspath("AspectAdvice.jar","AspectAdvice.aj",null,false); buildJarWithClasspath("AspectAdvice_nodebug.jar","AspectAdvice.aj","Simple.jar",true); buildJarWithClasspath("AspectDeclare.jar","AspectDeclare.aj","Simple.jar",false); buildJarWithClasspath("AspectDeclare_nodebug.jar","AspectDeclare.aj","Simple.jar",true); buildJarWithClasspath("AspectITD.jar","AspectITD.aj","Simple.jar",false); buildJarWithClasspath("AspectITD_nodebug.jar","AspectITD.aj","Simple.jar",true); buildJarWithClasspath("AspectDeclareSoft.jar","AspectDeclareSoft.aj","Simple.jar",false); buildJarWithClasspath("AspectDeclareSoft_nodebug.jar","AspectDeclareSoft.aj","Simple.jar",true); } public static void makeDuplicateManifestTestJars() throws IOException { List args = new ArrayList(); /* * injar */ args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../ajde/testdata/DuplicateManifestTest/injar.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/Hello.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * aspectjar */ args = new ArrayList(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("../ajde/testdata/DuplicateManifestTest/aspectjar.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/Trace.java"); args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/TraceHello.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeAspectPathTestJars() throws IOException { List args = new ArrayList(); args.clear(); args.add("-classpath"); args.add(cp); args.add("-outjar"); args.add("../tests/bugs/perCflowAndJar/lib.jar"); args.add("../tests/bugs/perCflowAndJar/PerCFlowCompileFromJar.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeAjc11TestJars() throws IOException { List args = new ArrayList(); args.clear(); args.add("-classpath"); args.add(cp); args.add("-outjar"); args.add("../tests/bugs/cflowAndJar/lib.jar"); args.add("../tests/bugs/cflowAndJar/AbstractAspect.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } public static void makeOutjarTestJars() throws IOException { List args = new ArrayList(); /* * parent */ args.clear(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("./testdata/OutjarTest/parent.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/OutjarTest/src/jar1/Parent.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * child */ args.clear(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path") + File.pathSeparator + "./testdata/OutjarTest/parent.jar"); args.add("-outjar"); args.add("./testdata/OutjarTest/child.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/OutjarTest/src/jar2/Child.java"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * aspects */ args.clear(); args.add("-classpath"); args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + File.pathSeparator + System.getProperty("aspectjrt.path")); args.add("-outjar"); args.add("./testdata/OutjarTest/aspects.jar"); args.add(AjdtAjcTests.TESTDATA_PATH + "/OutjarTest/src/jar3/Aspect.aj"); CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); /* * aspectjar */ // args = new ArrayList(); // args.add("-classpath"); // args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" + // File.pathSeparator + System.getProperty("aspectjrt.path")); // args.add("-outjar"); // args.add("../ajde/testdata/DuplicateManifestTest/aspectjar.jar"); // args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/Trace.java"); // args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/TraceHello.java"); // CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/core/builder/AjCompilerOptionsTest.java
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.util.HashMap; import java.util.Map; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import junit.framework.TestCase; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class AjCompilerOptionsTest extends TestCase { private AjCompilerOptions options; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); options = new AjCompilerOptions(); } public void testDefaultValues() { assertFalse(options.noWeave); assertFalse(options.xSerializableAspects); assertFalse(options.xLazyThisJoinPoint); assertFalse(options.xNoInline); assertFalse(options.xNotReweavable); assertFalse(options.generateModel); assertFalse(options.generateJavaDocsInModel); assertFalse(options.generateEmacsSymFiles); assertFalse(options.noAtAspectJProcessing); Map map = options.getMap(); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportUnresolvableMember)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportShadowNotInStructure)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall)); assertEquals(CompilerOptions.WARNING,map.get(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField)); assertEquals(CompilerOptions.IGNORE,map.get(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion)); } public void testDirectSet() { options.noWeave = true; options.xSerializableAspects = true; options.xLazyThisJoinPoint = true; options.xNoInline = true; options.xNotReweavable = true; options.generateModel = true; options.generateJavaDocsInModel = true; options.generateEmacsSymFiles = true; options.noAtAspectJProcessing = true; Map map = options.getMap(); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_NoWeave)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XSerializableAspects)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XLazyThisJoinPoint)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XNoInline)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XNotReweavable)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_GenerateModel)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_GenerateJavaDocsInModel)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_Emacssym)); assertEquals(CompilerOptions.ENABLED,map.get(AjCompilerOptions.OPTION_XDevNoAtAspectJProcessing)); } public void testMapSet() { Map map = new HashMap(); map.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportUnresolvableMember,CompilerOptions.IGNORE); map.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure,CompilerOptions.WARNING); map.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField,CompilerOptions.WARNING); map.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion,CompilerOptions.ERROR); map.put(AjCompilerOptions.OPTION_NoWeave,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XSerializableAspects,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XLazyThisJoinPoint,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XNoInline,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XNotReweavable,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_GenerateModel,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_GenerateJavaDocsInModel,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_Emacssym,CompilerOptions.ENABLED); map.put(AjCompilerOptions.OPTION_XDevNoAtAspectJProcessing,CompilerOptions.ENABLED); options.set(map); assertTrue(options.noWeave); assertTrue(options.xSerializableAspects); assertTrue(options.xLazyThisJoinPoint); assertTrue(options.xNoInline); assertTrue(options.xNotReweavable); assertTrue(options.generateModel); assertTrue(options.generateJavaDocsInModel); assertTrue(options.generateEmacsSymFiles); assertTrue(options.noAtAspectJProcessing); Map newMap = options.getMap(); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName)); assertEquals(CompilerOptions.IGNORE,newMap.get(AjCompilerOptions.OPTION_ReportUnresolvableMember)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver)); assertEquals(CompilerOptions.WARNING,newMap.get(AjCompilerOptions.OPTION_ReportShadowNotInStructure)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP)); assertEquals(CompilerOptions.WARNING,newMap.get(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField)); assertEquals(CompilerOptions.ERROR,newMap.get(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion)); } /* * Class to test for String toString() */ public void testToString() { String s = options.toString(); assertTrue("Should have info on AspectJ options",s.indexOf("AspectJ Specific Options:") > 0); } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
taskdefs/src/org/aspectj/tools/ant/taskdefs/AjcTask.java
/* ******************************************************************* * Copyright (c) 2001-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC) * 2003-2004 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Wes Isberg 2003-2004 changes * ******************************************************************/ package org.aspectj.tools.ant.taskdefs; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Location; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.taskdefs.Delete; import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.taskdefs.Expand; import org.apache.tools.ant.taskdefs.Javac; import org.apache.tools.ant.taskdefs.LogStreamHandler; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.taskdefs.Mkdir; import org.apache.tools.ant.taskdefs.PumpStreamHandler; import org.apache.tools.ant.taskdefs.Zip; import org.apache.tools.ant.taskdefs.compilers.DefaultCompilerAdapter; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.types.CommandlineJava; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.PatternSet; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.types.ZipFileSet; import org.apache.tools.ant.util.TaskLogger; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.tools.ajc.Main; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; /** * This runs the AspectJ 1.1 compiler, * supporting all the command-line options. * In 1.1.1, ajc copies resources from input jars, * but you can copy resources from the source directories * using sourceRootCopyFilter. * When not forking, things will be copied as needed * for each iterative compile, * but when forking things are only copied at the * completion of a successful compile. * <p> * See the development environment guide for * usage documentation. * * @since AspectJ 1.1, Ant 1.5 */ public class AjcTask extends MatchingTask { /* * This task mainly converts ant specification for ajc, * verbosely ignoring improper input. * It also has some special features for non-obvious clients: * (1) Javac compiler adapter supported in * <code>setupAjc(AjcTask, Javac, File)</code> * and * <code>readArguments(String[])</code>; * (2) testing is supported by * (a) permitting the same specification to be re-run * with added flags (settings once made cannot be * removed); and * (b) permitting recycling the task with * <code>reset()</code> (untested). * * The parts that do more than convert ant specs are * (a) code for forking; * (b) code for copying resources. * * If you maintain/upgrade this task, keep in mind: * (1) changes to the semantics of ajc (new options, new * values permitted, etc.) will have to be reflected here. * (2) the clients: * the iajc ant script, Javac compiler adapter, * maven clients of iajc, and testing code. */ // XXX move static methods after static initializer /** * This method extracts javac arguments to ajc, * and add arguments to make ajc behave more like javac * in copying resources. * <p> * Pass ajc-specific options using compilerarg sub-element: * <pre> * &lt;javac srcdir="src"> * &lt;compilerarg compiler="..." line="-argfile src/args.lst"/> * &lt;javac> * </pre> * Some javac arguments are not supported in this component (yet): * <pre> * String memoryInitialSize; * boolean includeAntRuntime = true; * boolean includeJavaRuntime = false; * </pre> * Other javac arguments are not supported in ajc 1.1: * <pre> * boolean optimize; * String forkedExecutable; * FacadeTaskHelper facade; * boolean depend; * String debugLevel; * Path compileSourcepath; * </pre> * @param javac the Javac command to implement (not null) * @param ajc the AjcTask to adapt (not null) * @param destDir the File class destination directory (may be null) * @return null if no error, or String error otherwise */ public String setupAjc(Javac javac) { if (null == javac) { return "null javac"; } AjcTask ajc = this; // no null checks b/c AjcTask handles null input gracefully ajc.setProject(javac.getProject()); ajc.setLocation(javac.getLocation()); ajc.setTaskName("javac-iajc"); ajc.setDebug(javac.getDebug()); ajc.setDeprecation(javac.getDeprecation()); ajc.setFailonerror(javac.getFailonerror()); final boolean fork = javac.isForkedJavac(); ajc.setFork(fork); if (fork) { ajc.setMaxmem(javac.getMemoryMaximumSize()); } ajc.setNowarn(javac.getNowarn()); ajc.setListFileArgs(javac.getListfiles()); ajc.setVerbose(javac.getVerbose()); ajc.setTarget(javac.getTarget()); ajc.setSource(javac.getSource()); ajc.setEncoding(javac.getEncoding()); File javacDestDir = javac.getDestdir(); if (null != javacDestDir) { ajc.setDestdir(javacDestDir); // filter requires dest dir // mimic Javac task's behavior in copying resources, ajc.setSourceRootCopyFilter("**/CVS/*,**/*.java,**/*.aj"); } ajc.setBootclasspath(javac.getBootclasspath()); ajc.setExtdirs(javac.getExtdirs()); ajc.setClasspath(javac.getClasspath()); // ignore srcDir -- all files picked up in recalculated file list // ajc.setSrcDir(javac.getSrcdir()); ajc.addFiles(javac.getFileList()); // arguments can override the filter, add to paths, override options ajc.readArguments(javac.getCurrentCompilerArgs()); return null; } /** * Find aspectjtools.jar on the task or system classpath. * Accept <code>aspectj{-}tools{...}.jar</code> * mainly to support build systems using maven-style * re-naming * (e.g., <code>aspectj-tools-1.1.0.jar</code>. * Note that we search the task classpath first, * though an entry on the system classpath would be loaded first, * because it seems more correct as the more specific one. * @return readable File for aspectjtools.jar, or null if not found. */ public static File findAspectjtoolsJar() { File result = null; ClassLoader loader = AjcTask.class.getClassLoader(); if (loader instanceof AntClassLoader) { AntClassLoader taskLoader = (AntClassLoader) loader; String cp = taskLoader.getClasspath(); String[] cps = LangUtil.splitClasspath(cp); for (int i = 0; (i < cps.length) && (null == result); i++) { result = isAspectjtoolsjar(cps[i]); } } if (null == result) { final Path classpath = Path.systemClasspath; final String[] paths = classpath.list(); for (int i = 0; (i < paths.length) && (null == result); i++) { result = isAspectjtoolsjar(paths[i]); } } return (null == result? null : result.getAbsoluteFile()); } /** @return File if readable jar with aspectj tools name, or null */ private static File isAspectjtoolsjar(String path) { if (null == path) { return null; } final String prefix = "aspectj"; final String infix = "tools"; final String altInfix = "-tools"; final String suffix = ".jar"; final int prefixLength = 7; // prefix.length(); final int minLength = 16; // prefixLength + infix.length() + suffix.length(); if (!path.endsWith(suffix)) { return null; } int loc = path.lastIndexOf(prefix); if ((-1 != loc) && ((loc + minLength) <= path.length())) { String rest = path.substring(loc+prefixLength); if (-1 != rest.indexOf(File.pathSeparator)) { return null; } if (rest.startsWith(infix) || rest.startsWith(altInfix)) { File result = new File(path); if (result.canRead() && result.isFile()) { return result; } } } return null; } /** * Maximum length (in chars) of command line * before converting to an argfile when forking */ private static final int MAX_COMMANDLINE = 4096; private static final File DEFAULT_DESTDIR = new File(".") { public String toString() { return "(no destination dir specified)"; } }; /** do not throw BuildException on fail/abort message with usage */ private static final String USAGE_SUBSTRING = "AspectJ-specific options"; /** valid -X[...] options other than -Xlint variants */ private static final List VALID_XOPTIONS; /** valid warning (-warn:[...]) variants */ private static final List VALID_WARNINGS; /** valid debugging (-g:[...]) variants */ private static final List VALID_DEBUG; /** * -Xlint variants (error, warning, ignore) * @see org.aspectj.weaver.Lint */ private static final List VALID_XLINT; public static final String COMMAND_EDITOR_NAME = AjcTask.class.getName() + ".COMMAND_EDITOR"; static final String[] TARGET_INPUTS = new String [] { "1.1", "1.2", "1.3", "1.4", "1.5" }; static final String[] SOURCE_INPUTS = new String [] { "1.3", "1.4", "1.5" }; static final String[] COMPLIANCE_INPUTS = new String [] { "-1.3", "-1.4", "-1.5" }; private static final ICommandEditor COMMAND_EDITOR; static { // many now deprecated: reweavable*, noWeave, ... String[] xs = new String[] { "serializableAspects", "incrementalFile", "lazyTjp", "reweavable", "reweavable:compress", "notReweavable", "noInline", "noWeave","hasMember", "ajruntimelevel:1.2", "ajruntimelevel:1.5", //, "targetNearSource", "OcodeSize", }; VALID_XOPTIONS = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] {"constructorName", "packageDefaultMethod", "deprecation", "maskedCatchBlocks", "unusedLocals", "unusedArguments", "unusedImports", "syntheticAccess", "assertIdentifier", "none" }; VALID_WARNINGS = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] {"none", "lines", "vars", "source" }; VALID_DEBUG = Collections.unmodifiableList(Arrays.asList(xs)); xs = new String[] { "error", "warning", "ignore"}; VALID_XLINT = Collections.unmodifiableList(Arrays.asList(xs)); ICommandEditor editor = null; try { String editorClassName = System.getProperty(COMMAND_EDITOR_NAME); if (null != editorClassName) { ClassLoader cl = AjcTask.class.getClassLoader(); Class editorClass = cl.loadClass(editorClassName); editor = (ICommandEditor) editorClass.newInstance(); } } catch (Throwable t) { System.err.println("Warning: unable to load command editor"); t.printStackTrace(System.err); } COMMAND_EDITOR = editor; } // ---------------------------- state and Ant interface thereto private boolean verbose; private boolean listFileArgs; private boolean failonerror; private boolean fork; private String maxMem; private TaskLogger logger; // ------- single entries dumped into cmd protected GuardedCommand cmd; // ------- lists resolved in addListArgs() at execute() time private Path srcdir; private Path injars; private Path inpath; private Path classpath; private Path bootclasspath; private Path forkclasspath; private Path extdirs; private Path aspectpath; private Path argfiles; private List ignored; private Path sourceRoots; private File xweaveDir; private String xdoneSignal; // ----- added by adapter - integrate better? private List /* File */ adapterFiles; private String[] adapterArguments; private IMessageHolder messageHolder; private ICommandEditor commandEditor; // -------- resource-copying /** true if copying injar non-.class files to the output jar */ private boolean copyInjars; private boolean copyInpath; /** non-null if copying all source root files but the filtered ones */ private String sourceRootCopyFilter; /** non-null if copying all inpath dir files but the filtered ones */ private String inpathDirCopyFilter; /** directory sink for classes */ private File destDir; /** zip file sink for classes */ private File outjar; /** track whether we've supplied any temp outjar */ private boolean outjarFixedup; /** * When possibly copying resources to the output jar, * pass ajc a fake output jar to copy from, * so we don't change the modification time of the output jar * when copying injars/inpath into the actual outjar. */ private File tmpOutjar; private boolean executing; /** non-null only while executing in same vm */ private Main main; /** true only when executing in other vm */ private boolean executingInOtherVM; /** true if -incremental */ private boolean inIncrementalMode; /** true if -XincrementalFile (i.e, setTagFile)*/ private boolean inIncrementalFileMode; /** used when forking */ private CommandlineJava javaCmd = new CommandlineJava(); // also note MatchingTask grabs source files... public AjcTask() { reset(); } /** to use this same Task more than once (testing) */ public void reset() { // XXX possible to reset MatchingTask? // need declare for "all fields initialized in ..." adapterArguments = null; adapterFiles = new ArrayList(); argfiles = null; executing = false; aspectpath = null; bootclasspath = null; classpath = null; cmd = new GuardedCommand(); copyInjars = false; copyInpath = false; destDir = DEFAULT_DESTDIR; executing = false; executingInOtherVM = false; extdirs = null; failonerror = true; // non-standard default forkclasspath = null; inIncrementalMode = false; inIncrementalFileMode = false; ignored = new ArrayList(); injars = null; inpath = null; listFileArgs = false; maxMem = null; messageHolder = null; outjar = null; sourceRootCopyFilter = null; inpathDirCopyFilter = null; sourceRoots = null; srcdir = null; tmpOutjar = null; verbose = false; xweaveDir = null; xdoneSignal = null; javaCmd = new CommandlineJava(); } protected void ignore(String ignored) { this.ignored.add(ignored + " at " + getLocation()); } //---------------------- option values // used by entries with internal commas protected String validCommaList(String list, List valid, String label) { return validCommaList(list, valid, label, valid.size()); } protected String validCommaList(String list, List valid, String label, int max) { StringBuffer result = new StringBuffer(); StringTokenizer st = new StringTokenizer(list, ","); int num = 0; while (st.hasMoreTokens()) { String token = st.nextToken().trim(); num++; if (num > max) { ignore("too many entries for -" + label + ": " + token); break; } if (!valid.contains(token)) { ignore("bad commaList entry for -" + label + ": " + token); } else { if (0 < result.length()) { result.append(","); } result.append(token); } } return (0 == result.length() ? null : result.toString()); } public void setIncremental(boolean incremental) { cmd.addFlag("-incremental", incremental); inIncrementalMode = incremental; } public void setHelp(boolean help) { cmd.addFlag("-help", help); } public void setVersion(boolean version) { cmd.addFlag("-version", version); } public void setXNoweave(boolean noweave) { cmd.addFlag("-XnoWeave", noweave); } public void setXReweavable(boolean reweavable) { cmd.addFlag("-Xreweavable",reweavable); } public void setXNotReweavable(boolean notReweavable) { cmd.addFlag("-XnotReweavable",notReweavable); } public void setXNoInline(boolean noInline) { cmd.addFlag("-XnoInline",noInline); } public void setShowWeaveInfo(boolean showweaveinfo) { cmd.addFlag("-showWeaveInfo",showweaveinfo); } public void setNowarn(boolean nowarn) { cmd.addFlag("-nowarn", nowarn); } public void setDeprecation(boolean deprecation) { cmd.addFlag("-deprecation", deprecation); } public void setWarn(String warnings) { warnings = validCommaList(warnings, VALID_WARNINGS, "warn"); cmd.addFlag("-warn:" + warnings, (null != warnings)); } public void setDebug(boolean debug) { cmd.addFlag("-g", debug); } public void setDebugLevel(String level) { level = validCommaList(level, VALID_DEBUG, "g"); cmd.addFlag("-g:" + level, (null != level)); } public void setEmacssym(boolean emacssym) { cmd.addFlag("-emacssym", emacssym); } public void setCrossrefs(boolean on) { cmd.addFlag("-crossrefs", on); } /** * -Xlint - set default level of -Xlint messages to warning * (same as </code>-Xlint:warning</code>) */ public void setXlintwarnings(boolean xlintwarnings) { cmd.addFlag("-Xlint", xlintwarnings); } /** -Xlint:{error|warning|info} - set default level for -Xlint messages * @param xlint the String with one of error, warning, ignored */ public void setXlint(String xlint) { xlint = validCommaList(xlint, VALID_XLINT, "Xlint", 1); cmd.addFlag("-Xlint:" + xlint, (null != xlint)); } /** * -Xlintfile {lint.properties} - enable or disable specific forms * of -Xlint messages based on a lint properties file * (default is * <code>org/aspectj/weaver/XLintDefault.properties</code>) * @param xlintFile the File with lint properties */ public void setXlintfile(File xlintFile) { cmd.addFlagged("-Xlintfile", xlintFile.getAbsolutePath()); } public void setPreserveAllLocals(boolean preserveAllLocals) { cmd.addFlag("-preserveAllLocals", preserveAllLocals); } public void setNoImportError(boolean noImportError) { cmd.addFlag("-warn:-unusedImport", noImportError); } public void setEncoding(String encoding) { cmd.addFlagged("-encoding", encoding); } public void setLog(File file) { cmd.addFlagged("-log", file.getAbsolutePath()); } public void setProceedOnError(boolean proceedOnError) { cmd.addFlag("-proceedOnError", proceedOnError); } public void setVerbose(boolean verbose) { cmd.addFlag("-verbose", verbose); this.verbose = verbose; } public void setListFileArgs(boolean listFileArgs) { this.listFileArgs = listFileArgs; } public void setReferenceInfo(boolean referenceInfo) { cmd.addFlag("-referenceInfo", referenceInfo); } public void setTime(boolean time) { cmd.addFlag("-time", time); } public void setNoExit(boolean noExit) { cmd.addFlag("-noExit", noExit); } public void setFailonerror(boolean failonerror) { this.failonerror = failonerror; } /** * @return true if fork was set */ public boolean isForked() { return fork; } public void setFork(boolean fork) { this.fork = fork; } public void setMaxmem(String maxMem) { this.maxMem = maxMem; } /** support for nested &lt;jvmarg&gt; elements */ public Commandline.Argument createJvmarg() { return this.javaCmd.createVmArgument(); } // ---------------- public void setTagFile(File file) { inIncrementalMode = true; cmd.addFlagged(Main.CommandController.TAG_FILE_OPTION, file.getAbsolutePath()); inIncrementalFileMode = true; } public void setOutjar(File file) { if (DEFAULT_DESTDIR != destDir) { String e = "specifying both output jar (" + file + ") and destination dir (" + destDir + ")"; throw new BuildException(e); } outjar = file; outjarFixedup = false; tmpOutjar = null; } public void setOutxml(boolean outxml) { cmd.addFlag("-outxml",outxml); } public void setOutxmlfile(String name) { cmd.addFlagged("-outxmlfile", name); } public void setDestdir(File dir) { if (null != outjar) { String e = "specifying both output jar (" + outjar + ") and destination dir (" + dir + ")"; throw new BuildException(e); } cmd.addFlagged("-d", dir.getAbsolutePath()); destDir = dir; } /** * @param input a String in TARGET_INPUTS */ public void setTarget(String input) { String ignore = cmd.addOption("-target", TARGET_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Language compliance level. * If not set explicitly, eclipse default holds. * @param input a String in COMPLIANCE_INPUTS */ public void setCompliance(String input) { String ignore = cmd.addOption(null, COMPLIANCE_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Source compliance level. * If not set explicitly, eclipse default holds. * @param input a String in SOURCE_INPUTS */ public void setSource(String input) { String ignore = cmd.addOption("-source", SOURCE_INPUTS, input); if (null != ignore) { ignore(ignore); } } /** * Flag to copy all non-.class contents of injars * to outjar after compile completes. * Requires both injars and outjar. * @param doCopy */ public void setCopyInjars(boolean doCopy){ ignore("copyInJars"); log("copyInjars not required since 1.1.1.\n", Project.MSG_WARN); //this.copyInjars = doCopy; } /** * Option to copy all files from * all source root directories * except those specified here. * If this is specified and sourceroots are specified, * then this will copy all files except * those specified in the filter pattern. * Requires sourceroots. * * @param filter a String acceptable as an excludes * filter for an Ant Zip fileset. */ public void setSourceRootCopyFilter(String filter){ this.sourceRootCopyFilter = filter; } /** * Option to copy all files from * all inpath directories * except the files specified here. * If this is specified and inpath directories are specified, * then this will copy all files except * those specified in the filter pattern. * Requires inpath. * If the input does not contain "**\/*.class", then * this prepends it, to avoid overwriting woven classes * with unwoven input. * @param filter a String acceptable as an excludes * filter for an Ant Zip fileset. */ public void setInpathDirCopyFilter(String filter){ if (null != filter) { if (-1 == filter.indexOf("**/*.class")) { filter = "**/*.class," + filter; } } this.inpathDirCopyFilter = filter; } public void setX(String input) { // ajc-only eajc-also docDone StringTokenizer tokens = new StringTokenizer(input, ",", false); while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); if (1 < token.length()) { if (VALID_XOPTIONS.contains(token)) { cmd.addFlag("-X" + token, true); } else { ignore("-X" + token); } } } } public void setXDoneSignal(String doneSignal) { this.xdoneSignal = doneSignal; } /** direct API for testing */ public void setMessageHolder(IMessageHolder holder) { this.messageHolder = holder; } /** * Setup custom message handling. * @param className the String fully-qualified-name of a class * reachable from this object's class loader, * implementing IMessageHolder, and * having a public no-argument constructor. * @throws BuildException if unable to create instance of className */ public void setMessageHolderClass(String className) { try { Class mclass = Class.forName(className); IMessageHolder holder = (IMessageHolder) mclass.newInstance(); setMessageHolder(holder); } catch (Throwable t) { String m = "unable to instantiate message holder: " + className; throw new BuildException(m, t); } } /** direct API for testing */ public void setCommandEditor(ICommandEditor editor) { this.commandEditor = editor; } /** * Setup command-line filter. * To do this staticly, define the environment variable * <code>org.aspectj.tools.ant.taskdefs.AjcTask.COMMAND_EDITOR</code> * with the <code>className</code> parameter. * @param className the String fully-qualified-name of a class * reachable from this object's class loader, * implementing ICommandEditor, and * having a public no-argument constructor. * @throws BuildException if unable to create instance of className */ public void setCommandEditorClass(String className) { // skip Ant interface? try { Class mclass = Class.forName(className); setCommandEditor((ICommandEditor) mclass.newInstance()); } catch (Throwable t) { String m = "unable to instantiate command editor: " + className; throw new BuildException(m, t); } } //---------------------- Path lists /** * Add path elements to source path and return result. * Elements are added even if they do not exist. * @param source the Path to add to - may be null * @param toAdd the Path to add - may be null * @return the (never-null) Path that results */ protected Path incPath(Path source, Path toAdd) { if (null == source) { source = new Path(project); } if (null != toAdd) { source.append(toAdd); } return source; } public void setSourcerootsref(Reference ref) { createSourceRoots().setRefid(ref); } public void setSourceRoots(Path roots) { sourceRoots = incPath(sourceRoots, roots); } public Path createSourceRoots() { if (sourceRoots == null) { sourceRoots = new Path(project); } return sourceRoots.createPath(); } public void setXWeaveDir(File file) { if ((null != file) && file.isDirectory() && file.canRead()) { xweaveDir = file; } } public void setInjarsref(Reference ref) { createInjars().setRefid(ref); } public void setInpathref(Reference ref) { createInpath().setRefid(ref); } public void setInjars(Path path) { injars = incPath(injars, path); } public void setInpath(Path path) { inpath = incPath(inpath,path); } public Path createInjars() { if (injars == null) { injars = new Path(project); } return injars.createPath(); } public Path createInpath() { if (inpath == null) { inpath = new Path(project); } return inpath.createPath(); } public void setClasspath(Path path) { classpath = incPath(classpath, path); } public void setClasspathref(Reference classpathref) { createClasspath().setRefid(classpathref); } public Path createClasspath() { if (classpath == null) { classpath = new Path(project); } return classpath.createPath(); } public void setBootclasspath(Path path) { bootclasspath = incPath(bootclasspath, path); } public void setBootclasspathref(Reference bootclasspathref) { createBootclasspath().setRefid(bootclasspathref); } public Path createBootclasspath() { if (bootclasspath == null) { bootclasspath = new Path(project); } return bootclasspath.createPath(); } public void setForkclasspath(Path path) { forkclasspath = incPath(forkclasspath, path); } public void setForkclasspathref(Reference forkclasspathref) { createForkclasspath().setRefid(forkclasspathref); } public Path createForkclasspath() { if (forkclasspath == null) { forkclasspath = new Path(project); } return forkclasspath.createPath(); } public void setExtdirs(Path path) { extdirs = incPath(extdirs, path); } public void setExtdirsref(Reference ref) { createExtdirs().setRefid(ref); } public Path createExtdirs() { if (extdirs == null) { extdirs = new Path(project); } return extdirs.createPath(); } public void setAspectpathref(Reference ref) { createAspectpath().setRefid(ref); } public void setAspectpath(Path path) { aspectpath = incPath(aspectpath, path); } public Path createAspectpath() { if (aspectpath == null) { aspectpath = new Path(project); } return aspectpath.createPath(); } public void setSrcDir(Path path) { srcdir = incPath(srcdir, path); } public Path createSrc() { return createSrcdir(); } public Path createSrcdir() { if (srcdir == null) { srcdir = new Path(project); } return srcdir.createPath(); } /** @return true if in incremental mode (command-line or file) */ public boolean isInIncrementalMode() { return inIncrementalMode; } /** @return true if in incremental file mode */ public boolean isInIncrementalFileMode() { return inIncrementalFileMode; } public void setArgfilesref(Reference ref) { createArgfiles().setRefid(ref); } public void setArgfiles(Path path) { // ajc-only eajc-also docDone argfiles = incPath(argfiles, path); } public Path createArgfiles() { if (argfiles == null) { argfiles = new Path(project); } return argfiles.createPath(); } // ------------------------------ run /** * Compile using ajc per settings. * @exception BuildException if the compilation has problems * or if there were compiler errors and failonerror is true. */ public void execute() throws BuildException { this.logger = new TaskLogger(this); if (executing) { throw new IllegalStateException("already executing"); } else { executing = true; } setupOptions(); verifyOptions(); try { String[] args = makeCommand(); logVerbose("ajc " + Arrays.asList(args)); if (!fork) { executeInSameVM(args); } else { // when forking, Adapter handles failonerror executeInOtherVM(args); } } catch (BuildException e) { throw e; } catch (Throwable x) { this.logger.error(Main.renderExceptionForUser(x)); throw new BuildException("IGNORE -- See " + LangUtil.unqualifiedClassName(x) + " rendered to ant logger"); } finally { executing = false; if (null != tmpOutjar) { tmpOutjar.delete(); } } } /** * Halt processing. * This tells main in the same vm to quit. * It fails when running in forked mode. * @return true if not in forked mode * and main has quit or been told to quit */ public boolean quit() { if (executingInOtherVM) { return false; } Main me = main; if (null != me) { me.quit(); } return true; } // package-private for testing String[] makeCommand() { ArrayList result = new ArrayList(); if (0 < ignored.size()) { for (Iterator iter = ignored.iterator(); iter.hasNext();) { logVerbose("ignored: " + iter.next()); } } // when copying resources, use temp jar for class output // then copy temp jar contents and resources to output jar if ((null != outjar) && !outjarFixedup) { if (copyInjars || copyInpath || (null != sourceRootCopyFilter) || (null != inpathDirCopyFilter)) { String path = outjar.getAbsolutePath(); int len = FileUtil.zipSuffixLength(path); if (len < 1) { this.logger.info("not copying resources - weird outjar: " + path); } else { path = path.substring(0, path.length()-len) + ".tmp.jar"; tmpOutjar = new File(path); } } if (null == tmpOutjar) { cmd.addFlagged("-outjar", outjar.getAbsolutePath()); } else { cmd.addFlagged("-outjar", tmpOutjar.getAbsolutePath()); } outjarFixedup = true; } result.addAll(cmd.extractArguments()); addListArgs(result); String[] command = (String[]) result.toArray(new String[0]); if (null != commandEditor) { command = commandEditor.editCommand(command); } else if (null != COMMAND_EDITOR) { command = COMMAND_EDITOR.editCommand(command); } return command; } /** * Create any pseudo-options required to implement * some of the macro options * @throws BuildException if options conflict */ protected void setupOptions() { if (null != xweaveDir) { if (DEFAULT_DESTDIR != destDir) { throw new BuildException("weaveDir forces destdir"); } if (null != outjar) { throw new BuildException("weaveDir forces outjar"); } if (null != injars) { throw new BuildException("weaveDir incompatible with injars now"); } if (null != inpath) { throw new BuildException("weaveDir incompatible with inpath now"); } File injar = zipDirectory(xweaveDir); setInjars(new Path(getProject(), injar.getAbsolutePath())); setDestdir(xweaveDir); } } protected File zipDirectory(File dir) { File tempDir = new File("."); try { tempDir = File.createTempFile("AjcTest", ".tmp"); tempDir.mkdirs(); tempDir.deleteOnExit(); // XXX remove zip explicitly.. } catch (IOException e) { // ignore } // File result = new File(tempDir, String filename = "AjcTask-" + System.currentTimeMillis() + ".zip"; File result = new File(filename); Zip zip = new Zip(); zip.setProject(getProject()); zip.setDestFile(result); zip.setTaskName(getTaskName() + " - zip"); FileSet fileset = new FileSet(); fileset.setDir(dir); zip.addFileset(fileset); zip.execute(); Delete delete = new Delete(); delete.setProject(getProject()); delete.setTaskName(getTaskName() + " - delete"); delete.setDir(dir); delete.execute(); Mkdir mkdir = new Mkdir(); mkdir.setProject(getProject()); mkdir.setTaskName(getTaskName() + " - mkdir"); mkdir.setDir(dir); mkdir.execute(); return result; } /** * @throw BuildException if options conflict */ protected void verifyOptions() { StringBuffer sb = new StringBuffer(); if (fork && isInIncrementalMode() && !isInIncrementalFileMode()) { sb.append("can fork incremental only using tag file.\n"); } if (((null != inpathDirCopyFilter) || (null != sourceRootCopyFilter)) && (null == outjar) && (DEFAULT_DESTDIR == destDir)) { final String REQ = " requires dest dir or output jar.\n"; if (null == inpathDirCopyFilter) { sb.append("sourceRootCopyFilter"); } else if (null == sourceRootCopyFilter) { sb.append("inpathDirCopyFilter"); } else { sb.append("sourceRootCopyFilter and inpathDirCopyFilter"); } sb.append(REQ); } if (0 < sb.length()) { throw new BuildException(sb.toString()); } } /** * Run the compile in the same VM by * loading the compiler (Main), * setting up any message holders, * doing the compile, * and converting abort/failure and error messages * to BuildException, as appropriate. * @throws BuildException if abort or failure messages * or if errors and failonerror. * */ protected void executeInSameVM(String[] args) { if (null != maxMem) { log("maxMem ignored unless forked: " + maxMem, Project.MSG_WARN); } IMessageHolder holder = messageHolder; int numPreviousErrors; if (null == holder) { MessageHandler mhandler = new MessageHandler(true); final IMessageHandler delegate; delegate = new AntMessageHandler(this.logger,this.verbose, false); mhandler.setInterceptor(delegate); holder = mhandler; numPreviousErrors = 0; } else { numPreviousErrors = holder.numMessages(IMessage.ERROR, true); } { Main newmain = new Main(); newmain.setHolder(holder); newmain.setCompletionRunner(new Runnable() { public void run() { doCompletionTasks(); } }); if (null != main) { MessageUtil.fail(holder, "still running prior main"); return; } main = newmain; } main.runMain(args, false); if (failonerror) { int errs = holder.numMessages(IMessage.ERROR, false); errs -= numPreviousErrors; if (0 < errs) { String m = errs + " errors"; MessageUtil.print(System.err, holder, "", MessageUtil.MESSAGE_ALL, MessageUtil.PICK_ERROR, true); throw new BuildException(m); } } // Throw BuildException if there are any fail or abort // messages. // The BuildException message text has a list of class names // for the exceptions found in the messages, or the // number of fail/abort messages found if there were // no exceptions for any of the fail/abort messages. // The interceptor message handler should have already // printed the messages, including any stack traces. // HACK: this ignores the Usage message { IMessage[] fails = holder.getMessages(IMessage.FAIL, true); if (!LangUtil.isEmpty(fails)) { StringBuffer sb = new StringBuffer(); String prefix = "fail due to "; int numThrown = 0; for (int i = 0; i < fails.length; i++) { String message = fails[i].getMessage(); if (LangUtil.isEmpty(message)) { message = "<no message>"; } else if (-1 != message.indexOf(USAGE_SUBSTRING)) { continue; } Throwable t = fails[i].getThrown(); if (null != t) { numThrown++; sb.append(prefix); sb.append(LangUtil.unqualifiedClassName(t.getClass())); String thrownMessage = t.getMessage(); if (!LangUtil.isEmpty(thrownMessage)) { sb.append(" \"" + thrownMessage + "\""); } } sb.append("\"" + message + "\""); prefix = ", "; } if (0 < sb.length()) { sb.append(" (" + numThrown + " exceptions)"); throw new BuildException(sb.toString()); } } } } /** * Execute in a separate VM. * Differences from normal same-VM execution: * <ul> * <li>ignores any message holder {class} set</li> * <li>No resource-copying between interative runs</li> * <li>failonerror fails when process interface fails * to return negative values</li> * </ul> * @param args String[] of the complete compiler command to execute * * @see DefaultCompilerAdapter#executeExternalCompile(String[], int) * @throws BuildException if ajc aborts (negative value) * or if failonerror and there were compile errors. */ protected void executeInOtherVM(String[] args) { javaCmd.setClassname(org.aspectj.tools.ajc.Main.class.getName()); final Path vmClasspath = javaCmd.createClasspath(getProject()); { File aspectjtools = null; int vmClasspathSize = vmClasspath.size(); if ((null != forkclasspath) && (0 != forkclasspath.size())) { vmClasspath.addExisting(forkclasspath); } else { aspectjtools = findAspectjtoolsJar(); if (null != aspectjtools) { vmClasspath.createPathElement().setLocation(aspectjtools); } } int newVmClasspathSize = vmClasspath.size(); if (vmClasspathSize == newVmClasspathSize) { String m = "unable to find aspectjtools to fork - "; if (null != aspectjtools) { m += "tried " + aspectjtools.toString(); } else if (null != forkclasspath) { m += "tried " + forkclasspath.toString(); } else { m += "define forkclasspath or put aspectjtools on classpath"; } throw new BuildException(m); } } if (null != maxMem) { javaCmd.setMaxmemory(maxMem); } File tempFile = null; int numArgs = args.length; args = GuardedCommand.limitTo(args, MAX_COMMANDLINE, getLocation()); if (args.length != numArgs) { tempFile = new File(args[1]); } try { boolean setMessageHolderOnForking = (this.messageHolder != null); String[] javaArgs = javaCmd.getCommandline(); String[] both = new String[javaArgs.length + args.length + (setMessageHolderOnForking ? 2 : 0)]; System.arraycopy(javaArgs,0,both,0,javaArgs.length); System.arraycopy(args,0,both,javaArgs.length,args.length); if (setMessageHolderOnForking) { both[both.length - 2] = "-messageHolder"; both[both.length - 1] = this.messageHolder.getClass().getName(); } // try to use javaw instead on windows if (both[0].endsWith("java.exe")) { String path = both[0]; path = path.substring(0, path.length()-4); path = path + "w.exe"; File javaw = new File(path); if (javaw.canRead() && javaw.isFile()) { both[0] = path; } } logVerbose("forking " + Arrays.asList(both)); int result = execInOtherVM(both); if (0 > result) { throw new BuildException("failure[" + result + "] running ajc"); } else if (failonerror && (0 < result)) { throw new BuildException("compile errors: " + result); } // when forking, do completion only at end and when successful doCompletionTasks(); } finally { if (null != tempFile) { tempFile.delete(); } } } /** * Execute in another process using the same JDK * and the base directory of the project. XXX correct? * @param args * @return */ protected int execInOtherVM(String[] args) { try { Project project = getProject(); PumpStreamHandler handler = new LogStreamHandler(this, verbose ? Project.MSG_VERBOSE : Project.MSG_INFO, Project.MSG_WARN); // replace above two lines with what follows as an aid to debugging when running the unit tests.... // LogStreamHandler handler = new LogStreamHandler(this, // Project.MSG_INFO, Project.MSG_WARN) { // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // /* (non-Javadoc) // * @see org.apache.tools.ant.taskdefs.PumpStreamHandler#createProcessOutputPump(java.io.InputStream, java.io.OutputStream) // */ // protected void createProcessErrorPump(InputStream is, // OutputStream os) { // super.createProcessErrorPump(is, baos); // } // // /* (non-Javadoc) // * @see org.apache.tools.ant.taskdefs.LogStreamHandler#stop() // */ // public void stop() { // byte[] written = baos.toByteArray(); // System.err.print(new String(written)); // super.stop(); // } // }; Execute exe = new Execute(handler); exe.setAntRun(project); exe.setWorkingDirectory(project.getBaseDir()); exe.setCommandline(args); try { if (executingInOtherVM) { String s = "already running in other vm?"; throw new BuildException(s, location); } executingInOtherVM = true; exe.execute(); } finally { executingInOtherVM = false; } return exe.getExitValue(); } catch (IOException e) { String m = "Error executing command " + Arrays.asList(args); throw new BuildException(m, e, location); } } // ------------------------------ setup and reporting /** @return null if path null or empty, String rendition otherwise */ protected static void addFlaggedPath(String flag, Path path, List list) { if (!LangUtil.isEmpty(flag) && ((null != path) && (0 < path.size()))) { list.add(flag); list.add(path.toString()); } } /** * Add to list any path or plural arguments. */ protected void addListArgs(List list) throws BuildException { addFlaggedPath("-classpath", classpath, list); addFlaggedPath("-bootclasspath", bootclasspath, list); addFlaggedPath("-extdirs", extdirs, list); addFlaggedPath("-aspectpath", aspectpath, list); addFlaggedPath("-injars", injars, list); addFlaggedPath("-inpath", inpath, list); addFlaggedPath("-sourceroots", sourceRoots, list); if (argfiles != null) { String[] files = argfiles.list(); for (int i = 0; i < files.length; i++) { File argfile = project.resolveFile(files[i]); if (check(argfile, files[i], false, location)) { list.add("-argfile"); list.add(argfile.getAbsolutePath()); } } } if (srcdir != null) { // todo: ignore any srcdir if any argfiles and no explicit includes String[] dirs = srcdir.list(); for (int i = 0; i < dirs.length; i++) { File dir = project.resolveFile(dirs[i]); check(dir, dirs[i], true, location); // relies on compiler to prune non-source files String[] files = getDirectoryScanner(dir).getIncludedFiles(); for (int j = 0; j < files.length; j++) { File file = new File(dir, files[j]); if (FileUtil.hasSourceSuffix(file)) { list.add(file.getAbsolutePath()); } } } } if (0 < adapterFiles.size()) { for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) { File file = (File) iter.next(); if (file.canRead() && FileUtil.hasSourceSuffix(file)) { list.add(file.getAbsolutePath()); } else { this.logger.warning("skipping file: " + file); } } } } /** * Throw BuildException unless file is valid. * @param file the File to check * @param name the symbolic name to print on error * @param isDir if true, verify file is a directory * @param loc the Location used to create sensible BuildException * @return * @throws BuildException unless file valid */ protected final boolean check(File file, String name, boolean isDir, Location loc) { loc = loc != null ? loc : location; if (file == null) { throw new BuildException(name + " is null!", loc); } if (!file.exists()) { throw new BuildException(file + " doesn't exist!", loc); } if (isDir ^ file.isDirectory()) { String e = file + " should" + (isDir ? "" : "n't") + " be a directory!"; throw new BuildException(e, loc); } return true; } /** * Called when compile or incremental compile is completing, * this completes the output jar or directory * by copying resources if requested. * Note: this is a callback run synchronously by the compiler. * That means exceptions thrown here are caught by Main.run(..) * and passed to the message handler. */ protected void doCompletionTasks() { if (!executing) { throw new IllegalStateException("should be executing"); } if (null != outjar) { completeOutjar(); } else { completeDestdir(); } if (null != xdoneSignal) { MessageUtil.info(messageHolder, xdoneSignal); } } /** * Complete the destination directory * by copying resources from the source root directories * (if the filter is specified) * and non-.class files from the input jars * (if XCopyInjars is enabled). */ private void completeDestdir() { if (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter)) { return; } else if ((destDir == DEFAULT_DESTDIR) || !destDir.canWrite()) { String s = "unable to copy resources to destDir: " + destDir; throw new BuildException(s); } final Project project = getProject(); if (copyInjars) { // XXXX remove as unused since 1.1.1 if (null != inpath) { log("copyInjars does not support inpath.\n", Project.MSG_WARN); } String taskName = getTaskName() + " - unzip"; String[] paths = injars.list(); if (!LangUtil.isEmpty(paths)) { PatternSet patternSet = new PatternSet(); patternSet.setProject(project); patternSet.setIncludes("**/*"); patternSet.setExcludes("**/*.class"); for (int i = 0; i < paths.length; i++) { Expand unzip = new Expand(); unzip.setProject(project); unzip.setTaskName(taskName); unzip.setDest(destDir); unzip.setSrc(new File(paths[i])); unzip.addPatternset(patternSet); unzip.execute(); } } } if ((null != sourceRootCopyFilter) && (null != sourceRoots)) { String[] paths = sourceRoots.list(); if (!LangUtil.isEmpty(paths)) { Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destDir); for (int i = 0; i < paths.length; i++) { FileSet fileSet = new FileSet(); fileSet.setDir(new File(paths[i])); fileSet.setIncludes("**/*"); fileSet.setExcludes(sourceRootCopyFilter); copy.addFileset(fileSet); } copy.execute(); } } if ((null != inpathDirCopyFilter) && (null != inpath)) { String[] paths = inpath.list(); if (!LangUtil.isEmpty(paths)) { Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destDir); boolean gotDir = false; for (int i = 0; i < paths.length; i++) { File inpathDir = new File(paths[i]); if (inpathDir.isDirectory() && inpathDir.canRead()) { if (!gotDir) { gotDir = true; } FileSet fileSet = new FileSet(); fileSet.setDir(inpathDir); fileSet.setIncludes("**/*"); fileSet.setExcludes(inpathDirCopyFilter); copy.addFileset(fileSet); } } if (gotDir) { copy.execute(); } } } } /** * Complete the output jar * by copying resources from the source root directories * if the filter is specified. * and non-.class files from the input jars if enabled. */ private void completeOutjar() { if (((null == tmpOutjar) || !tmpOutjar.canRead()) || (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter))) { return; } Zip zip = new Zip(); Project project = getProject(); zip.setProject(project); zip.setTaskName(getTaskName() + " - zip"); zip.setDestFile(outjar); ZipFileSet zipfileset = new ZipFileSet(); zipfileset.setProject(project); zipfileset.setSrc(tmpOutjar); zipfileset.setIncludes("**/*.class"); zip.addZipfileset(zipfileset); if (copyInjars) { String[] paths = injars.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File jarFile = new File(paths[i]); zipfileset = new ZipFileSet(); zipfileset.setProject(project); zipfileset.setSrc(jarFile); zipfileset.setIncludes("**/*"); zipfileset.setExcludes("**/*.class"); zip.addZipfileset(zipfileset); } } } if ((null != sourceRootCopyFilter) && (null != sourceRoots)) { String[] paths = sourceRoots.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File srcRoot = new File(paths[i]); FileSet fileset = new FileSet(); fileset.setProject(project); fileset.setDir(srcRoot); fileset.setIncludes("**/*"); fileset.setExcludes(sourceRootCopyFilter); zip.addFileset(fileset); } } } if ((null != inpathDirCopyFilter) && (null != inpath)) { String[] paths = inpath.list(); if (!LangUtil.isEmpty(paths)) { for (int i = 0; i < paths.length; i++) { File inpathDir = new File(paths[i]); if (inpathDir.isDirectory() && inpathDir.canRead()) { FileSet fileset = new FileSet(); fileset.setProject(project); fileset.setDir(inpathDir); fileset.setIncludes("**/*"); fileset.setExcludes(inpathDirCopyFilter); zip.addFileset(fileset); } } } } zip.execute(); } // -------------------------- compiler adapter interface extras /** * Add specified source files. */ void addFiles(File[] paths) { for (int i = 0; i < paths.length; i++) { addFile(paths[i]); } } /** * Add specified source file. */ void addFile(File path) { if (null != path) { adapterFiles.add(path); } } /** * Read arguments in as if from a command line, * mainly to support compiler adapter compilerarg subelement. * * @param args the String[] of arguments to read */ public void readArguments(String[] args) { // XXX slow, stupid, unmaintainable if ((null == args) || (0 == args.length)) { return; } /** String[] wrapper with increment, error reporting */ class Args { final String[] args; int index = 0; Args(String[] args) { this.args = args; // not null or empty } boolean hasNext() { return index < args.length; } String next() { String err = null; if (!hasNext()) { err = "need arg for flag " + args[args.length-1]; } else { String s = args[index++]; if (null == s) { err = "null value"; } else { s = s.trim(); if (0 == s.trim().length()) { err = "no value"; } else { return s; } } } err += " at [" + index + "] of " + Arrays.asList(args); throw new BuildException(err); } } // class Args Args in = new Args(args); String flag; while (in.hasNext()) { flag = in.next(); if ("-1.3".equals(flag)) { setCompliance(flag); } else if ("-1.4".equals(flag)) { setCompliance(flag); } else if ("-1.5".equals(flag)) { setCompliance("1.5"); } else if ("-argfile".equals(flag)) { setArgfiles(new Path(project, in.next())); } else if ("-aspectpath".equals(flag)) { setAspectpath(new Path(project, in.next())); } else if ("-classpath".equals(flag)) { setClasspath(new Path(project, in.next())); } else if ("-extdirs".equals(flag)) { setExtdirs(new Path(project, in.next())); } else if ("-Xcopyinjars".equals(flag)) { setCopyInjars(true); // ignored - will be flagged by setter } else if ("-g".equals(flag)) { setDebug(true); } else if (flag.startsWith("-g:")) { setDebugLevel(flag.substring(2)); } else if ("-deprecation".equals(flag)) { setDeprecation(true); } else if ("-d".equals(flag)) { setDestdir(new File(in.next())); } else if ("-crossrefs".equals(flag)) { setCrossrefs(true); } else if ("-emacssym".equals(flag)) { setEmacssym(true); } else if ("-encoding".equals(flag)) { setEncoding(in.next()); } else if ("-Xfailonerror".equals(flag)) { setFailonerror(true); } else if ("-fork".equals(flag)) { setFork(true); } else if ("-forkclasspath".equals(flag)) { setForkclasspath(new Path(project, in.next())); } else if ("-help".equals(flag)) { setHelp(true); } else if ("-incremental".equals(flag)) { setIncremental(true); } else if ("-injars".equals(flag)) { setInjars(new Path(project, in.next())); } else if ("-inpath".equals(flag)) { setInpath(new Path(project,in.next())); } else if ("-Xlistfileargs".equals(flag)) { setListFileArgs(true); } else if ("-Xmaxmem".equals(flag)) { setMaxmem(in.next()); } else if ("-Xmessageholderclass".equals(flag)) { setMessageHolderClass(in.next()); } else if ("-noexit".equals(flag)) { setNoExit(true); } else if ("-noimport".equals(flag)) { setNoExit(true); } else if ("-noExit".equals(flag)) { setNoExit(true); } else if ("-noImportError".equals(flag)) { setNoImportError(true); } else if ("-noWarn".equals(flag)) { setNowarn(true); } else if ("-noexit".equals(flag)) { setNoExit(true); } else if ("-outjar".equals(flag)) { setOutjar(new File(in.next())); } else if ("-outxml".equals(flag)) { setOutxml(true); } else if ("-outxmlfile".equals(flag)) { setOutxmlfile(in.next()); } else if ("-preserveAllLocals".equals(flag)) { setPreserveAllLocals(true); } else if ("-proceedOnError".equals(flag)) { setProceedOnError(true); } else if ("-referenceInfo".equals(flag)) { setReferenceInfo(true); } else if ("-source".equals(flag)) { setSource(in.next()); } else if ("-Xsourcerootcopyfilter".equals(flag)) { setSourceRootCopyFilter(in.next()); } else if ("-sourceroots".equals(flag)) { setSourceRoots(new Path(project, in.next())); } else if ("-Xsrcdir".equals(flag)) { setSrcDir(new Path(project, in.next())); } else if ("-Xtagfile".equals(flag)) { setTagFile(new File(in.next())); } else if ("-target".equals(flag)) { setTarget(in.next()); } else if ("-time".equals(flag)) { setTime(true); } else if ("-time".equals(flag)) { setTime(true); } else if ("-verbose".equals(flag)) { setVerbose(true); } else if ("-showWeaveInfo".equals(flag)) { setShowWeaveInfo(true); } else if ("-version".equals(flag)) { setVersion(true); } else if ("-warn".equals(flag)) { setWarn(in.next()); } else if (flag.startsWith("-warn:")) { setWarn(flag.substring(6)); } else if ("-Xlint".equals(flag)) { setXlintwarnings(true); } else if (flag.startsWith("-Xlint:")) { setXlint(flag.substring(7)); } else if ("-Xlintfile".equals(flag)) { setXlintfile(new File(in.next())); } else if ("-Xnoweave".equals(flag)) { setXNoweave(true); } else if ("-Xreweavable".equals(flag)) { setXReweavable(true); } else if ("-XnotReweavable".equals(flag)) { setXNotReweavable(true); } else if (flag.startsWith("@")) { File file = new File(flag.substring(1)); if (file.canRead()) { setArgfiles(new Path(project, file.getPath())); } else { ignore(flag); } } else { File file = new File(flag); if (file.isFile() && file.canRead() && FileUtil.hasSourceSuffix(file)) { addFile(file); } else { ignore(flag); } } } } protected void logVerbose(String text) { if (this.verbose) { this.logger.info(text); } else { this.logger.verbose(text); } } /** * Commandline wrapper that * only permits addition of non-empty values * and converts to argfile form if necessary. */ public static class GuardedCommand { Commandline command; //int size; static boolean isEmpty(String s) { return ((null == s) || (0 == s.trim().length())); } GuardedCommand() { command = new Commandline(); } void addFlag(String flag, boolean doAdd) { if (doAdd && !isEmpty(flag)) { command.createArgument().setValue(flag); //size += 1 + flag.length(); } } /** @return null if added or ignoreString otherwise */ String addOption(String prefix, String[] validOptions, String input) { if (isEmpty(input)) { return null; } for (int i = 0; i < validOptions.length; i++) { if (input.equals(validOptions[i])) { if (isEmpty(prefix)) { addFlag(input, true); } else { addFlagged(prefix, input); } return null; } } return (null == prefix ? input : prefix + " " + input); } void addFlagged(String flag, String argument) { if (!isEmpty(flag) && !isEmpty(argument)) { command.addArguments(new String[] {flag, argument}); //size += 1 + flag.length() + argument.length(); } } // private void addFile(File file) { // if (null != file) { // String path = file.getAbsolutePath(); // addFlag(path, true); // } // } List extractArguments() { ArrayList result = new ArrayList(); String[] cmds = command.getArguments(); if (!LangUtil.isEmpty(cmds)) { result.addAll(Arrays.asList(cmds)); } return result; } /** * Adjust args for size if necessary by creating * an argument file, which should be deleted by the client * after the compiler run has completed. * @param max the int maximum length of the command line (in char) * @return the temp File for the arguments (if generated), * for deletion when done. * @throws IllegalArgumentException if max is negative */ static String[] limitTo(String[] args, int max, Location location) { if (max < 0) { throw new IllegalArgumentException("negative max: " + max); } // sigh - have to count anyway for now int size = 0; for (int i = 0; (i < args.length) && (size < max); i++) { size += 1 + (null == args[i] ? 0 : args[i].length()); } if (size <= max) { return args; } File tmpFile = null; PrintWriter out = null; // adapted from DefaultCompilerAdapter.executeExternalCompile try { String userDirName = System.getProperty("user.dir"); File userDir = new File(userDirName); tmpFile = File.createTempFile("argfile", "", userDir); out = new PrintWriter(new FileWriter(tmpFile)); for (int i = 0; i < args.length; i++) { out.println(args[i]); } out.flush(); return new String[] {"-argfile", tmpFile.getAbsolutePath()}; } catch (IOException e) { throw new BuildException("Error creating temporary file", e, location); } finally { if (out != null) { try {out.close();} catch (Throwable t) {} } } } } private static class AntMessageHandler implements IMessageHandler { private TaskLogger logger; private final boolean taskLevelVerbose; private final boolean handledMessage; public AntMessageHandler(TaskLogger logger, boolean taskVerbose, boolean handledMessage) { this.logger = logger; this.taskLevelVerbose = taskVerbose; this.handledMessage = handledMessage; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage) */ public boolean handleMessage(IMessage message) throws AbortException { Kind messageKind = message.getKind(); String messageText = message.toString(); if (messageKind == IMessage.ABORT) { this.logger.error(messageText); } else if (messageKind == IMessage.DEBUG) { this.logger.debug(messageText); } else if (messageKind == IMessage.ERROR) { this.logger.error(messageText); } else if (messageKind == IMessage.FAIL){ this.logger.error(messageText); } else if (messageKind == IMessage.INFO) { if (this.taskLevelVerbose) { this.logger.info(messageText); } else { this.logger.verbose(messageText); } } else if (messageKind == IMessage.WARNING) { this.logger.warning(messageText); } else if (messageKind == IMessage.WEAVEINFO) { this.logger.info(messageText); } else if (messageKind == IMessage.TASKTAG) { // ignore } else { throw new BuildException("Unknown message kind from AspectJ compiler: " + messageKind.toString()); } return handledMessage; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) */ public boolean isIgnoring(Kind kind) { return false; } /* (non-Javadoc) * @see org.aspectj.bridge.IMessageHandler#dontIgnore(org.aspectj.bridge.IMessage.Kind) */ public void dontIgnore(Kind kind) { } } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
taskdefs/testsrc/org/aspectj/tools/ant/taskdefs/AjcTaskTest.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC) * 2003 Contributors. * 2005 Contributors * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * IBM ongoing maintenance * ******************************************************************/ package org.aspectj.tools.ant.taskdefs; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.jar.JarEntry; import java.util.jar.JarFile; import junit.framework.TestCase; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Location; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.selectors.FilenameSelector; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; /** * AjcTask test cases. * Please put new ones with others between ------- comments. * * Some API tests, but mostly functional tests driving * the task execute using data in ../taskdefs/testdata. * This will re-run in forked mode for any nonfailing * compile if aspectjtools-dist is built into * ../aj-build/dist/tools/lib/aspectjtools.jar. */ public class AjcTaskTest extends TestCase { private static final Class NO_EXCEPTION = null; private static final String NOFILE = "NOFILE"; private static final File tempDir; private static final String aspectjtoolsJar; private static final String testdataDir; private static final StringBuffer MESSAGES = new StringBuffer(); /** accept writable .class files */ private static FileFilter PICK_CLASS_FILES; static { tempDir = new File("IncrementalAjcTaskTest-temp"); String toolsPath = "../aj-build/dist/tools/lib/aspectjtools.jar"; File toolsjar = new File(toolsPath); if (toolsjar.canRead()) { aspectjtoolsJar = toolsjar.getAbsolutePath(); } else { aspectjtoolsJar = null; String s = "AjcTaskTest not forking - build aspectjtools-dist to get " + toolsPath; System.out.println(s); } File dir = new File("../taskdefs/testdata"); if (dir.canRead() && dir.isDirectory()) { testdataDir = dir.getAbsolutePath(); } else { testdataDir = null; } PICK_CLASS_FILES = new FileFilter() { public boolean accept(File file) { return ( (null != file) && file.isFile() && file.canWrite() && file.getPath().endsWith(".class")); } }; } /** * Check that aspectjtools are found on the classpath, * reporting any errors to System.err. * * Run multiple times with different classpaths. * This should find variants * aspectjtools.jar, * aspectj-tools.jar, * aspectj-tools-1.1.jar, and * aspectjtools-1.0.6.jar * but not * aspectjrt.jar or * aspectj/tools.jar. * XXX use testing aspect to stub out * <code>System.getProperty("java.class.path")</code> * @param args a String[], first is expected path, if any */ public static void main(String[] args) { java.io.File toolsjar = AjcTask.findAspectjtoolsJar(); if ((null == args) || (0 == args.length)) { if (null != toolsjar) { System.err.println("FAIL - not expected: " + toolsjar); } } else if ("-help".equals(args[0])) { System.out.println( "java " + AjcTaskTest.class.getName() + " <expectedPathToAspectjtoolsJar>"); } else if (null == toolsjar) { System.err.println("FAIL - expected: " + args[0]); } else { String path = toolsjar.getAbsolutePath(); if (!path.equals(args[0])) { System.err.println( "FAIL - expected: " + args[0] + " actual: " + path); } } } public static void collectMessage(String s) { MESSAGES.append(s); } private static void deleteTempDir() { if ((null != tempDir) && tempDir.exists()) { FileUtil.deleteContents(tempDir); tempDir.delete(); // when tempDir not used... if (null != testdataDir) { File dataDir = new File(testdataDir); if (dataDir.canRead()) { FileUtil.deleteContents(dataDir, PICK_CLASS_FILES, false); } } } } private static final File getTempDir() { return tempDir; } public AjcTaskTest(String name) { super(name); } public void tearDown() { deleteTempDir(); MESSAGES.setLength(0); } private void checkRun(AjcTask task, String exceptionString) { try { task.execute(); assertTrue(null == exceptionString); } catch (BuildException e) { if (null == exceptionString) { assertTrue("unexpected " + e.getMessage(), false); } else { String m = e.getMessage(); if (null == m) { assertTrue("not " + exceptionString, false); } else if (-1 == m.indexOf(exceptionString)) { assertEquals(exceptionString, e.getMessage()); } } } } private void checkContains(String[] cmd, String option, boolean contains) { for (int i = 0; i < cmd.length; i++) { if (option.equals(cmd[i])) { if (contains) { return; } else { assertTrue( "not expecting " + option + " in " + Arrays.asList(cmd), false); } } } if (contains) { assertTrue( "expecting " + option + " in " + Arrays.asList(cmd), false); } } protected AjcTask getTask(String input) { return getTask(input, getTempDir()); } protected AjcTask getTask(String input, File destDir) { AjcTask task = new AjcTask(); Project p = new Project(); task.setProject(p); if (null != destDir) { task.setDestdir(destDir); } if (NOFILE.equals(input)) { // add nothing } else if (input.endsWith(".lst")) { if (-1 != input.indexOf(",")) { throw new IllegalArgumentException( "lists not supported: " + input); } else if (null == testdataDir) { throw new Error("testdata not found - run in ../taskdefs"); } else { String path = testdataDir + File.separator + input; task.setArgfiles(new Path(task.getProject(), path)); } } else if ((input.endsWith(".java") || input.endsWith(".aj"))) { FilenameSelector fns = new FilenameSelector(); fns.setName(input); task.addFilename(fns); } else { String path = testdataDir + File.separator + input; task.setSourceRoots(new Path(task.getProject(), path)); } task.setClasspath(new Path(p, "../lib/test/aspectjrt.jar")); return task; } /** used in testMessageHolderClassName */ public static class InfoHolder extends MessageHandler { public InfoHolder() { } public boolean handleMessage(IMessage message) { if (0 == IMessage.INFO.compareTo(message.getKind())) { AjcTaskTest.collectMessage(message.getMessage()); } return true; } } /** used in testMessageHolderClassName */ public static class Holder extends MessageHandler { public Holder() { } public boolean handleMessage(IMessage message) { IMessage.Kind kind = message.getKind(); if (IMessage.ERROR.isSameOrLessThan(kind)) { String m = kind.toString(); AjcTaskTest.collectMessage(m.substring(0, 1)); } return true; } } // ------------------------------------------------------ // ------------------------------------------------------ // ------------------------------------------------------ // ------------------------------------------------------ // ------------------------------------------------------ // ------------------------------------------------------ // Start of test cases public void testNullDestDir() { AjcTask task = getTask(NOFILE, null); String[] cmd = task.makeCommand(); for (int i = 0; i < cmd.length; i++) { assertTrue(!"-d".equals(cmd[i])); } } public void testOutputRequirement() { AjcTask task = getTask("default.lst"); checkRun(task, null); // copyInJars now just emits warning b/c unused task = getTask("default.lst", null); task.setCopyInjars(true); checkRun(task, null); // sourceRootCopyFilter requires destDir task = getTask("default.lst", null); task.setSourceRootCopyFilter("**/*.java"); checkRun(task, "sourceRoot"); } public void testSourceRootCopyFilter() { // sourceRootCopyFilter works.. File destDir = getTempDir(); assertTrue( "unable to create " + destDir, destDir.canRead() || destDir.mkdirs()); AjcTask task = getTask("sourceroot", destDir); task.setSourceRootCopyFilter("doNotCopy,**/*.txt"); File file = new File(destDir, "Default.java").getAbsoluteFile(); assertTrue(file + ".canRead() prematurely", !file.canRead()); checkRun(task, null); // got expected resources assertTrue(file + ".canRead() failed", file.canRead()); File pack = new File(destDir, "pack"); file = new File(pack, "Pack.java").getAbsoluteFile(); assertTrue(file + ".canRead() failed", file.canRead()); file = new File(pack, "includeme").getAbsoluteFile(); assertTrue(file + ".canRead() failed", file.canRead()); // didn't get unexpected resources file = new File(pack, "something.txt"); assertTrue(file + ".canRead() passed", !file.canRead()); file = new File(destDir, "doNotCopy"); assertTrue(file + ".canRead() passed", !file.canRead()); file = new File(destDir, "skipTxtFiles.txt"); assertTrue(file + ".canRead() passed", !file.canRead()); } public void testInpathDirCopyFilter() { // inpathDirCopyFilter works with output directory File destDir = getTempDir(); assertTrue( "unable to create " + destDir, destDir.canRead() || destDir.mkdirs()); AjcTask task = getTask(NOFILE, destDir); Project p = task.getProject(); Path indirs = new Path(p); File dir = new File(testdataDir, "inpathDirs").getAbsoluteFile(); indirs.addExisting(new Path(p, new File(dir, "inpathDirOne").getAbsolutePath())); indirs.addExisting(new Path(p, new File(dir, "inpathDirTwo").getAbsolutePath())); task.setInpath(indirs); task.setInpathDirCopyFilter("doNotCopy,**/*.txt"); File file = new File(destDir, "Default.java").getAbsoluteFile(); assertTrue(file + ".canRead() prematurely", !file.canRead()); checkRun(task, null); // got expected resources File pack = new File(destDir, "pack"); file = new File(pack, "includeme").getAbsoluteFile(); assertTrue(file + ".canRead() failed", file.canRead()); file = new File(pack, "Pack.class").getAbsoluteFile(); assertTrue(file + ".canRead() failed", file.canRead()); file = new File(destDir, "copyMe.htm").getAbsoluteFile(); assertTrue(file + ".canRead() failed", file.canRead()); file = new File(destDir, "Default.class").getAbsoluteFile(); assertTrue(file + ".canRead() failed", file.canRead()); // didn't get unexpected resources file = new File(pack, "something.txt"); assertTrue(file + ".canRead() passed", !file.canRead()); file = new File(destDir, "doNotCopy"); assertTrue(file + ".canRead() passed", !file.canRead()); file = new File(destDir, "skipTxtFiles.txt"); assertTrue(file + ".canRead() passed", !file.canRead()); } public void testInpathDirCopyFilterWithJar() throws IOException { // inpathDirCopyFilter works with output jar File destDir = getTempDir(); assertTrue( "unable to create " + destDir, destDir.canRead() || destDir.mkdirs()); AjcTask task = getTask(NOFILE, null); File destJar = new File(destDir, "testInpathDirCopyFilterWithJar-out.jar"); task.setOutjar(destJar); Project p = task.getProject(); Path indirs = new Path(p); File dir = new File(testdataDir, "inpathDirs").getAbsoluteFile(); indirs.addExisting(new Path(p, new File(dir, "inpathDirOne").getAbsolutePath())); indirs.addExisting(new Path(p, new File(dir, "inpathDirTwo").getAbsolutePath())); task.setInpath(indirs); task.setInpathDirCopyFilter("doNotCopy,**/*.txt,**/*.class"); checkRun(task, null); JarFile jarFile = new JarFile(destJar); String[] expected = {"copyMe.htm", "pack/includeme", "pack/Pack.class", "Default.class"}; String[] unexpected = {"doNotCopy", "skipTxtFiles.txt", "pack/something.txt"}; for (int i = 0; i < expected.length; i++) { JarEntry entry = jarFile.getJarEntry(expected[i]); assertTrue(expected[i] + " not found", null != entry); } for (int i = 0; i < unexpected.length; i++) { JarEntry entry = jarFile.getJarEntry(unexpected[i]); assertTrue(unexpected[i] + " found", null == entry); } } public void testInpathDirCopyFilterError() { // inpathDirCopyFilter fails with no output directory or jar iff specified AjcTask task = getTask(NOFILE, null); Project p = task.getProject(); Path indirs = new Path(p); File dir = new File(testdataDir, "inpathDirs").getAbsoluteFile(); indirs.addExisting(new Path(p, new File(dir, "inpathDirOne").getAbsolutePath())); indirs.addExisting(new Path(p, new File(dir, "inpathDirTwo").getAbsolutePath())); task.setInpath(indirs); task.setInpathDirCopyFilter("doNotCopy,**/*.txt,**/*.class"); // expecting error checkRun(task, "inpathDirCopyFilter"); } // this test method submitted by patch from Andrew Huff (IBM) // verifies that the log attribute of AjcTask writes output to the given log file public void testLoggingMode() { AjcTask task = getTask("default.lst"); task.setFailonerror(false); File logFile = new File("testLogFile1.txt"); String s = logFile.getAbsolutePath(); logFile.delete(); long initialLength = logFile.length(); task.setLog(logFile); runTest(task,null,null); long newLength = logFile.length(); assertTrue(newLength > initialLength); logFile.delete(); } public void testCommandEditor() { String className = VerboseCommandEditor.class.getName(); System.setProperty(AjcTask.COMMAND_EDITOR_NAME, className); assertEquals( className, System.getProperty(AjcTask.COMMAND_EDITOR_NAME)); AjcTask task = getTask(NOFILE); task.setCommandEditor(new VerboseCommandEditor()); String[] cmd = task.makeCommand(); assertEquals(VerboseCommandEditor.VERBOSE, cmd[0]); task = getTask(NOFILE); task.setCommandEditorClass(VerboseCommandEditor.class.getName()); cmd = task.makeCommand(); assertEquals(VerboseCommandEditor.VERBOSE, cmd[0]); } // public void testStaticCommandEditor() { // // XXX need to test COMMAND_EDITOR, but can't require property when run // } public void testLimitTo() { int numArgs = 100; String arg = "123456789"; String[] args = new String[numArgs]; for (int i = 0; i < args.length; i++) { args[i] = arg; } // no limit int max = numArgs * (arg.length() + 1); Location location = new Location("AjcTaskTest.java"); String[] newArgs = AjcTask.GuardedCommand.limitTo(args, max, location); assertTrue("same", args == newArgs); // limited - read file and verify arguments max--; newArgs = AjcTask.GuardedCommand.limitTo(args, max, location); assertTrue("not same", args != newArgs); assertTrue("not null", null != newArgs); String label = "newArgs " + Arrays.asList(newArgs); assertTrue("size 2" + label, 2 == newArgs.length); assertEquals("-argfile", newArgs[0]); File file = new File(newArgs[1]); assertTrue("readable newArgs[1]" + label, file.canRead()); FileReader fin = null; try { fin = new FileReader(file); BufferedReader reader = new BufferedReader(fin); String line; int i = 0; while (null != (line = reader.readLine())) { assertEquals(i + ": ", args[i++], line); } assertEquals("num entries", i, args.length); } catch (IOException e) { assertTrue("IOException " + e.getMessage(), false); } finally { if (null != fin) { try { fin.close(); } catch (IOException e) { // ignore } } file.delete(); } } public void testFindAspectjtoolsJar() { File toolsJar = AjcTask.findAspectjtoolsJar(); if (null != toolsJar) { assertNull("tools jar found?: " + toolsJar, toolsJar); } // not found when unit testing b/c not on system classpath // so just checking for exceptions. // XXX need aspect to stub out System.getProperty(..) } public void testMessageHolderClassName() { AjcTask task = getTask("compileError.lst"); task.setFailonerror(false); MESSAGES.setLength(0); runTest( task, null, MessageHolderChecker.ONE_ERROR, Holder.class.getName()); String result = MESSAGES.toString(); MESSAGES.setLength(0); assertEquals("messages", "e", result); } // TODO skipped test - works locally but not on build machine? public void skip_testMessageHolderClassWithDoneSignal() { AjcTask task = getTask("default.lst"); task.setFailonerror(false); String DONE = "This is a unique message, not confused with others."; task.setXDoneSignal(DONE); MESSAGES.setLength(0); runTest( task, null, MessageHolderChecker.INFOS, InfoHolder.class.getName()); final String result = MESSAGES.toString(); String temp = new String(result); MESSAGES.setLength(0); if (!temp.endsWith(DONE)) { if (temp.length() > 20) { temp = "..." + temp.substring(temp.length()-20, temp.length()); } assertTrue(DONE + " is not suffix of \"" + temp + "\"", false); } // exactly one such message temp = new String(result); temp = temp.substring(0, temp.length()-DONE.length()); if (temp.endsWith(DONE)) { temp = new String(result); if (temp.length() > 20) { temp = "..." + temp.substring(temp.length()-20, temp.length()); } assertTrue(DONE + " signalled twice: \"" + temp + "\"", false); } } public void testDefaultListForkedNoTools() { AjcTask task = getTask("default.lst"); task.setFork(true); boolean passed = false; try { runTest(task, BuildException.class, MessageHolderChecker.NONE); passed = true; } finally { if (!passed) { String m = "AjcTaskTest.testDefaultListForkedNoTools()" + " fails if aspectjtools.jar is on the classpath"; System.err.println(m); } } } public void testDefaultListForkedIncremental() { AjcTask task = getTask("default.lst"); task.setFork(true); task.setIncremental(true); runTest(task, BuildException.class, MessageHolderChecker.NONE); } /** failonerror should default to true, unlike other booleans */ public void testCompileErrorFailOnErrorDefault() { AjcTask task = getTask("compileError.lst"); final PrintStream serr = System.err; try { System.setErr(new PrintStream(new java.io.ByteArrayOutputStream())); runTest(task, BuildException.class, MessageHolderChecker.ONE_ERROR); } finally { System.setErr(serr); } } public void testCompileErrorListDefaultHolder() { AjcTask task = getTask("compileError.lst"); final PrintStream serr = System.err; try { System.setErr(new PrintStream(new java.io.ByteArrayOutputStream())); task.execute(); fail("expected BuildException from failed compile by default"); } catch (BuildException t) { // ok } finally { System.setErr(serr); deleteTempDir(); } } public void testDefaultList() { AjcTask task = getTask("default.lst"); runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS); } public void testCompileErrorList() { AjcTask task = getTask("compileError.lst"); task.setFailonerror(false); runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR); } public void testShowWeaveInfo() { AjcTask task = getTask("showweaveinfo.lst"); task.setShowWeaveInfo(true); MessageHandler mh = new MessageHandler(false); mh.dontIgnore(IMessage.WEAVEINFO); MessageHolderChecker mhc = new MessageHolderChecker(0,0,0,0,MessageHolderChecker.IGNORE); mhc.weaveinfos = 2; // Expect 2 weaving messages runTest(task,NO_EXCEPTION,mhc); mhc.weaveinfos = MessageHolderChecker.IGNORE; } public void testCompileWarningList() { AjcTask task = getTask("compileWarning.lst"); runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_WARNING); } public void testNoSuchFileList() { AjcTask task = getTask("NoSuchFile.lst"); task.setFailonerror(false); runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT); } public void testVersions() { String[] inputs = AjcTask.TARGET_INPUTS; for (int i = 0; i < inputs.length; i++) { AjcTask task = getTask(NOFILE); task.setTarget(inputs[i]); String[] cmd = task.makeCommand(); checkContains(cmd, "-target", true); checkContains(cmd, inputs[i], true); } inputs = AjcTask.SOURCE_INPUTS; for (int i = 0; i < inputs.length; i++) { AjcTask task = getTask(NOFILE); task.setSource(inputs[i]); String[] cmd = task.makeCommand(); checkContains(cmd, "-source", true); checkContains(cmd, inputs[i], true); } inputs = AjcTask.COMPLIANCE_INPUTS; for (int i = 0; i < inputs.length; i++) { AjcTask task = getTask(NOFILE); task.setCompliance(inputs[i]); String[] cmd = task.makeCommand(); checkContains(cmd, inputs[i], true); } } public void testClasspath() { AjcTask task = getTask(NOFILE); String[] cmd = task.makeCommand(); checkContains(cmd, "-bootclasspath", false); String classpath = null; for (int i = 0; i < cmd.length; i++) { if ("-classpath".equals(cmd[i])) { classpath = cmd[i + 1]; break; } } assertTrue( "expecting aspectj in classpath", (-1 != classpath.indexOf("aspectjrt.jar"))); } // ---------------------------------------- sourcefile // XXX need to figure out how to specify files directly programmatically // public void testDefaultFile() { // AjcTask task = getTask("testdata/Default.java"); // runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS); // } public void testNoFile() { AjcTask task = getTask(NOFILE); task.setFailonerror(false); runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT); } public void testCompileErrorFile() { AjcTask task = getTask("compileError.lst"); task.setFailonerror(false); runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR); } public void testCompileWarningFile() { AjcTask task = getTask("compileWarning.lst"); task.setFailonerror(false); runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_WARNING); } public void testNoSuchFile() { AjcTask task = getTask("NoSuchFile.lst"); task.setFailonerror(false); runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT); } public void testDefaultFileComplete() { AjcTask task = getTask("default.lst"); task.setDebugLevel("none"); task.setDeprecation(true); task.setFailonerror(false); task.setNoExit(true); // ok to override Ant? task.setNoImportError(true); task.setNowarn(true); task.setXNoweave(true); task.setPreserveAllLocals(true); task.setProceedOnError(true); task.setReferenceInfo(true); task.setSource("1.3"); task.setTarget("1.1"); task.setTime(true); task.setVerbose(true); task.setXlint("info"); runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS); } public void testXOptions() { String[] xopts = new String[] { "serializableAspects", "lazyTjp", "reweavable", "reweavable:compress", "noInline" }; for (int i = 0; i < xopts.length; i++) { AjcTask task = getTask(NOFILE); task.setX(xopts[i]); String[] cmd = task.makeCommand(); checkContains(cmd,"-X" + xopts[i],true); } } public void testOutxml () { File destDir = getTempDir(); assertTrue( "unable to create " + destDir, destDir.canRead() || destDir.mkdirs()); AjcTask task = getTask("showweaveinfo.lst",destDir); task.setOutxml(true); checkRun(task,null); File outxmlFile = new File(destDir,"META-INF/aop.xml"); assertTrue("META-INF/aop.xml missing",outxmlFile.exists()); } public void testOutxmlFile () { String customName = "custom/aop.xml"; File destDir = getTempDir(); assertTrue( "unable to create " + destDir, destDir.canRead() || destDir.mkdirs()); AjcTask task = getTask("showweaveinfo.lst",destDir); task.setOutxmlfile(customName); checkRun(task,null); File outxmlFile = new File(destDir,customName); assertTrue(customName + " missing",outxmlFile.exists()); } // End of test cases // ------------------------------------------------------ // ------------------------------------------------------ // ------------------------------------------------------ // ------------------------------------------------------ // ------------------------------------------------------ // ------------------------------------------------------ protected void runTest( AjcTask task, Class exceptionType, MessageHolderChecker checker, String messageHolderClass) { task.setMessageHolderClass(messageHolderClass); runTest(task, exceptionType, checker, (MessageHandler) null); } protected void runTest( AjcTask task, Class exceptionType, MessageHolderChecker checker) { MessageHandler holder = new MessageHandler(); task.setMessageHolder(holder); runTest(task, exceptionType, checker, holder); } protected void runTest( AjcTask task, Class exceptionType, MessageHolderChecker checker, MessageHandler holder) { Throwable thrown = null; // re-run forked iff tools.jar and expect to pass boolean rerunForked = ((null != aspectjtoolsJar) && (null == exceptionType) && ((null == checker) || !checker.expectFail())); String label = "same-vm "; while (true) { // same vm, then perhaps forked try { task.execute(); } catch (Throwable t) { thrown = t; } finally { deleteTempDir(); } if (null == exceptionType) { if (null != thrown) { assertTrue(label + "thrown: " + render(thrown), false); } } else if (null == thrown) { assertTrue( label + "expected " + exceptionType.getName(), false); } else if (!(exceptionType.isAssignableFrom(thrown.getClass()))) { assertTrue( label + "expected " + exceptionType.getName() + " got " + render(thrown), false); } if (null != holder) { if (null == checker) { checker = MessageHolderChecker.NONE; } checker.check(holder, label); } if (!rerunForked) { break; } else { label = "other-vm "; rerunForked = false; // can't reset without losing values... task.setFork(true); task.setFailonerror(true); task.setForkclasspath( new Path(task.getProject(), aspectjtoolsJar)); } } } protected String render(Throwable thrown) { return LangUtil.renderException(thrown); } static class MessageHolderChecker { // XXX export to testing-utils /** use as value to ignore results */ static int IGNORE = Integer.MIN_VALUE; static MessageHolderChecker NONE = new MessageHolderChecker(0, 0, 0, 0, 0); /** any number (0+) of info messages */ static MessageHolderChecker INFOS = new MessageHolderChecker(0, 0, 0, 0, IGNORE); /** one error, any number of info messages */ static MessageHolderChecker ONE_ERROR = new MessageHolderChecker(0, 0, 1, 0, IGNORE); static MessageHolderChecker ONE_ERROR_ONE_ABORT = new MessageHolderChecker(1, 0, 1, 0, IGNORE); /** one warning, any number of info messages */ static MessageHolderChecker ONE_WARNING = new MessageHolderChecker(0, 0, 0, 1, IGNORE); int aborts, fails, errors, warnings, infos; int weaveinfos; public MessageHolderChecker( int aborts, int fails, int errors, int warnings, int infos) { this.aborts = aborts; this.fails = fails; this.errors = errors; this.warnings = warnings; this.infos = infos; this.weaveinfos = IGNORE; } public boolean expectFail() { return (0 < (aborts + fails + errors)); } public void check(IMessageHolder holder, String label) { boolean failed = true; try { check(holder, aborts, IMessage.ABORT); check(holder, fails, IMessage.FAIL); check(holder, errors, IMessage.ERROR); check(holder, warnings, IMessage.WARNING); check(holder, infos, IMessage.INFO); check(holder, weaveinfos, IMessage.WEAVEINFO); failed = false; } finally { if (failed) { MessageUtil.print(System.err, holder, label + "failed?"); } } } private void check( IMessageHolder holder, int num, IMessage.Kind kind) { if (num != IGNORE) { int actual = holder.numMessages(kind, false); if (num != actual) { if (actual > 0) { MessageUtil.print( System.err, holder, kind + " expected " + num + " got " + actual); } assertEquals(kind.toString(), num, actual); } } } } } class SnoopingCommandEditor implements ICommandEditor { private static final String[] NONE = new String[0]; String[] lastCommand; public String[] editCommand(String[] command) { lastCommand = (String[]) LangUtil.safeCopy(command, NONE); return command; } public String[] lastCommand() { return (String[]) LangUtil.safeCopy(lastCommand, NONE); } } class VerboseCommandEditor implements ICommandEditor { public static final String VERBOSE = "-verbose"; public String[] editCommand(String[] command) { for (int i = 0; i < command.length; i++) { if (VERBOSE.equals(command[i])) { return command; } } String[] result = new String[1 + command.length]; result[0] = VERBOSE; System.arraycopy(result, 1, command, 0, command.length); return result; } } class AppendingCommandEditor implements ICommandEditor { private static String[] NONE = new String[0]; public static ICommandEditor VERBOSE = new AppendingCommandEditor(new String[] { "-verbose" }, NONE); public static ICommandEditor INVALID = new AppendingCommandEditor(NONE, new String[] { "-invalidOption" }); final String[] prefix; final String[] suffix; public AppendingCommandEditor(String[] prefix, String[] suffix) { this.prefix = prefix; this.suffix = suffix; } public String[] editCommand(String[] command) { int len = command.length + prefix.length + suffix.length; String[] result = new String[len]; System.arraycopy(result, 0, prefix, 0, prefix.length); System.arraycopy(result, prefix.length, command, 0, command.length); System.arraycopy( result, prefix.length + command.length, suffix, 0, suffix.length); return result; } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
testing/src/org/aspectj/testing/harness/bridge/CompilerRun.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC), * 2003 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * Wes Isberg 2003 updates * ******************************************************************/ package org.aspectj.testing.harness.bridge; import java.io.*; import java.util.*; import org.aspectj.bridge.*; import org.aspectj.testing.ajde.CompileCommand; import org.aspectj.testing.run.*; import org.aspectj.testing.taskdefs.AjcTaskCompileCommand; import org.aspectj.testing.util.options.*; import org.aspectj.testing.util.options.Option.*; import org.aspectj.testing.xml.*; import org.aspectj.util.*; /** * Run the compiler once. * The lifecycle is as follows: * <ul> * <li>Spec (specification) is created.</li> * <li>This is created using the Spec.</li> * <li>setupAjcRun(Sandbox, Validator) is invoked, * at which point this populates the shared sandbox * with values derived from the spec and also * sets up internal state based on both the sandbox * and the spec.</li> * <li>run(IRunStatus) is invoked, and this runs the compiler * based on internal state, the spec, and the sandbox.</li> * </ul> * Programmer notes: * <ul> * <li>Paths are resolved absolutely, which fails to test the * compiler's ability to find files relative to a source base</li> * <li>This does not enforce the lifecycle.</li> * <li>This must be used as the initial compile * before doing an incremental compile. * In that case, staging must be enabled.</li> * </ul> */ public class CompilerRun implements IAjcRun { // static final String JAVAC_COMPILER // = JavacCompileCommand.class.getName(); static final String[] RA_String = new String[0]; static final String[] JAR_SUFFIXES = new String[] { ".jar", ".zip" }; static final String[] SOURCE_SUFFIXES = (String[]) FileUtil.SOURCE_SUFFIXES.toArray(new String[0]); /** specifications, set on construction */ Spec spec; //------------ calculated during setup /** get shared stuff during setup */ Sandbox sandbox; /** * During run, these String are passed as the source and arg files to compile. * The list is set up in setupAjcRun(..), when arg files are prefixed with "@". */ final List /*String*/ arguments; /** * During run, these String are collapsed and passed as the injar option. * The list is set up in setupAjcRun(..). */ final List /*String*/ injars; /** * During run, these String are collapsed and passed as the inpath option. * The list is set up in setupAjcRun(..), * which extracts only directories from the files attribute. */ final List inpaths; private CompilerRun(Spec spec) { if (null == spec) { throw new IllegalArgumentException("null spec"); } this.spec = spec; arguments = new ArrayList(); injars = new ArrayList(); inpaths = new ArrayList(); } /** * This checks that the spec is reasonable and does setup: * <ul> * <li>calculate and set sandbox testBaseSrcDir as {Sandbox.testBaseDir}/ * {Spec.testSrcDirOffset}/<li> * <li>get the list of source File to compile as {Sandbox.testBaseSrcDir} / * {Spec.getPaths..}</li> * <li>get the list of extraClasspath entries to add to default classpath as * {Sandbox.testBaseSrcDir} / {Spec.classpath..}</li> * <li>get the list of aspectpath entries to use as the aspectpath as * {Sandbox. testBaseSrcDir} / {Spec.aspectpath..}</li> * </ul> * All sources must be readable at this time, * unless spec.badInput is true (for invalid-input tests). * If staging, the source files and source roots are copied * to a separate staging directory so they can be modified * for incremental tests. Note that (as of this writing) the * compiler only handles source roots for incremental tests. * @param classesDir the File * @see org.aspectj.testing.harness.bridge.AjcTest.IAjcRun#setup(File, File) * @throws AbortException containing IOException or IllegalArgumentException * if the staging operations fail */ public boolean setupAjcRun(Sandbox sandbox, Validator validator) { if (!validator.nullcheck(spec.getOptionsArray(), "localOptions") || !validator.nullcheck(sandbox, "sandbox") || !validator.nullcheck(spec.compiler, "compilerName") || !validator.canRead(Globals.F_aspectjrt_jar, "aspectjrt.jar") || !validator.canRead( Globals.F_testingclient_jar, "testing-client.jar")) { return false; } this.sandbox = sandbox; String rdir = spec.testSrcDirOffset; File testBaseSrcDir; if ((null == rdir) || (0 == rdir.length())) { testBaseSrcDir = sandbox.testBaseDir; } else { testBaseSrcDir = new File(sandbox.testBaseDir, rdir); // XXX what if rdir is two levels deep? if (!validator .canReadDir(testBaseSrcDir, "sandbox.testBaseSrcDir")) { return false; } } // Sources come as relative paths - check read, copy if staging. // This renders paths absolute before run(RunStatusI) is called. // For a compile run to support relative paths + source base, // change so the run calculates the paths (differently when staging) final String[] inpathPaths; final String[] injarPaths; final String[] srcPaths; { final String[] paths = spec.getPathsArray(); srcPaths = LangUtil.endsWith( paths, CompilerRun.SOURCE_SUFFIXES, true); injarPaths = LangUtil.endsWith(paths, CompilerRun.JAR_SUFFIXES, true); inpathPaths = LangUtil.selectDirectories(paths, testBaseSrcDir); if (!spec.badInput) { int found = inpathPaths.length + injarPaths.length + srcPaths.length; if (paths.length != found) { validator.fail("found " + found + " of " + paths.length + " sources"); } } } // validate readable for sources if (!spec.badInput) { if (!validator.canRead(testBaseSrcDir, srcPaths, "sources") // see validation of inpathPaths below due to ambiguous base dir || !validator.canRead( testBaseSrcDir, spec.argfiles, "argfiles") || !validator.canRead( testBaseSrcDir, spec.classpath, "classpath") || !validator.canRead( testBaseSrcDir, spec.aspectpath, "aspectpath") || !validator.canRead( testBaseSrcDir, spec.sourceroots, "sourceroots") || !validator.canRead( testBaseSrcDir, spec.extdirs, "extdirs")) { return false; } } int numSources = srcPaths.length + injarPaths.length + inpathPaths.length + spec.argfiles.length + spec.sourceroots.length; if (!spec.badInput && (numSources < 1)) { validator.fail( "no input jars, arg files, or source files or roots"); return false; } final File[] argFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, spec.argfiles); final File[] injarFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, injarPaths); final File[] inpathFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, inpathPaths); final File[] aspectFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, spec.aspectpath); final File[] extdirFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, spec.extdirs); final File[] classFiles = FileUtil.getBaseDirFiles(testBaseSrcDir, spec.classpath); final File[] xlintFiles = (null == spec.xlintfile ? new File[0] : FileUtil.getBaseDirFiles(testBaseSrcDir, new String[] {spec.xlintfile})); // injars might be outjars in the classes dir... for (int i = 0; i < injarFiles.length; i++) { if (!injarFiles[i].exists()) { injarFiles[i] = new File(sandbox.classesDir, injarPaths[i]); } } for (int i = 0; i < inpathFiles.length; i++) { if (!inpathFiles[i].exists()) { inpathFiles[i] = new File(sandbox.classesDir, inpathPaths[i]); } } // moved after solving any injars that were outjars if (!validator.canRead(injarFiles, "injars") || !validator.canRead(injarFiles, "injars")) { return false; } // hmm - duplicates validation above, verifying getBaseDirFiles? if (!spec.badInput) { if (!validator.canRead(argFiles, "argFiles") || !validator.canRead(injarFiles, "injarFiles") || !validator.canRead(inpathFiles, "inpathFiles") || !validator.canRead(aspectFiles, "aspectFiles") || !validator.canRead(classFiles, "classFiles") || !validator.canRead(xlintFiles, "xlintFiles")) { return false; } } final File[] srcFiles; File[] sourcerootFiles = new File[0]; // source text files are copied when staging incremental tests if (!spec.isStaging()) { // XXX why this? was always? || (testBaseSrcDir != sandbox.stagingDir))) { srcFiles = FileUtil.getBaseDirFiles( testBaseSrcDir, srcPaths, CompilerRun.SOURCE_SUFFIXES); if (!LangUtil.isEmpty(spec.sourceroots)) { sourcerootFiles = FileUtil.getBaseDirFiles( testBaseSrcDir, spec.sourceroots, null); } } else { // staging - copy files if (spec.badInput) { validator.info( "badInput ignored - files checked when staging"); } try { // copy all files, then remove tagged ones // XXX make copyFiles support a filter? srcFiles = FileUtil.copyFiles( testBaseSrcDir, srcPaths, sandbox.stagingDir); if (!LangUtil.isEmpty(spec.sourceroots)) { sourcerootFiles = FileUtil.copyFiles( testBaseSrcDir, spec.sourceroots, sandbox.stagingDir); // delete incremental files in sourceroot after copying // XXX inefficient // an incremental file has an extra "." in name // most .java files don't, because they are named after // the principle type they contain, and simple type names // have no dots. FileFilter pickIncFiles = new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) { // continue recursion return true; } String path = file.getPath(); // only source files are relevant to staging if (!FileUtil.hasSourceSuffix(path)) { return false; } int first = path.indexOf("."); int last = path.lastIndexOf("."); return (first != last); } }; for (int i = 0; i < sourcerootFiles.length; i++) { FileUtil.deleteContents( sourcerootFiles[i], pickIncFiles, false); } if (0 < sourcerootFiles.length) { FileUtil.sleepPastFinalModifiedTime( sourcerootFiles); } } File[] files = FileUtil.getBaseDirFiles(sandbox.stagingDir, srcPaths); if (0 < files.length) { FileUtil.sleepPastFinalModifiedTime(files); } } catch (IllegalArgumentException e) { validator.fail("staging - bad input", e); return false; } catch (IOException e) { validator.fail("staging - operations", e); return false; } } if (!spec.badInput && !validator.canRead(srcFiles, "copied paths")) { return false; } arguments.clear(); if (!LangUtil.isEmpty(xlintFiles)) { arguments.add("-Xlintfile"); String sr = FileUtil.flatten(xlintFiles, null); arguments.add(sr); } if (spec.outjar != null) { arguments.add("-outjar"); arguments.add(new File(sandbox.classesDir,spec.outjar).getPath()); } if (!LangUtil.isEmpty(extdirFiles)) { arguments.add("-extdirs"); String sr = FileUtil.flatten(extdirFiles, null); arguments.add(sr); } if (!LangUtil.isEmpty(sourcerootFiles)) { arguments.add("-sourceroots"); String sr = FileUtil.flatten(sourcerootFiles, null); arguments.add(sr); } if (!LangUtil.isEmpty(srcFiles)) { arguments.addAll(Arrays.asList(FileUtil.getPaths(srcFiles))); } injars.clear(); if (!LangUtil.isEmpty(injarFiles)) { injars.addAll(Arrays.asList(FileUtil.getPaths(injarFiles))); } inpaths.clear(); if (!LangUtil.isEmpty(inpathFiles)) { inpaths.addAll(Arrays.asList(FileUtil.getPaths(inpathFiles))); } if (!LangUtil.isEmpty(argFiles)) { String[] ra = FileUtil.getPaths(argFiles); for (int j = 0; j < ra.length; j++) { arguments.add("@" + ra[j]); } if (!spec.badInput && spec.isStaging) { validator.fail( "warning: files listed in argfiles not staged"); } } // save classpath and aspectpath in sandbox for this and other clients final boolean checkReadable = !spec.badInput; int size = spec.includeClassesDir ? 3 : 2; File[] cp = new File[size + classFiles.length]; System.arraycopy(classFiles, 0, cp, 0, classFiles.length); int index = classFiles.length; if (spec.includeClassesDir) { cp[index++] = sandbox.classesDir; } cp[index++] = Globals.F_aspectjrt_jar; cp[index++] = Globals.F_testingclient_jar; sandbox.compilerRunInit(this, testBaseSrcDir, aspectFiles, checkReadable, cp, checkReadable, null); // XXX todo set bootclasspath if set for forking? return true; } /** * Setup result evaluation and command line, run, and evaluate result. * <li>setup an AjcMessageHandler using the expected messages from * {@link Spec#getMessages()}.<li> * <li>heed any globals interpreted into a TestSetup by reading * {@link Spec@getOptions()}. For a list of supported globals, see * {@link setupArgs(ArrayList, IMessageHandler}.</li> * <li>construct a command line, using as classpath * {@link Sandbox.classpathToString()}<li> * <li>construct a compiler using {@link Spec#compiler} * or any overriding value set in TestSetup.<li> * <li>Just before running, set the compiler in the sandbox using * {@link Sandbox.setCompiler(ICommand)}.<li> * <li>After running, report AjcMessageHandler results to the status parameter. * If the AjcMessageHandler reports a failure, then send info messages * for the Spec, TestSetup, and command line.<li> * @see org.aspectj.testing.run.IRun#run(IRunStatus) */ public boolean run(IRunStatus status) { if (null == spec.testSetup) { MessageUtil.abort( status, "no test setup - adoptParentValues not called"); return false; } else if (!spec.testSetup.result) { MessageUtil.abort(status, spec.testSetup.failureReason); return false; } AjcMessageHandler handler = new AjcMessageHandler(spec.getMessages()); handler.init(); boolean handlerResult = false; boolean result = false; boolean commandResult = false; ArrayList argList = new ArrayList(); final Spec.TestSetup setupResult = spec.testSetup; try { if (spec.outjar == null) { argList.add("-d"); String outputDirPath = sandbox.classesDir.getAbsolutePath(); try { // worth it to try for canonical? outputDirPath = sandbox.classesDir.getCanonicalPath(); } catch (IOException e) { MessageUtil.abort( status, "canonical " + sandbox.classesDir, e); } argList.add(outputDirPath); } String path = sandbox.classpathToString(this); if (!LangUtil.isEmpty(path)) { argList.add("-classpath"); argList.add(path); } path = sandbox.getBootclasspath(this); if (!LangUtil.isEmpty(path)) { argList.add("-bootclasspath"); argList.add(path); } path = sandbox.aspectpathToString(this); if (!LangUtil.isEmpty(path)) { argList.add("-aspectpath"); argList.add(path); } if (0 < injars.size()) { argList.add("-injars"); argList.add( FileUtil.flatten( (String[]) injars.toArray(new String[0]), null)); } if (0 < inpaths.size()) { argList.add("-inpath"); argList.add( FileUtil.flatten( (String[]) inpaths.toArray(new String[0]), null)); } // put specified arguments last, for better badInput tests argList.addAll(setupResult.commandOptions); // add both java/aspectj and argfiles argList.addAll(arguments); // XXX hack - seek on request as a side effect. reimplement as listener if (null != setupResult.seek) { String slopPrefix = Spec.SEEK_MESSAGE_PREFIX + " slop - "; PrintStream slop = MessageUtil.handlerPrintStream( status, IMessage.INFO, System.err, slopPrefix); List found = FileUtil.lineSeek( setupResult.seek, arguments, false, slop); if (!LangUtil.isEmpty(found)) { for (Iterator iter = found.iterator(); iter.hasNext(); ) { MessageUtil.info( status, Spec.SEEK_MESSAGE_PREFIX + iter.next()); } } } ICommand compiler = spec.reuseCompiler // throws IllegalStateException if null ? sandbox.getCommand(this) : ReflectionFactory.makeCommand(setupResult.compilerName, status); DirChanges dirChanges = null; if (null == compiler) { MessageUtil.fail( status, "unable to make compiler " + setupResult.compilerName); return false; } else { if (setupResult.compilerName != Spec.DEFAULT_COMPILER) { MessageUtil.info( status, "compiler: " + setupResult.compilerName); } if (status.aborted()) { MessageUtil.debug( status, "aborted, but compiler valid?: " + compiler); } else { // same DirChanges handling for JavaRun, CompilerRun, IncCompilerRun // XXX around advice or template method/class if (!LangUtil.isEmpty(spec.dirChanges)) { LangUtil.throwIaxIfFalse( 1 == spec.dirChanges.size(), "expecting 0..1 dirChanges"); dirChanges = new DirChanges( (DirChanges.Spec) spec.dirChanges.get(0)); if (!dirChanges .start(status, sandbox.classesDir)) { return false; // setup failed } } MessageUtil.info( status, compiler + "(" + argList + ")"); sandbox.setCommand(compiler, this); String[] args = (String[]) argList.toArray(RA_String); commandResult = compiler.runCommand(args, handler); } } handlerResult = handler.passed(); if (!handlerResult) { return false; } else { result = (commandResult == handler.expectingCommandTrue()); if (!result) { String m = commandResult ? "compile did not fail as expected" : "compile failed unexpectedly"; MessageUtil.fail(status, m); } else if (null != dirChanges) { result = dirChanges.end(status, sandbox.testBaseDir); } } return result; } finally { if (!handlerResult) { // more debugging context in case of failure MessageUtil.info(handler, spec.toLongString()); MessageUtil.info(handler, "" + argList); if (null != setupResult) { MessageUtil.info(handler, "" + setupResult); } } handler.report(status); // XXX weak - actual messages not reported in real-time, no fast-fail } } public String toString() { return "CompilerRun(" + spec + ")"; } /** * Initializer/factory for CompilerRun * any path or file is relative to this test base dir */ public static class Spec extends AbstractRunSpec { public static final String XMLNAME = "compile"; public static final String DEFAULT_COMPILER = ReflectionFactory.ECLIPSE; static final String SEEK_PREFIX = "-seek:"; static final String SEEK_MESSAGE_PREFIX = "found: "; private static final CRSOptions CRSOPTIONS = new CRSOptions(); /** * Retitle description to title, paths to files, do comment, * staging, badInput, * do dirChanges, and print no chidren. */ private static final AbstractRunSpec.XMLNames NAMES = new AbstractRunSpec.XMLNames( AbstractRunSpec.XMLNames.DEFAULT, "title", null, null, null, "files", null, null, null, false, false, true); /** * If the source version warrants, add a -bootclasspath * entry to the list of arguments to add. * This will fail and return an error String if the * required library is not found. * @param sourceVersion the String (if any) describing the -source option * (expecting one of [null, "1.3", "1.4", "1.5"]. * @param compilerName the String name of the target compiler * @param toAdd the ArrayList to add -bootclasspath to * @return the String describing any errors, or null if no errors */ private static String updateBootclasspathForSourceVersion( String sourceVersion, String compilerName, ArrayList toAdd) { if (null == sourceVersion) { return null; } if (3 != sourceVersion.length()) { throw new IllegalArgumentException( "bad version: " + sourceVersion); } if (null == toAdd) { throw new IllegalArgumentException("null toAdd"); } int version = sourceVersion.charAt(2) - '0'; switch (version) { case (3) : if (LangUtil.supportsJava("1.4")) { if (!FileUtil.canReadFile(Globals.J2SE13_RTJAR)) { return "no 1.3 libraries to handle -source 1.3"; } toAdd.add("-bootclasspath"); toAdd.add(Globals.J2SE13_RTJAR.getAbsolutePath()); } break; case (4) : if (!LangUtil.supportsJava("1.4")) { if (ReflectionFactory .ECLIPSE .equals(compilerName)) { return "run eclipse under 1.4 to handle -source 1.4"; } if (!FileUtil.canReadFile(Globals.J2SE14_RTJAR)) { return "no 1.4 libraries to handle -source 1.4"; } toAdd.add("-bootclasspath"); toAdd.add(Globals.J2SE14_RTJAR.getAbsolutePath()); } break; case (5) : return "1.5 not supported in CompilerRun"; case (0) : // ignore - no version specified break; default : throw new Error("unexpected version: " + version); } return null; } static CRSOptions testAccessToCRSOptions() { return CRSOPTIONS; } static Options testAccessToOptions() { return CRSOPTIONS.getOptions(); } private static String[] copy(String[] input) { if (null == input) { return null; } String[] result = new String[input.length]; System.arraycopy(input, 0, result, 0, input.length); return result; } protected String compiler; // use same command - see also IncCompiler.Spec.fresh protected boolean reuseCompiler; protected boolean permitAnyCompiler; protected boolean includeClassesDir; protected TestSetup testSetup; protected String[] argfiles = new String[0]; protected String[] aspectpath = new String[0]; protected String[] classpath = new String[0]; protected String[] sourceroots = new String[0]; protected String[] extdirs = new String[0]; /** src path = {suiteParentDir}/{testBaseDirOffset}/{testSrcDirOffset}/{path} */ protected String testSrcDirOffset; protected String xlintfile; protected String outjar; public Spec() { super(XMLNAME); setXMLNames(NAMES); compiler = DEFAULT_COMPILER; } protected void initClone(Spec spec) throws CloneNotSupportedException { super.initClone(spec); spec.argfiles = copy(argfiles); spec.aspectpath = copy(aspectpath); spec.classpath = copy(classpath); spec.compiler = compiler; spec.includeClassesDir = includeClassesDir; spec.reuseCompiler = reuseCompiler; spec.permitAnyCompiler = permitAnyCompiler; spec.sourceroots = copy(sourceroots); spec.extdirs = copy(extdirs); spec.outjar = outjar; spec.testSetup = null; if (null != testSetup) { spec.testSetup = (TestSetup) testSetup.clone(); } spec.testSrcDirOffset = testSrcDirOffset; } public Object clone() throws CloneNotSupportedException { Spec result = new Spec(); initClone(result); return result; } public void setIncludeClassesDir(boolean include) { this.includeClassesDir = include; } public void setReuseCompiler(boolean reuse) { this.reuseCompiler = reuse; } public void setPermitAnyCompiler(boolean permitAny) { this.permitAnyCompiler = permitAny; } public void setCompiler(String compilerName) { this.compiler = compilerName; } public void setTestSrcDirOffset(String s) { if (null != s) { testSrcDirOffset = s; } } /** override to set dirToken to Sandbox.CLASSES and default suffix to ".class" */ public void addDirChanges(DirChanges.Spec spec) { if (null == spec) { return; } spec.setDirToken(Sandbox.CLASSES_DIR); spec.setDefaultSuffix(".class"); super.addDirChanges(spec); } public String toLongString() { return getPrintName() + "(" + super.containedSummary() + ")"; } public String toString() { return getPrintName() + "(" + super.containedSummary() + ")"; } /** bean mapping for writers */ public void setFiles(String paths) { addPaths(paths); } /** * Add to default classpath * (which includes aspectjrt.jar and testing-client.jar). * @param files comma-delimited list of classpath entries - ignored if * null or empty */ public void setClasspath(String files) { if (!LangUtil.isEmpty(files)) { classpath = XMLWriter.unflattenList(files); } } /** * Set source roots, deleting any old ones * @param files comma-delimited list of directories * - ignored if null or empty */ public void setSourceroots(String dirs) { if (!LangUtil.isEmpty(dirs)) { sourceroots = XMLWriter.unflattenList(dirs); } } public void setXlintfile(String path) { xlintfile = path; } public void setOutjar(String path) { outjar = path; } /** * Set extension dirs, deleting any old ones * @param files comma-delimited list of directories * - ignored if null or empty */ public void setExtdirs(String dirs) { if (!LangUtil.isEmpty(dirs)) { extdirs = XMLWriter.unflattenList(dirs); } } /** * Set aspectpath, deleting any old ones * @param files comma-delimited list of aspect jars - ignored if null or * empty */ public void setAspectpath(String files) { if (!LangUtil.isEmpty(files)) { aspectpath = XMLWriter.unflattenList(files); } } /** * Set argfiles, deleting any old ones * @param files comma-delimited list of argfiles - ignored if null or empty */ public void setArgfiles(String files) { if (!LangUtil.isEmpty(files)) { argfiles = XMLWriter.unflattenList(files); } } /** @return String[] copy of argfiles array */ public String[] getArgfilesArray() { String[] argfiles = this.argfiles; if (LangUtil.isEmpty(argfiles)) { return new String[0]; } return (String[]) LangUtil.copy(argfiles); } /** * This implementation skips if: * <ul> * <li>incremental test, but using ajc (not eclipse)</li> * <li>usejavac, but javac is not available on the classpath</li> * <li>eclipse, but -usejavac or -preprocess test</li> * <li>-source 1.4, but running under 1.2 (XXX design)</li> * <li>local/global option conflicts (-lenient/-strict)</li> * <li>semantic conflicts (e.g., -lenient/-strict)</li> * </ul> * @return false if this wants to be skipped, true otherwise */ protected boolean doAdoptParentValues( RT parentRuntime, IMessageHandler handler) { if (!super.doAdoptParentValues(parentRuntime, handler)) { return false; } testSetup = setupArgs(handler); if (!testSetup.result) { skipMessage(handler, testSetup.failureReason); } return testSetup.result; } private String getShortCompilerName() { String compilerClassName = compiler; if (null != testSetup) { compilerClassName = testSetup.compilerName; } if (null != compilerClassName) { int loc = compilerClassName.lastIndexOf("."); if (-1 != loc) { compilerClassName = compilerClassName.substring(loc + 1); } } return compilerClassName; } /** @return a CompilerRun with this as spec if setup completes successfully. */ public IRunIterator makeRunIterator( Sandbox sandbox, Validator validator) { CompilerRun run = new CompilerRun(this); if (run.setupAjcRun(sandbox, validator)) { // XXX need name for compilerRun return new WrappedRunIterator(this, run); } return null; } protected String getPrintName() { return "CompilerRun.Spec " + getShortCompilerName(); } /** * Each non-incremental run, fold the global flags in with * the run flags, which may involve adding or removing from * either list, depending on the flag prefix: * <ul> * <li>-foo: use -foo unless forced off.<li> * <li>^foo: (force off) remove any -foo option from the run flags</li> * <li>!foo: (force on) require the -foo flag </li> * </ul> * If there is a force conflict, then the test is skipped * ("skipping" info message, TestSetup.result is false). * This means an option local to the test which was specified * without forcing may be overridden by a globally-forced option. * <p> * There are some flags which are interpreted by the test * and removed from the list of flags passed to the command * (see testFlag()): * <ul> * <li>eclipse: use the new eclipse compiler (can force)</li> * <li>ajc: use the old ajc compiler (can force)</li> * <li>ignoreWarnings: ignore warnings in result evaluations (no force)</li> * </ul> * <p> * There are some flags which are inconsistent with each other. * These are treated as conflicts and the test is skipped: * <ul> * <li>lenient, strict</li> * </ul> * <p> * <p> * This also interprets any relevant System properties, * e.g., from <code>JavaRun.BOOTCLASSPATH_KEY</code>. * <p> * Finally, compiler limitations are enforced here by skipping * tests which the compiler cannot do: * <ul> * <li>eclipse does not do -lenient, -strict, -usejavac, -preprocess, * -XOcodeSize, -XSerializable, XaddSafePrefix, * -XserializableAspects,-XtargetNearSource</li> * <li>ajc does not run in incremental (staging) mode, * nor with -usejavac if javac is not on the classpath</li> * </ul> * <u>Errors</u>:This will remove an arg not prefixed by [-|!|^] after * providing an info message. * <u>TestSetup Result</u>: * If this completes successfully, then TestSetup.result is true, * and commandOptions is not null, and any test flags (ignore warning, * compiler) are reflected in the TestSetup. * If this fails, then TestSetup.result is false, * and a TestSetup.failreason is set. * This means the test is skipped. * @return TestSetup with results * (TestSetup result=false if the run should not continue) */ protected TestSetup setupArgs(IMessageHandler handler) { // warning: HarnessSelectionTest checks for specific error wording final Spec spec = this; final TestSetup result = new TestSetup(); result.compilerName = spec.compiler; // urk - s.b. null, but expected Values values = gatherValues(result); if ((null == values) || (null != result.failureReason)) { return checkResult(result); } // send info messages about // forced staging when -incremental // or staging but no -incremental flag Option.Family getFamily = CRSOPTIONS.crsIncrementalOption.getFamily(); final boolean haveIncrementalFlag = (null != values.firstInFamily(getFamily)); if (spec.isStaging()) { if (!haveIncrementalFlag) { MessageUtil.info( handler, "staging but no -incremental flag"); } } else if (haveIncrementalFlag) { spec.setStaging(true); MessageUtil.info(handler, "-incremental forcing staging"); } if (hasInvalidOptions(values, result)) { return checkResult(result); } // set compiler in result getFamily = CRSOPTIONS.ajccompilerOption.getFamily(); Option.Value compiler = values.firstInFamily(getFamily); if (null != compiler) { result.compilerName = CRSOPTIONS.compilerClassName(compiler.option); if (null == result.compilerName) { result.failureReason = "unable to get class name for " + compiler; return checkResult(result); } } String compilerName = (null == result.compilerName ? spec.compiler : result.compilerName); // check compiler semantics if (hasCompilerSpecErrors(compilerName, values, result)) { return checkResult(result); } // add toadd and finish result ArrayList args = new ArrayList(); String[] rendered = values.render(); if (!LangUtil.isEmpty(rendered)) { args.addAll(Arrays.asList(rendered)); } // update bootclasspath getFamily = CRSOPTIONS.crsSourceOption.getFamily(); Option.Value source = values.firstInFamily(getFamily); if (null != source) { String sourceVersion = source.unflatten()[1]; ArrayList toAdd = new ArrayList(); /*String err =*/ updateBootclasspathForSourceVersion( sourceVersion, spec.compiler, toAdd); args.addAll(toAdd); } result.commandOptions = args; result.result = true; return checkResult(result); } /** * Ensure exit invariant: * <code>result.result == (null == result.failureReason) * == (null != result.commandOptions)</code> * @param result the TestSetup to verify * @return result * @throws Error if invariant is not true */ TestSetup checkResult(TestSetup result) { String err = null; if (null == result) { err = "null result"; } else if (result.result != (null == result.failureReason)) { err = result.result ? "expected no failure: " + result.failureReason : "fail for no reason"; } else if (result.result != (null != result.commandOptions)) { err = result.result ? "expected command options" : "unexpected command options"; } if (null != err) { throw new Error(err); } return result; } boolean hasInvalidOptions(Values values, TestSetup result) { // not supporting 1.0 options any more for (Iterator iter = CRSOPTIONS.invalidOptions.iterator(); iter.hasNext(); ) { Option option = (Option) iter.next(); if (null != values.firstOption(option)) { result.failureReason = "invalid option in harness: " + option; return true; } } return false; } boolean hasCompilerSpecErrors( String compilerName, Values values, TestSetup result) { /* * Describe any semantic conflicts between options. * This skips: * - old 1.0 options, including lenient v. strict * - old ajc options, include !incremental and usejavac w/o javac * - invalid eclipse options (mostly ajc) * @param compilerName the String name of the target compiler * @return a String describing any conflicts, or null if none */ if (!permitAnyCompiler && (!(ReflectionFactory.ECLIPSE.equals(compilerName) || ReflectionFactory.OLD_AJC.equals(compilerName) || CRSOptions.AJDE_COMPILER.equals(compilerName) || CRSOptions.AJCTASK_COMPILER.equals(compilerName) || permitAnyCompiler ))) { //|| BUILDER_COMPILER.equals(compilerName)) result.failureReason = "unrecognized compiler: " + compilerName; return true; } // not supporting ajc right now if (null != values.firstOption(CRSOPTIONS.ajccompilerOption)) { result.failureReason = "ajc not supported"; return true; } // not supporting 1.0 options any more for (Iterator iter = CRSOPTIONS.ajc10Options.iterator(); iter.hasNext(); ) { Option option = (Option) iter.next(); if (null != values.firstOption(option)) { result.failureReason = "old ajc 1.0 option: " + option; return true; } } return false; } protected Values gatherValues(TestSetup result) { final Spec spec = this; // ---- local option values final Values localValues; final Options options = CRSOPTIONS.getOptions(); try { String[] input = getOptionsArray(); // this handles reading options, // flattening two-String options, etc. localValues = options.acceptInput(input); // all local values should be picked up String err = Options.missedMatchError(input, localValues); if (!LangUtil.isEmpty(err)) { result.failureReason = err; return null; } } catch (InvalidInputException e) { result.failureReason = e.getFullMessage(); return null; } // ---- global option values StringBuffer errs = new StringBuffer(); final Values globalValues = spec.runtime.extractOptions(options, true, errs); if (errs.length() > 0) { result.failureReason = errs.toString(); return null; } final Values combined = Values.wrapValues( new Values[] { localValues, globalValues }); String err = combined.resolve(); if (null != err) { result.failureReason = err; return null; } return handleTestArgs(combined, result); } // final int len = globalValues.length() + localValues.length(); // final Option.Value[] combinedValues = new Option.Value[len]; // System.arraycopy( // globalValues, // 0, // combinedValues, // 0, // globalValues.length()); // System.arraycopy( // localValues, // 0, // combinedValues, // globalValues.length(), // localValues.length()); // // result.compilerName = spec.compiler; // if (0 < combinedValues.length) { // // this handles option forcing, etc. // String err = Options.resolve(combinedValues); // if (null != err) { // result.failureReason = err; // return null; // } // if (!handleTestArgs(combinedValues, result)) { // return null; // } // } // return Values.wrapValues(combinedValues); // } /** * This interprets and nullifies values for the test. * @param values the Option.Value[] being processed * @param result the TestSetup to modify * @return false if error (caller should return), true otherwise */ Values handleTestArgs(Values values, final TestSetup result) { final Option.Family compilerFamily = CRSOPTIONS.ajccompilerOption.getFamily(); Values.Selector selector = new Values.Selector() { protected boolean accept(Option.Value value) { if (null == value) { return false; } Option option = value.option; if (compilerFamily.sameFamily(option.getFamily())) { if (value.prefix.isSet()) { String compilerClass = CRSOPTIONS.compilerClassName(option); if (null == compilerClass) { result.failureReason = "unrecognized compiler: " + value; throw Values.Selector.STOP; } if (!CRSOPTIONS.compilerIsLoadable(option)) { result.failureReason = "unable to load compiler: " + option; throw Values.Selector.STOP; } result.compilerName = compilerClass; } return true; } else if ( CRSOPTIONS.crsIgnoreWarnings.sameOptionIdentifier( option)) { result.ignoreWarnings = value.prefix.isSet(); result.ignoreWarningsSet = true; return true; } return false; } }; return values.nullify(selector); } // /** // * This interprets and nullifies values for the test. // * @param values the Option.Value[] being processed // * @param result the TestSetup to modify // * @return false if error (caller should return), true otherwise // */ // boolean handleTestArgs(Option.Value[] values, TestSetup result) { // if (!LangUtil.isEmpty(values)) { // for (int i = 0; i < values.length; i++) { // Option.Value value = values[i]; // if (null == value) { // continue; // } // Option option = value.option; // if (option.sameOptionFamily(ECLIPSE_OPTION)) { // if (!value.prefix.isSet()) { // values[i] = null; // continue; // } // String compilerClass = // (String) COMPILER_OPTION_TO_CLASSNAME.get( // option); // if (null == compilerClass) { // result.failureReason = // "unrecognized compiler: " + value; // return false; // } // result.compilerName = compilerClass; // values[i] = null; // } else if ( // option.sameOptionFamily(crsIgnoreWarnings)) { // result.ignoreWarnings = value.prefix.isSet(); // result.ignoreWarningsSet = true; // values[i] = null; // } // } // } // return true; // } // XXX need keys, cache... /** @return index of global in argList, ignoring first char */ protected int indexOf(String global, ArrayList argList) { int max = argList.size(); for (int i = 0; i < max; i++) { if (global .equals(((String) argList.get(i)).substring(1))) { return i; } } return -1; } /** * Write this out as a compile element as defined in * AjcSpecXmlReader.DOCTYPE. * @see AjcSpecXmlReader#DOCTYPE * @see IXmlWritable#writeXml(XMLWriter) */ public void writeXml(XMLWriter out) { out.startElement(xmlElementName, false); if (!LangUtil.isEmpty(testSrcDirOffset)) { out.printAttribute("dir", testSrcDirOffset); } super.writeAttributes(out); if (!DEFAULT_COMPILER.equals(compiler)) { out.printAttribute("compiler", compiler); } if (reuseCompiler) { out.printAttribute("reuseCompiler", "true"); } // test-only feature // if (permitAnyCompiler) { // out.printAttribute("permitAnyCompiler", "true"); // } if (includeClassesDir) { out.printAttribute("includeClassesDir", "true"); } if (!LangUtil.isEmpty(argfiles)) { out.printAttribute( "argfiles", XMLWriter.flattenFiles(argfiles)); } if (!LangUtil.isEmpty(aspectpath)) { out.printAttribute( "aspectpath", XMLWriter.flattenFiles(aspectpath)); } if (!LangUtil.isEmpty(sourceroots)) { out.printAttribute( "sourceroots", XMLWriter.flattenFiles(sourceroots)); } if (!LangUtil.isEmpty(extdirs)) { out.printAttribute( "extdirs", XMLWriter.flattenFiles(extdirs)); } out.endAttributes(); if (!LangUtil.isEmpty(dirChanges)) { DirChanges.Spec.writeXml(out, dirChanges); } SoftMessage.writeXml(out, getMessages()); out.endElement(xmlElementName); } /** * Encapsulate the directives that can be set using * global arguments supplied in {@link Spec.getOptions()}. * This supports changing the compiler and ignoring warnings. */ class TestSetup { /** null unless overriding the compiler to be used */ String compilerName; /** * true if we should tell AjcMessageHandler whether * to ignore warnings in its result evaluation */ boolean ignoreWarningsSet; /** if telling AjcMessageHandler, what we tell it */ boolean ignoreWarnings; /** false if setup failed */ boolean result; /** if setup failed, this has the reason why */ String failureReason; /** beyond running test, also seek text in sources */ String seek; /** if setup completed, this has the combined global/local options */ ArrayList commandOptions; public Object clone() { TestSetup testSetup = new TestSetup(); testSetup.compilerName = compilerName; testSetup.ignoreWarnings = ignoreWarnings; testSetup.ignoreWarningsSet = ignoreWarningsSet; testSetup.result = result; testSetup.failureReason = failureReason; testSetup.seek = seek; if (null != commandOptions) { testSetup.commandOptions = new ArrayList(); testSetup.commandOptions.addAll(commandOptions); } return testSetup; } public String toString() { return "TestSetup(" + (null == compilerName ? "" : compilerName + " ") + (!ignoreWarningsSet ? "" : (ignoreWarnings ? "" : "do not ") + "ignore warnings ") + (result ? "" : "setup failed") + ")"; } } /** * Options-related stuff in the spec. */ static class CRSOptions { // static final String BUILDER_COMPILER = // "org.aspectj.ajdt.internal.core.builder.Builder.Command"; static final String AJDE_COMPILER = CompileCommand.class.getName(); static final String AJCTASK_COMPILER = AjcTaskCompileCommand.class.getName(); private final Map compilerOptionToLoadable = new TreeMap(); /* * The options field in a compiler test permits some arbitrary * command-line options to be set. It does not permit things * like classpath, aspectpath, files, etc. which are set * using other fields in the test specification, so the options * permitted are a subset of those permitted on the command-line. * * Global options specified on the harness command-line are * adopted for the compiler command-line if they are permitted * in the options field. That means we have to detect each * permitted option, rather than just letting all through * for the compiler. * * Conversely, some options are targeted not at the compiler, * but at the test itself (e.g., to ignore warnings, or to * select a compiler. * * The harness can run many compilers, and they differ in * which options are permitted. You can specify a compiler * as an option (e.g., -eclipse). So the set of constraints * on the list of permitted options can differ from test to test. * * The following code sets up the lists of permitted options * and breaks out subsets for different compiler-variant checks. * Most options are created but not named, but some options * are named to detect corresponding values for further * processing. e.g., the compiler options are saved so * we can do per-compiler option verification. * */ private final Options crsOptions; private final Family compilerFamily; private final Option crsIncrementalOption; private final Option crsSourceOption; // these are options handled/absorbed by CompilerRun private final Option crsIgnoreWarnings; private final Option eclipseOption; private final Option buildercompilerOption; private final Option ajdecompilerOption; private final Option javacOption; private final Option ajctaskcompilerOption; private final Option ajccompilerOption; private final Map compilerOptionToClassname; private final Set compilerOptions; // compiler verification - permit but flag ajc 1.0 options private final List ajc10Options; private final List invalidOptions; private CRSOptions() { crsOptions = new Options(true); Option.Factory factory = new Option.Factory("CompilerRun"); // compiler options go in map eclipseOption = factory.create( "eclipse", "compiler", Option.FORCE_PREFIXES, false); compilerFamily = eclipseOption.getFamily(); buildercompilerOption = factory.create( "builderCompiler", "compiler", Option.FORCE_PREFIXES, false); ajctaskcompilerOption = factory.create( "ajctaskCompiler", "compiler", Option.FORCE_PREFIXES, false); ajdecompilerOption = factory.create( "ajdeCompiler", "compiler", Option.FORCE_PREFIXES, false); ajccompilerOption = factory.create( "ajc", "compiler", Option.FORCE_PREFIXES, false); javacOption = factory.create( "javac", "compiler", Option.FORCE_PREFIXES, false); Map map = new TreeMap(); map.put(eclipseOption, ReflectionFactory.ECLIPSE); //map.put(BUILDERCOMPILER_OPTION, BUILDER_COMPILER); map.put( ajctaskcompilerOption, AJCTASK_COMPILER); map.put(ajdecompilerOption, AJDE_COMPILER); map.put(ajccompilerOption, ReflectionFactory.OLD_AJC); //map.put(JAVAC_OPTION, "XXX javac option not supported"); compilerOptionToClassname = Collections.unmodifiableMap(map); compilerOptions = Collections.unmodifiableSet( compilerOptionToClassname.keySet()); // options not permitted in the harness List list = new ArrayList(); list.add(factory.create("workingdir")); list.add(factory.create("argfile")); list.add(factory.create("sourceroots")); list.add(factory.create("outjar")); invalidOptions = Collections.unmodifiableList(list); // other options added directly crsIncrementalOption = factory.create("incremental"); crsIgnoreWarnings = factory.create("ignoreWarnings"); crsSourceOption = factory .create( "source", "source", Option.FORCE_PREFIXES, false, new String[][] { new String[] { "1.3", "1.4", "1.5" } }); // ajc 1.0 options // workingdir above in invalid options list = new ArrayList(); list.add(factory.create("usejavac")); list.add(factory.create("preprocess")); list.add(factory.create("nocomment")); list.add(factory.create("porting")); list.add(factory.create("XOcodeSize")); list.add(factory.create("XTargetNearSource")); list.add(factory.create("XaddSafePrefix")); list.add( factory.create( "lenient", "lenient", Option.FORCE_PREFIXES, false)); list.add( factory.create( "strict", "lenient", Option.FORCE_PREFIXES, false)); ajc10Options = Collections.unmodifiableList(list); // -warn:.. and -g/-g:.. are not exclusive if (!(factory.setupFamily("debug", true) && factory.setupFamily("warning", true))) { System.err.println("CompilerRun debug/warning fail!"); } Option[] options = new Option[] { crsIncrementalOption, crsIgnoreWarnings, crsSourceOption, factory.create( "Xlint", "XLint", Option.FORCE_PREFIXES, true), factory.create("verbose"), factory.create("emacssym"), factory.create("referenceInfo"), factory.create("nowarn"), factory.create("deprecation"), factory.create("noImportError"), factory.create("proceedOnError"), factory.create("preserveAllLocals"), factory.create( "warn", "warning", Option.STANDARD_PREFIXES, true), factory.create( "g", "debug", Option.STANDARD_PREFIXES, false), factory.create( "g:", "debug", Option.STANDARD_PREFIXES, true), factory.create( "1.3", "compliance", Option.FORCE_PREFIXES, false), factory.create( "1.4", "compliance", Option.FORCE_PREFIXES, false), factory.create( "1.5", "compliance", Option.FORCE_PREFIXES, false), factory .create( "target", "target", Option.FORCE_PREFIXES, false, new String[][] { new String[] { "1.1", "1.2", "1.3", "1.4", "1.5" }}), factory.create("XnoInline"), factory.create("XnoWeave"), factory.create("Xreweavable"), factory.create("XnotReweavable"), factory.create("XserializableAspects") }; // among options not permitted: extdirs... for (int i = 0; i < options.length; i++) { crsOptions.addOption(options[i]); } for (Iterator iter = compilerOptions.iterator(); iter.hasNext(); ) { crsOptions.addOption((Option) iter.next()); } // these are recognized but records with them are skipped for (Iterator iter = ajc10Options.iterator(); iter.hasNext(); ) { crsOptions.addOption((Option) iter.next()); } crsOptions.freeze(); } Options getOptions() { return crsOptions; } /** * @return unmodifiable Set of options sharing the * family "compiler". */ Set compilerOptions() { return compilerOptions; } /** * @param option the compiler Option to get name for * @return null if option is null or not a compiler option, * or the fully-qualified classname of the ICommand * implementing the compiler. */ String compilerClassName(Option option) { if ((null == option) || (!compilerFamily.sameFamily(option.getFamily()))) { return null; } return (String) compilerOptionToClassname.get(option); } /** * Check that the compiler class associated with a compiler * option can be loaded. This check only happens once; * the result is cached (by compilerOption key) for later calls. * @param compilerOption the Option (family compiler) to check * @return true if compiler class for this option can be loaded */ boolean compilerIsLoadable(Option compilerOption) { LangUtil.throwIaxIfNull(compilerOption, "compilerName"); synchronized (compilerOptionToLoadable) { Boolean result = (Boolean) compilerOptionToLoadable.get( compilerOption); if (null == result) { MessageHandler sink = new MessageHandler(); String compilerClassname = (String) compilerOptionToClassname.get( compilerOption); if (null == compilerClassname) { result = Boolean.FALSE; } else { ICommand c = ReflectionFactory.makeCommand( compilerClassname, sink); if ((null == c) || sink.hasAnyMessage( IMessage.ERROR, true)) { result = Boolean.FALSE; } else { result = Boolean.TRUE; } } compilerOptionToLoadable.put( compilerOption, result); } return result.booleanValue(); } } } // CompilerRun.Spec.CRSOptions } // CompilerRun.Spec } // CompilerRun
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
/******************************************************************************* * Copyright (c) 2004 IBM * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andy Clement - initial API and implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.Signature; import org.aspectj.apache.bcel.util.ClassPath; import org.aspectj.apache.bcel.util.SyntheticRepository; import org.aspectj.asm.AsmManager; import org.aspectj.asm.IHierarchy; import org.aspectj.asm.IProgramElement; import org.aspectj.asm.IRelationship; import org.aspectj.asm.internal.Relationship; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.LangUtil; public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml"); } public void testMixingCodeStyles_pr121385() { runTest("mixing aspect styles");} public void testTypeVars_pr121575() { runTest("different numbers of type vars");} public void testTypeVars_pr121575_2() { runTest("different numbers of type vars - 2");} public void testTypeVars_pr121575_3() { runTest("different numbers of type vars - 3");} public void testTypeVars_pr121575_4() { runTest("different numbers of type vars - 4");} public void testDecps1() { runTest("decps - 1"); } public void testDecps1b() { runTest("decps - 1b"); } public void testDecps2() { runTest("decps - 2"); } public void testDecps2b() { runTest("decps - 2b"); } public void testDecps3() { runTest("decps - 3"); } public void testDecps3b() { runTest("decps - 3b"); } public void testDecps3c() { runTest("decps - 3c"); } public void testVarargsNPE_pr120826() { runTest("varargs NPE");} public void testNamedPointcutPertarget_pr120521() { runTest("named pointcut not resolved in pertarget pointcut");} public void testDollarClasses_pr120474() { runTest("Dollar classes");} public void testGenericPTW_pr119539_1() { runTest("generic pertypewithin aspect - 1");} public void testGenericPTW_pr119539_2() { runTest("generic pertypewithin aspect - 2");} public void testGenericPTW_pr119539_3() { runTest("generic pertypewithin aspect - 3");} /* public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");} public void testMissingAccessor_pr73856() { runTest("missing accessor");} public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");} public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");} */ public void testIncorrectSignatureMatchingWithExceptions_pr119749() { runTest("incorrect exception signature matching");} public void testGeneratingCodeForAnOldRuntime_pr116679_1() { runTest("generating code for a 1.2.1 runtime - 1");} public void testGeneratingCodeForAnOldRuntime_pr116679_2() { runTest("generating code for a 1.2.1 runtime - 2");} public void testAmbiguousMethod_pr118599_1() { runTest("ambiguous method when binary weaving - 1");} public void testAmbiguousMethod_pr118599_2() { runTest("ambiguous method when binary weaving - 2");} public void testAroundAdviceArrayAdviceSigs_pr118781() { runTest("verify error with around advice array sigs");} public void testAtDeclareParents_pr117681() { runTest("at declare parents");} public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");} public void testRangeProblem_pr109614() { runTest("Range problem");} public void testGenericAspects_pr115237() { runTest("aspectOf and generic aspects");} public void testClassFormatError_pr114436() { runTest("ClassFormatError binary weaving perthis");} public void testParserException_pr115788() { runTest("parser exception");} public void testPossibleStaticImports_pr113066_1() { runTest("possible static imports bug - 1");} public void testPossibleStaticImports_pr113066_2() { runTest("possible static imports bug - 2");} public void testPossibleStaticImports_pr113066_3() { runTest("possible static imports bug - 3");} public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");} public void testAnnotatedITDFs_pr114005_1() { runTest("Annotated ITDFs - 1");} public void testAnnotatedITDFs_pr114005_2() { runTest("Annotated ITDFs - 2");} public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");} public void testBrokenDecp_pr112476() { runTest("binary weaving decp broken");} public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");} public void testNPEScopeSetup_pr115038() { runTest("NPE in ensureScopeSetup");} public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");} public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");} public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");} public void testFieldGet_pr114343() { runTest("field-get, generics and around advice");} public void testFieldGet_pr114343_2() { runTest("field-get, generics and around advice - 2");} public void testFieldGet_pr114343_3() { runTest("field-get, generics and around advice - 3");} public void testCaptureBinding_pr114744() { runTest("capturebinding wildcard problem");} public void testAutoboxingAroundAdvice_pr119210_1() { runTest("autoboxing around advice - 1");} public void testAutoboxingAroundAdvice_pr119210_2() { runTest("autoboxing around advice - 2");} public void testAutoboxingAroundAdvice_pr119210_3() { runTest("autoboxing around advice - 3");} public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");} public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");} public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");} public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");} public void testSpuriousOverrideMethodWarning_pr119570_1() { runTest("spurious override method warning");} public void testSpuriousOverrideMethodWarning_pr119570_2() { runTest("spurious override method warning - 2");} public void testBrokenSwitch_pr117854() { runTest("broken switch transform");} public void testVarargsITD_pr110906() { runTest("ITD varargs problem");} public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");} //public void testIllegalInitialization_pr118326_1() { runTest("illegal initialization - 1");} //public void testIllegalInitialization_pr118326_2() { runTest("illegal initialization - 2");} public void testLintForAdviceSorting_pr111667() { runTest("lint for advice sorting");} public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");} public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");} public void testFieldGetProblemWithGenericField_pr113861() {runTest("field-get problems with generic field");} public void testAccesstoPrivateITDInNested_pr118698() { runTest("access to private ITD from nested type");} public void testDeclareAnnotationOnNonExistentType_pr99191_1() { runTest("declare annotation on non existent type - 1");} public void testDeclareAnnotationOnNonExistentType_pr99191_2() { runTest("declare annotation on non existent type - 2");} public void testDeclareAnnotationOnNonExistentType_pr99191_3() { runTest("declare annotation on non existent type - 3");} public void testDeclareAnnotationOnNonExistentType_pr99191_4() { runTest("declare annotation on non existent type - 4");} public void testDeclareAnnotationOnNonExistentType_pr99191_5() { runTest("declare annotation on non existent type - 5");} public void testBadGenericSigAttribute_pr110927() { runTest("cant create signature attribute"); Signature sig = GenericsTests.getClassSignature(ajc,"I"); if (sig==null) fail("Couldn't find signature attribute for type I"); String sigString = sig.getSignature(); if (!(sigString.equals("Ljava/lang/Object;LIE2;LIE1<Ljava/lang/String;>;") || sigString.equals("Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"))) { fail("Signature was "+sigString+" when should have been something like Ljava/lang/Object;LIE1<Ljava/lang/String;>;LIE2;"); } } public void test_typeProcessingOrderWhenDeclareParents() { runTest("Order of types passed to compiler determines weaving behavior"); } public void test_aroundMethod() { runTest("method called around in class"); } public void test_aroundMethodAspect() { runTest("method called around in aspect"); } public void test_ambiguousBindingsDetection() { runTest("Various kinds of ambiguous bindings"); } public void test_ambiguousArgsDetection() { runTest("ambiguous args"); } public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() { runTest("Injecting exception into while loop with break statement causes catch block to be ignored"); } public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() { runTest("Return in try-block disables catch-block if final-block is present"); } public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException { runTest("Weaved code does not include debug lines"); boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); Method[] meths = jc.getMethods(); for (int i = 0; i < meths.length; i++) { Method method = meths[i]; if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable()); assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(), method.getLineNumberTable()!=null); } // This test would determine the info isn't there if you pass -g:none ... // cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"}); // assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages()); // System.err.println(cR.getStandardError()); // jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1"); // meths = jc.getMethods(); // for (int i = 0; i < meths.length; i++) { // Method method = meths[i]; // assertTrue("Found a line number table for method "+method.getName(), // method.getLineNumberTable()==null); // } } public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() { runTest("compiler error when mixing inheritance, overriding and polymorphism"); } public void testPerTypeWithin_pr106554() {runTest("Problem in staticinitialization with pertypewithin aspect");} public void testPerTypeWithinMissesNamedInnerTypes() { runTest("pertypewithin() handing of inner classes (1)"); } public void testPerTypeWithinMissesAnonymousInnerTypes() { runTest("pertypewithin() handing of inner classes (2)"); } public void testPerTypeWithinIncorrectlyMatchingInterfaces() { runTest("pertypewithin({interface}) illegal field modifier"); } public void test051_arrayCloningInJava5() { runTest("AJC possible bug with static nested classes"); } public void testBadASMforEnums() throws IOException { runTest("bad asm for enums"); if (LangUtil.is15VMOrGreater()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0); pw.flush(); String tree = baos.toString(); assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1); } } public void npeOnTypeNotFound() { runTest("structure model npe on type not found"); } public void testNoRuntimeExceptionSoftening() { runTest("declare soft of runtime exception"); } public void testRuntimeNoSoftenWithHandler() { runTest("declare soft w. catch block"); } public void testSyntaxError() { runTest("invalid cons syntax"); } public void testVarargsInConsBug() { runTest("varargs in constructor sig"); } public void testAspectpathdirs() { runTest("dirs on aspectpath"); } public void testIntroSample() { runTest("introduction sample"); } public void testPTWInterface() { runTest("pertypewithin({interface}) illegal field modifier"); } public void testEnumCalledEnumEtc() { runTest("enum called Enum, annotation called Annotation, etc"); } public void testInternalCompilerError_pr86832() { runTest("Internal compiler error"); } public void testCloneMethod_pr83311() { runTest("overriding/polymorphism error on interface method introduction"); } // IfPointcut.findResidueInternal() was modified to make this test complete in a short amount // of time - if you see it hanging, someone has messed with the optimization. public void testIfEvaluationExplosion_pr94086() { runTest("Exploding compile time with if() statements in pointcut"); } public void testReflectNPE_pr94167() {runTest("NPE in reflect implementation");} public void testStaticImports_pr84260() {runTest("static import failures");} public void testGenerics_pr99089() {runTest("ArrayIndexOutOfBoundsException - Generics in privileged aspects");} public void testGenerics_pr95993() {runTest("NPE at ClassScope.java:660 when compiling generic class");} public void testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");} public void testItdGenerics_pr98320() {runTest("intertype with nested generic type");} public void testItdGenerics_pr100227() {runTest("inner class with generic enclosing class");} public void testItdGenerics_pr100260() {runTest("methods inherited from a generic parent");} public void testSyntaxErrorNPE_pr103266() {runTest("NPE on syntax error");} public void testFinalAbstractClass_pr109486() { runTest("Internal compiler error (ClassParser.java:242)");} public void testComplexBinding_pr102210() { runTest("NullPointerException trying to compile");} public void testIllegalStateExceptionOnNestedParameterizedType_pr106634() { runTest("IllegalStateException unpacking signature of nested parameterized type"); } public void testParseErrorOnAnnotationStarPlusPattern() { runTest("(@Foo *)+ type pattern parse error"); } public void test_pr106130_tooManyLocals() { runTest("test weaving with > 256 locals"); } public void testMissingNamePattern_pr106461() { runTest("missing name pattern"); } public void testMissingNamePattern_pr107059() { runTest("parser crashes on call(void (@a *)(..)"); } public void testIntermediateAnnotationMatching() { runTest("intermediate annotation matching"); } public void testBadRuntimeTestGeneration() { runTest("target(@Foo *)"); } public void testErrorMessageOnITDWithTypePatterns() { runTest("clear error message on itd with type pattern"); } public void testAjKeywordsAsIdentifiers() { runTest("before and after are valid identifiers in classes"); } public void testAjKeywordsAsIdentifiers2() { runTest("before and after are valid identifiers in classes, part 2"); } public void testNoBeforeReturningAdvice() { runTest("before returning advice not allowed!"); } public void testDetectVoidFieldType() { runTest("void field type in pointcut expression"); } public void testPointcutOverriding() { runTest("overriding final pointcut from super-aspect"); } public void testAtSuppressWarnings() { runTest("@SuppressWarnings should suppress"); } public void testDEOWWithBindingPointcut() { runTest("declare warning : foo(str) : ...;"); } public void testAroundAdviceAndInterfaceInitializer() { runTest("around advice on interface initializer"); } public void testGoodErrorMessageOnUnmatchedMemberSyntax() { runTest("good error message for unmatched member syntax"); } public void testITDWithNoExceptionAndIntermediary() { runTest("itd override with no exception clause"); } public void testAnonymousInnerClasses() { runTest("anonymous inner classes"); } public void testMultipleAnonymousInnerClasses() { runTest("multiple anonymous inner classes"); } public void testPrivilegedMethodAccessorsGetRightExceptions_pr82989() { runTest("Compiler error due to a wrong exception check in try blocks"); } public void testAnonymousInnerClassWithMethodReturningTypeParameter_pr107898() { runTest("anonymous inner class with method returning type parameter"); } public void testMatchingOfObjectArray() { runTest("matching against Object[]"); } public void testMultipleAnonymousInnerClasses_pr108104() { runTest("multiple anonymous inner classes 2"); } public void testSignatureMatchingInMultipleOverrideScenario() { runTest("signature matching in override scenario"); } public void testWildcardAnnotationMatching_pr108245() { runTest("wildcard annotation matching - pr108245"); } public void testInnerTypesAndTypeVariables() { runTest("inner types and type variables"); } public void testAtAfterThrowingWithNoFormal() { runTest("@AfterThrowing with no formal specified"); } public void testParameterizedVarArgsMatch() { runTest("varargs with type variable"); } public void testFieldAccessInsideITDM() { runTest("itd field access inside itd method"); } public void testTypeVarWithTypeVarBound() { runTest("type variable with type variable bound"); } public void testEnumSwitchInITD() { runTest("switch on enum inside ITD method"); } public void testInnerTypeOfGeneric() { runTest("inner type of generic interface reference from parameterized type"); } public void testDeclareParentsIntroducingCovariantReturnType() { runTest("declare parents introducing override with covariance"); } public void testInnerClassPassedToVarargs() { runTest("inner class passed as argument to varargs method"); } public void testInlinedFieldAccessInProceedCall() { runTest("inlined field access in proceed call"); } public void testVisibiltyInSignatureMatchingWithOverridesPart1() { runTest("visibility in signature matching with overrides - 1"); } public void testVisibiltyInSignatureMatchingWithOverridesPart2() { runTest("visibility in signature matching with overrides - 2"); } public void testVisibiltyInSignatureMatchingWithOverridesPart3() { runTest("visibility in signature matching with overrides - 3"); } public void testArgsGeneratedCorrectlyForAdviceExecution() { runTest("args generated correctly for advice execution join point"); } public void testNoUnusedWarningsOnAspectTypes() { runTest("no unused warnings on aspect types"); } public void testSyntheticArgumentsOnITDConstructorsNotUsedInMatching() { runTest("synthetic arguments on itd cons are not used in matching"); } public void testParsingOfGenericTypeSignature() { runTest("parse generic type signature with parameterized type in interface"); } public void testOverrideAndCovarianceWithDecPRuntime() { runTest("override and covariance with decp - runtime"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFiles() { runTest("override and covariance with decp - runtime separate files"); } public void testOverrideAndCovarianceWithDecPRuntimeMultiFilesBinaryWeaving() { runTest("override and covariance with decp - binary weaving"); } public void testAbstractSynchronizedITDMethods() { runTest("abstract synchronized itdms not detected"); } public void testSynchronizedITDInterfaceMethods() { runTest("synchronized itd interface methods"); } public void testNoWarningOnUnusedPointcut() { runTest("unused private pointcuts"); } public void testITDOnInterfaceWithExistingMember() { runTest("itd interface method already existing on interface"); } public void testFinalITDMOnInterface() { runTest("final itd methods on interfaces"); } public void testPrivatePointcutOverriding() { runTest("can't override private pointcut in abstract aspect"); } public void testAdviceOnCflow() { runTest("advising cflow advice execution"); } public void testNoTypeMismatchOnSameGenericTypes() { runTest("no type mismatch on generic types in itds"); } public void testSuperCallInITD() { runTest("super call in ITD"); } public void testSuperCallInITDPart2() { runTest("super call in ITD - part 2"); } public void testAtAnnotationBadTest_pr103740() { runTest("Compiler failure on at_annotation"); } public void testNoUnusedParameterWarningsForSyntheticAdviceArgs() { runTest("no unused parameter warnings for synthetic advice args"); } public void testNoVerifyErrorWithSetOnInnerType() { runTest("no verify error with set on inner type"); } public void testCantFindTypeErrorWithGenericReturnTypeOrParameter() { runTest("cant find type error with generic return type or parameter"); } public void testNoVerifyErrorOnGenericCollectionMemberAccess() { runTest("no verify error on generic collection member access"); } public void testRawAndGenericTypeConversionITDCons() { runTest("raw and generic type conversion with itd cons"); } public void testAtAnnotationBindingWithAround() { runTest("@annotation binding with around advice"); } public void testUnableToBuildShadows_pr109728() { runTest("Unable to build shadows");} public void testMessageOnMissingTypeInDecP() { runTest("declare parents on a missing type"); } public void testParameterizedGenericMethods() { runTest("parameterized generic methods"); } public void testIllegalChangeToPointcutDeclaration_pr111915() { runTest("test illegal change to pointcut declaration"); } public void testCantProvideDefaultImplViaITD_pr110307_1() {runTest("Cant provide default implementation via ITD - 1");} public void testCantProvideDefaultImplViaITD_pr110307_2() {runTest("Cant provide default implementation via ITD - 2");} public void testCantProvideDefaultImplViaITD_pr110307_3() {runTest("Cant provide default implementation via ITD - 3");} public void testCantProvideDefaultImplViaITD_pr110307_4() {runTest("Cant provide default implementation via ITD - 4");} public void testCantProvideDefaultImplViaITD_pr110307_5() {runTest("Cant provide default implementation via ITD - 5");} // Needs a change in the compiler so that getType() can be overridden in the intertype scope - thats // where we can police whether a type variable has been used without being specified appropriately. //public void testCantProvideDefaultImplViaITD_pr110307_6() {runTest("Cant provide default implementation via ITD - 6");} public void testCantProvideDefaultImplViaITD_pr110307_7() {runTest("Cant provide default implementation via ITD - 7");} public void testCallJoinPointsInAnonymousInnerClasses() { runTest("call join points in anonymous inner classes"); } public void testNoRequirementForUnwovenTypesToBeExposedToWeaver() { runTest("default impl of Runnable"); } public void testArrayCloneCallJoinPoints() { runTest("array clone call join points in 1.4 vs 1.3"); } public void testDebugInfoForAroundAdvice() { runTest("debug info in around advice inlining"); } public void testCCEWithGenericWildcard_pr112602() { runTest("ClassCastException with generic wildcard"); } public void testAdviceInStructureModelWithAnonymousInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the run() method inside anonymous inner class is in // the structure model IProgramElement anonRunMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"run()"); assertNotNull("Couldn't find 'run()' element in the tree",anonRunMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(anonRunMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'run()' but is " + target.toLabelString(),"run()",target.toLabelString()); } public void testAdviceInStructureModelWithNamedInnerClass_pr77269() { //AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("advice in structure model with named inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); // checking that the m() method inside named inner class is in // the structure model IProgramElement namedMethodIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.METHOD,"m()"); assertNotNull("Couldn't find 'm()' element in the tree",namedMethodIPE); List l = AsmManager.getDefault().getRelationshipMap().get(namedMethodIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have one relationship but has " + l.size(),l.size()==1); Relationship rel = (Relationship)l.get(0); List targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'before(): p..' but is " + target.toLabelString(),"before(): p..",target.toLabelString()); IProgramElement adviceIPE = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE,"before(): p.."); assertNotNull("Couldn't find 'before(): p..' element in the tree",adviceIPE); l = AsmManager.getDefault().getRelationshipMap().get(adviceIPE); assertNotNull("Should have some relationships but does not",l); assertTrue("Should have a relationship but does not ",l.size()>0); for (Iterator iter = l.iterator(); iter.hasNext();) { IRelationship element = (IRelationship) iter.next(); if (element.getName().equals("advises")) { rel = (Relationship) element; break; } } targets = rel.getTargets(); assertTrue("Should have one target but has" + targets.size(), targets.size()==1); target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)targets.get(0)); assertEquals("target of relationship should be 'm()' but is " + target.toLabelString(),"m()",target.toLabelString()); } public void testDWInStructureModelWithAnonymousInnerClass_pr77269() { // AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("declare warning in structure model with anonymous inner class"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.CODE,"method-call(void pack.Test.someMethod())"); assertNotNull("Couldn't find 'method-call(void pack.Test.someMethod())' element in the tree",pe); } public void testVarArgsIITDInConstructor() { runTest("ITD varargs in constructor"); } public void testWeaveInfoMessageForDeclareAtMethodOnITDdMethod() { runTest("weaveinfo message for declare at method on an ITDd method"); } public void testITDCWithNoExplicitConsCall() { runTest("ITDC with no explicit cons call"); } public void testJava5SpecificFeaturesUsedAtJava14OrLower() { runTest("java 5 pointcuts and declares at pre-java 5 compliance levels"); } public void testAnonymousTypes() { runTest("Anonymous types and nome matching"); } public void testAdviceExecutionJPToStringForms() { runTest("adviceexecution join point toString forms"); } public void testAssertWithinPointcutExpression() { runTest("pointcut expression containing 'assert'"); } public void testNoVerifyErrorWithTwoThisPCDs_pr113447() { runTest("no verify error with two this pcds"); } public void testNoVerifyErrorWithTwoAtThisPCDs_pr113447() { runTest("no verify error with two at this pcds"); } public void testNoVerifyErrorWithAtWithinPCDs_pr113447() { runTest("no verify error with at within pcds"); } public void testNoVerifyErrorWithAtWithincodePCDs_pr113447() { runTest("no verify error with at withincode pcds"); } public void testNoVerifyErrorWithAtAnnotationPCDs_pr113447() { runTest("no verify error with at annotation pcds"); } public void testNoVerifyErrorWithTwoArgsPCDs_pr113447() { runTest("no verify error with two args pcds"); } public void testNoStackOverflowWithCircularPCDInGenericAspect() { runTest("no StackOverflowError with circular pcd in generic aspect"); } public void testNoStackOverflowWithCircularPCDInGenericAspect2() { runTest("no StackOverflowError with circular pcd in generic aspect - 2"); } public void testNPEInThisJoinPointStaticPart() { runTest("thisJoinPointStaticPart in if test"); } public void testPointcutParsingOfCompiledPointcuts() { runTest("pointcut parsing with ajc compiled pointcut references"); } public void testReflectionOfAbstractITDs() { runTest("reflection on abstract ITDs (Billing example)"); } public void testDeclareSoftWithAdviceExecution() { runTest("declare soft and adviceexecution"); } public void testDeclareSoftWithExclusions() { runTest("declare soft and exclusions"); } public void testReturningObjectBinding() { runTest("returning(Object) binding"); } public void testPerTargetAndNegation() { runTest("pertarget and negated pointcut"); } public void testParameterizedPointcutAndAdvice() { runTest("parameterized pointcut and advice"); } public void testDoublyParameterizedAbstractType() { runTest("double parameter generic abstract type"); } public void testArgNamesInAdviceAnnotations() { runTest("arg names in advice annotations"); } /* * Load-time weaving bugs */ public void testNPEinWeavingAdaptor_pr116626() { runTest("NPE in WeavingAdaptor");} public void testXlintMessageForImproperAnnotationType_pr115252_Exact() {runTest("xlint message for improper exact annotation type");} public void testXlintMessageForImproperAnnotationType_pr115252_OR() {runTest("xlint message for improper annotation type inside OR");} public void testXlintMessageForImproperAnnotationType_pr115252_AND() {runTest("xlint message for improper annotation type inside AND");} public void testXlintMessageForImproperAnnotationType_pr115252_Return() {runTest("xlint message for improper annotated return type");} public void testXlintMessageForImproperAnnotationType_pr115252_Declaring() {runTest("xlint message for improper annotated declaring type");} public void testXlintMessageForImproperAnnotationType_pr115252_Parameter() {runTest("xlint message for improper annotated parameter type");} public void testXlintMessageForImproperAnnotationType_pr115252_Throws() {runTest("xlint message for improper annotated throws pattern");} public void testXlintMessageForImproperAnnotationType_pr115252_MoreThanOne() {runTest("xlint message for more than one improper annotated parameter type");} public void testDeclareAtTypeInStructureModel_pr115607() { AsmManager.setReporting("c:/debug.txt",true,true,true,true); runTest("declare at type appears correctly in structure model"); IHierarchy top = AsmManager.getDefault().getHierarchy(); IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,"declare @type: Simple : @I"); assertNotNull("Couldn't find 'declare @type: Simple : @I' element in the tree",pe); List l = AsmManager.getDefault().getRelationshipMap().get(pe); assertNotNull("Should have some relationships but does not",l); } public void testNoNPEWhenInaccessibleMethodIsCalledWithinITD_pr119019() { runTest("no NPE when inaccessible method is called within itd"); } public void testNoNPEWithOrPointcutAndMoreThanOneArgs_pr118149() { runTest("no NPE with or pointcut and more than one args"); } public void testNoSOBWithGenericInnerAspects_pr119543() { runTest("no StringOutOfBoundsException with generic inner aspects"); } public void testIllegalAccessErrorWithAroundAdvice_pr119657() { runTest("IllegalAccessError with around advice on interface method call"); } public void testIllegalAccessErrorWithAroundAdviceNotSelf_pr119657() { runTest("IllegalAccessError with around advice on interface method call not self"); } public void testIllegalAccessErrorWithAroundAdviceNoWeaveLTW_pr119657() { runTest("IllegalAccessError with around advice on interface method call using -XnoWeave and LTW"); } public void testIllegalAccessErrorWithAroundAdviceLTW_pr119657() { runTest("IllegalAccessError with around advice on interface method call using LTW"); } public void testIllegalAccessErrorWithAroundAdviceNotSelfLTW_pr119657() { runTest("IllegalAccessError with around advice on interface method call not self using LTW"); } public void testIllegalAccessErrorWithAroundAdviceSelfAndNotSelfLTW_pr119657() { runTest("IllegalAccessError with around advice on interface method call self and not self using LTW"); } public void testIllegalAccessErrorWithAroundAdviceLTWNoInline_pr119657() { runTest("IllegalAccessError with around advice on interface method call using LTW and -XnoInline"); } public void testReflectOnCodeStyleITDs() { runTest("reflection on itds"); } public void testReflectOnAtAspectJDecP() { runTest("reflection on @DeclareParents"); } public void testModifierOverrides() { runTest("modifier overrides"); } public void testAbstractPerThisInAtAspectJ() { runTest("abstract perthis in @AspectJ"); } public void testNPEInBcelAdviceWithConcreteAspect_pr121385() { runTest("override protected pointcut in aop.xml concrete aspect"); } // 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); } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
tests/src/org/aspectj/systemtest/ajc150/ataspectj/AtAjLTWTests.java
/******************************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Alexandre Vasseur initial implementation *******************************************************************************/ package org.aspectj.systemtest.ajc150.ataspectj; import java.io.File; import java.io.FilenameFilter; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; import org.aspectj.util.FileUtil; /** * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> */ public class AtAjLTWTests extends XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(org.aspectj.systemtest.ajc150.ataspectj.AtAjLTWTests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/ajc150/ataspectj/ltw.xml"); } public void testRunThemAllWithJavacCompiledAndLTW() { runTest("RunThemAllWithJavacCompiledAndLTW"); } public void testAjcLTWPerClauseTest_XnoWeave() { runTest("AjcLTW PerClauseTest -XnoWeave"); } public void testAjcLTWPerClauseTest_Xreweavable() { runTest("AjcLTW PerClauseTest -Xreweavable"); } public void testJavaCAjcLTWPerClauseTest() { runTest("JavaCAjcLTW PerClauseTest"); } public void testAjcLTWAroundInlineMungerTest_XnoWeave() { runTest("AjcLTW AroundInlineMungerTest -XnoWeave"); } public void testAjcLTWAroundInlineMungerTest_Xreweavable() { runTest("AjcLTW AroundInlineMungerTest"); } public void testAjcLTWAroundInlineMungerTest() { runTest("AjcLTW AroundInlineMungerTest"); } public void testAjcLTWAroundInlineMungerTest_XnoInline_Xreweavable() { runTest("AjcLTW AroundInlineMungerTest -XnoInline -Xreweavable"); } public void testAjcLTWAroundInlineMungerTest2() { runTest("AjcLTW AroundInlineMungerTest2"); } public void testLTWDumpNone() { runTest("LTW DumpTest none"); File f = new File("_ajdump/ataspectj/DumpTest.class"); assertFalse(f.exists()); f = new File("_ajdump/_before/ataspectj/DumpTestTheDump.class"); assertFalse(f.exists()); f = new File("_ajdump/ataspectj/DumpTestTheDump.class"); assertFalse(f.exists()); } public void testLTWDump() { runTest("LTW DumpTest"); File f = new File("_ajdump/ataspectj/DumpTest.class"); assertFalse(f.exists()); f = new File("_ajdump/_before/ataspectj/DumpTestTheDump.class"); assertFalse(f.exists()); f = new File("_ajdump/ataspectj/DumpTestTheDump.class"); assertTrue(f.exists()); // tidy up... f = new File("_ajdump"); FileUtil.deleteContents(f); f.delete(); } public void testLTWDumpBeforeAndAfter() { runTest("LTW DumpTest before and after"); // before File f = new File("_ajdump/_before/com/foo/bar"); CountingFilenameFilter cff = new CountingFilenameFilter(); f.listFiles(cff); assertEquals("Expected dump file in " + f.getAbsolutePath(),1,cff.getCount()); // after f = new File("_ajdump/com/foo/bar"); cff = new CountingFilenameFilter(); f.listFiles(cff); assertEquals("Expected dump file in " + f.getAbsolutePath(),1,cff.getCount()); // tidy up... f = new File("_ajdump"); FileUtil.deleteContents(f); f.delete(); } public void testLTWDumpClosure() { runTest("LTW DumpTest closure"); File f = new File("_ajdump/ataspectj/DumpTestTheDump$AjcClosure1.class"); assertTrue("Missing dump file " + f.getAbsolutePath(),f.exists()); // tidy up... f = new File("_ajdump"); FileUtil.deleteContents(f); f.delete(); } public void testLTWDumpProxy() { runTest("LTW DumpTest proxy"); // The working directory is different because this test must be forked File dir = new File("../tests/java5/ataspectj"); File f = new File(dir,"_ajdump/_before"); CountingFilenameFilter cff = new CountingFilenameFilter(); f.listFiles(cff); assertEquals("Expected dump file in " + f.getAbsolutePath(),1,cff.getCount()); f = new File(dir,"_ajdump"); cff = new CountingFilenameFilter(); f.listFiles(cff); assertEquals(1,cff.getCount()); // tidy up... f = new File(dir,"_ajdump"); FileUtil.deleteContents(f); f.delete(); } public void testAjcAspect1LTWAspect2_Xreweavable() { runTest("Ajc Aspect1 LTW Aspect2 -Xreweavable"); } public void testLTWLogSilent() { runTest("LTW Log silent"); } public void testLTWLogVerbose() { runTest("LTW Log verbose"); } public void testLTWLogVerboseAndShow() { runTest("LTW Log verbose and showWeaveInfo"); } public void testLTWLogMessageHandlerClass() { runTest("LTW Log messageHandlerClass"); } public void testLTWUnweavable() { // actually test that we do LTW proxy and jit classes runTest("LTW Unweavable"); } public void testLTWDecp() { runTest("LTW Decp"); } public void testLTWDecp2() { runTest("LTW Decp2"); } public void testCompileTimeAspectsDeclaredToLTWWeaver() { runTest("Compile time aspects declared to ltw weaver"); } public void testConcreteAtAspect() { runTest("Concrete@Aspect"); } public void testConcreteAspect() { runTest("ConcreteAspect"); } public void testConcretePrecedenceAspect() { runTest("ConcretePrecedenceAspect"); } public void testAspectOfWhenAspectNotInInclude() { runTest("AspectOfWhenAspectNotInInclude"); } public void testAppContainer() { runTest("AppContainer"); } public void testCflowBelowStack() { runTest("CflowBelowStack"); } private static class CountingFilenameFilter implements FilenameFilter { private int count; public boolean accept(File dir, String name) { if (name.endsWith(".class")) count++; return false; } public int getCount() { return count; } } }
130,300
Bug 130300 Remove, hide or obfuscate -XnoWeave
This option is redundant apart from use in AspectJ development and maintenance. It is confusing to users and is a source new problems for LTW.
verified fixed
b225911
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-05T17:00:04Z
2006-03-03T12:46:40Z
tests/src/org/aspectj/systemtest/inpath/InPathTests.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.systemtest.inpath; import java.io.File; import junit.framework.Test; import org.aspectj.testing.XMLBasedAjcTestCase; public class InPathTests extends org.aspectj.testing.XMLBasedAjcTestCase { public static Test suite() { return XMLBasedAjcTestCase.loadSuite(InPathTests.class); } protected File getSpecFile() { return new File("../tests/src/org/aspectj/systemtest/inpath/inpath.xml"); } public void test001(){ runTest("source for options -injars"); } public void test002(){ runTest("options -injars"); } public void test003(){ runTest("options -injars checking declare parents interactions"); } // test removed from suite since aspects are *always* generated reweavable // public void test004(){ // runTest("The compiler crashes when using aspect libraries created without using -noweave"); // } public void test005(){ runTest("declare warnings on main"); } public void test006(){ runTest("declare warnings on binary javac 1.4 classes"); } public void test007(){ runTest("declare warnings on binary ajc 1.1 classes"); } public void test008(){ runTest("Weaving rt.jar results in stack overflow"); } public void test009(){ runTest("Weaving failure when using injars (no jars)"); } public void test010(){ runTest("Weaving failure when using injars (on aspectpath)"); } public void test011(){ runTest("Weaving failure when using injars (on classpath)"); } public void test012(){ runTest("Weaving failure when using injars (actual injars)"); } public void test013(){ runTest("Introduced abstract method on interface not implemented by subtype (injars)"); } public void test014(){ runTest("error Type mismatch: cannot convert from java.lang.String to java.lang.String"); } public void test015(){ runTest("declare error binary-weaving NPE"); } public void test016(){ runTest("declare error binary-weaving NPE"); } public void test017(){ runTest("Regression from 1.1: NPE in CompilationResult"); } }
101,411
Bug 101411 SerialVersionUID handling
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
resolved fixed
6e6658a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2006-03-09T17:24:19Z
2005-06-23T07:00:00Z
bcel-builder/src/org/aspectj/apache/bcel/generic/ClassGen.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 apache@apache.org. * * 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.Iterator; import java.util.List; import org.aspectj.apache.bcel.Constants; import org.aspectj.apache.bcel.classfile.AccessFlags; import org.aspectj.apache.bcel.classfile.Attribute; import org.aspectj.apache.bcel.classfile.ConstantPool; import org.aspectj.apache.bcel.classfile.Field; import org.aspectj.apache.bcel.classfile.JavaClass; import org.aspectj.apache.bcel.classfile.Method; import org.aspectj.apache.bcel.classfile.SourceFile; import org.aspectj.apache.bcel.classfile.Utility; import org.aspectj.apache.bcel.classfile.annotation.Annotation; import org.aspectj.apache.bcel.classfile.annotation.RuntimeInvisibleAnnotations; import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisibleAnnotations; import org.aspectj.apache.bcel.generic.annotation.AnnotationGen; /** * Template class for building up a java class. May be initialized with an * existing java class (file). * * @see JavaClass * @version $Id: ClassGen.java,v 1.5 2005/03/10 12:15:04 aclement Exp $ * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A> */ public class ClassGen extends AccessFlags implements Cloneable { /* Corresponds to the fields found in a JavaClass object. */ private String class_name, super_class_name, file_name; private int class_name_index = -1, superclass_name_index = -1; private int major = Constants.MAJOR_1_1, minor = Constants.MINOR_1_1; private ConstantPoolGen cp; // Template for building up constant pool // ArrayLists instead of arrays to gather fields, methods, etc. private ArrayList field_vec = new ArrayList(); private ArrayList method_vec = new ArrayList(); private ArrayList attribute_vec = new ArrayList(); private ArrayList interface_vec = new ArrayList(); private ArrayList annotation_vec= new ArrayList(); private boolean unpackedAnnotations = false; /** Convenience constructor to set up some important values initially. * * @param class_name fully qualified class name * @param super_class_name fully qualified superclass name * @param file_name source file name * @param access_flags access qualifiers * @param interfaces implemented interfaces * @param cp constant pool to use */ public ClassGen(String class_name, String super_class_name, String file_name, int access_flags, String[] interfaces, ConstantPoolGen cp) { this.class_name = class_name; this.super_class_name = super_class_name; this.file_name = file_name; this.access_flags = access_flags; this.cp = cp; // Put everything needed by default into the constant pool and the vectors if(file_name != null) addAttribute(new SourceFile(cp.addUtf8("SourceFile"), 2, cp.addUtf8(file_name), cp.getConstantPool())); class_name_index = cp.addClass(class_name); superclass_name_index = cp.addClass(super_class_name); if(interfaces != null) for(int i=0; i < interfaces.length; i++) addInterface(interfaces[i]); } /** Convenience constructor to set up some important values initially. * * @param class_name fully qualified class name * @param super_class_name fully qualified superclass name * @param file_name source file name * @param access_flags access qualifiers * @param interfaces implemented interfaces */ public ClassGen(String class_name, String super_class_name, String file_name, int access_flags, String[] interfaces) { this(class_name, super_class_name, file_name, access_flags, interfaces, new ConstantPoolGen()); } /** * Initialize with existing class. * @param clazz JavaClass object (e.g. read from file) */ public ClassGen(JavaClass clazz) { class_name_index = clazz.getClassNameIndex(); superclass_name_index = clazz.getSuperclassNameIndex(); class_name = clazz.getClassName(); super_class_name = clazz.getSuperclassName(); file_name = clazz.getSourceFileName(); access_flags = clazz.getAccessFlags(); cp = new ConstantPoolGen(clazz.getConstantPool()); major = clazz.getMajor(); minor = clazz.getMinor(); Attribute[] attributes = clazz.getAttributes(); // J5TODO: Could make unpacking lazy, done on first reference AnnotationGen[] annotations = unpackAnnotations(attributes); Method[] methods = clazz.getMethods(); Field[] fields = clazz.getFields(); String[] interfaces = clazz.getInterfaceNames(); for(int i=0; i < interfaces.length; i++) addInterface(interfaces[i]); for(int i=0; i < attributes.length; i++) { // Dont add attributes for annotations as those will have been unpacked if (annotations.length==0) { addAttribute(attributes[i]); } else if (!attributes[i].getName().equals("RuntimeVisibleAnnotations") && !attributes[i].getName().equals("RuntimeInvisibleAnnotations")) { addAttribute(attributes[i]); } } for(int i=0; i < annotations.length; i++) addAnnotation(annotations[i]); for(int i=0; i < methods.length; i++) { Method m = methods[i]; addMethod(m); } for(int i=0; i < fields.length; i++) addField(fields[i]); } /** * Look for attributes representing annotations and unpack them. */ private AnnotationGen[] unpackAnnotations(Attribute[] attrs) { List /*AnnotationGen*/ annotationGenObjs = new ArrayList(); for (int i = 0; i < attrs.length; i++) { Attribute attr = attrs[i]; if (attr instanceof RuntimeVisibleAnnotations) { RuntimeVisibleAnnotations rva = (RuntimeVisibleAnnotations)attr; List annos = rva.getAnnotations(); for (Iterator iter = annos.iterator(); iter.hasNext();) { Annotation a = (Annotation) iter.next(); annotationGenObjs.add(new AnnotationGen(a,getConstantPool(),false)); } } else if (attr instanceof RuntimeInvisibleAnnotations) { RuntimeInvisibleAnnotations ria = (RuntimeInvisibleAnnotations)attr; List annos = ria.getAnnotations(); for (Iterator iter = annos.iterator(); iter.hasNext();) { Annotation a = (Annotation) iter.next(); annotationGenObjs.add(new AnnotationGen(a,getConstantPool(),false)); } } } return (AnnotationGen[])annotationGenObjs.toArray(new AnnotationGen[]{}); } /** * @return the (finally) built up Java class object. */ public JavaClass getJavaClass() { int[] interfaces = getInterfaces(); Field[] fields = getFields(); Method[] methods = getMethods(); Attribute[] attributes = null; if (annotation_vec.size()==0) { attributes = getAttributes(); } else { // TODO: Sometime later, trash any attributes called 'RuntimeVisibleAnnotations' or 'RuntimeInvisibleAnnotations' Attribute[] annAttributes = Utility.getAnnotationAttributes(cp,annotation_vec); attributes = new Attribute[attribute_vec.size()+annAttributes.length]; attribute_vec.toArray(attributes); System.arraycopy(annAttributes,0,attributes,attribute_vec.size(),annAttributes.length); } // Must be last since the above calls may still add something to it ConstantPool cp = this.cp.getFinalConstantPool(); return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, access_flags, cp, interfaces, fields, methods, attributes); } /** * Add an interface to this class, i.e., this class has to implement it. * @param name interface to implement (fully qualified class name) */ public void addInterface(String name) { interface_vec.add(name); } /** * Remove an interface from this class. * @param name interface to remove (fully qualified name) */ public void removeInterface(String name) { interface_vec.remove(name); } /** * @return major version number of class file */ public int getMajor() { return major; } /** Set major version number of class file, default value is 45 (JDK 1.1) * @param major major version number */ public void setMajor(int major) { this.major = major; } /** Set minor version number of class file, default value is 3 (JDK 1.1) * @param minor minor version number */ public void setMinor(int minor) { this.minor = minor; } /** * @return minor version number of class file */ public int getMinor() { return minor; } /** * Add an attribute to this class. * @param a attribute to add */ public void addAttribute(Attribute a) { attribute_vec.add(a); } public void addAnnotation(AnnotationGen a) { annotation_vec.add(a); } /** * Add a method to this class. * @param m method to add */ public void addMethod(Method m) { method_vec.add(m); } /** * Convenience method. * * Add an empty constructor to this class that does nothing but calling super(). * @param access rights for constructor */ public void addEmptyConstructor(int access_flags) { InstructionList il = new InstructionList(); il.append(InstructionConstants.THIS); // Push `this' il.append(new INVOKESPECIAL(cp.addMethodref(super_class_name, "<init>", "()V"))); il.append(InstructionConstants.RETURN); MethodGen mg = new MethodGen(access_flags, Type.VOID, Type.NO_ARGS, null, "<init>", class_name, il, cp); mg.setMaxStack(1); mg.setMaxLocals(); addMethod(mg.getMethod()); } /** * Add a field to this class. * @param f field to add */ public void addField(Field f) { field_vec.add(f); } public boolean containsField(Field f) { return field_vec.contains(f); } /** @return field object with given name, or null */ public Field containsField(String name) { for(Iterator e=field_vec.iterator(); e.hasNext(); ) { Field f = (Field)e.next(); if(f.getName().equals(name)) return f; } return null; } /** @return method object with given name and signature, or null */ public Method containsMethod(String name, String signature) { for(Iterator e=method_vec.iterator(); e.hasNext();) { Method m = (Method)e.next(); if(m.getName().equals(name) && m.getSignature().equals(signature)) return m; } return null; } /** * Remove an attribute from this class. * @param a attribute to remove */ public void removeAttribute(Attribute a) { attribute_vec.remove(a); } public void removeAnnotation(AnnotationGen a) {annotation_vec.remove(a);} /** * Remove a method from this class. * @param m method to remove */ public void removeMethod(Method m) { method_vec.remove(m); } /** Replace given method with new one. If the old one does not exist * add the new_ method to the class anyway. */ public void replaceMethod(Method old, Method new_) { if(new_ == null) throw new ClassGenException("Replacement method must not be null"); int i = method_vec.indexOf(old); if(i < 0) method_vec.add(new_); else method_vec.set(i, new_); } /** Replace given field with new one. If the old one does not exist * add the new_ field to the class anyway. */ public void replaceField(Field old, Field new_) { if(new_ == null) throw new ClassGenException("Replacement method must not be null"); int i = field_vec.indexOf(old); if(i < 0) field_vec.add(new_); else field_vec.set(i, new_); } /** * Remove a field to this class. * @param f field to remove */ public void removeField(Field f) { field_vec.remove(f); } public String getClassName() { return class_name; } public String getSuperclassName() { return super_class_name; } public String getFileName() { return file_name; } public void setClassName(String name) { class_name = name.replace('/', '.'); class_name_index = cp.addClass(name); } public void setSuperclassName(String name) { super_class_name = name.replace('/', '.'); superclass_name_index = cp.addClass(name); } public Method[] getMethods() { Method[] methods = new Method[method_vec.size()]; method_vec.toArray(methods); return methods; } public void setMethods(Method[] methods) { method_vec.clear(); for(int m=0; m<methods.length; m++) addMethod(methods[m]); } public void setMethodAt(Method method, int pos) { method_vec.set(pos, method); } public Method getMethodAt(int pos) { return (Method)method_vec.get(pos); } public String[] getInterfaceNames() { int size = interface_vec.size(); String[] interfaces = new String[size]; interface_vec.toArray(interfaces); return interfaces; } public int[] getInterfaces() { int size = interface_vec.size(); int[] interfaces = new int[size]; for(int i=0; i < size; i++) interfaces[i] = cp.addClass((String)interface_vec.get(i)); return interfaces; } public Field[] getFields() { Field[] fields = new Field[field_vec.size()]; field_vec.toArray(fields); return fields; } public Attribute[] getAttributes() { Attribute[] attributes = new Attribute[attribute_vec.size()]; attribute_vec.toArray(attributes); return attributes; } // J5TODO: Should we make calling unpackAnnotations() lazy and put it in here? public AnnotationGen[] getAnnotations() { AnnotationGen[] annotations = new AnnotationGen[annotation_vec.size()]; annotation_vec.toArray(annotations); return annotations; } public ConstantPoolGen getConstantPool() { return cp; } public void setConstantPool(ConstantPoolGen constant_pool) { cp = constant_pool; } public void setClassNameIndex(int class_name_index) { this.class_name_index = class_name_index; class_name = cp.getConstantPool(). getConstantString(class_name_index, Constants.CONSTANT_Class).replace('/', '.'); } public void setSuperclassNameIndex(int superclass_name_index) { this.superclass_name_index = superclass_name_index; super_class_name = cp.getConstantPool(). getConstantString(superclass_name_index, Constants.CONSTANT_Class).replace('/', '.'); } public int getSuperclassNameIndex() { return superclass_name_index; } public int getClassNameIndex() { return class_name_index; } private ArrayList observers; /** Add observer for this object. */ public void addObserver(ClassObserver o) { if(observers == null) observers = new ArrayList(); observers.add(o); } /** Remove observer for this object. */ public void removeObserver(ClassObserver 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(); ) ((ClassObserver)e.next()).notify(this); } public Object clone() { try { return super.clone(); } catch(CloneNotSupportedException e) { System.err.println(e); return null; } } // J5SUPPORT: /** * Returns true if this class represents an annotation type */ public final boolean isAnnotation() { return (access_flags & Constants.ACC_ANNOTATION) != 0; } /** * Returns true if this class represents an enum type */ public final boolean isEnum() { return (access_flags & Constants.ACC_ENUM) != 0; } }