issue_id
int64 2.03k
426k
| title
stringlengths 9
251
| body
stringlengths 1
32.8k
⌀ | status
stringclasses 6
values | after_fix_sha
stringlengths 7
7
| project_name
stringclasses 6
values | repo_url
stringclasses 6
values | repo_name
stringclasses 6
values | language
stringclasses 1
value | issue_url
null | before_fix_sha
null | pull_url
null | commit_datetime
timestamp[us, tz=UTC] | report_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 2
187
| file_content
stringlengths 0
368k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
108,892
|
Bug 108892 Load Time Weaving problem with Aspect Definition at 2 Levels of Hierarchy
|
I am trying to weave into Tomcat with a system-level aspect (META-INF/aop.xml is found in a jar on the system classpath), and also have a Web application with an aop.xml properly deployed. When I try to run them both together, only the system-level aspects work. If I remove the system-level aspect jar from the classpath, the application-level aspects work. What would be a reasonable way to isolate this into a test case? If I could package up a simple system.jar and app.war file for Tomcat 5.5.9, would that be useful for you to use in debugging it? I tried making a simple standalone version with 2 aop.xml files in the same app classloader but that works just fine.
|
resolved fixed
|
794f9b5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-10-28T12:07:14Z
| 2005-09-07T02:26:40Z
|
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.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) {
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;
}
//FIXME 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;
// }
// the following block will not detect @Pointcut in non @Aspect types for optimization purpose
if (!hasAtAspectAnnotation) {
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)
|| handleDeclareImplementsAnnotation(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());
struct.ajAttributes.add(new AjAttribute.Aspect(perClause));
FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
final IScope binding;
binding = new BindingScope(
struct.enclosingType,
struct.context,
bindings
);
perClause.resolve(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 poincut = null;
TypePattern typePattern = null;
final PerClause perClause;
if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOW.getName())) {
pointcutString = PerClause.KindAnnotationPrefix.PERCFLOW.extractPointcut(perClauseString);
poincut = parsePointcut(pointcutString, struct, false);
perClause = new PerCflow(poincut, false);
} else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOWBELOW.getName())) {
pointcutString = PerClause.KindAnnotationPrefix.PERCFLOWBELOW.extractPointcut(perClauseString);
poincut = parsePointcut(pointcutString, struct, false);
perClause = new PerCflow(poincut, true);
} else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTARGET.getName())) {
pointcutString = PerClause.KindAnnotationPrefix.PERTARGET.extractPointcut(perClauseString);
poincut = parsePointcut(pointcutString, struct, false);
perClause = new PerObject(poincut, false);
} else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTHIS.getName())) {
pointcutString = PerClause.KindAnnotationPrefix.PERTHIS.extractPointcut(perClauseString);
poincut = parsePointcut(pointcutString, struct, false);
perClause = new PerObject(poincut, 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())
&& poincut == 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.isPrimitiveType()) {
return false;
} else if (fieldType.isInterface() && (struct.field.isPublic() && struct.field.isStatic())) {
TypePattern parent = new ExactTypePattern(UnresolvedType.forSignature(struct.field.getSignature()), false, false);
parent.resolve(struct.enclosingType.getWorld());
//TODO kick ISourceLocation sl = struct.bField.getSourceLocation(); ??
// first add the declare implements like
List parents = new ArrayList(1); parents.add(parent);
struct.ajAttributes.add(
new AjAttribute.DeclareAttribute(
new DeclareParents(
typePattern,
parents,
false
)
)
);
// then iterate on field interface hierarchy (not object)
for (Iterator it = fieldType.getMethods(); it.hasNext();) {
ResolvedMember method = (ResolvedMember)it.next();
if (method.isAbstract()) {
struct.ajAttributes.add(
new AjAttribute.TypeMunger(
new MethodDelegateTypeMunger(
method,
struct.enclosingType,
struct.field.getName(),
typePattern
)
)
);
}
}
return true;
} else {
reportError("@DeclareParents: can only be used on a public static 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) {
// 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.getLeft().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.getLeft().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; }
}
}
|
113,510
|
Bug 113510 readAspect
|
clearly define what the goal for readAspect is old byte per byte reading cause NPE in some test case current impl is hashcode for aspect name + classloader - ie unstable across startups.
|
resolved fixed
|
62d16d5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-02T10:36:05Z
| 2005-10-24T10:33:20Z
|
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
* David Knibb weaving context enhancments
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.Utility;
import org.aspectj.weaver.bcel.BcelObjectType;
import org.aspectj.weaver.loadtime.definition.Definition;
import org.aspectj.weaver.loadtime.definition.DocumentParser;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.tools.GeneratedClassHandler;
import org.aspectj.weaver.tools.WeavingAdaptor;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class ClassLoaderWeavingAdaptor extends WeavingAdaptor {
private final static String AOP_XML = "META-INF/aop.xml";
private List m_dumpTypePattern = new ArrayList();
private List m_includeTypePattern = new ArrayList();
private List m_excludeTypePattern = new ArrayList();
private List m_includeStartsWith = new ArrayList();
private List m_excludeStartsWith = new ArrayList();
private List m_aspectExcludeTypePattern = new ArrayList();
private List m_aspectExcludeStartsWith = new ArrayList();
private StringBuffer namespace;
private IWeavingContext weavingContext;
public ClassLoaderWeavingAdaptor(final ClassLoader loader, IWeavingContext wContext) {
super(null);
}
void initialize(final ClassLoader loader, IWeavingContext wContext) {
//super(null);// at this stage we don't have yet a generatedClassHandler to define to the VM the closures
this.generatedClassHandler = new GeneratedClassHandler() {
/**
* Callback when we need to define a Closure in the JVM
*
* @param name
* @param bytes
*/
public void acceptClass(String name, byte[] bytes) {
try {
if (shouldDump(name.replace('/', '.'))) {
Aj.dump(name, bytes);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
Aj.defineClass(loader, name, bytes);// could be done lazily using the hook
}
};
if(wContext==null){
weavingContext = new DefaultWeavingContext(loader);
}else{
weavingContext = wContext ;
}
bcelWorld = new BcelWorld(
loader, messageHandler, new ICrossReferenceHandler() {
public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) {
;// for tools only
}
}
);
// //TODO this AJ code will call
// //org.aspectj.apache.bcel.Repository.setRepository(this);
// //ie set some static things
// //==> bogus as Bcel is expected to be
// org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader));
weaver = new BcelWeaver(bcelWorld);
// register the definitions
registerDefinitions(weaver, loader);
// AV - see #113511 - not sure it is good to skip message handler
if (enabled) {
messageHandler = bcelWorld.getMessageHandler();
// after adding aspects
weaver.prepareForWeave();
}
}
/**
* Load and cache the aop.xml/properties according to the classloader visibility rules
*
* @param weaver
* @param loader
*/
private void registerDefinitions(final BcelWeaver weaver, final ClassLoader loader) {
try {
MessageUtil.info(messageHandler, "register classloader " + ((loader!=null)?loader.getClass().getName()+"@"+loader.hashCode():"null"));
//TODO av underoptimized: we will parse each XML once per CL that see it
List definitions = new ArrayList();
//TODO av dev mode needed ? TBD -Daj5.def=...
if (ClassLoader.getSystemClassLoader().equals(loader)) {
String file = System.getProperty("aj5.def", null);
if (file != null) {
MessageUtil.info(messageHandler, "using (-Daj5.def) " + file);
definitions.add(DocumentParser.parse((new File(file)).toURL()));
}
}
String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration",AOP_XML);
StringTokenizer st = new StringTokenizer(resourcePath,";");
while(st.hasMoreTokens()){
Enumeration xmls = weavingContext.getResources(st.nextToken());
// System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader);
while (xmls.hasMoreElements()) {
URL xml = (URL) xmls.nextElement();
MessageUtil.info(messageHandler, "using " + xml.getFile());
definitions.add(DocumentParser.parse(xml));
}
}
// still go thru if definitions is empty since we will configure
// the default message handler in there
registerOptions(weaver, loader, definitions);
// AV - see #113511
if (!definitions.isEmpty()) {
registerAspectExclude(weaver, loader, definitions);
registerAspects(weaver, loader, definitions);
registerIncludeExclude(weaver, loader, definitions);
registerDump(weaver, loader, definitions);
} else {
enabled = false;// will allow very fast skip in shouldWeave()
}
} catch (Exception e) {
weaver.getWorld().getMessageHandler().handleMessage(
new Message("Register definition failed", IMessage.WARNING, e, null)
);
}
}
/**
* Configure the weaver according to the option directives
* TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
StringBuffer allOptions = new StringBuffer();
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
allOptions.append(definition.getWeaverOptions()).append(' ');
}
Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader);
// configure the weaver and world
// AV - code duplicates AspectJBuilder.initWorldAndWeaver()
World world = weaver.getWorld();
world.setMessageHandler(weaverOption.messageHandler);
world.setXlazyTjp(weaverOption.lazyTjp);
world.setXHasMemberSupportEnabled(weaverOption.hasMember);
world.setPinpointMode(weaverOption.pinpoint);
weaver.setReweavableMode(weaverOption.notReWeavable);
world.setXnoInline(weaverOption.noInline);
world.setBehaveInJava5Way(weaverOption.java5);//TODO should be autodetected ?
//-Xlintfile: first so that lint wins
if (weaverOption.lintFile != null) {
InputStream resource = null;
try {
resource = loader.getResourceAsStream(weaverOption.lintFile);
Exception failure = null;
if (resource != null) {
try {
Properties properties = new Properties();
properties.load(resource);
world.getLint().setFromProperties(properties);
} catch (IOException e) {
failure = e;
}
}
if (failure != null || resource == null) {
world.getMessageHandler().handleMessage(new Message(
"Cannot access resource for -Xlintfile:"+weaverOption.lintFile,
IMessage.WARNING,
failure,
null));
}
} finally {
try { resource.close(); } catch (Throwable t) {;}
}
}
if (weaverOption.lint == null) {
bcelWorld.getLint().loadDefaultProperties();
} else {
if (weaverOption.lint.equals("default")) {//FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps..
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(weaverOption.lint);
}
}
//TODO proceedOnError option
}
private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_aspectExcludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_aspectExcludeStartsWith.add(fastMatchInfo);
}
}
}
}
/**
* Register the aspect, following include / exclude rules
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
//TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
// if not, review the getResource so that we track which resource is defined by which CL
//iterate aspectClassNames
//exclude if in any of the exclude list
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) {
String aspectClassName = (String) aspects.next();
if (acceptAspect(aspectClassName)) {
ResolvedType aspect = weaver.addLibraryAspect(aspectClassName);
if (aspect.isAbstract()) {
// this is a warning
weaver.getWorld().getMessageHandler().handleMessage(
new Message("Abstract aspect registered in aop.xml, use a <concrete-aspect> element instead", IMessage.WARNING, null, null)
);
}
//generate key for SC
String aspectCode = readAspect(aspectClassName, loader);
if(namespace==null){
namespace=new StringBuffer(aspectCode);
}else{
namespace = namespace.append(";"+aspectCode);
}
}
}
}
//iterate concreteAspects
//exclude if in any of the exclude list - note that the user defined name matters for that to happen
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getConcreteAspects().iterator(); aspects.hasNext();) {
Definition.ConcreteAspect concreteAspect = (Definition.ConcreteAspect) aspects.next();
if (acceptAspect(concreteAspect.name)) {
ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld());
if (!gen.validate()) {
weaver.getWorld().getMessageHandler().handleMessage(
new Message("Concrete-aspect '"+concreteAspect.name+"' could not be registered", IMessage.ERROR, null, null)
);
break;
}
this.generatedClassHandler.acceptClass(
concreteAspect.name,
gen.getBytes()
);
ResolvedType aspect = weaver.addLibraryAspect(concreteAspect.name);
//generate key for SC
String aspectCode = readAspect(concreteAspect.name, loader);
if(namespace==null){
namespace=new StringBuffer(aspectCode);
}else{
namespace = namespace.append(";"+aspectCode);
}
}
}
}
}
/**
* Register the include / exclude filters
* We duplicate simple patterns in startWith filters that will allow faster matching without ResolvedType
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_includeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_includeStartsWith.add(fastMatchInfo);
}
}
for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_excludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_excludeStartsWith.add(fastMatchInfo);
}
}
}
}
/**
* Checks if the type pattern can be handled as a startswith check
*
* TODO AV - enhance to support "char.sss" ie FQN direclty (match iff equals)
* we could also add support for "*..*charss" endsWith style?
*
* @param typePattern
* @return null if not possible, or the startWith sequence to test against
*/
private String looksLikeStartsWith(String typePattern) {
if (typePattern.indexOf('@') >= 0
|| typePattern.indexOf('+') >= 0
|| typePattern.indexOf(' ') >= 0
|| typePattern.charAt(typePattern.length()-1) != '*') {
return null;
}
// now must looks like with "charsss..*" or "cha.rss..*" etc
// note that "*" and "*..*" won't be fast matched
// and that "charsss.*" will not neither
int length = typePattern.length();
if (typePattern.endsWith("..*") && length > 3) {
if (typePattern.indexOf("..") == length-3 // no ".." before last sequence
&& typePattern.indexOf('*') == length-1) { // no "*" before last sequence
return typePattern.substring(0, length-2).replace('$', '.');
// ie "charsss." or "char.rss." etc
}
}
return null;
}
/**
* Register the dump filter
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) {
String dump = (String) iterator1.next();
TypePattern pattern = new PatternParser(dump).parseTypePattern();
m_dumpTypePattern.add(pattern);
}
}
}
protected boolean accept(String className, byte[] bytes) {
// avoid ResolvedType if not needed
if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
String fastClassName = className.replace('/', '.').replace('$', '.');
for (int i = 0; i < m_excludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_excludeStartsWith.get(i))) {
return false;
}
}
boolean fastAccept = false;//defaults to false if no fast include
for (int i = 0; i < m_includeStartsWith.size(); i++) {
fastAccept = fastClassName.startsWith((String)m_includeStartsWith.get(i));
if (fastAccept) {
break;
}
}
if (fastAccept) {
return true;
}
// needs further analysis
// TODO AV - needs refactoring
// during LTW this calling resolve at that stage is BAD as we do have the bytecode from the classloader hook
// but still go thru resolve that will do a getResourcesAsStream on disk
// this is also problematic for jit stub which are not on disk - as often underlying infra
// does returns null or some other info for getResourceAsStream (f.e. WLS 9 CR248491)
// Instead I parse the given bytecode. But this also means it will be parsed again in
// new WeavingClassFileProvider() from WeavingAdaptor.getWovenBytes()...
BcelObjectType bct = ((BcelWorld)weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(null, bytes));
ResolvedType classInfo = bct.getResolvedTypeX();//BAD: weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//exclude are "AND"ed
for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
private boolean acceptAspect(String aspectClassName) {
// avoid ResolvedType if not needed
if (m_aspectExcludeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectExcludeStartsWith.get(i))) {
return false;
}
}
// needs further analysis
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
//exclude are "AND"ed
for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
return true;
}
public boolean shouldDump(String className) {
// avoid ResolvedType if not needed
if (m_dumpTypePattern.isEmpty()) {
return false;
}
//TODO AV - optimize for className.startWith only
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//dump
for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// dump match
return true;
}
}
return false;
}
/*
* shared classes methods
*/
/**
* @return Returns the key.
*/
public String getNamespace() {
if(namespace==null) return "";
else return new String(namespace);
}
/**
* Check to see if any classes are stored in the generated classes cache.
* Then flush the cache if it is not empty
* @return true if a class has been generated and is stored in the cache
*/
public boolean generatedClassesExist(){
if(generatedClasses.size()>0) {
return true;
}
return false;
}
/**
* Flush the generated classes cache
*/
public void flushGeneratedClasses(){
generatedClasses = new HashMap();
}
/**
* Read in an aspect from the disk and return its bytecode as a String
* @param name the name of the aspect to read in
* @return the bytecode representation of the aspect
*/
private String readAspect(String name, ClassLoader loader){
if (true) return name+"@"+(loader==null?"0":Integer.toString(loader.hashCode()));
// FIXME AV - ?? can someone tell me why we read the whole bytecode
// especially one byte by one byte
// also it does some NPE sometime (see AtAjLTW "LTW Decp2")
InputStream is = null;
try {
String result = "";
is = loader.getResourceAsStream(name.replace('.','/')+".class");
int b = is.read();
while(b!=-1){
result = result + b;
b=is.read();
}
is.close();
return result;
} catch (IOException e) {
e.printStackTrace();
return "";
} catch (NullPointerException e) {
//probably tried to read in a "non aspect @missing@" aspect
System.err.println("ClassLoaderWeavingAdaptor.readAspect() name: "+name+" Exception: "+e);
return "";
} finally {
try {is.close();} catch (Throwable t) {;}
}
}
}
|
114,744
|
Bug 114744 NPE at CaptureBinding.java on wildcard in intertype field type
|
When compiling this program with ajc -1.5 public aspect Wildcard { Class<? extends Wildcard> Wildcard.cl; void foo() throws Exception { Wildcard ci = cl.newInstance(); } } ajc throws this exception java.lang.NullPointerException at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CaptureBinding.initializeBounds(CaptureBinding.java:75) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding.capture(ParameterizedTypeBinding.java:105) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference.resolveType(SingleNameReference.java:772) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:293) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.resolve(LocalDeclaration.java:199) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:422) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:178) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:400) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1076) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.resolve(AspectDeclaration.java:114) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1125) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:305) 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:759) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:225) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:151) at org.aspectj.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.ajc.Main.main(Main.java:83)
|
resolved fixed
|
ade32bc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-02T16:16:29Z
| 2005-11-02T14:00:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten 2004-07-26 extended to allow overloading of
* hierarchy builder
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding;
import org.aspectj.weaver.BoundedReferenceType;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeFactory;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableDeclaringElement;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.UnresolvedTypeVariableReferenceType;
import org.aspectj.weaver.World;
/**
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
private AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private boolean xSerializableAspects;
private World world;
private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap();
public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) {
AjLookupEnvironment aenv = (AjLookupEnvironment)env;
return aenv.factory;
}
public static EclipseFactory fromScopeLookupEnvironment(Scope scope) {
return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment);
}
public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) {
this.lookupEnvironment = lookupEnvironment;
this.buildManager = buildManager;
this.world = buildManager.getWorld();
this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects();
}
public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) {
this.lookupEnvironment = lookupEnvironment;
this.world = world;
this.xSerializableAspects = xSer;
this.buildManager = null;
}
public World getWorld() {
return world;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedType fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedType.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedType ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedType fromTypeBindingToRTX(TypeBinding tb) {
if (tb == null) return ResolvedType.MISSING;
ResolvedType ret = getWorld().resolve(fromBinding(tb));
return ret;
}
public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedType.NONE;
}
int len = bindings.length;
ResolvedType[] ret = new ResolvedType[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
public static String getName(TypeBinding binding) {
if (binding instanceof TypeVariableBinding) {
// The first bound may be null - so default to object?
TypeVariableBinding tvb = (TypeVariableBinding)binding;
if (tvb.firstBound!=null) {
return getName(tvb.firstBound);
} else {
return getName(tvb.superclass);
}
}
if (binding instanceof ReferenceBinding) {
return new String(
CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.'));
}
String packageName = new String(binding.qualifiedPackageName());
String className = new String(binding.qualifiedSourceName()).replace('.', '$');
if (packageName.length() > 0) {
className = packageName + "." + className;
}
//XXX doesn't handle arrays correctly (or primitives?)
return new String(className);
}
/**
* Some generics notes:
*
* Andy 6-May-05
* We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we
* see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not
* sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back
* the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to
* remember the type variable.
* Adrian 10-July-05
* When we forget it's a type variable we come unstuck when getting the declared members of a parameterized
* type - since we don't know it's a type variable we can't replace it with the type parameter.
*/
//??? going back and forth between strings and bindings is a waste of cycles
public UnresolvedType fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedType.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tb = (TypeVariableBinding) binding;
UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb);
return utvrt;
}
// handle arrays since the component type may need special treatment too...
if (binding instanceof ArrayBinding) {
ArrayBinding aBinding = (ArrayBinding) binding;
UnresolvedType componentType = fromBinding(aBinding.leafComponentType);
return UnresolvedType.makeArray(componentType, aBinding.dimensions);
}
if (binding instanceof WildcardBinding) {
WildcardBinding eWB = (WildcardBinding) binding;
UnresolvedType theType = TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature()));
// Repair the bound
// e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then
// the type variable in the unresolvedtype will be correct only in name. In that
// case let's set it correctly based on the one in the eclipse WildcardBinding
UnresolvedType theBound = null;
if (eWB.bound instanceof TypeVariableBinding) {
theBound = fromTypeVariableBinding((TypeVariableBinding)eWB.bound);
} else {
theBound = fromBinding(eWB.bound);
}
if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound);
if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound);
return theType;
}
if (binding instanceof ParameterizedTypeBinding) {
if (binding instanceof RawTypeBinding) {
// special case where no parameters are specified!
return UnresolvedType.forRawTypeName(getName(binding));
}
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
UnresolvedType[] arguments = null;
if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227)
arguments = new UnresolvedType[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = fromBinding(ptb.arguments[i]);
}
}
String baseTypeSignature = null;
ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true);
if (baseType != ResolvedType.MISSING) {
// can legitimately be missing if a bound refers to a type we haven't added to the world yet...
if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType();
baseTypeSignature = baseType.getErasureSignature();
} else {
baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature();
}
// Create an unresolved parameterized type. We can't create a resolved one as the
// act of resolution here may cause recursion problems since the parameters may
// be type variables that we haven't fixed up yet.
if (arguments==null) arguments=new UnresolvedType[0];
String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1);
return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments);
}
// Convert the source type binding for a generic type into a generic UnresolvedType
// notice we can easily determine the type variables from the eclipse object
// and we can recover the generic signature from it too - so we pass those
// to the forGenericType() method.
if (binding.isGenericType() &&
!binding.isParameterizedType() &&
!binding.isRawType()) {
TypeVariableBinding[] tvbs = binding.typeVariables();
TypeVariable[] tVars = new TypeVariable[tvbs.length];
for (int i = 0; i < tvbs.length; i++) {
TypeVariableBinding eclipseV = tvbs[i];
String name = CharOperation.charToString(eclipseV.sourceName);
tVars[i] = new TypeVariable(name,fromBinding(eclipseV.superclass()),fromBindings(eclipseV.superInterfaces()));
}
//TODO asc generics - temporary guard....
if (!(binding instanceof SourceTypeBinding))
throw new RuntimeException("Cant get the generic sig for "+binding.debugName());
return UnresolvedType.forGenericType(getName(binding),tVars,
CharOperation.charToString(((SourceTypeBinding)binding).genericSignature()));
}
// LocalTypeBinding have a name $Local$, we can get the real name by using the signature....
if (binding instanceof LocalTypeBinding) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
return UnresolvedType.forSignature(new String(binding.signature()));
} else {
// we're reporting a problem and don't have a resolved name for an
// anonymous local type yet, report the issue on the enclosing type
return UnresolvedType.forSignature(new String(ltb.enclosingType.signature()));
}
}
return UnresolvedType.forName(getName(binding));
}
/**
* Some type variables refer to themselves recursively, this enables us to avoid
* recursion problems.
*/
private static Map typeVariableBindingsInProgress = new HashMap();
/**
* Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ
* form (TypeVariable).
*/
private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) {
// first, check for recursive call to this method for the same tvBinding
if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) {
return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding);
}
// Check if its a type variable binding that we need to recover to an alias...
if (typeVariablesForAliasRecovery!=null) {
String aliasname = (String)typeVariablesForAliasRecovery.get(aTypeVariableBinding);
if (aliasname!=null) {
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
ret.setTypeVariable(new TypeVariable(aliasname));
return ret;
}
}
if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) {
return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName));
}
// Create the UnresolvedTypeVariableReferenceType for the type variable
String name = CharOperation.charToString(aTypeVariableBinding.sourceName());
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
typeVariableBindingsInProgress.put(aTypeVariableBinding,ret);
// Dont set any bounds here, you'll get in a recursive mess
// TODO -- what about lower bounds??
UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass());
UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length];
for (int i = 0; i < superinterfaces.length; i++) {
superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]);
}
TypeVariable tv = new TypeVariable(name,superclassType,superinterfaces);
tv.setUpperBound(superclassType);
tv.setAdditionalInterfaceBounds(superinterfaces);
tv.setRank(aTypeVariableBinding.rank);
if (aTypeVariableBinding.declaringElement instanceof MethodBinding) {
tv.setDeclaringElementKind(TypeVariable.METHOD);
// tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement);
} else {
tv.setDeclaringElementKind(TypeVariable.TYPE);
// // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement));
}
ret.setTypeVariable(tv);
if (aTypeVariableBinding.declaringElement instanceof MethodBinding)
typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret);
typeVariableBindingsInProgress.remove(aTypeVariableBinding);
return ret;
}
public UnresolvedType[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return UnresolvedType.NONE;
int len = bindings.length;
UnresolvedType[] ret = new UnresolvedType[len];
for (int i=0; i<len; i++) {
ret[i] = fromBinding(bindings[i]);
}
return ret;
}
public static ASTNode astForLocation(IHasPosition location) {
return new EmptyStatement(location.getStart(), location.getEnd());
}
public Collection getDeclareParents() {
return getWorld().getDeclareParents();
}
public Collection getDeclareAnnotationOnTypes() {
return getWorld().getDeclareAnnotationOnTypes();
}
public Collection getDeclareAnnotationOnFields() {
return getWorld().getDeclareAnnotationOnFields();
}
public Collection getDeclareAnnotationOnMethods() {
return getWorld().getDeclareAnnotationOnMethods();
}
public Collection finishedTypeMungers = null;
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers();
baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers());
for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next();
EclipseTypeMunger etm = makeEclipseTypeMunger(munger);
if (etm != null) ret.add(etm);
}
finishedTypeMungers = ret;
}
public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) {
//System.err.println("make munger: " + concrete);
//!!! can't do this if we want incremental to work right
//if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete;
//System.err.println(" was not eclipse");
if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) {
AbstractMethodDeclaration method = null;
if (concrete instanceof EclipseTypeMunger) {
method = ((EclipseTypeMunger)concrete).getSourceMethod();
}
EclipseTypeMunger ret =
new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method);
if (ret.getSourceLocation() == null) {
ret.setSourceLocation(concrete.getSourceLocation());
}
return ret;
} else {
return null;
}
}
public Collection getTypeMungers() {
//??? assert finishedTypeMungers != null
return finishedTypeMungers;
}
public ResolvedMember makeResolvedMember(MethodBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
/**
* Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done
* in the scope of some type variables. Before converting the parts of a methodbinding
* (params, return type) we store the type variables in this structure, then should any
* component of the method binding refer to them, we grab them from the map.
*/
private Map typeVariablesForThisMember = new HashMap();
/**
* This is a map from typevariablebindings (eclipsey things) to the names the user
* originally specified in their ITD. For example if the target is 'interface I<N extends Number> {}'
* and the ITD was 'public void I<X>.m(List<X> lxs) {}' then this map would contain a pointer
* from the eclipse type 'N extends Number' to the letter 'X'.
*/
private Map typeVariablesForAliasRecovery;
/**
* Construct a resolvedmember from a methodbinding. The supplied map tells us about any
* typevariablebindings that replaced typevariables whilst the compiler was resolving types -
* this only happens if it is a generic itd that shares type variables with its target type.
*/
public ResolvedMember makeResolvedMemberForITD(MethodBinding binding,TypeBinding declaringType,
Map /*TypeVariableBinding > original alias name*/ recoveryAliases) {
ResolvedMember result = null;
try {
typeVariablesForAliasRecovery = recoveryAliases;
result = makeResolvedMember(binding,declaringType);
} finally {
typeVariablesForAliasRecovery = null;
}
return result;
}
public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
// Convert the type variables and store them
UnresolvedType[] ajTypeRefs = null;
typeVariablesForThisMember.clear();
// This is the set of type variables available whilst building the resolved member...
if (binding.typeVariables!=null) {
ajTypeRefs = new UnresolvedType[binding.typeVariables.length];
for (int i = 0; i < binding.typeVariables.length; i++) {
ajTypeRefs[i] = fromBinding(binding.typeVariables[i]);
typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]);
}
}
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
ResolvedMemberImpl ret = new ResolvedMemberImpl(
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD,
realDeclaringType,
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions)
);
if (binding.isVarargs()) {
ret.setVarargsMethod();
}
if (ajTypeRefs!=null) {
TypeVariable[] tVars = new TypeVariable[ajTypeRefs.length];
for (int i=0;i<ajTypeRefs.length;i++) {
tVars[i]=((TypeVariableReference)ajTypeRefs[i]).getTypeVariable();
}
ret.setTypeVariables(tVars);
}
typeVariablesForThisMember.clear();
ret.resolve(world);
return ret;
}
public ResolvedMember makeResolvedMember(FieldBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) {
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
return new ResolvedMemberImpl(
Member.FIELD,
realDeclaringType,
binding.modifiers,
world.resolve(fromBinding(binding.type)),
new String(binding.name),
UnresolvedType.NONE);
}
public TypeBinding makeTypeBinding(UnresolvedType typeX) {
TypeBinding ret = null;
// looking up type variables can get us into trouble
if (!typeX.isTypeVariableReference())
ret = (TypeBinding)typexToBinding.get(typeX);
if (ret == null) {
ret = makeTypeBinding1(typeX);
// FIXME asc keep type variables *out* of the map for now, they go in typeVariableToTypeBinding
if (!(typeX instanceof BoundedReferenceType) && !(typeX instanceof UnresolvedTypeVariableReferenceType))
typexToBinding.put(typeX, ret);
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
private TypeBinding makeTypeBinding1(UnresolvedType typeX) {
if (typeX.isPrimitiveType()) {
if (typeX == ResolvedType.BOOLEAN) return BaseTypes.BooleanBinding;
if (typeX == ResolvedType.BYTE) return BaseTypes.ByteBinding;
if (typeX == ResolvedType.CHAR) return BaseTypes.CharBinding;
if (typeX == ResolvedType.DOUBLE) return BaseTypes.DoubleBinding;
if (typeX == ResolvedType.FLOAT) return BaseTypes.FloatBinding;
if (typeX == ResolvedType.INT) return BaseTypes.IntBinding;
if (typeX == ResolvedType.LONG) return BaseTypes.LongBinding;
if (typeX == ResolvedType.SHORT) return BaseTypes.ShortBinding;
if (typeX == ResolvedType.VOID) return BaseTypes.VoidBinding;
throw new RuntimeException("weird primitive type " + typeX);
} else if (typeX.isArray()) {
int dim = 0;
while (typeX.isArray()) {
dim++;
typeX = typeX.getComponentType();
}
return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim);
} else if (typeX.isParameterizedType()) {
// Converting back to a binding from a UnresolvedType
UnresolvedType[] typeParameters = typeX.getTypeParameters();
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length];
for (int i = 0; i < argumentBindings.length; i++) {
argumentBindings[i] = makeTypeBinding(typeParameters[i]);
}
ParameterizedTypeBinding ptb =
lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType());
return ptb;
} else if (typeX.isTypeVariableReference()) {
// return makeTypeVariableBinding((TypeVariableReference)typeX);
return makeTypeVariableBindingFromAJTypeVariable(((TypeVariableReference)typeX).getTypeVariable());
} else if (typeX.isRawType()) {
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType());
return rtb;
} else if (typeX.isGenericWildcard()) {
// translate from boundedreferencetype to WildcardBinding
BoundedReferenceType brt = (BoundedReferenceType)typeX;
// Work out 'kind' for the WildcardBinding
int boundkind = Wildcard.UNBOUND;
TypeBinding bound = null;
if (brt.isExtends()) {
boundkind = Wildcard.EXTENDS;
bound = makeTypeBinding(brt.getUpperBound());
} else if (brt.isSuper()) {
boundkind = Wildcard.SUPER;
bound = makeTypeBinding(brt.getLowerBound());
}
TypeBinding[] otherBounds = null;
if (brt.getAdditionalBounds()!=null && brt.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(brt.getAdditionalBounds());
// FIXME asc rank should not always be 0 ...
WildcardBinding wb = lookupEnvironment.createWildcard(null,0,bound,otherBounds,boundkind);
return wb;
} else {
return lookupBinding(typeX.getName());
}
}
private ReferenceBinding lookupBinding(String sname) {
char[][] name = CharOperation.splitOn('.', sname.toCharArray());
ReferenceBinding rb = lookupEnvironment.getType(name);
return rb;
}
public TypeBinding[] makeTypeBindings(UnresolvedType[] types) {
int len = types.length;
TypeBinding[] ret = new TypeBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeBinding(types[i]);
}
return ret;
}
// just like the code above except it returns an array of ReferenceBindings
private ReferenceBinding[] makeReferenceBindings(UnresolvedType[] types) {
int len = types.length;
ReferenceBinding[] ret = new ReferenceBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = (ReferenceBinding)makeTypeBinding(types[i]);
}
return ret;
}
// field related
public FieldBinding makeFieldBinding(NewFieldTypeMunger nftm) {
return internalMakeFieldBinding(nftm.getSignature(),nftm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member,List aliases) {
return internalMakeFieldBinding(member,aliases);
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member) {
return internalMakeFieldBinding(member,null);
}
/**
* Take a normal AJ member and convert it into an eclipse fieldBinding.
* Taking into account any aliases that it may include due to being
* a generic itd. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* fieldbinding.
*/
public FieldBinding internalMakeFieldBinding(ResolvedMember member,List aliases) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()>0) {
int i =0;
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,declaringType.typeVariables()[i++]);
}
}
currentType = declaringType;
FieldBinding fb = new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
currentType,
Constant.NotAConstant);
typeVariableToTypeBinding.clear();
currentType = null;
return fb;
}
private ReferenceBinding currentType = null;
// method binding related
public MethodBinding makeMethodBinding(NewMethodTypeMunger nmtm) {
return internalMakeMethodBinding(nmtm.getSignature(),nmtm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases);
}
/**
* Creates a method binding for a resolvedmember taking into account type variable aliases -
* this variant can take an aliasTargetType and should be used when the alias target type
* cannot be retrieved from the resolvedmember.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
return internalMakeMethodBinding(member,aliases,aliasTargetType);
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member) {
return internalMakeMethodBinding(member,null); // there are no aliases
}
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases,member.getDeclaringType());
}
/**
* Take a normal AJ member and convert it into an eclipse methodBinding.
* Taking into account any aliases that it may include due to being a
* generic ITD. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* methodbinding
*/
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
if (member.getTypeVariables()!=null) {
if (member.getTypeVariables().length==0) {
tvbs = MethodBinding.NoTypeVariables;
} else {
tvbs = makeTypeVariableBindingsFromAJTypeVariables(member.getTypeVariables());
// QQQ do we need to bother fixing up the declaring element here?
}
}
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()!=0) {
int i=0;
ReferenceBinding aliasTarget = (ReferenceBinding)makeTypeBinding(aliasTargetType);
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,aliasTarget.typeVariables()[i++]);
}
}
currentType = declaringType;
MethodBinding mb = new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
declaringType);
if (tvbs!=null) mb.typeVariables = tvbs;
typeVariableToTypeBinding.clear();
currentType = null;
return mb;
}
/**
* Convert a bunch of type variables in one go, from AspectJ form to Eclipse form.
*/
// private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) {
// int len = typeVariables.length;
// TypeVariableBinding[] ret = new TypeVariableBinding[len];
// for (int i = 0; i < len; i++) {
// ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]);
// }
// return ret;
// }
private TypeVariableBinding[] makeTypeVariableBindingsFromAJTypeVariables(TypeVariable[] typeVariables) {
int len = typeVariables.length;
TypeVariableBinding[] ret = new TypeVariableBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeVariableBindingFromAJTypeVariable(typeVariables[i]);
}
return ret;
}
// only accessed through private methods in this class. Ensures all type variables we encounter
// map back to the same type binding - this is important later when Eclipse code is processing
// a methodbinding trying to come up with possible bindings for the type variables.
// key is currently the name of the type variable...is that ok?
private Map typeVariableToTypeBinding = new HashMap();
/**
* Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference
* in AspectJ world holds a TypeVariable and it is this type variable that is converted
* to the TypeVariableBinding.
*/
private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) {
TypeVariable tv = tvReference.getTypeVariable();
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
private TypeVariableBinding makeTypeVariableBindingFromAJTypeVariable(TypeVariable tv) {
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
public MethodBinding makeMethodBindingForCall(Member member) {
return new MethodBinding(member.getCallsiteModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
new ReferenceBinding[0],
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public void finishedCompilationUnit(CompilationUnitDeclaration unit) {
if ((buildManager != null) && buildManager.doGenerateModel()) {
AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig);
}
}
public void addTypeBinding(TypeBinding binding) {
typexToBinding.put(fromBinding(binding), binding);
}
public Shadow makeShadow(ASTNode location, ReferenceContext context) {
return EclipseShadow.makeShadow(this, location, context);
}
public Shadow makeShadow(ReferenceContext context) {
return EclipseShadow.makeShadow(this, (ASTNode) context, context);
}
public void addSourceTypeBinding(SourceTypeBinding binding, CompilationUnitDeclaration unit) {
TypeDeclaration decl = binding.scope.referenceContext;
// Deal with the raw/basic type to give us an entry in the world type map
UnresolvedType simpleTx = null;
if (binding.isGenericType()) {
simpleTx = UnresolvedType.forRawTypeName(getName(binding));
} else if (binding.isLocalType()) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
simpleTx = UnresolvedType.forSignature(new String(binding.signature()));
} else {
simpleTx = UnresolvedType.forName(getName(binding));
}
}else {
simpleTx = UnresolvedType.forName(getName(binding));
}
ReferenceType name = getWorld().lookupOrCreateName(simpleTx);
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl, unit);
// For generics, go a bit further - build a typex for the generic type
// give it the same delegate and link it to the raw type
if (binding.isGenericType()) {
UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info
ReferenceType complexName = new ReferenceType(complexTx,world);//getWorld().lookupOrCreateName(complexTx);
name.setGenericType(complexName);
complexName.setDelegate(t);
complexName.setSourceContext(t.getResolvedTypeX().getSourceContext());
}
name.setDelegate(t);
if (decl instanceof AspectDeclaration) {
((AspectDeclaration)decl).typeX = name;
((AspectDeclaration)decl).concreteName = t;
}
ReferenceBinding[] memberTypes = binding.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit);
}
}
// XXX this doesn't feel like it belongs here, but it breaks a hard dependency on
// exposing AjBuildManager (needed by AspectDeclaration).
public boolean isXSerializableAspects() {
return xSerializableAspects;
}
public ResolvedMember fromBinding(MethodBinding binding) {
return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers,
fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters));
}
public TypeVariableDeclaringElement fromBinding(Binding declaringElement) {
if (declaringElement instanceof TypeBinding) {
return fromBinding(((TypeBinding)declaringElement));
} else {
return fromBinding((MethodBinding)declaringElement);
}
}
}
|
114,744
|
Bug 114744 NPE at CaptureBinding.java on wildcard in intertype field type
|
When compiling this program with ajc -1.5 public aspect Wildcard { Class<? extends Wildcard> Wildcard.cl; void foo() throws Exception { Wildcard ci = cl.newInstance(); } } ajc throws this exception java.lang.NullPointerException at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CaptureBinding.initializeBounds(CaptureBinding.java:75) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding.capture(ParameterizedTypeBinding.java:105) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleNameReference.resolveType(SingleNameReference.java:772) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MessageSend.resolveType(MessageSend.java:293) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.resolve(LocalDeclaration.java:199) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolveStatements(AbstractMethodDeclaration.java:422) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.resolveStatements(MethodDeclaration.java:178) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:400) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1076) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.resolve(AspectDeclaration.java:114) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1125) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:305) 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:759) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:225) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:151) at org.aspectj.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.ajc.Main.main(Main.java:83)
|
resolved fixed
|
ade32bc
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-02T16:16:29Z
| 2005-11-02T14:00:00Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
*/
public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");}
public void testCCEGenerics_pr113445() { runTest("Generics ClassCastException");}
public void testMatthewsAspect_pr113947_1() { runTest("maws generic aspect - 1");}
public void testMatthewsAspect_pr113947_2() { runTest("maws generic aspect - 2");}
public void testFieldGet_pr114343() { runTest("field-get, generics and around advice");}
public void testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testIncompatibleClassChangeError_pr113630_1() {runTest("IncompatibleClassChangeError - errorscenario");}
public void testIncompatibleClassChangeError_pr113630_2() {runTest("IncompatibleClassChangeError - workingscenario");}
public void testFieldGetProblemWithGenericField_pr113861() {runTest("field-get problems with generic field");}
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 testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
112,476
|
Bug 112476 "declare parents" does not work with bytecode weaving
| null |
resolved fixed
|
a7e13f1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-04T10:47:47Z
| 2005-10-13T13:26:40Z
|
tests/bugs150/pr112476/case1/lib/A.java
| |
112,476
|
Bug 112476 "declare parents" does not work with bytecode weaving
| null |
resolved fixed
|
a7e13f1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-04T10:47:47Z
| 2005-10-13T13:26:40Z
|
tests/bugs150/pr112476/case1/lib/B.java
| |
112,476
|
Bug 112476 "declare parents" does not work with bytecode weaving
| null |
resolved fixed
|
a7e13f1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-04T10:47:47Z
| 2005-10-13T13:26:40Z
|
tests/bugs150/pr112476/case1/lib/C.java
| |
112,476
|
Bug 112476 "declare parents" does not work with bytecode weaving
| null |
resolved fixed
|
a7e13f1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-04T10:47:47Z
| 2005-10-13T13:26:40Z
|
tests/bugs150/pr112476/case1/weaved/SuperC.java
| |
112,476
|
Bug 112476 "declare parents" does not work with bytecode weaving
| null |
resolved fixed
|
a7e13f1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-04T10:47:47Z
| 2005-10-13T13:26:40Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
*/
public void testUnboundFormal_pr112027() { runTest("unexpected error unboundFormalInPC");}
public void 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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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 testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
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");
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
112,476
|
Bug 112476 "declare parents" does not work with bytecode weaving
| null |
resolved fixed
|
a7e13f1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-04T10:47:47Z
| 2005-10-13T13:26:40Z
|
weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* 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.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.PerObjectInterface) {
changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) {
// PTWIMPL Transform the target type (add the aspect instance field)
changed = mungePerTypeWithinTransformer(weaver);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) {
changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger)munger);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.Constructor) {
changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.Parent) {
changed = mungeNewParent(weaver, (NewParentTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) {
changed = mungeNewAnnotationOnType(weaver,(AnnotationOnTypeMunger)munger);
} else {
throw new RuntimeException("unimplemented");
}
if (changed && munger.changesPublicSignature()) {
WeaverStateInfo info =
weaver.getLazyClassGen().getOrCreateWeaverStateInfo(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 {
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) {
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();
List mgs = newParentTarget.getMethodGens();
// Look for ctors to modify
for (Iterator iter = mgs.iterator(); iter.hasNext();) {
LazyMethodGen aMethod = (LazyMethodGen) iter.next();
if (aMethod.getName().equals("<init>")) {
InstructionList insList = aMethod.getBody();
InstructionHandle handle = insList.getStart();
while (handle!= null) {
if (handle.getInstruction() instanceof INVOKESPECIAL) {
ConstantPoolGen cpg = newParentTarget.getConstantPoolGen();
INVOKESPECIAL invokeSpecial = (INVOKESPECIAL)handle.getInstruction();
if (invokeSpecial.getClassName(cpg).equals(currentParent) && invokeSpecial.getMethodName(cpg).equals("<init>")) {
// System.err.println("Transforming super call '<init>"+sp.getSignature(cpg)+"'");
// 1. Check there is a ctor in the new parent with the same signature
ResolvedMember newCtor = getConstructorWithSignature(newParent,invokeSpecial.getSignature(cpg));
if (newCtor == null) {
// 2. Check ITDCs to see if the necessary ctor is provided that way
boolean satisfiedByITDC = false;
for (Iterator ii = newParentTarget.getType().getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC; ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)ii.next();
if (m.getMunger() instanceof NewConstructorTypeMunger) {
if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) {
satisfiedByITDC = true;
}
}
}
if (!satisfiedByITDC) {
String csig = createReadableCtorSig(newParent, cpg, invokeSpecial);
weaver.getWorld().getMessageHandler().handleMessage(MessageUtil.error(
"Unable to modify hierarchy for "+newParentTarget.getClassName()+" - the constructor "+
csig+" is missing",this.getSourceLocation()));
return false;
}
}
int idx = cpg.addMethodref(newParent.getClassName(), invokeSpecial.getMethodName(cpg), invokeSpecial.getSignature(cpg));
invokeSpecial.setIndex(idx);
}
}
handle = handle.getNext();
}
}
}
return true;
}
/**
* Creates a nice signature for the ctor, something like "(int,Integer,String)"
*/
private String createReadableCtorSig(ResolvedType newParent, ConstantPoolGen cpg, INVOKESPECIAL invokeSpecial) {
StringBuffer sb = new StringBuffer();
Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg);
sb.append(newParent.getClassName());
sb.append("(");
for (int i = 0; i < ctorArgs.length; i++) {
String argtype = ctorArgs[i].toString();
if (argtype.lastIndexOf(".")!=-1)
sb.append(argtype.substring(argtype.lastIndexOf(".")+1));
else
sb.append(argtype);
if (i+1<ctorArgs.length) sb.append(",");
}
sb.append(")");
return sb.toString();
}
private ResolvedMember getConstructorWithSignature(ResolvedType tx,String signature) {
ResolvedMember[] mems = tx.getDeclaredJavaMethods();
for (int i = 0; i < mems.length; i++) {
ResolvedMember rm = mems[i];
if (rm.getName().equals("<init>")) {
if (rm.getSignature().equals(signature)) return rm;
}
}
return null;
}
private boolean mungePrivilegedAccess(
BcelClassWeaver weaver,
PrivilegedAccessMunger munger)
{
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedMember member = munger.getMember();
ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(),munger.getSourceLocation());
if (onType.isRawType()) onType = onType.getGenericType();
//System.out.println("munging: " + gen + " with " + member);
if (onType.equals(gen.getType())) {
if (member.getKind() == Member.FIELD) {
//System.out.println("matched: " + gen);
addFieldGetter(gen, member,
AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member));
addFieldSetter(gen, member,
AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member));
return true;
} else if (member.getKind() == Member.METHOD) {
addMethodDispatch(gen, member,
AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member));
return true;
} else if (member.getKind() == Member.CONSTRUCTOR) {
for (Iterator i = gen.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen m = (LazyMethodGen)i.next();
if (m.getMemberView() != null
&& m.getMemberView().getKind() == Member.CONSTRUCTOR) {
// m.getMemberView().equals(member)) {
m.forcePublic();
//return true;
}
}
return true;
//throw new BCException("no match for " + member + " in " + gen);
} else if (member.getKind() == Member.STATIC_INITIALIZATION) {
gen.forcePublic();
return true;
} else {
throw new RuntimeException("unimplemented");
}
}
return false;
}
private void addFieldGetter(
LazyClassGen gen,
ResolvedMember field,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
if (field.isStatic()) {
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
BcelWorld.makeBcelType(field.getType()), Constants.GETSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
BcelWorld.makeBcelType(field.getType()), Constants.GETFIELD));
}
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType())));
mg.getBody().insert(il);
gen.addMethodGen(mg,getSignature().getSourceLocation());
}
private void addFieldSetter(
LazyClassGen gen,
ResolvedMember field,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
Type fieldType = BcelWorld.makeBcelType(field.getType());
if (field.isStatic()) {
il.append(InstructionFactory.createLoad(fieldType, 0));
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
fieldType, Constants.PUTSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(InstructionFactory.createLoad(fieldType, 1));
il.append(fact.createFieldAccess(
gen.getClassName(),
field.getName(),
fieldType, Constants.PUTFIELD));
}
il.append(InstructionFactory.createReturn(Type.VOID));
mg.getBody().insert(il);
gen.addMethodGen(mg,getSignature().getSourceLocation());
}
private void addMethodDispatch(
LazyClassGen gen,
ResolvedMember method,
ResolvedMember accessMethod)
{
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
//Type fieldType = BcelWorld.makeBcelType(field.getType());
Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes());
int pos = 0;
if (!method.isStatic()) {
il.append(InstructionConstants.ALOAD_0);
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
il.append(InstructionFactory.createLoad(paramType, pos));
pos+=paramType.getSize();
}
il.append(Utility.createInvoke(fact, (BcelWorld)aspectType.getWorld(),
method));
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType())));
mg.getBody().insert(il);
gen.addMethodGen(mg);
}
protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) {
LazyMethodGen ret = new LazyMethodGen(
member.getModifiers(),
BcelWorld.makeBcelType(member.getReturnType()),
member.getName(),
BcelWorld.makeBcelTypes(member.getParameterTypes()),
UnresolvedType.getNames(member.getExceptions()),
gen);
// 43972 : Static crosscutting makes interfaces unusable for javac
// ret.makeSynthetic();
return ret;
}
protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) {
return new FieldGen(
member.getModifiers(),
BcelWorld.makeBcelType(member.getReturnType()),
member.getName(),
gen.getConstantPoolGen());
}
private boolean mungePerObjectInterface(
BcelClassWeaver weaver,
PerObjectInterfaceTypeMunger munger)
{
LazyClassGen gen = weaver.getLazyClassGen();
if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) {
FieldGen fg = makeFieldGen(gen,
AjcMemberMaker.perObjectField(gen.getType(), aspectType));
gen.addField(fg.getField(),getSourceLocation());
Type fieldType = BcelWorld.makeBcelType(aspectType);
LazyMethodGen mg = new LazyMethodGen(
Modifier.PUBLIC,
fieldType,
NameMangler.perObjectInterfaceGet(aspectType),
new Type[0], new String[0],
gen);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.GETFIELD));
il.append(InstructionFactory.createReturn(fieldType));
mg.getBody().insert(il);
gen.addMethodGen(mg);
LazyMethodGen mg1 = new LazyMethodGen(
Modifier.PUBLIC,
Type.VOID,
NameMangler.perObjectInterfaceSet(aspectType),
new Type[]{fieldType,}, new String[0],
gen);
InstructionList il1 = new InstructionList();
il1.append(InstructionConstants.ALOAD_0);
il1.append(InstructionFactory.createLoad(fieldType, 1));
il1.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.PUTFIELD));
il1.append(InstructionFactory.createReturn(Type.VOID));
mg1.getBody().insert(il1);
gen.addMethodGen(mg1);
gen.addInterface(munger.getInterfaceType(),getSourceLocation());
return true;
} else {
return false;
}
}
// PTWIMPL Add field to hold aspect instance and an accessor
private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) {
LazyClassGen gen = weaver.getLazyClassGen();
// if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) {
// Add (to the target type) the field that will hold the aspect instance
// e.g ajc$com_blah_SecurityAspect$ptwAspectInstance
FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType));
gen.addField(fg.getField(),getSourceLocation());
// Add an accessor for this new field, the ajc$<aspectname>$localAspectOf() method
// e.g. "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()"
Type fieldType = BcelWorld.makeBcelType(aspectType);
LazyMethodGen mg = new LazyMethodGen(
Modifier.PUBLIC | Modifier.STATIC,fieldType,
NameMangler.perTypeWithinLocalAspectOf(aspectType),
new Type[0], new String[0],gen);
InstructionList il = new InstructionList();
//PTWIMPL ?? Should check if it is null and throw NoAspectBoundException
InstructionFactory fact = gen.getFactory();
il.append(fact.createFieldAccess(
gen.getClassName(),
fg.getName(),
fieldType, Constants.GETSTATIC));
il.append(InstructionFactory.createReturn(fieldType));
mg.getBody().insert(il);
gen.addMethodGen(mg);
return true;
// } else {
// return false;
// }
}
// ??? Why do we have this method? I thought by now we would know if it matched or not
private boolean couldMatch(
BcelObjectType bcelObjectType,
Pointcut pointcut) {
return !bcelObjectType.isInterface();
}
private boolean mungeNewMethod(BcelClassWeaver weaver, NewMethodTypeMunger munger) {
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();
// getstatic field from aspect
body.append(Utility.createGet(fact, munger.getDelegate()));
int pos = 0;
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 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));
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();
}
}
|
90,143
|
Bug 90143 [itds] Problem with an ITD on an interface
|
If an ITD method is declared on an interface with an anonymous inner class returned as the result, the compiler generates an error for any "super.xxx" calls in the anonymous inner class. The example project shows this with a nested inner interface, but the same problem occurs with an ITD of this kind on any interface. The error does not occur if the ITD is declared on an inner class (as shown in the example) or a normal class.
|
resolved fixed
|
21cf37d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-04T16:26:06Z
| 2005-04-04T10:20:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterSuperFixerVisitor.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 org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceLocation;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression;
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.SuperReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* Walks the body of inter-type declarations and replaces SuperReference with InterSuperReference
*
* @author Jim Hugunin
*/
public class InterSuperFixerVisitor extends ASTVisitor {
InterTypeDeclaration dec;
ReferenceBinding onType;
TypeBinding superType;
EclipseFactory world;
public InterSuperFixerVisitor(InterTypeDeclaration dec, EclipseFactory world, Scope scope) {
this.dec = dec;
this.onType = dec.onTypeBinding;
this.world = world;
// AMC with the java 5 compiler the superclass() of an interface is object,
// not a parent interface (if one exists)
if (onType.isInterface() && onType.superInterfaces().length == 1) {
superType=onType.superInterfaces()[0];
} else if (onType.superclass() != null) {
superType = onType.superclass();
} else if (onType.superInterfaces() == null || onType.superInterfaces().length == 0) {
superType = scope.getJavaLangObject();
} else if (onType.superInterfaces().length == 1) {
superType = onType.superInterfaces()[0];
} else {
superType = null;
}
}
public void endVisit(FieldReference ref, BlockScope scope) {
ref.receiver = fixReceiver(ref.receiver, scope);
}
public void endVisit(MessageSend send, BlockScope scope) {
send.receiver = fixReceiver(send.receiver, scope);
}
private Expression fixReceiver(Expression expression, BlockScope scope) {
if (expression instanceof SuperReference) {
SuperReference superRef = (SuperReference) expression;
if (superType == null) {
ISourceLocation location =
new EclipseSourceLocation(scope.problemReporter().referenceContext.compilationResult(),
expression.sourceStart, expression.sourceEnd);
world.showMessage(IMessage.ERROR, "multiple supertypes for this interface", location, null);
dec.ignoreFurtherInvestigation = true;
}
//FIXME ??? note error
expression = new InterSuperReference(superRef, superType);
}
return expression;
}
}
|
90,143
|
Bug 90143 [itds] Problem with an ITD on an interface
|
If an ITD method is declared on an interface with an anonymous inner class returned as the result, the compiler generates an error for any "super.xxx" calls in the anonymous inner class. The example project shows this with a nested inner interface, but the same problem occurs with an ITD of this kind on any interface. The error does not occur if the ITD is declared on an inner class (as shown in the example) or a normal class.
|
resolved fixed
|
21cf37d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-04T16:26:06Z
| 2005-04-04T10:20:00Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCantCallSuperMethods_pr90143() { runTest("cant call super methods");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
public void testITDCtor_pr112783() { runTest("Problem with constructor ITDs");}
*/
public void 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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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 testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
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");
}
// 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);
}
}
|
114,005
|
Bug 114005 annotated ITD fields on interfaces have no annotation
| null |
resolved fixed
|
d9757d7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-08T12:13:05Z
| 2005-10-27T16:20:00Z
|
tests/bugs150/pr114005/Declaration1.java
| |
114,005
|
Bug 114005 annotated ITD fields on interfaces have no annotation
| null |
resolved fixed
|
d9757d7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-08T12:13:05Z
| 2005-10-27T16:20:00Z
|
tests/bugs150/pr114005/Declaration2.java
| |
114,005
|
Bug 114005 annotated ITD fields on interfaces have no annotation
| null |
resolved fixed
|
d9757d7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-08T12:13:05Z
| 2005-10-27T16:20:00Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
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 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 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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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 testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
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");
}
// 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);
}
}
|
114,005
|
Bug 114005 annotated ITD fields on interfaces have no annotation
| null |
resolved fixed
|
d9757d7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-08T12:13:05Z
| 2005-10-27T16: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.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.PerObjectInterface) {
changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger)munger);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) {
// PTWIMPL Transform the target type (add the aspect instance field)
changed = mungePerTypeWithinTransformer(weaver);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) {
changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger)munger);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.Constructor) {
changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.Parent) {
changed = mungeNewParent(weaver, (NewParentTypeMunger)munger);
} else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) {
changed = mungeNewAnnotationOnType(weaver,(AnnotationOnTypeMunger)munger);
} else {
throw new RuntimeException("unimplemented");
}
if (changed && munger.changesPublicSignature()) {
WeaverStateInfo info =
weaver.getLazyClassGen().getOrCreateWeaverStateInfo(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 {
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) {
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();
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)
{
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();
// getstatic field from aspect
body.append(Utility.createGet(fact, munger.getDelegate()));
int pos = 0;
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 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));
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();
}
}
|
112,830
|
Bug 112830 Warning "couldn't find aspectjrt.jar on classpath"
|
The compiler makes this warning if "aspectrt.jar" file has a different name like "aspectrt-1.3.jar", which is the case when compiling with maven.
|
resolved fixed
|
1f51499
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-08T16:41:54Z
| 2005-10-17T17:26: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.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.CountingMessageHandler;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.bridge.Version;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextFormatter;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.core.compiler.IProblem;
import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathDirectory;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.eclipse.core.runtime.OperationCanceledException;
//import org.aspectj.org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory {
private static final String 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;
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 (zos != null) {
closeOutputStream(buildConfig.getOutputJar());
}
ret = !handler.hasErrors();
getBcelWorld().tidyUp();
// bug 59895, don't release reference to handler as may be needed by a nested call
//handler = null;
}
return ret;
}
private boolean openOutputStream(File outJar) {
try {
OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar());
zos = new JarOutputStream(os,getWeaver().getManifest(true));
} catch (IOException ex) {
IMessage message =
new Message("Unable to open outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
return false;
}
return true;
}
private void closeOutputStream(File outJar) {
try {
if (zos != null) zos.close();
zos = null;
/* Ensure we don't write an incomplete JAR bug-71339 */
if (handler.hasErrors()) {
outJar.delete();
}
} catch (IOException ex) {
IMessage message =
new Message("Unable to write outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
copyResourcesFromJarFile(inJar);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory()) {
copyResourcesFromDirectory(inPathElement);
} else {
copyResourcesFromJarFile(inPathElement);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
File from = (File)buildConfig.getSourcePathResources().get(resource);
copyResourcesFromFile(from,resource,from);
}
}
writeManifest();
}
private void copyResourcesFromJarFile(File jarFile) throws IOException {
JarInputStream inStream = null;
try {
inStream = new JarInputStream(new FileInputStream(jarFile));
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
String filename = entry.getName();
// System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'");
if (!entry.isDirectory() && acceptResource(filename)) {
byte[] bytes = FileUtil.readAsByteArray(inStream);
writeResource(filename,bytes,jarFile);
}
inStream.closeEntry();
}
} finally {
if (inStream != null) inStream.close();
}
}
private void copyResourcesFromDirectory(File dir) throws IOException {
if (!COPY_INPATH_DIR_RESOURCES) return;
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
copyResourcesFromFile(files[i],filename,dir);
}
}
private void copyResourcesFromFile(File f,String filename,File src) throws IOException {
if (!acceptResource(filename)) return;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
writeResource(filename,bytes,src);
} finally {
if (fis != null) fis.close();
}
}
private void writeResource(String filename, byte[] content, File srcLocation) throws IOException {
if (state.resources.contains(filename)) {
IMessage msg = new Message("duplicate resource: '" + filename + "'",
IMessage.WARNING,
null,
new SourceLocation(srcLocation,0));
handler.handleMessage(msg);
return;
}
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(content);
zos.closeEntry();
} else {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename));
fos.write(content);
fos.close();
}
state.resources.add(filename);
}
/*
* If we are writing to an output directory copy the manifest but only
* if we already have one
*/
private void writeManifest () throws IOException {
Manifest manifest = getWeaver().getManifest(false);
if (manifest != null && zos == null) {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME));
manifest.write(fos);
fos.close();
}
}
private boolean acceptResource(String resourceName) {
if (
(resourceName.startsWith("CVS/")) ||
(resourceName.indexOf("/CVS/") != -1) ||
(resourceName.endsWith("/CVS")) ||
(resourceName.endsWith(".class")) ||
(resourceName.toUpperCase().equals(MANIFEST_NAME))
)
{
return false;
} else {
return true;
}
}
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.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";
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
if (p.isFile() && p.getName().equals("aspectjrt.jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
return "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
return "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
}
} catch (IOException ioe) {
return "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null;
} else {
// might want to catch other classpath errors
}
}
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig);
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[])
*/
public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) {
String filename = new String(eclipseClassFileName);
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
return outFile;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler)
*/
public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
// complete compiler config and return a suitable adapter...
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
forCompiler.options, getProblemFactory());
forCompiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le,this);
le.factory = factory;
pr.factory = factory;
forCompiler.lookupEnvironment = le;
forCompiler.parser =
new Parser(
pr,
forCompiler.options.parseLiteralExpressionsAsConstants);
return new AjCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(),
factory,
getInterimResultRequestor(),
progressListener,
this, // IOutputFilenameProvider
this, // IBinarySourceProvider
state.binarySourceFiles,
state.resultsFromFile.values(),
buildConfig.isNoWeave(),
buildConfig.getProceedOnError(),
buildConfig.isNoAtAspectJAnnotationProcessing());
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave()
*/
public Map getBinarySourcesForThisWeave() {
return binarySourcesForTheNextCompile;
}
public static AsmHierarchyBuilder getAsmHierarchyBuilder() {
return asmHierarchyBuilder;
}
/**
* Override the the default hierarchy builder.
*/
public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) {
asmHierarchyBuilder = newBuilder;
}
public AjState getState() {
return state;
}
public void setState(AjState buildState) {
state = buildState;
}
private static class AjBuildContexFormatter implements ContextFormatter {
public String formatEntry(int phaseId, Object data) {
StringBuffer sb = new StringBuffer();
if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) {
sb.append("batch building ");
} else {
sb.append("incrementally building ");
}
AjBuildConfig config = (AjBuildConfig) data;
List classpath = config.getClasspath();
sb.append("with classpath: ");
for (Iterator iter = classpath.iterator(); iter.hasNext();) {
sb.append(iter.next().toString());
sb.append(File.pathSeparator);
}
return sb.toString();
}
}
}
|
112,756
|
Bug 112756 ajdt compiler generate false warnings
|
I was working on aspect that should raise an error for junit test methods that didn't use any assertions. Apparently I had to use pointcut like "call(void Assert+.assert*(..))" on which ajdt compiler complained about using "assert" keyword. I don't think such warning should be shown in such case. Anyway, here is the complete aspect code. import junit.framework.Test; import junit.framework.Assert; import junit.framework.AssertionFailedError; public aspect AssertionCounter { private ThreadLocal counts = new ThreadLocal(); public pointcut testMethodExecution() : execution(void Test+.test*()); public pointcut assertCall() : cflow(testMethodExecution()) && call(void Assert+.assert*(..)); void around() : testMethodExecution() { counts.set( new Counter()); proceed(); if(((Counter) counts.get()).getCount()==0) { throw new AssertionFailedError("No assertions had been called"); } } before() : assertCall() { ((Counter) counts.get()).inc(); } }
|
resolved fixed
|
7a1002a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-09T10:37:51Z
| 2005-10-17T03:33:20Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
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 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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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 testNoVerifyErrorWithTwoThisPCDs_pr113447() {
runTest("no verify error with two this pcds");
}
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");
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
113,118
|
Bug 113118 ClassFormatException with tracing aspect
|
Build id: 20051017111807 AspectJ version: 1.5.0.200510141300 The following aspect resulted in the CFE: public aspect CallTrace { /** * A marker interface used to pick the classes to trace. Declare any class you want to * trace to implement this interface. The best way is using an aspect like the one in * the class comment block above. */ public static interface Traced {} /** * A marker annoation, can be used instead of {@link Traced}. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) public @interface TracedAnno {} private static Level level = Level.INFO; /** * Set the global logging level used for reporting traced calls. Defaults to INFO. * @param newLevel */ public static void setLevel (Level newLevel) { level = newLevel; } /** * @return the Level used for writing traced output. */ public static Level getLevel () { return level; } private static Logger log = Logger.getLogger(Traced.class); private int nesting = 0; private static StringBuffer prefixStr = null; static { new StringBuffer(1024); for (int i=0; i<128; i++) { // stuff with "+". prefixStr.append("++++++++"); } } public pointcut exclusions(): within(CallTrace) || within(*Tracer); // Distinguish between initialization JPs and other method calls, to work // around AJ limitation that around advice isn't supported for initializations. public pointcut traceIntfInit(): initialization(Traced+.new(..)); public pointcut traceIntf(): call(* Traced+.*(..)); public pointcut traceAnnoInit(): initialization(com.adteractive..*.new(..)) && @target(TracedAnno); public pointcut traceAnno(): call(* com.adteractive..*.*(..)) && @target(TracedAnno); public pointcut traceInit(): !exclusions() && (traceIntfInit() || traceAnnoInit()); public pointcut trace(): !exclusions() && (traceIntf() || traceAnno()); before(): traceInit() { nesting++; String pre = prefixStr.substring(0,nesting); log.log (level, pre+"> "+thisJoinPointStaticPart); } after(): traceInit() { String pre = prefixStr.substring(0,nesting); log.log (level, pre+"< "+thisJoinPointStaticPart); nesting--; } Object around(): trace() { nesting++; String pre = prefixStr.substring(0,nesting); log.log (level, pre+"> "+thisJoinPointStaticPart); Object result = proceed(); log.log (level, pre+"< "+thisJoinPointStaticPart); nesting--; return result; } } A separate aspect is used to "declare parent" or "declare @type" either the marker interface or annotation, thereby adding tracing to the user-specified classes. E.g., public aspect CallTraceTestTracer { // declare @type: com.me.foo..*: @CallTrace.TracedAnno; declare parents: com.me.foo..* implements CallTrace.Traced; } The exception wasn't thrown in a previous version when I used just before advice for both the "trace" and "traceInit" pointcuts. org.aspectj.apache.bcel.classfile.ClassFormatException at org.aspectj.apache.bcel.classfile.Utility.typeOfSignature(Utility.java:1293) at org.aspectj.apache.bcel.generic.Type.getTypeInternal(Type.java:166) at org.aspectj.apache.bcel.generic.Type.getTypeInternal(Type.java:174) at org.aspectj.apache.bcel.generic.Type.getType(Type.java:155) at org.aspectj.weaver.bcel.BcelWorld.makeBcelType(BcelWorld.java:198) at org.aspectj.weaver.bcel.BcelShadow.createMethodGen(BcelShadow.java:2999) at org.aspectj.weaver.bcel.BcelShadow.extractMethod(BcelShadow.java:2826) at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2020) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:211) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:514) at org.aspectj.weaver.Shadow.implement(Shadow.java:391) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:1781) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:394) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:98) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1464) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1429) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1203) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1039) 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.a jdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:759) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:249) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:158) 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 com.adteractive.framework.test.ConditionTestFilterTest extends junit.framework.TestCase: com.adteractive.framework.ConditionTestFilter ctf [Signature(Lcom/adteractive/framework/ConditionTestFilter<Lcom/adteractive/framework/test/InputStub;Lcom/adteractive/framework/test/OutputStub;>;)] static Class class$0 private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_0 public void <init>(): ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 16) INVOKESPECIAL junit.framework.TestCase.<init> ()V constructor-execution(void com.adteractive.framework.test.ConditionTestFilterTest.<init>()) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 17) | ACONST_NULL | PUTFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | RETURN (line 16) constructor-execution(void com.adteractive.framework.test.ConditionTestFilterTest.<init>()) end public void <init>() protected void setUp() throws java.lang.Exception org.aspectj.weaver.MethodDeclarationLineNumber: 23:543 : method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.setUp()) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 24) | INVOKESPECIAL junit.framework.TestCase.setUp ()V | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 25) | NEW com.adteractive.framework.test.ConditionTestFilterStub | DUP | LDC "ctf" | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this | ASTORE_1 | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.test.ConditionTestFilterTest.makeBranches()) | | ALOAD_1 | | INVOKESPECIAL com.adteractive.framework.test.ConditionTestFilterTest.makeBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.test.ConditionTestFilterTest.makeBranches()) | INVOKESPECIAL com.adteractive.framework.test.ConditionTestFilterStub.<init> (Ljava/lang/String;[Lcom/adteractive/framework/Filter;)V | PUTFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | RETURN (line 26) method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.setUp()) end protected void setUp() throws java.lang.Exception public void testExecute() org.aspectj.weaver.MethodDeclarationLineNumber: 31:754 : method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testExecute()) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 32) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | NEW com.adteractive.framework.test.InputStub | DUP | INVOKESPECIAL com.adteractive.framework.test.InputStub.<init> ()V | method-call(com.adteractive.framework.Output com.adteractive.framework.ConditionTestFilter.execute(com.adteractive.framework.Input)) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.execute (Lcom/adteractive/framework/Input;)Lcom/adteractive/framework/Output; | method-call(com.adteractive.framework.Output com.adteractive.framework.ConditionTestFilter.execute(com.adteractive.framework.Input)) | CHECKCAST com.adteractive.framework.test.OutputStub | ASTORE_1 | LDC "bf12" (line 33) | ALOAD_1 // com.adteractive.framework.test.OutputStub output | method-call(com.adteractive.framework.Status com.adteractive.framework.test.OutputStub.getStatus()) | | INVOKEVIRTUAL com.adteractive.framework.test.OutputStub.getStatus ()Lcom/adteractive/framework/Status; | method-call(com.adteractive.framework.Status com.adteractive.framework.test.OutputStub.getStatus()) | method-call(java.lang.String com.adteractive.framework.Status.getAdditionalMessage()) | | INVOKEINTERFACE com.adteractive.framework.Status.getAdditionalMessage ()Ljava/lang/String; | method-call(java.lang.String com.adteractive.framework.Status.getAdditionalMessage()) | method-call(void junit.framework.Assert.assertEquals(java.lang.String, java.lang.String)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertEquals (Ljava/lang/String;Ljava/lang/String;)V | method-call(void junit.framework.Assert.assertEquals(java.lang.String, java.lang.String)) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 34) | NEW com.adteractive.framework.test.ConditionTestFilterStub | DUP | INVOKESPECIAL com.adteractive.framework.test.ConditionTestFilterStub.<init> ()V | PUTFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 35) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | NEW com.adteractive.framework.test.InputStub | DUP | INVOKESPECIAL com.adteractive.framework.test.InputStub.<init> ()V | method-call(com.adteractive.framework.Output com.adteractive.framework.ConditionTestFilter.execute(com.adteractive.framework.Input)) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.execute (Lcom/adteractive/framework/Input;)Lcom/adteractive/framework/Output; | method-call(com.adteractive.framework.Output com.adteractive.framework.ConditionTestFilter.execute(com.adteractive.framework.Input)) | CHECKCAST com.adteractive.framework.test.OutputStub | ASTORE_1 // com.adteractive.framework.test.OutputStub output | ALOAD_1 // com.adteractive.framework.test.OutputStub output (line 36) | method-call(void junit.framework.Assert.assertNotNull(java.lang.Object)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertNotNull (Ljava/lang/Object;)V | method-call(void junit.framework.Assert.assertNotNull(java.lang.Object)) | RETURN (line 37) method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testExecute()) end public void testExecute() public void testGetFilterBranches() org.aspectj.weaver.MethodDeclarationLineNumber: 42:1111 : method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testGetFilterBranches()) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 43) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.getFilterBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | method-call(void junit.framework.Assert.assertNotNull(java.lang.Object)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertNotNull (Ljava/lang/Object;)V | method-call(void junit.framework.Assert.assertNotNull(java.lang.Object)) | ICONST_3 (line 44) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.getFilterBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | ARRAYLENGTH | method-call(void junit.framework.Assert.assertEquals(int, int)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertEquals (II)V | method-call(void junit.framework.Assert.assertEquals(int, int)) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 45) | NEW com.adteractive.framework.test.ConditionTestFilterStub | DUP | INVOKESPECIAL com.adteractive.framework.test.ConditionTestFilterStub.<init> ()V | PUTFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 46) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.getFilterBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | method-call(void junit.framework.Assert.assertNull(java.lang.Object)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertNull (Ljava/lang/Object;)V | method-call(void junit.framework.Assert.assertNull(java.lang.Object)) | RETURN (line 47) method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testGetFilterBranches()) end public void testGetFilterBranches() public void testSetFilterBranches() org.aspectj.weaver.MethodDeclarationLineNumber: 52:1441 : method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testSetFilterBranches()) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 53) | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.test.ConditionTestFilterTest.makeBranches()) | | INVOKESPECIAL com.adteractive.framework.test.ConditionTestFilterTest.makeBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.test.ConditionTestFilterTest.makeBranches()) | ASTORE_1 | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 54) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | ALOAD_1 // com.adteractive.framework.Filter[] branches | method-call(void com.adteractive.framework.ConditionTestFilter.setFilterBranches(com.adteractive.framework.Filter[])) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.setFilterBranches ([Lcom/adteractive/framework/Filter;)V | method-call(void com.adteractive.framework.ConditionTestFilter.setFilterBranches(com.adteractive.framework.Filter[])) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 55) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.getFilterBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | method-call(void junit.framework.Assert.assertNotNull(java.lang.Object)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertNotNull (Ljava/lang/Object;)V | method-call(void junit.framework.Assert.assertNotNull(java.lang.Object)) | ICONST_3 (line 56) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.getFilterBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | ARRAYLENGTH | method-call(void junit.framework.Assert.assertEquals(int, int)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertEquals (II)V | method-call(void junit.framework.Assert.assertEquals(int, int)) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 57) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | ACONST_NULL | method-call(void com.adteractive.framework.ConditionTestFilter.setFilterBranches(com.adteractive.framework.Filter[])) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.setFilterBranches ([Lcom/adteractive/framework/Filter;)V | method-call(void com.adteractive.framework.ConditionTestFilter.setFilterBranches(com.adteractive.framework.Filter[])) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 58) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.getFilterBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | method-call(void junit.framework.Assert.assertNull(java.lang.Object)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertNull (Ljava/lang/Object;)V | method-call(void junit.framework.Assert.assertNull(java.lang.Object)) | RETURN (line 59) method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testSetFilterBranches()) end public void testSetFilterBranches() public void testConditionTestFilter() org.aspectj.weaver.MethodDeclarationLineNumber: 64:1847 : method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testConditionTestFilter()) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 65) | NEW com.adteractive.framework.test.ConditionTestFilterStub | DUP | INVOKESPECIAL com.adteractive.framework.test.ConditionTestFilterStub.<init> ()V | PUTFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 66) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.getFilterBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | method-call(void junit.framework.Assert.assertNull(java.lang.Object)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertNull (Ljava/lang/Object;)V | method-call(void junit.framework.Assert.assertNull(java.lang.Object)) | LDC com.adteractive.framework.test.ConditionTestFilterStub (line 67) | method-call(java.lang.String java.lang.Class.getSimpleName()) | | INVOKEVIRTUAL java.lang.Class.getSimpleName ()Ljava/lang/String; | method-call(java.lang.String java.lang.Class.getSimpleName()) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(java.lang.String com.adteractive.framework.FilterHelper.getName()) | | INVOKEVIRTUAL com.adteractive.framework.FilterHelper.getName ()Ljava/lang/String; | method-call(java.lang.String com.adteractive.framework.FilterHelper.getName()) | method-call(void junit.framework.Assert.assertEquals(java.lang.String, java.lang.String)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertEquals (Ljava/lang/String;Ljava/lang/String;)V | method-call(void junit.framework.Assert.assertEquals(java.lang.String, java.lang.String)) | RETURN (line 68) method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testConditionTestFilter()) end public void testConditionTestFilter() public void testConditionTestFilterString() org.aspectj.weaver.MethodDeclarationLineNumber: 73:2158 : method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testConditionTestFilterString()) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 74) | NEW com.adteractive.framework.test.ConditionTestFilterStub | DUP | LDC "foo" | INVOKESPECIAL com.adteractive.framework.test.ConditionTestFilterStub.<init> (Ljava/lang/String;)V | PUTFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 75) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.getFilterBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | method-call(void junit.framework.Assert.assertNull(java.lang.Object)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertNull (Ljava/lang/Object;)V | method-call(void junit.framework.Assert.assertNull(java.lang.Object)) | LDC "foo" (line 76) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(java.lang.String com.adteractive.framework.FilterHelper.getName()) | | INVOKEVIRTUAL com.adteractive.framework.FilterHelper.getName ()Ljava/lang/String; | method-call(java.lang.String com.adteractive.framework.FilterHelper.getName()) | method-call(void junit.framework.Assert.assertEquals(java.lang.String, java.lang.String)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertEquals (Ljava/lang/String;Ljava/lang/String;)V | method-call(void junit.framework.Assert.assertEquals(java.lang.String, java.lang.String)) | RETURN (line 77) method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testConditionTestFilterString()) end public void testConditionTestFilterString() public void testConditionTestFilterStringFilterOfIOArray() org.aspectj.weaver.MethodDeclarationLineNumber: 82:2456 : method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testConditionTestFilterStringFilterOfIOArray()) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 83) | NEW com.adteractive.framework.test.ConditionTestFilterStub | DUP | LDC "foo" | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.test.ConditionTestFilterTest.makeBranches()) | | INVOKESPECIAL com.adteractive.framework.test.ConditionTestFilterTest.makeBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.test.ConditionTestFilterTest.makeBranches()) | INVOKESPECIAL com.adteractive.framework.test.ConditionTestFilterStub.<init> (Ljava/lang/String;[Lcom/adteractive/framework/Filter;)V | PUTFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this (line 84) | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.getFilterBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | method-call(void junit.framework.Assert.assertNotNull(java.lang.Object)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertNotNull (Ljava/lang/Object;)V | method-call(void junit.framework.Assert.assertNotNull(java.lang.Object)) | ICONST_3 (line 85) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | | INVOKEVIRTUAL com.adteractive.framework.ConditionTestFilter.getFilterBranches ()[Lcom/adteractive/framework/Filter; | method-call(com.adteractive.framework.Filter[] com.adteractive.framework.ConditionTestFilter.getFilterBranches()) | ARRAYLENGTH | method-call(void junit.framework.Assert.assertEquals(int, int)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertEquals (II)V | method-call(void junit.framework.Assert.assertEquals(int, int)) | LDC "foo" (line 86) | ALOAD_0 // com.adteractive.framework.test.ConditionTestFilterTest this | GETFIELD com.adteractive.framework.test.ConditionTestFilterTest.ctf Lcom/adteractive/framework/ConditionTestFilter; | method-call(java.lang.String com.adteractive.framework.FilterHelper.getName()) | | INVOKEVIRTUAL com.adteractive.framework.FilterHelper.getName ()Ljava/lang/String; | method-call(java.lang.String com.adteractive.framework.FilterHelper.getName()) | method-call(void junit.framework.Assert.assertEquals(java.lang.String, java.lang.String)) | | INVOKESTATIC com.adteractive.framework.test.ConditionTestFilterTest.assertEquals (Ljava/lang/String;Ljava/lang/String;)V | method-call(void junit.framework.Assert.assertEquals(java.lang.String, java.lang.String)) | RETURN (line 87) method-execution(void com.adteractive.framework.test.ConditionTestFilterTest.testConditionTestFilterStringFilterOfIOArray()) end public void testConditionTestFilterStringFilterOfIOArray() private com.adteractive.framework.Filter[] makeBranches() org.aspectj.weaver.MethodDeclarationLineNumber: 89:2749 : method-execution(com.adteractive.framework.Filter[] com.adteractive.framework.test.ConditionTestFilterTest.makeBranches()) | ICONST_3 (line 90) | ANEWARRAY com.adteractive.framework.test.FilterHelperStub | ASTORE_1 | ALOAD_1 // com.adteractive.framework.Filter[] branches (line 91) | ICONST_0 | NEW com.adteractive.framework.test.FilterHelperStub | DUP | LDC "bf1" | INVOKESPECIAL com.adteractive.framework.test.FilterHelperStub.<init> (Ljava/lang/String;)V | AASTORE | ALOAD_1 // com.adteractive.framework.Filter[] branches (line 92) | ICONST_1 | NEW com.adteractive.framework.test.FilterHelperStub | DUP | LDC "bf12" | INVOKESPECIAL com.adteractive.framework.test.FilterHelperStub.<init> (Ljava/lang/String;)V | AASTORE | ALOAD_1 // com.adteractive.framework.Filter[] branches (line 93) | ICONST_2 | NEW com.adteractive.framework.test.FilterHelperStub | DUP | LDC "bf" | INVOKESPECIAL com.adteractive.framework.test.FilterHelperStub.<init> (Ljava/lang/String;)V | AASTORE | ALOAD_1 // com.adteractive.framework.Filter[] branches (line 94) | ARETURN method-execution(com.adteractive.framework.Filter[] com.adteractive.framework.test.ConditionTestFilterTest.makeBranches()) end private com.adteractive.framework.Filter[] makeBranches() end public class com.adteractive.framework.test.ConditionTestFilterTest when implementing on shadow method-call(com.adteractive.framework.Filter[] com.adteractive.framework.test.ConditionTestFilterTest.makeBranches()) when weaving type com.adteractive.framework.test.ConditionTestFilterTest when weaving classes when weaving when incrementally building BuildConfig[C:\cygwin\home\dwampler\work\workspace\.metadata\.plugins\org.eclipse.ajdt.core\adserver-service.generated.lst] #Files=259
|
resolved fixed
|
d7d5947
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-11T15:13:33Z
| 2005-10-19T16:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.java
|
/* *******************************************************************
* Copyright (c) 2002 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Andy Clement 6Jul05 generics - signature attribute
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.ConstantUtf8;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.classfile.Unknown;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.generic.ClassGen;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldGen;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.RETURN;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.generic.annotation.AnnotationGen;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.CollectionUtil;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.AjAttribute.WeaverVersionInfo;
/**
* Lazy lazy lazy.
* We don't unpack the underlying class unless necessary. Things
* like new methods and annotations accumulate in here until they
* must be written out, don't add them to the underlying MethodGen!
* Things are slightly different if this represents an Aspect.
*/
public final class LazyClassGen {
int highestLineNumber = 0; // ---- JSR 45 info
private SortedMap /* <String, InlinedSourceFileInfo> */ inlinedFiles = new TreeMap();
private boolean regenerateGenericSignatureAttribute = false;
private BcelObjectType myType; // XXX is not set for types we create
private ClassGen myGen;
private ConstantPoolGen constantPoolGen;
private World world;
private String packageName = null;
private List /*LazyMethodGen*/ methodGens = new ArrayList();
private List /*LazyClassGen*/ classGens = new ArrayList();
private List /*AnnotationGen*/ annotations = new ArrayList();
private int childCounter = 0;
private InstructionFactory fact;
private boolean isSerializable = false;
private boolean hasSerialVersionUIDField = false;
private boolean hasClinit = false;
// ---
static class InlinedSourceFileInfo {
int highestLineNumber;
int offset; // calculated
InlinedSourceFileInfo(int highestLineNumber) {
this.highestLineNumber = highestLineNumber;
}
}
void addInlinedSourceFileInfo(String fullpath, int highestLineNumber) {
Object o = inlinedFiles.get(fullpath);
if (o != null) {
InlinedSourceFileInfo info = (InlinedSourceFileInfo) o;
if (info.highestLineNumber < highestLineNumber) {
info.highestLineNumber = highestLineNumber;
}
} else {
inlinedFiles.put(fullpath, new InlinedSourceFileInfo(highestLineNumber));
}
}
void calculateSourceDebugExtensionOffsets() {
int i = roundUpToHundreds(highestLineNumber);
for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) {
InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next();
element.offset = i;
i = roundUpToHundreds(i + element.highestLineNumber);
}
}
private static int roundUpToHundreds(int i) {
return ((i / 100) + 1) * 100;
}
int getSourceDebugExtensionOffset(String fullpath) {
return ((InlinedSourceFileInfo) inlinedFiles.get(fullpath)).offset;
}
private Unknown getSourceDebugExtensionAttribute() {
int nameIndex = constantPoolGen.addUtf8("SourceDebugExtension");
String data = getSourceDebugExtensionString();
//System.err.println(data);
byte[] bytes = Utility.stringToUTF(data);
int length = bytes.length;
return new Unknown(nameIndex, length, bytes, constantPoolGen.getConstantPool());
}
// private LazyClassGen() {}
// public static void main(String[] args) {
// LazyClassGen m = new LazyClassGen();
// m.highestLineNumber = 37;
// m.inlinedFiles.put("boo/baz/foo.java", new InlinedSourceFileInfo( 83));
// m.inlinedFiles.put("boo/barz/foo.java", new InlinedSourceFileInfo(292));
// m.inlinedFiles.put("boo/baz/moo.java", new InlinedSourceFileInfo(128));
// m.calculateSourceDebugExtensionOffsets();
// System.err.println(m.getSourceDebugExtensionString());
// }
// For the entire pathname, we're using package names. This is probably wrong.
private String getSourceDebugExtensionString() {
StringBuffer out = new StringBuffer();
String myFileName = getFileName();
// header section
out.append("SMAP\n");
out.append(myFileName);
out.append("\nAspectJ\n");
// stratum section
out.append("*S AspectJ\n");
// file section
out.append("*F\n");
out.append("1 ");
out.append(myFileName);
out.append("\n");
int i = 2;
for (Iterator iter = inlinedFiles.keySet().iterator(); iter.hasNext();) {
String element = (String) iter.next();
int ii = element.lastIndexOf('/');
if (ii == -1) {
out.append(i++); out.append(' ');
out.append(element); out.append('\n');
} else {
out.append("+ "); out.append(i++); out.append(' ');
out.append(element.substring(ii+1)); out.append('\n');
out.append(element); out.append('\n');
}
}
// emit line section
out.append("*L\n");
out.append("1#1,");
out.append(highestLineNumber);
out.append(":1,1\n");
i = 2;
for (Iterator iter = inlinedFiles.values().iterator(); iter.hasNext();) {
InlinedSourceFileInfo element = (InlinedSourceFileInfo) iter.next();
out.append("1#");
out.append(i++); out.append(',');
out.append(element.highestLineNumber); out.append(":");
out.append(element.offset + 1); out.append(",1\n");
}
// end section
out.append("*E\n");
// and finish up...
return out.toString();
}
// ---- end JSR45-related stuff
/** Emit disassembled class and newline to out */
public static void disassemble(String path, String name, PrintStream out)
throws IOException {
if (null == out) {
return;
}
//out.println("classPath: " + classPath);
BcelWorld world = new BcelWorld(path);
LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(name)));
clazz.print(out);
out.println();
}
public int getNewGeneratedNameTag() {
return childCounter++;
}
// ----
public LazyClassGen(
String class_name,
String super_class_name,
String file_name,
int access_flags,
String[] interfaces,
World world)
{
myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces);
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
regenerateGenericSignatureAttribute = true;
this.world = world;
}
//Non child type, so it comes from a real type in the world.
public LazyClassGen(BcelObjectType myType) {
myGen = new ClassGen(myType.getJavaClass());
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
this.myType = myType;
this.world = myType.getResolvedTypeX().getWorld();
/* Does this class support serialization */
if (implementsSerializable(getType())) {
isSerializable = true;
// ResolvedMember[] fields = getType().getDeclaredFields();
// for (int i = 0; i < fields.length; i++) {
// ResolvedMember field = fields[i];
// if (field.getName().equals("serialVersionUID")
// && field.isStatic() && field.getType().equals(ResolvedType.LONG)) {
// hasSerialVersionUIDField = true;
// }
// }
hasSerialVersionUIDField = hasSerialVersionUIDField(getType());
ResolvedMember[] methods = getType().getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
ResolvedMember method = methods[i];
if (method.getName().equals("<clinit>")) {
hasClinit = true;
}
}
}
Method[] methods = myGen.getMethods();
for (int i = 0; i < methods.length; i++) {
addMethodGen(new LazyMethodGen(methods[i], this));
}
}
public static boolean hasSerialVersionUIDField (ResolvedType type) {
ResolvedMember[] fields = type.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
ResolvedMember field = fields[i];
if (field.getName().equals("serialVersionUID")
&& field.isStatic() && field.getType().equals(ResolvedType.LONG)) {
return true;
}
}
return false;
}
// public void addAttribute(Attribute i) {
// myGen.addAttribute(i);
// }
// ----
public String getInternalClassName() {
return getConstantPoolGen().getConstantPool().getConstantString(
myGen.getClassNameIndex(),
Constants.CONSTANT_Class);
}
public String getInternalFileName() {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1) {
return getFileName();
} else {
return str.substring(0, index + 1) + getFileName();
}
}
public File getPackagePath(File root) {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return root;
return new File(root, str.substring(0, index));
}
/** Returns the packagename - if its the default package we return an empty string
*/
public String getPackageName() {
if (packageName!=null) return packageName;
String str = getInternalClassName();
int index = str.indexOf("<");
if (index!=-1) str = str.substring(0,index); // strip off the generics guff
index= str.lastIndexOf("/");
if (index==-1) return "";
return str.substring(0,index).replace('/','.');
}
public String getClassId() {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return str;
return str.substring(index + 1);
}
public void addMethodGen(LazyMethodGen gen) {
//assert gen.getClassName() == super.getClassName();
methodGens.add(gen);
if (highestLineNumber < gen.highestLineNumber) highestLineNumber = gen.highestLineNumber;
}
public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) {
addMethodGen(gen);
if (!gen.getMethod().isPrivate()) {
warnOnAddedMethod(gen.getMethod(),sourceLocation);
}
}
public void errorOnAddedField (Field field, ISourceLocation sourceLocation) {
if (isSerializable && !hasSerialVersionUIDField) {
getWorld().getLint().serialVersionUIDBroken.signal(
new String[] {
myType.getResolvedTypeX().getName().toString(),
field.getName()
},
sourceLocation,
null);
}
}
public void warnOnAddedInterface (String name, ISourceLocation sourceLocation) {
warnOnModifiedSerialVersionUID(sourceLocation,"added interface " + name);
}
public void warnOnAddedMethod (Method method, ISourceLocation sourceLocation) {
warnOnModifiedSerialVersionUID(sourceLocation,"added non-private method " + method.getName());
}
public void warnOnAddedStaticInitializer (Shadow shadow, ISourceLocation sourceLocation) {
if (!hasClinit) {
warnOnModifiedSerialVersionUID(sourceLocation,"added static initializer");
}
}
public void warnOnModifiedSerialVersionUID (ISourceLocation sourceLocation, String reason) {
if (isSerializable && !hasSerialVersionUIDField)
getWorld().getLint().needsSerialVersionUIDField.signal(
new String[] {
myType.getResolvedTypeX().getName().toString(),
reason
},
sourceLocation,
null);
}
public World getWorld () {
return world;
}
public List getMethodGens() {
return methodGens; //???Collections.unmodifiableList(methodGens);
}
// FIXME asc Should be collection returned here
public Field[] getFieldGens() {
return myGen.getFields();
}
public Field getField(String name) {
Field[] allFields = myGen.getFields();
if (allFields==null) return null;
for (int i = 0; i < allFields.length; i++) {
Field field = allFields[i];
if (field.getName().equals(name)) return field;
}
return null;
}
// FIXME asc How do the ones on the underlying class surface if this just returns new ones added?
// FIXME asc ...although no one calls this right now !
public List getAnnotations() {
return annotations;
}
private void writeBack(BcelWorld world) {
if (getConstantPoolGen().getSize() > Short.MAX_VALUE) {
reportClassTooBigProblem();
return;
}
if (annotations.size()>0) {
for (Iterator iter = annotations.iterator(); iter.hasNext();) {
AnnotationGen element = (AnnotationGen) iter.next();
myGen.addAnnotation(element);
}
// Attribute[] annAttributes = org.aspectj.apache.bcel.classfile.Utility.getAnnotationAttributes(getConstantPoolGen(),annotations);
// for (int i = 0; i < annAttributes.length; i++) {
// Attribute attribute = annAttributes[i];
// System.err.println("Adding attribute for "+attribute);
// myGen.addAttribute(attribute);
// }
}
// Add a weaver version attribute to the file being produced (if necessary...)
boolean hasVersionAttribute = false;
Attribute[] attrs = myGen.getAttributes();
for (int i = 0; i < attrs.length && !hasVersionAttribute; i++) {
Attribute attribute = attrs[i];
if (attribute.getName().equals("org.aspectj.weaver.WeaverVersion")) hasVersionAttribute=true;
}
if (!hasVersionAttribute)
myGen.addAttribute(BcelAttributes.bcelAttribute(new AjAttribute.WeaverVersionInfo(),getConstantPoolGen()));
if (myType != null && myType.getWeaverState() != null) {
myGen.addAttribute(BcelAttributes.bcelAttribute(
new AjAttribute.WeaverState(myType.getWeaverState()),
getConstantPoolGen()));
}
//FIXME ATAJ needed only for slow Aspects.aspectOf() - keep or remove
//make a lot of test fail since the test compare weaved class file
// based on some test data as text files...
// if (!myGen.isInterface()) {
// addAjClassField();
// }
addAjcInitializers();
int len = methodGens.size();
myGen.setMethods(new Method[0]);
calculateSourceDebugExtensionOffsets();
for (int i = 0; i < len; i++) {
LazyMethodGen gen = (LazyMethodGen) methodGens.get(i);
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
myGen.addMethod(gen.getMethod());
}
if (inlinedFiles.size() != 0) {
if (hasSourceDebugExtensionAttribute(myGen)) {
world.showMessage(
IMessage.WARNING,
WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45,getFileName()),
null,
null);
}
// 17Feb05 - ASC - Skip this for now - it crashes IBM 1.4.2 jvms (pr80430). Will be revisited when contents
// of attribute are confirmed to be correct.
// myGen.addAttribute(getSourceDebugExtensionAttribute());
}
fixupGenericSignatureAttribute();
}
/**
* When working with 1.5 generics, a signature attribute is attached to the type which indicates
* how it was declared. This routine ensures the signature attribute for what we are about
* to write out is correct. Basically its responsibilities are:
* 1. Checking whether the attribute needs changing (i.e. did weaving change the type hierarchy)
* 2. If it did, removing the old attribute
* 3. Check if we need an attribute at all, are we generic? are our supertypes parameterized/generic?
* 4. Build the new attribute which includes all typevariable, supertype and superinterface information
*/
private void fixupGenericSignatureAttribute () {
if (getWorld() != null && !getWorld().isInJava5Mode()) return;
// TODO asc generics Temporarily assume that types we generate dont need a signature attribute (closure/etc).. will need revisiting no doubt...
if (myType==null) return;
// 1. Has anything changed that would require us to modify this attribute?
if (!regenerateGenericSignatureAttribute) return;
// 2. Find the old attribute
Signature sigAttr = null;
if (myType!=null) { // if null, this is a type built from scratch, it won't already have a sig attribute
Attribute[] as = myGen.getAttributes();
for (int i = 0; i < as.length; i++) {
Attribute attribute = as[i];
if (attribute.getName().equals("Signature")) sigAttr = (Signature)attribute;
}
}
// 3. Do we need an attribute?
boolean needAttribute = false;
if (sigAttr!=null) needAttribute = true; // If we had one before, we definetly still need one as types can't be 'removed' from the hierarchy
// check the interfaces
if (!needAttribute) {
if (myType==null) {
boolean stop = true;
}
ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces();
for (int i = 0; i < interfaceRTXs.length; i++) {
ResolvedType typeX = interfaceRTXs[i];
if (typeX.isGenericType() || typeX.isParameterizedType()) needAttribute = true;
}
// check the supertype
ResolvedType superclassRTX = myType.getSuperclass();
if (superclassRTX.isGenericType() || superclassRTX.isParameterizedType()) needAttribute = true;
}
if (needAttribute) {
StringBuffer signature = new StringBuffer();
// first, the type variables...
TypeVariable[] tVars = myType.getTypeVariables();
if (tVars.length>0) {
signature.append("<");
for (int i = 0; i < tVars.length; i++) {
TypeVariable variable = tVars[i];
if (i!=0) signature.append(",");
signature.append(variable.getSignature());
}
signature.append(">");
}
// now the supertype
signature.append(myType.getSuperclass().getSignature());
ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces();
for (int i = 0; i < interfaceRTXs.length; i++) {
String s = interfaceRTXs[i].getSignatureForAttribute();
signature.append(s);
}
myGen.addAttribute(createSignatureAttribute(signature.toString()));
}
// TODO asc generics The 'old' signature is left in the constant pool - I wonder how safe it would be to
// remove it since we don't know what else (if anything) is referring to it
}
/**
* Helper method to create a signature attribute based on a string signature:
* e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;"
*/
private Signature createSignatureAttribute(String signature) {
int nameIndex = constantPoolGen.addUtf8("Signature");
int sigIndex = constantPoolGen.addUtf8(signature);
return new Signature(nameIndex,2,sigIndex,constantPoolGen.getConstantPool());
}
/**
*
*/
private void reportClassTooBigProblem() {
// PR 59208
// we've generated a class that is just toooooooooo big (you've been generating programs
// again haven't you? come on, admit it, no-one writes classes this big by hand).
// create an empty myGen so that we can give back a return value that doesn't upset the
// rest of the process.
myGen = new ClassGen(myGen.getClassName(), myGen.getSuperclassName(),
myGen.getFileName(), myGen.getAccessFlags(), myGen.getInterfaceNames());
// raise an error against this compilation unit.
getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CLASS_TOO_BIG,
this.getClassName()),
new SourceLocation(new File(myGen.getFileName()),0), null
);
}
private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) {
ConstantPoolGen pool = gen.getConstantPool();
Attribute[] attrs = gen.getAttributes();
for (int i = 0; i < attrs.length; i++) {
if ("SourceDebugExtension"
.equals(((ConstantUtf8) pool.getConstant(attrs[i].getNameIndex())).getBytes())) {
return true;
}
}
return false;
}
public JavaClass getJavaClass(BcelWorld world) {
writeBack(world);
return myGen.getJavaClass();
}
public byte [] getJavaClassBytesIncludingReweavable(BcelWorld world){
writeBack(world);
byte [] wovenClassFileData = myGen.getJavaClass().getBytes();
WeaverStateInfo wsi = myType.getWeaverState();//getOrCreateWeaverStateInfo();
if(wsi != null && wsi.isReweavable()){ // && !reweavableDataInserted
//reweavableDataInserted = true;
return wsi.replaceKeyWithDiff(wovenClassFileData);
} else{
return wovenClassFileData;
}
}
public void addGeneratedInner(LazyClassGen newClass) {
classGens.add(newClass);
}
public void addInterface(UnresolvedType typeX, ISourceLocation sourceLocation) {
regenerateGenericSignatureAttribute = true;
myGen.addInterface(typeX.getRawName());
if (!typeX.equals(UnresolvedType.SERIALIZABLE))
warnOnAddedInterface(typeX.getName(),sourceLocation);
}
public void setSuperClass(ResolvedType typeX) {
regenerateGenericSignatureAttribute = true;
myType.addParent(typeX); // used for the attribute
if (typeX.getGenericType()!=null) typeX = typeX.getGenericType();
myGen.setSuperclassName(typeX.getName()); // used in the real class data
}
public String getSuperClassname() {
return myGen.getSuperclassName();
}
// FIXME asc not great that some of these ask the gen and some ask the type ! (see the related setters too)
public ResolvedType getSuperClass() {
return myType.getSuperclass();
}
public String[] getInterfaceNames() {
return myGen.getInterfaceNames();
}
// non-recursive, may be a bug, ha ha.
private List getClassGens() {
List ret = new ArrayList();
ret.add(this);
ret.addAll(classGens);
return ret;
}
public List getChildClasses(BcelWorld world) {
if (classGens.isEmpty()) return Collections.EMPTY_LIST;
List ret = new ArrayList();
for (Iterator i = classGens.iterator(); i.hasNext();) {
LazyClassGen clazz = (LazyClassGen) i.next();
byte[] bytes = clazz.getJavaClass(world).getBytes();
String name = clazz.getName();
int index = name.lastIndexOf('$');
// XXX this could be bad, check use of dollar signs.
name = name.substring(index+1);
ret.add(new UnwovenClassFile.ChildClass(name, bytes));
}
return ret;
}
public String toString() {
return toShortString();
}
public String toShortString() {
String s =
org.aspectj.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true);
if (s != "")
s += " ";
s += org.aspectj.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags());
s += " ";
s += myGen.getClassName();
return s;
}
public String toLongString() {
ByteArrayOutputStream s = new ByteArrayOutputStream();
print(new PrintStream(s));
return new String(s.toByteArray());
}
public void print() { print(System.out); }
public void print(PrintStream out) {
List classGens = getClassGens();
for (Iterator iter = classGens.iterator(); iter.hasNext();) {
LazyClassGen element = (LazyClassGen) iter.next();
element.printOne(out);
if (iter.hasNext()) out.println();
}
}
private void printOne(PrintStream out) {
out.print(toShortString());
out.print(" extends ");
out.print(
org.aspectj.apache.bcel.classfile.Utility.compactClassName(
myGen.getSuperclassName(),
false));
int size = myGen.getInterfaces().length;
if (size > 0) {
out.print(" implements ");
for (int i = 0; i < size; i++) {
out.print(myGen.getInterfaceNames()[i]);
if (i < size - 1)
out.print(", ");
}
}
out.print(":");
out.println();
// XXX make sure to pass types correctly around, so this doesn't happen.
if (myType != null) {
myType.printWackyStuff(out);
}
Field[] fields = myGen.getFields();
for (int i = 0, len = fields.length; i < len; i++) {
out.print(" ");
out.println(fields[i]);
}
List methodGens = getMethodGens();
for (Iterator iter = methodGens.iterator(); iter.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) iter.next();
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
gen.print(out, (myType != null ? myType.getWeaverVersionAttribute() : WeaverVersionInfo.UNKNOWN));
if (iter.hasNext()) out.println();
}
// out.println(" ATTRIBS: " + Arrays.asList(myGen.getAttributes()));
out.println("end " + toShortString());
}
private boolean isEmptyClinit(LazyMethodGen gen) {
if (!gen.getName().equals("<clinit>")) return false;
//System.err.println("checking clinig: " + gen);
InstructionHandle start = gen.getBody().getStart();
while (start != null) {
if (Range.isRangeHandle(start) || (start.getInstruction() instanceof RETURN)) {
start = start.getNext();
} else {
return false;
}
}
return true;
}
public ConstantPoolGen getConstantPoolGen() {
return constantPoolGen;
}
public String getName() {
return myGen.getClassName();
}
public boolean isWoven() {
return myType.getWeaverState() != null;
}
public boolean isReweavable() {
if (myType.getWeaverState()==null) return true;
return myType.getWeaverState().isReweavable();
}
public Set getAspectsAffectingType() {
if (myType.getWeaverState()==null) return null;
return myType.getWeaverState().getAspectsAffectingType();
}
public WeaverStateInfo getOrCreateWeaverStateInfo(boolean inReweavableMode) {
WeaverStateInfo ret = myType.getWeaverState();
if (ret != null) return ret;
ret = new WeaverStateInfo(inReweavableMode);
myType.setWeaverState(ret);
return ret;
}
public InstructionFactory getFactory() {
return fact;
}
public LazyMethodGen getStaticInitializer() {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals("<clinit>")) return gen;
}
LazyMethodGen clinit = new LazyMethodGen(
Modifier.STATIC,
Type.VOID,
"<clinit>",
new Type[0],
CollectionUtil.NO_STRINGS,
this);
clinit.getBody().insert(InstructionConstants.RETURN);
methodGens.add(clinit);
return clinit;
}
public LazyMethodGen getAjcPreClinit() {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(NameMangler.AJC_PRE_CLINIT_NAME)) return gen;
}
LazyMethodGen ajcClinit = new LazyMethodGen(
Modifier.STATIC,
Type.VOID,
NameMangler.AJC_PRE_CLINIT_NAME,
new Type[0],
CollectionUtil.NO_STRINGS,
this);
ajcClinit.getBody().insert(InstructionConstants.RETURN);
methodGens.add(ajcClinit);
getStaticInitializer().getBody().insert(Utility.createInvoke(getFactory(), ajcClinit));
return ajcClinit;
}
// reflective thisJoinPoint support
Map/*BcelShadow, Field*/ tjpFields = new HashMap();
public static final ObjectType proceedingTjpType =
new ObjectType("org.aspectj.lang.ProceedingJoinPoint");
public static final ObjectType tjpType =
new ObjectType("org.aspectj.lang.JoinPoint");
public static final ObjectType staticTjpType =
new ObjectType("org.aspectj.lang.JoinPoint$StaticPart");
public static final ObjectType enclosingStaticTjpType =
new ObjectType("org.aspectj.lang.JoinPoint$EnclosingStaticPart");
private static final ObjectType sigType =
new ObjectType("org.aspectj.lang.Signature");
// private static final ObjectType slType =
// new ObjectType("org.aspectj.lang.reflect.SourceLocation");
private static final ObjectType factoryType =
new ObjectType("org.aspectj.runtime.reflect.Factory");
private static final ObjectType classType =
new ObjectType("java.lang.Class");
public Field getTjpField(BcelShadow shadow, final boolean isEnclosingJp) {
Field ret = (Field)tjpFields.get(shadow);
if (ret != null) return ret;
int modifiers = Modifier.STATIC | Modifier.FINAL;
// XXX - Do we ever inline before or after advice? If we do, then we
// better include them in the check below. (or just change it to
// shadow.getEnclosingMethod().getCanInline())
// If the enclosing method is around advice, we could inline the join point
// that has led to this shadow. If we do that then the TJP we are creating
// here must be PUBLIC so it is visible to the type in which the
// advice is inlined. (PR71377)
LazyMethodGen encMethod = shadow.getEnclosingMethod();
boolean shadowIsInAroundAdvice = false;
if (encMethod!=null && encMethod.getName().startsWith(NameMangler.PREFIX+"around")) {
shadowIsInAroundAdvice = true;
}
if (getType().isInterface() || shadowIsInAroundAdvice) {
modifiers |= Modifier.PUBLIC;
}
else {
modifiers |= Modifier.PRIVATE;
}
ret = new FieldGen(modifiers,
isEnclosingJp?enclosingStaticTjpType:staticTjpType,
"ajc$tjp_" + tjpFields.size(),
getConstantPoolGen()).getField();
addField(ret);
tjpFields.put(shadow, ret);
return ret;
}
//FIXME ATAJ needed only for slow Aspects.aspectOf - keep or remove
// private void addAjClassField() {
// // Andy: Why build it again??
// Field ajClassField = new FieldGen(
// Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
// classType,
// "aj$class",
// getConstantPoolGen()).getField();
// addField(ajClassField);
//
// InstructionList il = new InstructionList();
// il.append(new PUSH(getConstantPoolGen(), getClassName()));
// il.append(fact.createInvoke("java.lang.Class", "forName", classType,
// new Type[] {Type.STRING}, Constants.INVOKESTATIC));
// il.append(fact.createFieldAccess(getClassName(), ajClassField.getName(),
// classType, Constants.PUTSTATIC));
//
// getStaticInitializer().getBody().insert(il);
// }
private void addAjcInitializers() {
if (tjpFields.size() == 0) return;
InstructionList il = initializeAllTjps();
getStaticInitializer().getBody().insert(il);
}
private InstructionList initializeAllTjps() {
InstructionList list = new InstructionList();
InstructionFactory fact = getFactory();
// make a new factory
list.append(fact.createNew(factoryType));
list.append(InstructionFactory.createDup(1));
list.append(new PUSH(getConstantPoolGen(), getFileName()));
// load the current Class object
//XXX check that this works correctly for inners/anonymous
list.append(new PUSH(getConstantPoolGen(), getClassName()));
//XXX do we need to worry about the fact the theorectically this could throw
//a ClassNotFoundException
list.append(fact.createInvoke("java.lang.Class", "forName", classType,
new Type[] {Type.STRING}, Constants.INVOKESTATIC));
list.append(fact.createInvoke(factoryType.getClassName(), "<init>",
Type.VOID, new Type[] {Type.STRING, classType},
Constants.INVOKESPECIAL));
list.append(InstructionFactory.createStore(factoryType, 0));
List entries = new ArrayList(tjpFields.entrySet());
Collections.sort(entries, new Comparator() {
public int compare(Object a, Object b) {
Map.Entry ae = (Map.Entry) a;
Map.Entry be = (Map.Entry) b;
return ((Field) ae.getValue())
.getName()
.compareTo(((Field)be.getValue()).getName());
}
});
for (Iterator i = entries.iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
initializeTjp(fact, list, (Field)entry.getValue(), (BcelShadow)entry.getKey());
}
return list;
}
private void initializeTjp(InstructionFactory fact, InstructionList list,
Field field, BcelShadow shadow)
{
Member sig = shadow.getSignature();
//ResolvedMember mem = shadow.getSignature().resolve(shadow.getWorld());
// load the factory
list.append(InstructionFactory.createLoad(factoryType, 0));
// load the kind
list.append(new PUSH(getConstantPoolGen(), shadow.getKind().getName()));
// create the signature
list.append(InstructionFactory.createLoad(factoryType, 0));
if (sig.getKind().equals(Member.METHOD)) {
BcelWorld w = shadow.getWorld();
// For methods, push the parts of the signature on.
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),sig.getName()));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getReturnType())));
// And generate a call to the variant of makeMethodSig() that takes 7 strings
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING },
Constants.INVOKEVIRTUAL));
} else if (sig.getKind().equals(Member.HANDLER)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else if(sig.getKind().equals(Member.CONSTRUCTOR)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else if(sig.getKind().equals(Member.FIELD)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),sig.getName()));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getReturnType())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else if(sig.getKind().equals(Member.ADVICE)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),sig.getName()));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w))));
list.append(new PUSH(getConstantPoolGen(),makeString((sig.getReturnType()))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else if(sig.getKind().equals(Member.STATIC_INITIALIZATION)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else {
list.append(new PUSH(getConstantPoolGen(), sig.getSignatureString(shadow.getWorld())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING },
Constants.INVOKEVIRTUAL));
}
//XXX should load source location from shadow
list.append(Utility.createConstant(fact, shadow.getSourceLine()));
final String factoryMethod;
if (staticTjpType.equals(field.getType())) {
factoryMethod = "makeSJP";
} else if (enclosingStaticTjpType.equals(field.getType())) {
factoryMethod = "makeESJP";
} else {
throw new Error("should not happen");
}
list.append(fact.createInvoke(factoryType.getClassName(),
factoryMethod, field.getType(),
new Type[] { Type.STRING, sigType, Type.INT},
Constants.INVOKEVIRTUAL));
// put it in the field
list.append(fact.createFieldAccess(getClassName(), field.getName(),
field.getType(), Constants.PUTSTATIC));
}
protected String makeString(int i) {
return Integer.toString(i, 16); //??? expensive
}
protected String makeString(UnresolvedType t) {
// this is the inverse of the odd behavior for Class.forName w/ arrays
if (t.isArray()) {
// this behavior matches the string used by the eclipse compiler for Foo.class literals
return t.getSignature().replace('/', '.');
} else {
return t.getName();
}
}
protected String makeString(UnresolvedType[] types) {
if (types == null) return "";
StringBuffer buf = new StringBuffer();
for (int i = 0, len=types.length; i < len; i++) {
buf.append(makeString(types[i]));
buf.append(':');
}
return buf.toString();
}
protected String makeString(String[] names) {
if (names == null) return "";
StringBuffer buf = new StringBuffer();
for (int i = 0, len=names.length; i < len; i++) {
buf.append(names[i]);
buf.append(':');
}
return buf.toString();
}
public ResolvedType getType() {
if (myType == null) return null;
return myType.getResolvedTypeX();
}
public BcelObjectType getBcelObjectType() {
return myType;
}
public String getFileName() {
return myGen.getFileName();
}
private void addField(Field field) {
myGen.addField(field);
}
public void replaceField(Field oldF, Field newF){
myGen.removeField(oldF);
myGen.addField(newF);
}
public void addField(Field field, ISourceLocation sourceLocation) {
addField(field);
if (!(field.isPrivate()
&& (field.isStatic() || field.isTransient()))) {
errorOnAddedField(field,sourceLocation);
}
}
public String getClassName() {
return myGen.getClassName();
}
public boolean isInterface() {
return myGen.isInterface();
}
public boolean isAbstract() {
return myGen.isAbstract();
}
public LazyMethodGen getLazyMethodGen(Member m) {
return getLazyMethodGen(m.getName(), m.getSignature(),false);
}
public LazyMethodGen getLazyMethodGen(String name, String signature) {
return getLazyMethodGen(name,signature,false);
}
public LazyMethodGen getLazyMethodGen(String name, String signature,boolean allowMissing) {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(name) && gen.getSignature().equals(signature))
return gen;
}
if (!allowMissing) {
throw new BCException("Class " + this.getName() + " does not have a method "
+ name + " with signature " + signature);
}
return null;
}
public void forcePublic() {
myGen.setAccessFlags(Utility.makePublic(myGen.getAccessFlags()));
}
public boolean hasAnnotation(UnresolvedType t) {
// annotations on the real thing
AnnotationGen agens[] = myGen.getAnnotations();
if (agens==null) return false;
for (int i = 0; i < agens.length; i++) {
AnnotationGen gen = agens[i];
if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) return true;
}
// annotations added during this weave
return false;
}
public void addAnnotation(Annotation a) {
if (!hasAnnotation(UnresolvedType.forSignature(a.getTypeSignature()))) {
annotations.add(new AnnotationGen(a,getConstantPoolGen(),true));
}
}
// this test is like asking:
// if (UnresolvedType.SERIALIZABLE.resolve(getType().getWorld()).isAssignableFrom(getType())) {
// only we don't do that because this forces us to find all the supertypes of the type,
// and if one of them is missing we fail, and it's not worth failing just to put out
// a warning message!
private boolean implementsSerializable(ResolvedType aType) {
ResolvedType[] interfaces = aType.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (interfaces[i].getSignature().equals(UnresolvedType.SERIALIZABLE.getSignature())) {
return true;
} else {
if (interfaces[i].isMissing()) continue;
ResolvedType superInterface = interfaces[i].getSuperclass();
if (superInterface != null && !superInterface.isMissing()) {
if (implementsSerializable(superInterface)) return true;
}
}
}
ResolvedType superType = aType.getSuperclass();
if (superType != null && !superType.isMissing()) {
return implementsSerializable(superType);
}
return false;
}
}
|
115,235
|
Bug 115235 StackOverflowError on circular pointcut iff aspect parameterized
|
The code below overflows when concretizing a circular pointcut from a parameterized aspect. Not true when the aspect is not parameterized. --------------------------------------------- public class SelfPC { public static void main(String[] args) { new C().foo(); } static class C { pointcut doit() : C.doit(); // CE expected void foo() {} } // ------------ pertarget<T> static abstract aspect PT_PARM<T> pertarget(pc()) { abstract protected pointcut pc(); before() : pc() {} } static aspect CPT_PARM extends PT_PARM<C> { protected pointcut pc() : C.doit(); } // // ------------ issingleton<T> // static abstract aspect IS_PARM<T> { // abstract protected pointcut pc(); // before() : pc() {} // } // static aspect CIS_PARM extends IS_PARM<C> { // protected pointcut pc() : C.doit(); // } // // ------------ pertarget // static abstract aspect PT pertarget(pc()) { // abstract protected pointcut pc(); // before() : pc() {} // } // static aspect CPT extends PT{ // protected pointcut pc() : C.doit(); // } // // ------------ issingleton // static abstract aspect SIS { // abstract protected pointcut pc(); // before() : pc() {} // } // static aspect CSIS extends SIS { // protected pointcut pc() : C.doit(); // } } --------------------------------------------- java.lang.StackOverflowError at java.lang.StringBuffer.append(StringBuffer.java:225) at org.aspectj.weaver.UnresolvedType.nameToSignature(UnresolvedType.java:734) at org.aspectj.weaver.UnresolvedType.forName(UnresolvedType.java:308) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:302) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromEclipse(EclipseFactory.java:129) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.getSuperclass(EclipseSourceType.java:119) at org.aspectj.weaver.ReferenceType.getSuperclass(ReferenceType.java:481) at org.aspectj.weaver.ResolvedType.getDirectSupertypes(ResolvedType.java:65) at org.aspectj.weaver.ResolvedType$6.get(ResolvedType.java:447) at org.aspectj.weaver.Iterators$4.next(Iterators.java:148) at org.aspectj.weaver.Iterators$3$1.hasNext(Iterators.java:117) at org.aspectj.weaver.Iterators$3.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.findPointcut(ResolvedType.java:466) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:269) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:326) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) ... ---------------------------------------------
|
resolved fixed
|
4b8bed7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-14T10:38:47Z
| 2005-11-06T12:26:40Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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");
}
// 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);
}
}
|
115,235
|
Bug 115235 StackOverflowError on circular pointcut iff aspect parameterized
|
The code below overflows when concretizing a circular pointcut from a parameterized aspect. Not true when the aspect is not parameterized. --------------------------------------------- public class SelfPC { public static void main(String[] args) { new C().foo(); } static class C { pointcut doit() : C.doit(); // CE expected void foo() {} } // ------------ pertarget<T> static abstract aspect PT_PARM<T> pertarget(pc()) { abstract protected pointcut pc(); before() : pc() {} } static aspect CPT_PARM extends PT_PARM<C> { protected pointcut pc() : C.doit(); } // // ------------ issingleton<T> // static abstract aspect IS_PARM<T> { // abstract protected pointcut pc(); // before() : pc() {} // } // static aspect CIS_PARM extends IS_PARM<C> { // protected pointcut pc() : C.doit(); // } // // ------------ pertarget // static abstract aspect PT pertarget(pc()) { // abstract protected pointcut pc(); // before() : pc() {} // } // static aspect CPT extends PT{ // protected pointcut pc() : C.doit(); // } // // ------------ issingleton // static abstract aspect SIS { // abstract protected pointcut pc(); // before() : pc() {} // } // static aspect CSIS extends SIS { // protected pointcut pc() : C.doit(); // } } --------------------------------------------- java.lang.StackOverflowError at java.lang.StringBuffer.append(StringBuffer.java:225) at org.aspectj.weaver.UnresolvedType.nameToSignature(UnresolvedType.java:734) at org.aspectj.weaver.UnresolvedType.forName(UnresolvedType.java:308) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:302) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromEclipse(EclipseFactory.java:129) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.getSuperclass(EclipseSourceType.java:119) at org.aspectj.weaver.ReferenceType.getSuperclass(ReferenceType.java:481) at org.aspectj.weaver.ResolvedType.getDirectSupertypes(ResolvedType.java:65) at org.aspectj.weaver.ResolvedType$6.get(ResolvedType.java:447) at org.aspectj.weaver.Iterators$4.next(Iterators.java:148) at org.aspectj.weaver.Iterators$3$1.hasNext(Iterators.java:117) at org.aspectj.weaver.Iterators$3.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.findPointcut(ResolvedType.java:466) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:269) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:326) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) ... ---------------------------------------------
|
resolved fixed
|
4b8bed7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-14T10:38:47Z
| 2005-11-06T12:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/Pointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.util.TypeSafeEnum;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Checker;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
/**
* The lifecycle of Pointcuts is modeled by Pointcut.State. It has three things:
*
* <p>Creation -- SYMBOLIC -- then resolve(IScope) -- RESOLVED -- concretize(...) -- CONCRETE
*
* @author Erik Hilsdale
* @author Jim Hugunin
*
* A day in the life of a pointcut.... - AMC.
* ==========================================
*
* Pointcuts are created by the PatternParser, which is called by ajdt to
* parse a pointcut from the PseudoTokens AST node (which in turn are part
* of a PointcutDesignator AST node).
*
* Pointcuts are resolved by ajdt when an AdviceDeclaration or a
* PointcutDeclaration has its statements resolved. This happens as
* part of completeTypeBindings in the AjLookupEnvironment which is
* called after the diet parse phase of the compiler. Named pointcuts,
* and references to named pointcuts are instances of ReferencePointcut.
*
* At the end of the compilation process, the pointcuts are serialized
* (write method) into attributes in the class file.
*
* When the weaver loads the class files, it unpacks the attributes
* and deserializes the pointcuts (read). All aspects are added to the
* world, by calling addOrReplaceAspect on
* the crosscutting members set of the world. When aspects are added or
* replaced, the crosscutting members in the aspect are extracted as
* ShadowMungers (each holding a pointcut). The ShadowMungers are
* concretized, which concretizes the pointcuts. At this stage
* ReferencePointcuts are replaced by their declared content.
*
* During weaving, the weaver processes type by type. It first culls
* potentially matching ShadowMungers by calling the fastMatch method
* on their pointcuts. Only those that might match make it through to
* the next phase. At the next phase, all of the shadows within the
* type are created and passed to the pointcut for matching (match).
*
* When the actual munging happens, matched pointcuts are asked for
* their residue (findResidue) - the runtime test if any. Because of
* negation, findResidue may be called on pointcuts that could never
* match the shadow.
*
*/
public abstract class Pointcut extends PatternNode {
public static final class State extends TypeSafeEnum {
public State(String name, int key) {
super(name, key);
}
}
/**
* ATAJ the name of the formal for which we don't want any warning when unbound since
* we consider them as implicitly bound. f.e. JoinPoint for @AJ advices
*/
public String[] m_ignoreUnboundBindingForNames = new String[0];
public static final State SYMBOLIC = new State("symbolic", 0);
public static final State RESOLVED = new State("resolved", 1);
public static final State CONCRETE = new State("concrete", 2);
protected byte pointcutKind;
public State state;
protected int lastMatchedShadowId;
private FuzzyBoolean lastMatchedShadowResult;
private String[] typeVariablesInScope = new String[0];
/**
* Constructor for Pattern.
*/
public Pointcut() {
super();
this.state = SYMBOLIC;
}
/**
* Could I match any shadows in the code defined within this type?
*/
public abstract FuzzyBoolean fastMatch(FastMatchInfo info);
/**
* The set of ShadowKinds that this Pointcut could possibly match
*/
public abstract /*Enum*/Set/*<Shadow.Kind>*/ couldMatchKinds();
public String[] getTypeVariablesInScope() {
return typeVariablesInScope;
}
public void setTypeVariablesInScope(String[] typeVars) {
this.typeVariablesInScope = typeVars;
}
/**
* Do I really match this shadow?
* XXX implementors need to handle state
*/
public final FuzzyBoolean match(Shadow shadow) {
if (shadow.shadowId == lastMatchedShadowId) return lastMatchedShadowResult;
FuzzyBoolean ret;
// this next test will prevent a lot of un-needed matching going on....
if (couldMatchKinds().contains(shadow.getKind())) {
ret = matchInternal(shadow);
} else {
ret = FuzzyBoolean.NO;
}
lastMatchedShadowId = shadow.shadowId;
lastMatchedShadowResult = ret;
return ret;
}
protected abstract FuzzyBoolean matchInternal(Shadow shadow);
public static final byte KINDED = 1;
public static final byte WITHIN = 2;
public static final byte THIS_OR_TARGET = 3;
public static final byte ARGS = 4;
public static final byte AND = 5;
public static final byte OR = 6;
public static final byte NOT = 7;
public static final byte REFERENCE = 8;
public static final byte IF = 9;
public static final byte CFLOW = 10;
public static final byte WITHINCODE = 12;
public static final byte HANDLER = 13;
public static final byte IF_TRUE = 14;
public static final byte IF_FALSE = 15;
public static final byte ANNOTATION = 16;
public static final byte ATWITHIN = 17;
public static final byte ATWITHINCODE = 18;
public static final byte ATTHIS_OR_TARGET = 19;
public static final byte NONE = 20; // DO NOT CHANGE OR REORDER THIS SEQUENCE, THIS VALUE CAN BE PUT OUT BY ASPECTJ1.2.1
public static final byte ATARGS = 21;
public byte getPointcutKind() { return pointcutKind; }
// internal, only called from resolve
protected abstract void resolveBindings(IScope scope, Bindings bindings);
/**
* Returns this pointcut mutated
*/
public final Pointcut resolve(IScope scope) {
assertState(SYMBOLIC);
Bindings bindingTable = new Bindings(scope.getFormalCount());
IScope bindingResolutionScope = scope;
if (typeVariablesInScope.length > 0) {
bindingResolutionScope = new ScopeWithTypeVariables(typeVariablesInScope,scope);
}
this.resolveBindings(bindingResolutionScope, bindingTable);
bindingTable.checkAllBound(bindingResolutionScope);
this.state = RESOLVED;
return this;
}
/**
* Returns a new pointcut
* Only used by test cases
*/
public final Pointcut concretize(ResolvedType inAspect, ResolvedType declaringType, int arity) {
Pointcut ret = concretize(inAspect, declaringType, IntMap.idMap(arity));
// copy the unbound ignore list
ret.m_ignoreUnboundBindingForNames = m_ignoreUnboundBindingForNames;
return ret;
}
//XXX this is the signature we're moving to
public final Pointcut concretize(ResolvedType inAspect, ResolvedType declaringType, int arity, ShadowMunger advice) {
//if (state == CONCRETE) return this; //???
IntMap map = IntMap.idMap(arity);
map.setEnclosingAdvice(advice);
map.setConcreteAspect(inAspect);
return concretize(inAspect, declaringType, map);
}
public boolean isDeclare(ShadowMunger munger) {
if (munger == null) return false; // ??? Is it actually an error if we get a null munger into this method.
if (munger instanceof Checker) return true;
if (((Advice)munger).getKind().equals(AdviceKind.Softener)) return true;
return false;
}
public final Pointcut concretize(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) {
//!!! add this test -- assertState(RESOLVED);
Pointcut ret = this.concretize1(inAspect, declaringType, bindings);
if (shouldCopyLocationForConcretize()) ret.copyLocationFrom(this);
ret.state = CONCRETE;
// copy the unbound ignore list
ret.m_ignoreUnboundBindingForNames = m_ignoreUnboundBindingForNames;
return ret;
}
protected boolean shouldCopyLocationForConcretize() {
return true;
}
/**
* Resolves and removes ReferencePointcuts, replacing with basic ones
*
* @param inAspect the aspect to resolve relative to
* @param bindings a Map from formal index in the current lexical context
* -> formal index in the concrete advice that will run
*
* This must always return a new Pointcut object (even if the concretized
* Pointcut is identical to the resolved one). That behavior is
* assumed in many places.
* XXX fix implementors to handle state
*/
protected abstract Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings);
//XXX implementors need to handle state
/**
* This can be called from NotPointcut even for Pointcuts that
* don't match the shadow
*/
public final Test findResidue(Shadow shadow, ExposedState state) {
// if (shadow.shadowId == lastMatchedShadowId) return lastMatchedShadowResidue;
Test ret = findResidueInternal(shadow,state);
// lastMatchedShadowResidue = ret;
lastMatchedShadowId = shadow.shadowId;
return ret;
}
protected abstract Test findResidueInternal(Shadow shadow,ExposedState state);
//XXX we're not sure whether or not this is needed
//XXX currently it's unused we're keeping it around as a stub
public void postRead(ResolvedType enclosingType) {}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
byte kind = s.readByte();
Pointcut ret;
switch(kind) {
case KINDED: ret = KindedPointcut.read(s, context); break;
case WITHIN: ret = WithinPointcut.read(s, context); break;
case THIS_OR_TARGET: ret = ThisOrTargetPointcut.read(s, context); break;
case ARGS: ret = ArgsPointcut.read(s, context); break;
case AND: ret = AndPointcut.read(s, context); break;
case OR: ret = OrPointcut.read(s, context); break;
case NOT: ret = NotPointcut.read(s, context); break;
case REFERENCE: ret = ReferencePointcut.read(s, context); break;
case IF: ret = IfPointcut.read(s, context); break;
case CFLOW: ret = CflowPointcut.read(s, context); break;
case WITHINCODE: ret = WithincodePointcut.read(s, context); break;
case HANDLER: ret = HandlerPointcut.read(s, context); break;
case IF_TRUE: ret = IfPointcut.makeIfTruePointcut(RESOLVED); break;
case IF_FALSE: ret = IfPointcut.makeIfFalsePointcut(RESOLVED); break;
case ANNOTATION: ret = AnnotationPointcut.read(s, context); break;
case ATWITHIN: ret = WithinAnnotationPointcut.read(s, context); break;
case ATWITHINCODE: ret = WithinCodeAnnotationPointcut.read(s, context); break;
case ATTHIS_OR_TARGET: ret = ThisOrTargetAnnotationPointcut.read(s, context); break;
case ATARGS: ret = ArgsAnnotationPointcut.read(s,context); break;
case NONE: ret = makeMatchesNothing(RESOLVED); break;
default:
throw new BCException("unknown kind: " + kind);
}
ret.state = RESOLVED;
ret.pointcutKind = kind;
return ret;
}
//public void prepare(Shadow shadow) {}
// ---- test method
public static Pointcut fromString(String str) {
PatternParser parser = new PatternParser(str);
return parser.parsePointcut();
}
static class MatchesNothingPointcut extends Pointcut {
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
return Literal.FALSE; // can only get here if an earlier error occurred
}
public Set couldMatchKinds() {
return Collections.EMPTY_SET;
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.NO;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
return FuzzyBoolean.NO;
}
public void resolveBindings(IScope scope, Bindings bindings) {
}
public void postRead(ResolvedType enclosingType) {
}
public Pointcut concretize1(
ResolvedType inAspect,
ResolvedType declaringType,
IntMap bindings) {
return makeMatchesNothing(state);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(NONE);
}
public String toString() { return ""; }
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public Pointcut parameterizeWith(Map typeVariableMap) {
return this;
}
}
//public static Pointcut MatchesNothing = new MatchesNothingPointcut();
//??? there could possibly be some good optimizations to be done at this point
public static Pointcut makeMatchesNothing(State state) {
Pointcut ret = new MatchesNothingPointcut();
ret.state = state;
return ret;
}
public void assertState(State state) {
if (this.state != state) {
throw new BCException("expected state: " + state + " got: " + this.state);
}
}
public abstract Pointcut parameterizeWith(Map typeVariableMap);
}
|
115,235
|
Bug 115235 StackOverflowError on circular pointcut iff aspect parameterized
|
The code below overflows when concretizing a circular pointcut from a parameterized aspect. Not true when the aspect is not parameterized. --------------------------------------------- public class SelfPC { public static void main(String[] args) { new C().foo(); } static class C { pointcut doit() : C.doit(); // CE expected void foo() {} } // ------------ pertarget<T> static abstract aspect PT_PARM<T> pertarget(pc()) { abstract protected pointcut pc(); before() : pc() {} } static aspect CPT_PARM extends PT_PARM<C> { protected pointcut pc() : C.doit(); } // // ------------ issingleton<T> // static abstract aspect IS_PARM<T> { // abstract protected pointcut pc(); // before() : pc() {} // } // static aspect CIS_PARM extends IS_PARM<C> { // protected pointcut pc() : C.doit(); // } // // ------------ pertarget // static abstract aspect PT pertarget(pc()) { // abstract protected pointcut pc(); // before() : pc() {} // } // static aspect CPT extends PT{ // protected pointcut pc() : C.doit(); // } // // ------------ issingleton // static abstract aspect SIS { // abstract protected pointcut pc(); // before() : pc() {} // } // static aspect CSIS extends SIS { // protected pointcut pc() : C.doit(); // } } --------------------------------------------- java.lang.StackOverflowError at java.lang.StringBuffer.append(StringBuffer.java:225) at org.aspectj.weaver.UnresolvedType.nameToSignature(UnresolvedType.java:734) at org.aspectj.weaver.UnresolvedType.forName(UnresolvedType.java:308) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:302) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromEclipse(EclipseFactory.java:129) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.getSuperclass(EclipseSourceType.java:119) at org.aspectj.weaver.ReferenceType.getSuperclass(ReferenceType.java:481) at org.aspectj.weaver.ResolvedType.getDirectSupertypes(ResolvedType.java:65) at org.aspectj.weaver.ResolvedType$6.get(ResolvedType.java:447) at org.aspectj.weaver.Iterators$4.next(Iterators.java:148) at org.aspectj.weaver.Iterators$3$1.hasNext(Iterators.java:117) at org.aspectj.weaver.Iterators$3.hasNext(Iterators.java:128) at org.aspectj.weaver.ResolvedType.findPointcut(ResolvedType.java:466) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:269) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) at org.aspectj.weaver.patterns.ReferencePointcut.concretize1(ReferencePointcut.java:326) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:229) ... ---------------------------------------------
|
resolved fixed
|
4b8bed7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-14T10:38:47Z
| 2005-11-06T12:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/ReferencePointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Test;
/**
*/
//XXX needs check that arguments contains no WildTypePatterns
public class ReferencePointcut extends Pointcut {
public UnresolvedType onType;
public TypePattern onTypeSymbolic;
public String name;
public TypePatternList arguments;
/**
* if this is non-null then when the pointcut is concretized the result will be parameterized too.
*/
private Map typeVariableMap;
//public ResolvedPointcut binding;
public ReferencePointcut(TypePattern onTypeSymbolic, String name, TypePatternList arguments) {
this.onTypeSymbolic = onTypeSymbolic;
this.name = name;
this.arguments = arguments;
this.pointcutKind = REFERENCE;
}
public ReferencePointcut(UnresolvedType onType, String name, TypePatternList arguments) {
this.onType = onType;
this.name = name;
this.arguments = arguments;
this.pointcutKind = REFERENCE;
}
public Set couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS;
}
//??? do either of these match methods make any sense???
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
/**
* Do I really match this shadow?
*/
protected FuzzyBoolean matchInternal(Shadow shadow) {
return FuzzyBoolean.NO;
}
public String toString() {
StringBuffer buf = new StringBuffer();
if (onType != null) {
buf.append(onType);
buf.append(".");
// for (int i=0, len=fromType.length; i < len; i++) {
// buf.append(fromType[i]);
// buf.append(".");
// }
}
buf.append(name);
buf.append(arguments.toString());
return buf.toString();
}
public void write(DataOutputStream s) throws IOException {
//XXX ignores onType
s.writeByte(Pointcut.REFERENCE);
if (onType != null) {
s.writeBoolean(true);
onType.write(s);
} else {
s.writeBoolean(false);
}
s.writeUTF(name);
arguments.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
UnresolvedType onType = null;
if (s.readBoolean()) {
onType = UnresolvedType.read(s);
}
ReferencePointcut ret = new ReferencePointcut(onType, s.readUTF(),
TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
if (onTypeSymbolic != null) {
onType = onTypeSymbolic.resolveExactType(scope, bindings);
// in this case we've already signalled an error
if (onType == ResolvedType.MISSING) return;
}
ResolvedType searchType;
if (onType != null) {
searchType = scope.getWorld().resolve(onType);
} else {
searchType = scope.getEnclosingType();
}
arguments.resolveBindings(scope, bindings, true, true);
//XXX ensure that arguments has no ..'s in it
// check that I refer to a real pointcut declaration and that I match
ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name);
// if we're not a static reference, then do a lookup of outers
if (pointcutDef == null && onType == null) {
while (true) {
UnresolvedType declaringType = searchType.getDeclaringType();
if (declaringType == null) break;
searchType = declaringType.resolve(scope.getWorld());
pointcutDef = searchType.findPointcut(name);
if (pointcutDef != null) {
// make this a static reference
onType = searchType;
break;
}
}
}
if (pointcutDef == null) {
scope.message(IMessage.ERROR, this, "can't find referenced pointcut " + name);
return;
}
// check visibility
if (!pointcutDef.isVisible(scope.getEnclosingType())) {
scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible");
return;
}
if (Modifier.isAbstract(pointcutDef.getModifiers())) {
if (onType != null) {
scope.message(IMessage.ERROR, this,
"can't make static reference to abstract pointcut");
return;
} else if (!searchType.isAbstract()) {
scope.message(IMessage.ERROR, this,
"can't use abstract pointcut in concrete context");
return;
}
}
ResolvedType[] parameterTypes =
scope.getWorld().resolve(pointcutDef.getParameterTypes());
if (parameterTypes.length != arguments.size()) {
scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " +
parameterTypes.length + " found " + arguments.size());
return;
}
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (p == TypePattern.NO) {
scope.message(IMessage.ERROR, this,
"bad parameter to pointcut reference");
return;
}
if (!p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(UnresolvedType.OBJECT))
{
scope.message(IMessage.ERROR, p, "incompatible type, expected " +
parameterTypes[i].getName() + " found " + p +". Check the type specified in your pointcut");
return;
}
}
if (onType != null) {
if (onType.isParameterizedType()) {
// build a type map mapping type variable names in the generic type to
// the type parameters presented
typeVariableMap = new HashMap();
ResolvedType underlyingGenericType = ((ResolvedType) onType).getGenericType();
TypeVariable[] tVars = underlyingGenericType.getTypeVariables();
ResolvedType[] typeParams = ((ResolvedType)onType).getResolvedTypeParameters();
for (int i = 0; i < tVars.length; i++) {
typeVariableMap.put(tVars[i].getName(),typeParams[i]);
}
} else if (onType.isGenericType()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_REFERENCE_POINTCUT_IN_RAW_TYPE),
getSourceLocation()));
}
}
}
public void postRead(ResolvedType enclosingType) {
arguments.postRead(enclosingType);
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
throw new RuntimeException("shouldn't happen");
}
//??? This is not thread safe, but this class is not designed for multi-threading
private boolean concretizing = false;
// declaring type is the type that declared the member referencing this pointcut.
// If it declares a matching private pointcut, then that pointcut should be used
// and not one in a subtype that happens to have the same name.
public Pointcut concretize1(ResolvedType searchStart, ResolvedType declaringType, IntMap bindings) {
if (concretizing) {
//Thread.currentThread().dumpStack();
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.CIRCULAR_POINTCUT,this),
getSourceLocation()));
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
try {
concretizing = true;
ResolvedPointcutDefinition pointcutDec;
if (onType != null) {
searchStart = onType.resolve(searchStart.getWorld());
if (searchStart == ResolvedType.MISSING) {
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
}
if (declaringType == null) declaringType = searchStart;
pointcutDec = declaringType.findPointcut(name);
boolean foundMatchingPointcut = (pointcutDec != null && pointcutDec.isPrivate());
if (!foundMatchingPointcut) {
pointcutDec = searchStart.findPointcut(name);
if (pointcutDec == null) {
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_POINTCUT,name,searchStart.getName()),
getSourceLocation())
);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
}
if (pointcutDec.isAbstract()) {
//Thread.currentThread().dumpStack();
ShadowMunger enclosingAdvice = bindings.getEnclosingAdvice();
searchStart.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ABSTRACT_POINTCUT,pointcutDec),
getSourceLocation(),
(null == enclosingAdvice) ? null : enclosingAdvice.getSourceLocation());
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
//System.err.println("start: " + searchStart);
ResolvedType[] parameterTypes = searchStart.getWorld().resolve(pointcutDec.getParameterTypes());
TypePatternList arguments = this.arguments.resolveReferences(bindings);
IntMap newBindings = new IntMap();
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
if (p == TypePattern.NO) continue;
// we are allowed to bind to pointcuts which use subtypes as this is type safe
// 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) ret = ret.parameterizeWith(typeVariableMap);
return ret.concretize(searchStart, declaringType, newBindings);
} finally {
newBindings.popEnclosingDefinitition();
}
} finally {
concretizing = false;
}
}
/**
* make a version of this pointcut with any refs to typeVariables replaced by their entry in the map.
* Tricky thing is, we can't do this at the point in time this method will be called, so we make a
* version that will parameterize the pointcut it ultimately resolves to.
*/
public Pointcut parameterizeWith(Map typeVariableMap) {
ReferencePointcut ret = new ReferencePointcut(onType,name,arguments);
ret.onTypeSymbolic = onTypeSymbolic;
ret.typeVariableMap = typeVariableMap;
return ret;
}
// We want to keep the original source location, not the reference location
protected boolean shouldCopyLocationForConcretize() {
return false;
}
public boolean equals(Object other) {
if (!(other instanceof ReferencePointcut)) return false;
if (this == other) return true;
ReferencePointcut o = (ReferencePointcut)other;
return o.name.equals(name) && o.arguments.equals(arguments)
&& ((o.onType == null) ? (onType == null) : o.onType.equals(onType));
}
public int hashCode() {
int result = 17;
result = 37*result + ((onType == null) ? 0 : onType.hashCode());
result = 37*result + arguments.hashCode();
result = 37*result + name.hashCode();
return result;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
116,305
|
Bug 116305 Unexpected error: can't determine implemented interfaces of missing type
|
I have reusable library code that imports a type (a JAX-RPC Call in this case) for use in two ways: 1) matching in a method signature. 2) casting and use in an advice body It used to work properly when I used it in a load-time weaving configuration without the (Call) type being available on the classpath (I think it broke in the last week). However, I am now getting an abort error "can't determine implemented interfaces of missing type" when weaving this aspect into another type when the imported (Call) type isnt visible in a classloader. I tried changing the code to remove the import and to use a fully qualified name in the pointcut (and a reflective invocation in the advice body). However, this still fails in the same way. These pointcuts are presumably causing the error: public abstract aspect AbstractRequestMonitor { protected pointcut scope() : within(*);//if(true); protected pointcut monitorEnabled() : isMonitorEnabled() && scope(); protected abstract pointcut isMonitorEnabled(); ... } public abstract aspect AbstractResourceMonitor extends AbstractRequestMonitor { ... } public aspect RemoteCallMonitor extends AbstractResourceMonitor { protected pointcut isMonitorEnabled() : if(aspectOf().isEnabled()); public pointcut jaxRpcClientCall(Object wsCallObj) : call(public * javax.xml.rpc.Call.invoke*(..)) && target(wsCallObj); Object around(final Object wsCallObj) : jaxRpcClientCall(wsCallObj) && monitorEnabled() { ... Here is the output: org.aspectj.bridge.AbortException: can't determine implemented interfaces of missing type javax.xml.rpc.Call when matching pointcut ((((within(*) && call(public * javax.xml.rpc.Call.invoke* (..))) && target(BindingTypePattern(java.lang.Object, 0))) && if(boolean glassbox.inspector.monitor.resource.RemoteCallMonitor.ajc$if_12())) && persingleton(glassbox.inspector.monitor.resource.RemoteCallMonitor)) when matching shadow method-call(java.util.Locale java.util.Locale.getDefault()) when weaving type org.apache.struts.action.ActionServlet when weaving classes when weaving at org.aspectj.weaver.tools.WeavingAdaptor$WeavingAdaptorMessageHandler.handleMessa ge(WeavingAdaptor.java:364) at org.aspectj.bridge.MessageUtil.error(MessageUtil.java:81) at org.aspectj.weaver.MissingResolvedTypeWithKnownSignature.raiseCantFindType (MissingResolvedTypeWithKnownSignature.java:195) at org.aspectj.weaver.MissingResolvedTypeWithKnownSignature.getDeclaredInterfaces (MissingResolvedTypeWithKnownSignature.java:77) at org.aspectj.weaver.ResolvedType.getDirectSupertypes (ResolvedType.java:64) at org.aspectj.weaver.ReferenceType.isAssignableFrom (ReferenceType.java:312) at org.aspectj.weaver.ReferenceType.isAssignableFrom (ReferenceType.java:236) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig (KindedPointcut.java:151) at org.aspectj.weaver.patterns.KindedPointcut.matchInternal (KindedPointcut.java:108) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:145) at org.aspectj.weaver.patterns.AndPointcut.matchInternal (AndPointcut.java:57) 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.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:98) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:2098) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction (BcelClassWeaver.java:2085) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:1867) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInit (BcelClassWeaver.java:1731) at org.aspectj.weaver.bcel.BcelClassWeaver.match (BcelClassWeaver.java:1660) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:445) at org.aspectj.weaver.bcel.BcelClassWeaver.weave (BcelClassWeaver.java:101) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1531) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump (BcelWeaver.java:1485) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify (BcelWeaver.java:1266) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1088) at org.aspectj.weaver.tools.WeavingAdaptor.getWovenBytes (WeavingAdaptor.java:266) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass (WeavingAdaptor.java:198) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:67) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform (ClassPreProcessorAgentAdapter.java:52) ...
|
resolved fixed
|
676aa08
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-15T09:15:14Z
| 2005-11-14T20:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/KindedPointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.Checker;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
public class KindedPointcut extends Pointcut {
Shadow.Kind kind;
private SignaturePattern signature;
private Set matchKinds;
private ShadowMunger munger = null; // only set after concretization
public KindedPointcut(
Shadow.Kind kind,
SignaturePattern signature) {
this.kind = kind;
this.signature = signature;
this.pointcutKind = KINDED;
this.matchKinds = new HashSet();
matchKinds.add(kind);
}
public KindedPointcut(
Shadow.Kind kind,
SignaturePattern signature,
ShadowMunger munger) {
this(kind, signature);
this.munger = munger;
}
public SignaturePattern getSignature() {
return signature;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#couldMatchKinds()
*/
public Set couldMatchKinds() {
return matchKinds;
}
public boolean couldEverMatchSameJoinPointsAs(KindedPointcut other) {
if (this.kind != other.kind) return false;
String myName = signature.getName().maybeGetSimpleName();
String yourName = other.signature.getName().maybeGetSimpleName();
if (myName != null && yourName != null) {
if ( !myName.equals(yourName)) {
return false;
}
}
if (signature.getParameterTypes().ellipsisCount == 0) {
if (other.signature.getParameterTypes().ellipsisCount == 0) {
if (signature.getParameterTypes().getTypePatterns().length !=
other.signature.getParameterTypes().getTypePatterns().length) {
return false;
}
}
}
return true;
}
public FuzzyBoolean fastMatch(FastMatchInfo info) {
if (info.getKind() != null) {
if (info.getKind() != kind) return FuzzyBoolean.NO;
}
return FuzzyBoolean.MAYBE;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
if (shadow.getKind() != kind) return FuzzyBoolean.NO;
if (!signature.matches(shadow.getMatchingSignature(), shadow.getIWorld(),this.kind == Shadow.MethodCall)){
if(kind == Shadow.MethodCall) {
warnOnConfusingSig(shadow);
//warnOnBridgeMethod(shadow);
}
return FuzzyBoolean.NO;
}
return FuzzyBoolean.YES;
}
// private void warnOnBridgeMethod(Shadow shadow) {
// if (shadow.getIWorld().getLint().noJoinpointsForBridgeMethods.isEnabled()) {
// ResolvedMember rm = shadow.getSignature().resolve(shadow.getIWorld());
// if (rm!=null) {
// int shadowModifiers = rm.getModifiers(); //shadow.getSignature().getModifiers(shadow.getIWorld());
// if (ResolvedType.hasBridgeModifier(shadowModifiers)) {
// shadow.getIWorld().getLint().noJoinpointsForBridgeMethods.signal(new String[]{},getSourceLocation(),
// new ISourceLocation[]{shadow.getSourceLocation()});
// }
// }
// }
// }
private void warnOnConfusingSig(Shadow shadow) {
// Don't do all this processing if we don't need to !
if (!shadow.getIWorld().getLint().unmatchedSuperTypeInCall.isEnabled()) return;
// no warnings for declare error/warning
if (munger instanceof Checker) return;
World world = shadow.getIWorld();
// warning never needed if the declaring type is any
UnresolvedType exactDeclaringType = signature.getDeclaringType().getExactType();
ResolvedType shadowDeclaringType =
shadow.getSignature().getDeclaringType().resolve(world);
if (signature.getDeclaringType().isStar()
|| exactDeclaringType== ResolvedType.MISSING)
return;
// warning not needed if match type couldn't ever be the declaring type
if (!shadowDeclaringType.isAssignableFrom(exactDeclaringType.resolve(world))) {
return;
}
// if the method in the declaring type is *not* visible to the
// exact declaring type then warning not needed.
int shadowModifiers = shadow.getSignature().resolve(world).getModifiers();
if (!ResolvedType
.isVisible(
shadowModifiers,
shadowDeclaringType,
exactDeclaringType.resolve(world))) {
return;
}
if (!signature.getReturnType().matchesStatically(shadow.getSignature().getReturnType().resolve(world))) {
// Covariance issue...
// The reason we didn't match is that the type pattern for the pointcut (Car) doesn't match the
// return type for the specific declaration at the shadow. (FastCar Sub.getCar())
// XXX Put out another XLINT in this case?
return;
}
// PR60015 - Don't report the warning if the declaring type is object and 'this' is an interface
if (exactDeclaringType.resolve(world).isInterface() && shadowDeclaringType.equals(world.resolve("java.lang.Object"))) {
return;
}
SignaturePattern nonConfusingPattern =
new SignaturePattern(
signature.getKind(),
signature.getModifiers(),
signature.getReturnType(),
TypePattern.ANY,
signature.getName(),
signature.getParameterTypes(),
signature.getThrowsPattern(),
signature.getAnnotationPattern());
if (nonConfusingPattern
.matches(shadow.getSignature(), shadow.getIWorld(),true)) {
shadow.getIWorld().getLint().unmatchedSuperTypeInCall.signal(
new String[] {
shadow.getSignature().getDeclaringType().toString(),
signature.getDeclaringType().toString()
},
this.getSourceLocation(),
new ISourceLocation[] {shadow.getSourceLocation()} );
}
}
public boolean equals(Object other) {
if (!(other instanceof KindedPointcut)) return false;
KindedPointcut o = (KindedPointcut)other;
return o.kind == this.kind && o.signature.equals(this.signature);
}
public int hashCode() {
int result = 17;
result = 37*result + kind.hashCode();
result = 37*result + signature.hashCode();
return result;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(kind.getSimpleName());
buf.append("(");
buf.append(signature.toString());
buf.append(")");
return buf.toString();
}
public void postRead(ResolvedType enclosingType) {
signature.postRead(enclosingType);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.KINDED);
kind.write(s);
signature.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
Shadow.Kind kind = Shadow.Kind.read(s);
SignaturePattern sig = SignaturePattern.read(s, context);
KindedPointcut ret = new KindedPointcut(kind, sig);
ret.readLocation(context, s);
return ret;
}
// XXX note: there is no namebinding in any kinded pointcut.
// still might want to do something for better error messages
// We want to do something here to make sure we don't sidestep the parameter
// list in capturing type identifiers.
public void resolveBindings(IScope scope, Bindings bindings) {
if (kind == Shadow.Initialization) {
// scope.getMessageHandler().handleMessage(
// MessageUtil.error(
// "initialization unimplemented in 1.1beta1",
// this.getSourceLocation()));
}
signature = signature.resolveBindings(scope, bindings);
if (kind == Shadow.ConstructorExecution) { // Bug fix 60936
if (signature.getDeclaringType() != null) {
World world = scope.getWorld();
UnresolvedType exactType = signature.getDeclaringType().getExactType();
if (signature.getKind() == Member.CONSTRUCTOR &&
!exactType.equals(ResolvedType.MISSING) &&
exactType.resolve(world).isInterface() &&
!signature.getDeclaringType().isIncludeSubtypes()) {
world.getLint().noInterfaceCtorJoinpoint.signal(exactType.toString(), getSourceLocation());
}
}
}
// no parameterized types
if (kind == Shadow.StaticInitialization) {
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getDeclaringType().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_STATIC_INIT_JPS_FOR_PARAMETERIZED_TYPES),
getSourceLocation()));
}
}
// no parameterized types in declaring type position
if ((kind == Shadow.FieldGet) || (kind == Shadow.FieldSet)) {
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getDeclaringType().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.GET_AND_SET_DONT_SUPPORT_DEC_TYPE_PARAMETERS),
getSourceLocation()));
}
// fields can't have a void type!
UnresolvedType returnType = signature.getReturnType().getExactType();
if (returnType == ResolvedType.VOID) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.FIELDS_CANT_HAVE_VOID_TYPE),
getSourceLocation()));
}
}
// no join points for initialization and preinitialization of parameterized types
// no throwable parameterized types
if ((kind == Shadow.Initialization) || (kind == Shadow.PreInitialization)) {
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getDeclaringType().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_INIT_JPS_FOR_PARAMETERIZED_TYPES),
getSourceLocation()));
}
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getThrowsPattern().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES),
getSourceLocation()));
}
}
// no parameterized types in declaring type position
// no throwable parameterized types
if ((kind == Shadow.MethodExecution) || (kind == Shadow.ConstructorExecution)) {
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getDeclaringType().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.EXECUTION_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES),
getSourceLocation()));
}
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getThrowsPattern().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES),
getSourceLocation()));
}
}
// no parameterized types in declaring type position
// no throwable parameterized types
if ((kind == Shadow.MethodCall) || (kind == Shadow.ConstructorCall)) {
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getDeclaringType().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CALL_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES),
getSourceLocation()));
}
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getThrowsPattern().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES),
getSourceLocation()));
}
}
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE;
}
public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) {
Pointcut ret = new KindedPointcut(kind, signature, bindings.getEnclosingAdvice());
ret.copyLocationFrom(this);
return ret;
}
public Pointcut parameterizeWith(Map typeVariableMap) {
Pointcut ret = new KindedPointcut(kind, signature.parameterizeWith(typeVariableMap), munger );
ret.copyLocationFrom(this);
return ret;
}
public Shadow.Kind getKind() {
return kind;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
116,255
|
Bug 116255 XML Linkage Error with LTW
|
I am trying out a recent dev build of AspectJ and am now seeing a new linkage error when I load a Web app that contains an XML deployment descriptor. I'm trying to narrow down the date when this error first appeared. If I build and run with the Sept. 23 dev build all works properly. If I build and run with the Nov. 14 dev build it fails like this ... Here's the output: SEVERE: Error deploying configuration descriptor jpetstore.xml java.lang.LinkageError: org/apache/xerces/jaxp/SAXParserFactoryImpl : already defined in loader at java.lang.ClassLoader.defineClass(Ljava.lang.String; [BIILjava.security.ProtectionDomain;)Ljava.lang.Class;(Unknown Source ) at java.security.SecureClassLoader.defineClass (SecureClassLoader.java:124) at org.apache.catalina.loader.WebappClassLoader.findClassInternal (WebappClassLoader.java:1629) at org.apache.catalina.loader.WebappClassLoader.findClass (WebappClassLoader.java:850) at org.apache.catalina.loader.WebappClassLoader.loadClass (WebappClassLoader.java:1299) at org.apache.catalina.loader.WebappClassLoader.loadClass (WebappClassLoader.java:1181) at javax.xml.parsers.FactoryFinder.newInstance(FactoryFinder.java:88) at javax.xml.parsers.FactoryFinder.findJarServiceProvider (FactoryFinder.java:278) at javax.xml.parsers.FactoryFinder.find(FactoryFinder.java:185) at javax.xml.parsers.SAXParserFactory.newInstance (SAXParserFactory.java:107) at org.apache.tomcat.util.digester.Digester.getFactory (Digester.java:486) at org.apache.tomcat.util.digester.Digester.getParser(Digester.java:691) at org.apache.tomcat.util.digester.Digester.getXMLReader (Digester.java:899) at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1561) at org.apache.catalina.startup.TldConfig.tldScanStream (TldConfig.java:513) at org.apache.catalina.startup.TldConfig.tldScanTld(TldConfig.java:545) at org.apache.catalina.startup.TldConfig.execute(TldConfig.java:300) at org.apache.catalina.core.StandardContext.processTlds (StandardContext.java:4193) at org.apache.catalina.core.StandardContext.start (StandardContext.java:4049) at org.apache.catalina.core.ContainerBase.addChildInternal (ContainerBase.java:759) at org.apache.catalina.core.ContainerBase.addChild (ContainerBase.java:739) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:524) at org.apache.catalina.startup.HostConfig.deployDescriptor (HostConfig.java:589) at org.apache.catalina.startup.HostConfig.deployDescriptors (HostConfig.java:536) at org.apache.catalina.startup.HostConfig.deployApps (HostConfig.java:471) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1102) at org.apache.catalina.startup.HostConfig.lifecycleEvent (HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent (LifecycleSupport.java:119) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1020) at org.apache.catalina.core.StandardHost.start(StandardHost.java:718) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1012) error can't determine implemented interfaces of missing type javax.xml.rpc.Call when matching pointcut ((((within(*) && call(public * javax.xml.rpc.Call.invoke* (..))) && target(BindingTypePattern(java.lang.Object , 0))) && if(boolean glassbox.inspector.monitor.resource.RemoteCallMonitor.ajc$if_12())) && persingleton(glassbox.inspector.monitor. resource.RemoteCallMonitor)) when matching shadow method-call(boolean org.apache.crimson.parser.ContentModel.empty()) when weaving type org.apache.crimson.parser.ContentModel when weaving classes when weaving abort trouble in: final class org.apache.crimson.parser.ContentModel extends java.lang.Object: public char type public Object content public org.apache.crimson.parser.ContentModel next private org.apache.crimson.parser.SimpleHashtable cache public void <init>(String): ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 116) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void org.apache.crimson.parser.ContentModel.<init> (java.lang.String)) | ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 110) | NEW org.apache.crimson.parser.SimpleHashtable | DUP | constructor-call(void org.apache.crimson.parser.SimpleHashtable.<init>()) | | INVOKESPECIAL org.apache.crimson.parser.SimpleHashtable.<init> ()V | constructor-call(void org.apache.crimson.parser.SimpleHashtable.<init>()) | PUTFIELD org.apache.crimson.parser.ContentModel.cache Lorg/apache/crimson/parser/SimpleHashtable; | ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 117) | ICONST_0 | PUTFIELD org.apache.crimson.parser.ContentModel.type C | ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 118) | ALOAD_1 // java.lang.String element | PUTFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; | RETURN (line 119) constructor-execution(void org.apache.crimson.parser.ContentModel.<init> (java.lang.String)) end public void <init>(String) public void <init>(char, org.apache.crimson.parser.ContentModel): ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 125) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void org.apache.crimson.parser.ContentModel.<init> (char, org.apache.crimson.parser.ContentModel)) | ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 110) | NEW org.apache.crimson.parser.SimpleHashtable | DUP | constructor-call(void org.apache.crimson.parser.SimpleHashtable.<init>()) | | INVOKESPECIAL org.apache.crimson.parser.SimpleHashtable.<init> ()V | constructor-call(void org.apache.crimson.parser.SimpleHashtable.<init>()) | PUTFIELD org.apache.crimson.parser.ContentModel.cache Lorg/apache/crimson/parser/SimpleHashtable; | ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 126) | ILOAD_1 // char type | PUTFIELD org.apache.crimson.parser.ContentModel.type C | ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 127) | ALOAD_2 // org.apache.crimson.parser.ContentModel content | PUTFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; | RETURN (line 128) constructor-execution(void org.apache.crimson.parser.ContentModel.<init> (char, org.apache.crimson.parser.ContentModel)) end public void <init>(char, org.apache.crimson.parser.ContentModel) public boolean empty(): method-execution(boolean org.apache.crimson.parser.ContentModel.empty()) | ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 137) | GETFIELD org.apache.crimson.parser.ContentModel.type C | LOOKUPSWITCH | 0: L1 | 42: L0 | 43: L1 | 44: L7 | 63: L0 | 124: L2 | default: L13 | L0: ICONST_1 (line 140) | IRETURN | L1: ICONST_0 (line 144) | IRETURN | L2: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 147) | GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; | INSTANCEOF org.apache.crimson.parser.ContentModel | IFEQ L3 | ALOAD_0 // org.apache.crimson.parser.ContentModel this | GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; | CHECKCAST org.apache.crimson.parser.ContentModel | method-call(boolean org.apache.crimson.parser.ContentModel.empty()) | | INVOKEVIRTUAL org.apache.crimson.parser.ContentModel.empty ()Z | method-call(boolean org.apache.crimson.parser.ContentModel.empty()) | IFEQ L3 | ICONST_1 (line 149) | IRETURN | L3: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 151) | GETFIELD org.apache.crimson.parser.ContentModel.next Lorg/apache/crimson/parser/ContentModel; | ASTORE_1 | GOTO L6 | L4: ALOAD_1 // org.apache.crimson.parser.ContentModel m (line 154) | INVOKEVIRTUAL org.apache.crimson.parser.ContentModel.empty ()Z | IFEQ L5 | ICONST_1 (line 155) | IRETURN | L5: ALOAD_1 // org.apache.crimson.parser.ContentModel m (line 153) | GETFIELD org.apache.crimson.parser.ContentModel.next Lorg/apache/crimson/parser/ContentModel; | ASTORE_1 // org.apache.crimson.parser.ContentModel m | L6: ALOAD_1 // org.apache.crimson.parser.ContentModel m (line 152) | IFNONNULL L4 | ICONST_0 (line 157) | IRETURN | L7: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 160) | GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; | INSTANCEOF org.apache.crimson.parser.ContentModel | IFEQ L8 | ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 161) | GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; | CHECKCAST org.apache.crimson.parser.ContentModel | INVOKEVIRTUAL org.apache.crimson.parser.ContentModel.empty ()Z | IFNE L9 | ICONST_0 (line 162) | IRETURN | L8: ICONST_0 (line 165) | IRETURN | L9: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 167) | GETFIELD org.apache.crimson.parser.ContentModel.next Lorg/apache/crimson/parser/ContentModel; | ASTORE_2 | GOTO L12 | L10: ALOAD_2 // org.apache.crimson.parser.ContentModel m (line 170) | INVOKEVIRTUAL org.apache.crimson.parser.ContentModel.empty ()Z | IFNE L11 | ICONST_0 (line 171) | IRETURN | L11: ALOAD_2 // org.apache.crimson.parser.ContentModel m (line 169) | GETFIELD org.apache.crimson.parser.ContentModel.next Lorg/apache/crimson/parser/ContentModel; | ASTORE_2 // org.apache.crimson.parser.ContentModel m | L12: ALOAD_2 // org.apache.crimson.parser.ContentModel m (line 168) | IFNONNULL L10 | ICONST_1 (line 173) | IRETURN | L13: NEW java.lang.InternalError (line 176) | DUP | INVOKESPECIAL java.lang.InternalError.<init> ()V | ATHROW method-execution(boolean org.apache.crimson.parser.ContentModel.empty()) end public boolean empty() public boolean first(String): ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 186) GETFIELD org.apache.crimson.parser.ContentModel.cache Lorg/apache/crimson/parser/SimpleHashtable; ALOAD_1 // java.lang.String token INVOKEVIRTUAL org.apache.crimson.parser.SimpleHashtable.get (Ljava/lang/String;)Ljava/lang/Object; CHECKCAST java.lang.Boolean ASTORE_2 ALOAD_2 // java.lang.Boolean b (line 189) IFNULL L0 ALOAD_2 // java.lang.Boolean b (line 190) INVOKEVIRTUAL java.lang.Boolean.booleanValue ()Z IRETURN L0: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 193) GETFIELD org.apache.crimson.parser.ContentModel.type C LOOKUPSWITCH 0: L1 42: L1 43: L1 44: L5 63: L1 124: L12 default: L16 L1: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 198) GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; INSTANCEOF java.lang.String IFEQ L4 ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 199) GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; ALOAD_1 // java.lang.String token IF_ACMPNE L2 ICONST_1 GOTO L3 L2: ICONST_0 L3: ISTORE_3 GOTO L17 L4: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 201) GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; CHECKCAST org.apache.crimson.parser.ContentModel ALOAD_1 // java.lang.String token INVOKEVIRTUAL org.apache.crimson.parser.ContentModel.first (Ljava/lang/String;)Z ISTORE_3 // boolean retval GOTO L17 (line 202) L5: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 205) GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; INSTANCEOF java.lang.String IFEQ L8 ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 206) GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; ALOAD_1 // java.lang.String token IF_ACMPNE L6 ICONST_1 GOTO L7 L6: ICONST_0 L7: ISTORE_3 // boolean retval GOTO L17 L8: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 207) GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; CHECKCAST org.apache.crimson.parser.ContentModel ALOAD_1 // java.lang.String token INVOKEVIRTUAL org.apache.crimson.parser.ContentModel.first (Ljava/lang/String;)Z IFEQ L9 ICONST_1 (line 208) ISTORE_3 // boolean retval GOTO L17 L9: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 209) GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; CHECKCAST org.apache.crimson.parser.ContentModel INVOKEVIRTUAL org.apache.crimson.parser.ContentModel.empty ()Z IFNE L10 ICONST_0 (line 210) ISTORE_3 // boolean retval GOTO L17 L10: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 211) GETFIELD org.apache.crimson.parser.ContentModel.next Lorg/apache/crimson/parser/ContentModel; IFNULL L11 ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 212) GETFIELD org.apache.crimson.parser.ContentModel.next Lorg/apache/crimson/parser/ContentModel; ALOAD_1 // java.lang.String token INVOKEVIRTUAL org.apache.crimson.parser.ContentModel.first (Ljava/lang/String;)Z ISTORE_3 // boolean retval GOTO L17 L11: ICONST_0 (line 214) ISTORE_3 // boolean retval GOTO L17 (line 215) L12: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 218) GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; INSTANCEOF java.lang.String IFEQ L13 ALOAD_0 // org.apache.crimson.parser.ContentModel this GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; ALOAD_1 // java.lang.String token IF_ACMPNE L13 ICONST_1 (line 219) ISTORE_3 // boolean retval GOTO L17 L13: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 220) GETFIELD org.apache.crimson.parser.ContentModel.content Ljava/lang/Object; CHECKCAST org.apache.crimson.parser.ContentModel ALOAD_1 // java.lang.String token INVOKEVIRTUAL org.apache.crimson.parser.ContentModel.first (Ljava/lang/String;)Z IFEQ L14 ICONST_1 (line 221) ISTORE_3 // boolean retval GOTO L17 L14: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 222) GETFIELD org.apache.crimson.parser.ContentModel.next Lorg/apache/crimson/parser/ContentModel; IFNULL L15 ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 223) GETFIELD org.apache.crimson.parser.ContentModel.next Lorg/apache/crimson/parser/ContentModel; ALOAD_1 // java.lang.String token INVOKEVIRTUAL org.apache.crimson.parser.ContentModel.first (Ljava/lang/String;)Z ISTORE_3 // boolean retval GOTO L17 L15: ICONST_0 (line 225) ISTORE_3 // boolean retval GOTO L17 (line 226) L16: NEW java.lang.InternalError (line 229) DUP INVOKESPECIAL java.lang.InternalError.<init> ()V ATHROW L17: ILOAD_3 // boolean retval (line 233) IFEQ L18 ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 234) GETFIELD org.apache.crimson.parser.ContentModel.cache Lorg/apache/crimson/parser/SimpleHashtable; ALOAD_1 // java.lang.String token GETSTATIC java.lang.Boolean.TRUE Ljava/lang/Boolean; INVOKEVIRTUAL org.apache.crimson.parser.SimpleHashtable.put (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Obj ect; POP GOTO L19 L18: ALOAD_0 // org.apache.crimson.parser.ContentModel this (line 236) GETFIELD org.apache.crimson.parser.ContentModel.cache Lorg/apache/crimson/parser/SimpleHashtable; ALOAD_1 // java.lang.String token GETSTATIC java.lang.Boolean.FALSE Ljava/lang/Boolean; INVOKEVIRTUAL org.apache.crimson.parser.SimpleHashtable.put (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Obj ect; POP L19: ILOAD_3 // boolean retval (line 238) IRETURN end public boolean first(String) end final class org.apache.crimson.parser.ContentModel
|
verified fixed
|
fabf159
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-15T17:04:00Z
| 2005-11-14T17:40:00Z
|
loadtime/src/org/aspectj/weaver/loadtime/definition/DocumentParser.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.definition;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.SAXParserFactory;
import org.aspectj.util.LangUtil;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/**
* FIXME AV - doc, concrete aspect
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class DocumentParser extends DefaultHandler {
/**
* The current DTD public id. The matching dtd will be searched as a resource.
*/
private final static String DTD_PUBLIC_ID = "-//AspectJ//DTD 1.5.0//EN";
/**
* The DTD alias, for better user experience.
*/
private final static String DTD_PUBLIC_ID_ALIAS = "-//AspectJ//DTD//EN";
/**
* A handler to the DTD stream so that we are only using one file descriptor
*/
private final static InputStream DTD_STREAM = DocumentParser.class.getResourceAsStream("/aspectj_1_5_0.dtd");
private final static String ASPECTJ_ELEMENT = "aspectj";
private final static String WEAVER_ELEMENT = "weaver";
private final static String DUMP_ELEMENT = "dump";
private final static String INCLUDE_ELEMENT = "include";
private final static String EXCLUDE_ELEMENT = "exclude";
private final static String OPTIONS_ATTRIBUTE = "options";
private final static String ASPECTS_ELEMENT = "aspects";
private final static String ASPECT_ELEMENT = "aspect";
private final static String CONCRETE_ASPECT_ELEMENT = "concrete-aspect";
private final static String NAME_ATTRIBUTE = "name";
private final static String EXTEND_ATTRIBUTE = "extends";
private final static String PRECEDENCE_ATTRIBUTE = "precedence";
private final static String POINTCUT_ELEMENT = "pointcut";
private final static String WITHIN_ATTRIBUTE = "within";
private final static String EXPRESSION_ATTRIBUTE = "expression";
private final Definition m_definition;
private boolean m_inAspectJ;
private boolean m_inWeaver;
private boolean m_inAspects;
private Definition.ConcreteAspect m_lastConcreteAspect;
private DocumentParser() {
m_definition = new Definition();
}
public static Definition parse(final URL url) throws Exception {
InputStream in = null;
try {
DocumentParser parser = new DocumentParser();
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
xmlReader.setContentHandler(parser);
xmlReader.setErrorHandler(parser);
try {
xmlReader.setFeature("http://xml.org/sax/features/validation", false);
} catch (SAXException e) {
;//fine, the parser don't do validation
}
try {
xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
} catch (SAXException e) {
;//fine, the parser don't do validation
}
try {
xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch (SAXException e) {
;//fine, the parser don't do validation
}
xmlReader.setEntityResolver(parser);
in = url.openStream();
xmlReader.parse(new InputSource(in));
return parser.m_definition;
} finally {
try {
in.close();
} catch (Throwable t) {
;
}
}
}
public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
if (publicId.equals(DTD_PUBLIC_ID) || publicId.equals(DTD_PUBLIC_ID_ALIAS)) {
InputStream in = DTD_STREAM;
if (in == null) {
System.err.println(
"AspectJ - WARN - could not read DTD "
+ publicId
);
return null;
} else {
return new InputSource(in);
}
} else {
System.err.println(
"AspectJ - WARN - unknown DTD "
+ publicId
+ " - consider using "
+ DTD_PUBLIC_ID
);
return null;
}
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (ASPECT_ELEMENT.equals(qName)) {
String name = attributes.getValue(NAME_ATTRIBUTE);
if (!isNull(name)) {
m_definition.getAspectClassNames().add(name);
}
} else if (WEAVER_ELEMENT.equals(qName)) {
String options = attributes.getValue(OPTIONS_ATTRIBUTE);
if (!isNull(options)) {
m_definition.appendWeaverOptions(options);
}
m_inWeaver = true;
} else if (CONCRETE_ASPECT_ELEMENT.equals(qName)) {
String name = attributes.getValue(NAME_ATTRIBUTE);
String extend = attributes.getValue(EXTEND_ATTRIBUTE);
String precedence = attributes.getValue(PRECEDENCE_ATTRIBUTE);
if (!isNull(name)) {
if (isNull(precedence) && !isNull(extend)) {//if no precedence, then extends must be there
m_lastConcreteAspect = new Definition.ConcreteAspect(name, extend);
} else if (!isNull(precedence)) {
// wether a pure precedence def, or an extendsANDprecedence def.
m_lastConcreteAspect = new Definition.ConcreteAspect(name, extend, precedence);
}
m_definition.getConcreteAspects().add(m_lastConcreteAspect);
}
} else if (POINTCUT_ELEMENT.equals(qName) && m_lastConcreteAspect != null) {
String name = attributes.getValue(NAME_ATTRIBUTE);
String expression = attributes.getValue(EXPRESSION_ATTRIBUTE);
if (!isNull(name) && !isNull(expression)) {
m_lastConcreteAspect.pointcuts.add(new Definition.Pointcut(name, replaceXmlAnd(expression)));
}
} else if (ASPECTJ_ELEMENT.equals(qName)) {
if (m_inAspectJ) {
throw new SAXException("Found nested <aspectj> element");
}
m_inAspectJ = true;
} else if (ASPECTS_ELEMENT.equals(qName)) {
m_inAspects = true;
} else if (INCLUDE_ELEMENT.equals(qName) && m_inWeaver) {
String typePattern = attributes.getValue(WITHIN_ATTRIBUTE);
if (!isNull(typePattern)) {
m_definition.getIncludePatterns().add(typePattern);
}
} else if (EXCLUDE_ELEMENT.equals(qName) && m_inWeaver) {
String typePattern = attributes.getValue(WITHIN_ATTRIBUTE);
if (!isNull(typePattern)) {
m_definition.getExcludePatterns().add(typePattern);
}
} else if (DUMP_ELEMENT.equals(qName) && m_inWeaver) {
String typePattern = attributes.getValue(WITHIN_ATTRIBUTE);
if (!isNull(typePattern)) {
m_definition.getDumpPatterns().add(typePattern);
}
} else if (EXCLUDE_ELEMENT.equals(qName) && m_inAspects) {
String typePattern = attributes.getValue(WITHIN_ATTRIBUTE);
if (!isNull(typePattern)) {
m_definition.getAspectExcludePatterns().add(typePattern);
}
} else if (INCLUDE_ELEMENT.equals(qName) && m_inAspects) {
String typePattern = attributes.getValue(WITHIN_ATTRIBUTE);
if (!isNull(typePattern)) {
m_definition.getAspectIncludePatterns().add(typePattern);
}
} else {
throw new SAXException("Unknown element while parsing <aspectj> element: " + qName);
}
super.startElement(uri, localName, qName, attributes);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (CONCRETE_ASPECT_ELEMENT.equals(qName)) {
m_lastConcreteAspect = null;
} else if (ASPECTJ_ELEMENT.equals(qName)) {
m_inAspectJ = false;
} else if (WEAVER_ELEMENT.equals(qName)) {
m_inWeaver = false;
} else if (ASPECTS_ELEMENT.equals(qName)) {
m_inAspects = false;
}
super.endElement(uri, localName, qName);
}
//TODO AV - define what we want for XML parser error - for now stderr
public void warning(SAXParseException e) throws SAXException {
super.warning(e);
}
public void error(SAXParseException e) throws SAXException {
super.error(e);
}
public void fatalError(SAXParseException e) throws SAXException {
super.fatalError(e);
}
private static String replaceXmlAnd(String expression) {
//TODO AV do we need to handle "..)AND" or "AND(.." ?
return LangUtil.replace(expression, " AND ", " && ");
}
private boolean isNull(String s) {
return (s == null || s.length() <= 0);
}
}
|
116,626
|
Bug 116626 Load-time weaving - exception from the weaver
|
Hi again :-) I'm trying to use loadtime weaving and getting an exception. Please look at the testcase: Java code: ========== public class Test<T> { Set<T> intsSet; public Test() { this.intsSet = new HashSet<T>(); } public <T> T[] getObjs(T[] a) { return intsSet.toArray(a); } public static void main(String[] args) { System.out.println("AAA :-)"); new TTT().foo(); } } class TTT { public void foo() { Test<Object> mt = new Test<Object>(); Object[] arr = mt.getObjs(new Object[]{}); } } Aspect: ======= public privileged aspect TestAspect { pointcut TestToArray(Test mt) : target(mt) && !within(TestAspect); Object[] around(Test mt, Object[] objs) : TestToArray(mt) && args(objs) && execution(Object[] com.mprv.secsph.Test.getObjs(Object[])) { objs = proceed(mt, objs); System.out.println("GO Aspects!"); return objs; } } aop.xml ======= <aspectj> <aspects> <aspect name="com.mprv.secsph.TestAspect"/> </aspects> <weaver options="-verbose -XlazyTjp -showWeaveInfo"> <include within="com.mprv.*"/> </weaver> </aspectj> Program output: ============== AAA :-) info weaving 'com/mprv/secsph/TestAspect' java.lang.NullPointerException at org.aspectj.weaver.tools.WeavingAdaptor$WeavingClassFileProvider.getBytes (WeavingAdaptor.java:390) at org.aspectj.weaver.tools.WeavingAdaptor.getAtAspectJAspectBytes (WeavingAdaptor.java:259) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass (WeavingAdaptor.java:181) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:66) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform (ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform (TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform (InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass (SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at com.mprv.secsph.Test.getObjs(Test.java:1) at com.mprv.secsph.TTT.foo(Test.java:34) at com.mprv.secsph.Test.main(Test.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 java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:86) GO Aspects! ==== This exception doesn't happen all the time ... but if you will try a few times, you will probably get it. May you can understand what is the problem event without running the test case. Anyway, I took a look at your code, and have a guess (but it's only the guess) - My aspect is in the application classpath. Actually it's in the same package, so may be you are trying to weave the aspect with itself somehow ... Thanks! Misha.
|
resolved fixed
|
c760895
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-18T09:01:17Z
| 2005-11-16T08:33:20Z
|
tests/bugs150/pr116626/com/foo/bar/Test.java
| |
116,626
|
Bug 116626 Load-time weaving - exception from the weaver
|
Hi again :-) I'm trying to use loadtime weaving and getting an exception. Please look at the testcase: Java code: ========== public class Test<T> { Set<T> intsSet; public Test() { this.intsSet = new HashSet<T>(); } public <T> T[] getObjs(T[] a) { return intsSet.toArray(a); } public static void main(String[] args) { System.out.println("AAA :-)"); new TTT().foo(); } } class TTT { public void foo() { Test<Object> mt = new Test<Object>(); Object[] arr = mt.getObjs(new Object[]{}); } } Aspect: ======= public privileged aspect TestAspect { pointcut TestToArray(Test mt) : target(mt) && !within(TestAspect); Object[] around(Test mt, Object[] objs) : TestToArray(mt) && args(objs) && execution(Object[] com.mprv.secsph.Test.getObjs(Object[])) { objs = proceed(mt, objs); System.out.println("GO Aspects!"); return objs; } } aop.xml ======= <aspectj> <aspects> <aspect name="com.mprv.secsph.TestAspect"/> </aspects> <weaver options="-verbose -XlazyTjp -showWeaveInfo"> <include within="com.mprv.*"/> </weaver> </aspectj> Program output: ============== AAA :-) info weaving 'com/mprv/secsph/TestAspect' java.lang.NullPointerException at org.aspectj.weaver.tools.WeavingAdaptor$WeavingClassFileProvider.getBytes (WeavingAdaptor.java:390) at org.aspectj.weaver.tools.WeavingAdaptor.getAtAspectJAspectBytes (WeavingAdaptor.java:259) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass (WeavingAdaptor.java:181) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:66) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform (ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform (TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform (InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass (SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at com.mprv.secsph.Test.getObjs(Test.java:1) at com.mprv.secsph.TTT.foo(Test.java:34) at com.mprv.secsph.Test.main(Test.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 java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:86) GO Aspects! ==== This exception doesn't happen all the time ... but if you will try a few times, you will probably get it. May you can understand what is the problem event without running the test case. Anyway, I took a look at your code, and have a guess (but it's only the guess) - My aspect is in the application classpath. Actually it's in the same package, so may be you are trying to weave the aspect with itself somehow ... Thanks! Misha.
|
resolved fixed
|
c760895
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-18T09:01:17Z
| 2005-11-16T08:33:20Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
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 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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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");
}
// 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);
}
}
|
116,626
|
Bug 116626 Load-time weaving - exception from the weaver
|
Hi again :-) I'm trying to use loadtime weaving and getting an exception. Please look at the testcase: Java code: ========== public class Test<T> { Set<T> intsSet; public Test() { this.intsSet = new HashSet<T>(); } public <T> T[] getObjs(T[] a) { return intsSet.toArray(a); } public static void main(String[] args) { System.out.println("AAA :-)"); new TTT().foo(); } } class TTT { public void foo() { Test<Object> mt = new Test<Object>(); Object[] arr = mt.getObjs(new Object[]{}); } } Aspect: ======= public privileged aspect TestAspect { pointcut TestToArray(Test mt) : target(mt) && !within(TestAspect); Object[] around(Test mt, Object[] objs) : TestToArray(mt) && args(objs) && execution(Object[] com.mprv.secsph.Test.getObjs(Object[])) { objs = proceed(mt, objs); System.out.println("GO Aspects!"); return objs; } } aop.xml ======= <aspectj> <aspects> <aspect name="com.mprv.secsph.TestAspect"/> </aspects> <weaver options="-verbose -XlazyTjp -showWeaveInfo"> <include within="com.mprv.*"/> </weaver> </aspectj> Program output: ============== AAA :-) info weaving 'com/mprv/secsph/TestAspect' java.lang.NullPointerException at org.aspectj.weaver.tools.WeavingAdaptor$WeavingClassFileProvider.getBytes (WeavingAdaptor.java:390) at org.aspectj.weaver.tools.WeavingAdaptor.getAtAspectJAspectBytes (WeavingAdaptor.java:259) at org.aspectj.weaver.tools.WeavingAdaptor.weaveClass (WeavingAdaptor.java:181) at org.aspectj.weaver.loadtime.Aj.preProcess(Aj.java:66) at org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter.transform (ClassPreProcessorAgentAdapter.java:52) at sun.instrument.TransformerManager.transform (TransformerManager.java:122) at sun.instrument.InstrumentationImpl.transform (InstrumentationImpl.java:155) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:620) at java.security.SecureClassLoader.defineClass (SecureClassLoader.java:124) at java.net.URLClassLoader.defineClass(URLClassLoader.java:260) at java.net.URLClassLoader.access$100(URLClassLoader.java:56) at java.net.URLClassLoader$1.run(URLClassLoader.java:195) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at com.mprv.secsph.Test.getObjs(Test.java:1) at com.mprv.secsph.TTT.foo(Test.java:34) at com.mprv.secsph.Test.main(Test.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 java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:86) GO Aspects! ==== This exception doesn't happen all the time ... but if you will try a few times, you will probably get it. May you can understand what is the problem event without running the test case. Anyway, I took a look at your code, and have a guess (but it's only the guess) - My aspect is in the application classpath. Actually it's in the same package, so may be you are trying to weave the aspect with itself somehow ... Thanks! Misha.
|
resolved fixed
|
c760895
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-18T09:01:17Z
| 2005-11-16T08:33:20Z
|
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.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
*
* Contributors:
* Matthew Webster, Adrian Colyer,
* Martin Lippert initial implementation
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.MessageWriter;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
/**
* This adaptor allows the AspectJ compiler to be embedded in an existing
* system to facilitate load-time weaving. It provides an interface for a
* weaving class loader to provide a classpath to be woven by a set of
* aspects. A callback is supplied to allow a class loader to define classes
* generated by the compiler during the weaving process.
* <p>
* A weaving class loader should create a <code>WeavingAdaptor</code> before
* any classes are defined, typically during construction. The set of aspects
* passed to the adaptor is fixed for the lifetime of the adaptor although the
* classpath can be augmented. A system property can be set to allow verbose
* weaving messages to be written to the console.
*
*/
public class WeavingAdaptor {
/**
* System property used to turn on verbose weaving messages
*/
public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose";
public static final String SHOW_WEAVE_INFO_PROPERTY = "org.aspectj.weaver.showWeaveInfo";
protected boolean enabled = true;
protected boolean verbose = getVerbose();
protected BcelWorld bcelWorld = null;
protected BcelWeaver weaver = null;
protected IMessageHandler/*WeavingAdaptorMessageHandler*/ messageHandler = null;
protected GeneratedClassHandler generatedClassHandler;
protected Map generatedClasses = new HashMap(); /* String -> UnwovenClassFile */
protected WeavingAdaptor () {
createMessageHandler();
}
/**
* Construct a WeavingAdaptor with a reference to a weaving class loader. The
* adaptor will automatically search the class loader hierarchy to resolve
* classes. The adaptor will also search the hierarchy for WeavingClassLoader
* instances to determine the set of aspects to be used ofr weaving.
* @param loader instance of <code>ClassLoader</code>
*/
public WeavingAdaptor (WeavingClassLoader loader) {
// System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")");
generatedClassHandler = loader;
init(getFullClassPath((ClassLoader)loader),getFullAspectPath((ClassLoader)loader/*,aspectURLs*/));
}
/**
* Construct a WeavingAdator with a reference to a
* <code>GeneratedClassHandler</code>, a full search path for resolving
* classes and a complete set of aspects. The search path must include
* classes loaded by the class loader constructing the WeavingAdaptor and
* all its parents in the hierarchy.
* @param handler <code>GeneratedClassHandler</code>
* @param classURLs the URLs from which to resolve classes
* @param aspectURLs the aspects used to weave classes defined by this class loader
*/
public WeavingAdaptor (GeneratedClassHandler handler, URL[] classURLs, URL[] aspectURLs) {
// System.err.println("? WeavingAdaptor.<init>()");
generatedClassHandler = handler;
init(FileUtil.makeClasspath(classURLs),FileUtil.makeClasspath(aspectURLs));
}
private List getFullClassPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader)loader).getURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
else {
warn("cannot determine classpath");
}
}
list.addAll(0,makeClasspath(System.getProperty("sun.boot.class.path")));
return list;
}
private List getFullAspectPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof WeavingClassLoader) {
URL[] urls = ((WeavingClassLoader)loader).getAspectURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
}
return list;
}
private static boolean getVerbose () {
return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE);
}
private void init(List classPath, List aspectPath) {
createMessageHandler();
info("using classpath: " + classPath);
info("using aspectpath: " + aspectPath);
bcelWorld = new BcelWorld(classPath,messageHandler,null);
bcelWorld.setXnoInline(false);
bcelWorld.getLint().loadDefaultProperties();
if (LangUtil.is15VMOrGreater()) {
bcelWorld.setBehaveInJava5Way(true);
}
weaver = new BcelWeaver(bcelWorld);
registerAspectLibraries(aspectPath);
}
private void createMessageHandler() {
messageHandler = new WeavingAdaptorMessageHandler(new PrintWriter(System.err));
if (verbose) messageHandler.dontIgnore(IMessage.INFO);
if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) messageHandler.dontIgnore(IMessage.WEAVEINFO);
}
/**
* Appends URL to path used by the WeavingAdptor to resolve classes
* @param url to be appended to search path
*/
public void addURL(URL url) {
File libFile = new File(url.getPath());
try {
weaver.addLibraryJarFile(libFile);
}
catch (IOException ex) {
warn("bad library: '" + libFile + "'");
}
}
/**
* Weave a class using aspects previously supplied to the adaptor.
* @param name the name of the class
* @param bytes the class bytes
* @return the woven bytes
* @exception IOException weave failed
*/
public byte[] weaveClass (String name, byte[] bytes) throws IOException {
if (shouldWeave(name, bytes)) {
//System.out.println("WeavingAdaptor.weaveClass " + name);
info("weaving '" + name + "'");
bytes = getWovenBytes(name, bytes);
} else if (shouldWeaveAnnotationStyleAspect(name, bytes)) {
// an @AspectJ aspect needs to be at least munged by the aspectOf munger
info("weaving '" + name + "'");
bytes = getAtAspectJAspectBytes(name, bytes);
}
return bytes;
}
/**
* @param name
* @return true if should weave (but maybe we still need to munge it for @AspectJ aspectof support)
*/
private boolean shouldWeave (String name, byte[] bytes) {
name = name.replace('/','.');
boolean b = enabled && !generatedClasses.containsKey(name) && shouldWeaveName(name);
return b && accept(name, bytes);
// && shouldWeaveAnnotationStyleAspect(name);
// // we recall shouldWeaveAnnotationStyleAspect as we need to add aspectOf methods for @Aspect anyway
// //FIXME AV - this is half ok as the aspect will be weaved by others. In theory if the aspect
// // is excluded from include/exclude config we should only weave late type mungers for aspectof
// return b && (accept(name) || shouldWeaveAnnotationStyleAspect(name));
}
//ATAJ
protected boolean accept(String name, byte[] bytes) {
return true;
}
public boolean shouldDump(String name) {
return false;
}
private boolean shouldWeaveName (String name) {
return !((/*(name.startsWith("org.apache.bcel.")//FIXME AV why ? bcel is wrapped in org.aspectj.
||*/ name.startsWith("org.aspectj.")
|| name.startsWith("java.")
|| name.startsWith("javax."))
//|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy...
|| name.startsWith("sun.reflect."));//JDK reflect
}
/**
* We allow @AJ aspect weaving so that we can add aspectOf() as part of the weaving
* (and not part of the source compilation)
*
* @param name
* @param bytes bytecode (from classloader), allow to NOT lookup stuff on disk again during resolve
* @return true if @Aspect
*/
private boolean shouldWeaveAnnotationStyleAspect(String name, byte[] bytes) {
// AV: instead of doing resolve that would lookup stuff on disk thru BCEL ClassLoaderRepository
// we reuse bytes[] here to do a fast lookup for @Aspect annotation
return bcelWorld.isAnnotationStyleAspect(name, bytes);
}
/**
* Weave a set of bytes defining a class.
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getWovenBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
weaver.weave(wcp);
return wcp.getBytes();
}
/**
* Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect
* in a usefull form ie with aspectOf method - see #113587
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
wcp.setApplyAtAspectJMungersOnly();
weaver.weave(wcp);
return wcp.getBytes();
}
private void registerAspectLibraries(List aspectPath) {
// System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")");
for (Iterator i = aspectPath.iterator(); i.hasNext();) {
String libName = (String)i.next();
addAspectLibrary(libName);
}
weaver.prepareForWeave();
}
/*
* Register an aspect library with this classloader for use during
* weaving. This class loader will also return (unmodified) any of the
* classes in the library in response to a <code>findClass()</code> request.
* The library is not required to be on the weavingClasspath given when this
* classloader was constructed.
* @param aspectLibraryJarFile a jar file representing an aspect library
* @throws IOException
*/
private void addAspectLibrary(String aspectLibraryName) {
File aspectLibrary = new File(aspectLibraryName);
if (aspectLibrary.isDirectory()
|| (aspectLibrary.isFile()
&& FileUtil.hasZipSuffix(aspectLibraryName))) {
try {
info("adding aspect library: '" + aspectLibrary + "'");
weaver.addLibraryJarFile(aspectLibrary);
} catch (IOException ex) {
error("exception adding aspect library: '" + ex + "'");
}
} else {
error("bad aspect library: '" + aspectLibrary + "'");
}
}
private static List makeClasspath(String cp) {
List ret = new ArrayList();
if (cp != null) {
StringTokenizer tok = new StringTokenizer(cp,File.pathSeparator);
while (tok.hasMoreTokens()) {
ret.add(tok.nextToken());
}
}
return ret;
}
protected boolean info (String message) {
return MessageUtil.info(messageHandler,message);
}
protected boolean warn (String message) {
return MessageUtil.warn(messageHandler,message);
}
protected boolean warn (String message, Throwable th) {
return messageHandler.handleMessage(new Message("Register definition failed", IMessage.WARNING, th, null));
}
protected boolean error (String message) {
return MessageUtil.error(messageHandler,message);
}
/**
* Processes messages arising from weaver operations.
* Tell weaver to abort on any message more severe than warning.
*/
protected class WeavingAdaptorMessageHandler extends MessageWriter {
private Set ignoring = new HashSet();
private IMessage.Kind failKind;
public WeavingAdaptorMessageHandler (PrintWriter writer) {
super(writer,true);
ignore(IMessage.WEAVEINFO);
ignore(IMessage.INFO);
this.failKind = IMessage.ERROR;
}
public boolean handleMessage(IMessage message) throws AbortException {
boolean result = super.handleMessage(message);
if (0 <= message.getKind().compareTo(failKind)) {
throw new AbortException(message);
}
return true;
}
public boolean isIgnoring (Kind kind) {
return ((null != kind) && (ignoring.contains(kind)));
}
/**
* Set a message kind to be ignored from now on
*/
public void ignore (IMessage.Kind kind) {
if ((null != kind) && (!ignoring.contains(kind))) {
ignoring.add(kind);
}
}
/**
* Remove a message kind from the list of those ignored from now on.
*/
public void dontIgnore (IMessage.Kind kind) {
if (null != kind) {
ignoring.remove(kind);
}
}
}
private class WeavingClassFileProvider implements IClassFileProvider {
private List unwovenClasses = new ArrayList(); /* List<UnovenClassFile> */
private UnwovenClassFile wovenClass;
private boolean isApplyAtAspectJMungersOnly = false;
public WeavingClassFileProvider (String name, byte[] bytes) {
UnwovenClassFile unwoven = new UnwovenClassFile(name,bytes);
unwovenClasses.add(unwoven);
bcelWorld.addSourceObjectType(unwoven.getJavaClass());
}
public void setApplyAtAspectJMungersOnly() {
isApplyAtAspectJMungersOnly = true;
}
public boolean isApplyAtAspectJMungersOnly() {
return isApplyAtAspectJMungersOnly;
}
public byte[] getBytes () {
return wovenClass.getBytes();
}
public Iterator getClassFileIterator() {
return unwovenClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(UnwovenClassFile result) {
if (wovenClass == null) {
wovenClass = result;
}
/* Classes generated by weaver e.g. around closure advice */
else {
String className = result.getClassName();
generatedClasses.put(className,result);
generatedClassHandler.acceptClass(className,result.getBytes());
}
}
public void processingReweavableState() { }
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {}
};
}
}
}
|
116,949
|
Bug 116949 [waitingOnAJDTdrop]Exception thrown from AspectJ compiler
|
java.lang.ClassCastException at org.aspectj.weaver.bcel.BcelClassWeaver.checkForOverride (BcelClassWeaver.java:607) at org.aspectj.weaver.bcel.BcelClassWeaver.calculateAnyRequiredBridgeMethods (BcelClassWeaver.java:676) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1537) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1485) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1266) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1088) 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_aspect j_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:809) 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 ts.simul.client.AbstractClient$OptionSetter extends ts.util.CmdLineProgram$OptionSetterBase: final ts.simul.client.AbstractClient this$0 private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_0 public void <init>(ts.simul.client.AbstractClient) org.aspectj.weaver.MethodDeclarationLineNumber: 59:1411 : ALOAD_0 // ts.simul.client.AbstractClient$OptionSetter this (line 60) ALOAD_1 PUTFIELD ts.simul.client.AbstractClient$OptionSetter.this$0 Lts/simul/client/AbstractClient; ALOAD_0 // ts.simul.client.AbstractClient$OptionSetter this (line 59) ALOAD_1 INVOKESPECIAL ts.util.CmdLineProgram$OptionSetterBase.<init> (Lts/util/CmdLineProgram;)V constructor-execution(void ts.simul.client.AbstractClient$OptionSetter.<init> (ts.simul.client.AbstractClient)) | RETURN constructor-execution(void ts.simul.client.AbstractClient$OptionSetter.<init> (ts.simul.client.AbstractClient)) end public void <init>(ts.simul.client.AbstractClient) public boolean setOption_file(String) throws ts.util.IllegalProgramArgumentException org.aspectj.weaver.MethodDeclarationLineNumber: 62:1469 : method-execution(boolean ts.simul.client.AbstractClient$OptionSetter.setOption_file(java.lang.String)) | ALOAD_1 // java.lang.String optParam (line 65) | method-call(int java.lang.String.length()) | | INVOKEVIRTUAL java.lang.String.length ()I | method-call(int java.lang.String.length()) | IFLE L1 | ALOAD_0 // ts.simul.client.AbstractClient$OptionSetter this (line 66) | GETFIELD ts.simul.client.AbstractClient$OptionSetter.this$0 Lts/simul/client/AbstractClient; | ALOAD_1 // java.lang.String optParam | PUTFIELD ts.simul.client.AbstractClient.fileName Ljava/lang/String; | NEW java.io.File (line 67) | DUP | ALOAD_0 // ts.simul.client.AbstractClient$OptionSetter this | GETFIELD ts.simul.client.AbstractClient$OptionSetter.this$0 Lts/simul/client/AbstractClient; | GETFIELD ts.simul.client.AbstractClient.fileName Ljava/lang/String; | constructor-call(void java.io.File.<init>(java.lang.String)) | | INVOKESPECIAL java.io.File.<init> (Ljava/lang/String;)V | constructor-call(void java.io.File.<init>(java.lang.String)) | ASTORE_2 | ALOAD_2 // java.io.File file (line 68) | method-call(boolean java.io.File.exists()) | | INVOKEVIRTUAL java.io.File.exists ()Z | method-call(boolean java.io.File.exists()) | IFNE L0 | NEW ts.util.IllegalProgramArgumentException (line 69) | DUP | NEW java.lang.StringBuilder | DUP | LDC "Cannot find file: [" | constructor-call(void java.lang.StringBuilder.<init>(java.lang.String)) | | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | constructor-call(void java.lang.StringBuilder.<init>(java.lang.String)) | ALOAD_0 // ts.simul.client.AbstractClient$OptionSetter this | GETFIELD ts.simul.client.AbstractClient$OptionSetter.this$0 Lts/simul/client/AbstractClient; | GETFIELD ts.simul.client.AbstractClient.fileName Ljava/lang/String; | 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)) | LDC "]" | 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()) | constructor-call(void ts.util.IllegalProgramArgumentException.<init> (java.lang.String)) | | INVOKESPECIAL ts.util.IllegalProgramArgumentException.<init> (Ljava/lang/String;)V | constructor-call(void ts.util.IllegalProgramArgumentException.<init> (java.lang.String)) | ATHROW | L0: ICONST_1 (line 70) | IRETURN | L1: ICONST_0 (line 73) | IRETURN method-execution(boolean ts.simul.client.AbstractClient$OptionSetter.setOption_file(java.lang.String)) end public boolean setOption_file(String) throws ts.util.IllegalProgramArgumentException public boolean setOption_class(String) throws ts.util.IllegalProgramArgumentException org.aspectj.weaver.MethodDeclarationLineNumber: 76:1971 : method-execution(boolean ts.simul.client.AbstractClient$OptionSetter.setOption_class(java.lang.String)) | ALOAD_1 // java.lang.String optParam (line 79) | method-call(int java.lang.String.length()) | | INVOKEVIRTUAL java.lang.String.length ()I | method-call(int java.lang.String.length()) | IFLE L1 | ALOAD_0 // ts.simul.client.AbstractClient$OptionSetter this (line 80) | GETFIELD ts.simul.client.AbstractClient$OptionSetter.this$0 Lts/simul/client/AbstractClient; | ALOAD_1 // java.lang.String optParam | PUTFIELD ts.simul.client.AbstractClient.className Ljava/lang/String; | catch ts.simul.SimulationException -> E0 | | ALOAD_0 // ts.simul.client.AbstractClient$OptionSetter this (line 82) | | GETFIELD ts.simul.client.AbstractClient$OptionSetter.this$0 Lts/simul/client/AbstractClient; | | ALOAD_0 // ts.simul.client.AbstractClient$OptionSetter this | | GETFIELD ts.simul.client.AbstractClient$OptionSetter.this$0 Lts/simul/client/AbstractClient; | | GETFIELD ts.simul.client.AbstractClient.className Ljava/lang/String; | | method-call(java.lang.Class ts.simul.SceneFactory.getSceneClass (java.lang.String)) | | | INVOKESTATIC ts.simul.SceneFactory.getSceneClass (Ljava/lang/String;)Ljava/lang/Class; | | method-call(java.lang.Class ts.simul.SceneFactory.getSceneClass (java.lang.String)) | | PUTFIELD ts.simul.client.AbstractClient.sceneClass Ljava/lang/Class; | | ALOAD_0 // ts.simul.client.AbstractClient$OptionSetter this (line 83) | | GETFIELD ts.simul.client.AbstractClient$OptionSetter.this$0 Lts/simul/client/AbstractClient; | | method-call(void ts.simul.client.AbstractClient.setBeanInfoSearchPath()) | | | INVOKESTATIC ts.simul.Architecture.aspectOf () Lts/simul/Architecture; | | | GETSTATIC ts.simul.client.AbstractClient$OptionSetter.ajc$tjp_0 Lorg/aspectj/lang/JoinPoint$StaticPart; | | | INVOKEVIRTUAL ts.simul.Architecture.ajc$before$ts_simul_Architecture$1$ae285a4d (Lorg/aspectj/lang/JoinPoint$StaticPart;)V | | | INVOKEVIRTUAL ts.simul.client.AbstractClient.setBeanInfoSearchPath ()V | | method-call(void ts.simul.client.AbstractClient.setBeanInfoSearchPath()) | | GOTO L0 | catch ts.simul.SimulationException -> E0 | E0: ASTORE_2 (line 85) | NEW ts.util.IllegalProgramArgumentException (line 86) | DUP | ALOAD_2 // ts.simul.SimulationException e | method-call(java.lang.String ts.simul.SimulationException.getMessage()) | | INVOKEVIRTUAL ts.simul.SimulationException.getMessage () Ljava/lang/String; | method-call(java.lang.String ts.simul.SimulationException.getMessage()) | constructor-call(void ts.util.IllegalProgramArgumentException.<init> (java.lang.String)) | | INVOKESPECIAL ts.util.IllegalProgramArgumentException.<init> (Ljava/lang/String;)V | constructor-call(void ts.util.IllegalProgramArgumentException.<init> (java.lang.String)) | ATHROW | L0: ICONST_1 (line 88) | IRETURN | L1: ICONST_0 (line 91) | IRETURN method-execution(boolean ts.simul.client.AbstractClient$OptionSetter.setOption_class(java.lang.String)) end public boolean setOption_class(String) throws ts.util.IllegalProgramArgumentException public boolean setOption_name(String) org.aspectj.weaver.MethodDeclarationLineNumber: 94:2593 : method-execution(boolean ts.simul.client.AbstractClient$OptionSetter.setOption_name(java.lang.String)) | ALOAD_0 // ts.simul.client.AbstractClient$OptionSetter this (line 96) | GETFIELD ts.simul.client.AbstractClient$OptionSetter.this$0 Lts/simul/client/AbstractClient; | ALOAD_1 // java.lang.String optParam | PUTFIELD ts.simul.client.AbstractClient.sceneName Ljava/lang/String; | ICONST_1 (line 97) | IRETURN method-execution(boolean ts.simul.client.AbstractClient$OptionSetter.setOption_name(java.lang.String)) end public boolean setOption_name(String) public boolean setOption_actors(String) org.aspectj.weaver.MethodDeclarationLineNumber: 100:2739 : method-execution(boolean ts.simul.client.AbstractClient$OptionSetter.setOption_actors(java.lang.String)) | catch java.lang.NumberFormatException -> E0 | | ALOAD_1 // java.lang.String optParam (line 103) | | method-call(int java.lang.Integer.parseInt(java.lang.String)) | | | INVOKESTATIC java.lang.Integer.parseInt (Ljava/lang/String;) I | | method-call(int java.lang.Integer.parseInt(java.lang.String)) | | ISTORE_2 | | GOTO L0 | catch java.lang.NumberFormatException -> E0 | E0: ASTORE_2 // int n (line 105) | ICONST_0 (line 106) | IRETURN | L0: ICONST_1 (line 108) | IRETURN method-execution(boolean ts.simul.client.AbstractClient$OptionSetter.setOption_actors(java.lang.String)) end public boolean setOption_actors(String) end public class ts.simul.client.AbstractClient$OptionSetter when weaving type ts.simul.client.AbstractClient$OptionSetter when weaving classes when weaving when incrementally building BuildConfig [c:\Projects\eclipse\.metadata\.plugins\org.eclipse.ajdt.core\TS.generated.lst] #Files=79
|
verified fixed
|
dd9a9b2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-18T09:17:56Z
| 2005-11-17T23:26:40Z
|
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.CPInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldGen;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.IndexedInstruction;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LocalVariableInstruction;
import org.aspectj.apache.bcel.generic.MethodGen;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUTFIELD;
import org.aspectj.apache.bcel.generic.PUTSTATIC;
import org.aspectj.apache.bcel.generic.RET;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.Select;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.generic.annotation.AnnotationGen;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IClassWeaver;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MissingResolvedTypeWithKnownSignature;
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.ResolvedTypeMunger;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverMetrics;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.ExactTypePattern;
class BcelClassWeaver implements IClassWeaver {
/**
* This is called from {@link BcelWeaver} to perform the per-class weaving process.
*/
public static boolean weave(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers,
List lateTypeMungers)
{
boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers).weave();
//System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState());
//clazz.print();
return b;
}
// --------------------------------------------
private final LazyClassGen clazz;
private final List shadowMungers;
private final List typeMungers;
private final List lateTypeMungers;
private final BcelObjectType ty; // alias of clazz.getType()
private final BcelWorld world; // alias of ty.getWorld()
private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen()
private final InstructionFactory fact; // alias of clazz.getFactory();
private final List addedLazyMethodGens = new ArrayList();
private final Set addedDispatchTargets = new HashSet();
// Static setting across BcelClassWeavers
private static boolean inReweavableMode = false;
private List addedSuperInitializersAsList = null; // List<IfaceInitList>
private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList
private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger>
private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger>
private Map mapToAnnotations = new HashMap();
private BcelShadow clinitShadow = null;
/**
* This holds the initialization and pre-initialization shadows for this class
* that were actually matched by mungers (if no match, then we don't even create the
* shadows really).
*/
private final List initializationShadows = new ArrayList(1);
private BcelClassWeaver(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers,
List lateTypeMungers)
{
super();
// assert world == clazz.getType().getWorld()
this.world = world;
this.clazz = clazz;
this.shadowMungers = shadowMungers;
this.typeMungers = typeMungers;
this.lateTypeMungers = lateTypeMungers;
this.ty = clazz.getBcelObjectType();
this.cpg = clazz.getConstantPoolGen();
this.fact = clazz.getFactory();
fastMatchShadowMungers(shadowMungers);
initializeSuperInitializerMap(ty.getResolvedTypeX());
}
private List[] perKindShadowMungers;
private boolean canMatchBodyShadows = false;
private boolean canMatchInitialization = false;
private void fastMatchShadowMungers(List shadowMungers) {
// beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) !
perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1];
for (int i = 0; i < perKindShadowMungers.length; i++) {
perKindShadowMungers[i] = new ArrayList(0);
}
for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
Set couldMatchKinds = munger.getPointcut().couldMatchKinds();
for (Iterator kindIterator = couldMatchKinds.iterator();
kindIterator.hasNext();) {
Shadow.Kind aKind = (Shadow.Kind) kindIterator.next();
perKindShadowMungers[aKind.getKey()].add(munger);
}
}
if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty())
canMatchInitialization = true;
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
Shadow.Kind kind = Shadow.SHADOW_KINDS[i];
if (!kind.isEnclosingKind() && !perKindShadowMungers[i+1].isEmpty()) {
canMatchBodyShadows = true;
}
if (perKindShadowMungers[i+1].isEmpty()) {
perKindShadowMungers[i+1] = null;
}
}
}
private boolean canMatch(Shadow.Kind kind) {
return perKindShadowMungers[kind.getKey()] != null;
}
// private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) {
// FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind);
// for (Iterator i = shadowMungers.iterator(); i.hasNext();) {
// ShadowMunger munger = (ShadowMunger) i.next();
// FuzzyBoolean fb = munger.getPointcut().fastMatch(info);
// WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString()
// if (fb.maybeTrue()) mungers.add(munger);
// }
// }
private void initializeSuperInitializerMap(ResolvedType child) {
ResolvedType[] superInterfaces = child.getDeclaredInterfaces();
for (int i=0, len=superInterfaces.length; i < len; i++) {
if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) {
if (addSuperInitializer(superInterfaces[i])) {
initializeSuperInitializerMap(superInterfaces[i]);
}
}
}
}
private boolean addSuperInitializer(ResolvedType onType) {
if (onType.isRawType() || onType.isParameterizedType()) onType = onType.getGenericType();
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
if (l != null) return false;
l = new IfaceInitList(onType);
addedSuperInitializers.put(onType, l);
return true;
}
public void addInitializer(ConcreteTypeMunger cm) {
NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger();
ResolvedType onType = m.getSignature().getDeclaringType().resolve(world);
if (onType.isRawType()) onType = onType.getGenericType();
if (m.getSignature().isStatic()) {
addedClassInitializers.add(cm);
} else {
if (onType == ty.getResolvedTypeX()) {
addedThisInitializers.add(cm);
} else {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
l.list.add(cm);
}
}
}
private static class IfaceInitList implements PartialOrder.PartialComparable {
final ResolvedType onType;
List list = new ArrayList();
IfaceInitList(ResolvedType onType) {
this.onType = onType;
}
public int compareTo(Object other) {
IfaceInitList o = (IfaceInitList)other;
if (onType.isAssignableFrom(o.onType)) return +1;
else if (o.onType.isAssignableFrom(onType)) return -1;
else return 0;
}
public int fallbackCompareTo(Object other) {
return 0;
}
}
// XXX this is being called, but the result doesn't seem to be being used
public boolean addDispatchTarget(ResolvedMember m) {
return addedDispatchTargets.add(m);
}
public void addLazyMethodGen(LazyMethodGen gen) {
addedLazyMethodGens.add(gen);
}
public void addOrReplaceLazyMethodGen(LazyMethodGen mg) {
if (alreadyDefined(clazz, mg)) return;
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (existing.definingType == null) {
// this means existing was introduced on the class itself
return;
} else if (mg.definingType.isAssignableFrom(existing.definingType)) {
// existing is mg's subtype and dominates mg
return;
} else if (existing.definingType.isAssignableFrom(mg.definingType)) {
// mg is existing's subtype and dominates existing
i.remove();
addedLazyMethodGens.add(mg);
return;
} else {
throw new BCException("conflict between: " + mg + " and " + existing);
}
}
}
addedLazyMethodGens.add(mg);
}
private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) {
for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (!mg.isAbstract() && existing.isAbstract()) {
i.remove();
return false;
}
return true;
}
}
return false;
}
private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) {
return mg.getName().equals(existing.getName()) &&
mg.getSignature().equals(existing.getSignature());
}
protected static LazyMethodGen makeBridgeMethod(LazyClassGen gen, ResolvedMember member) {
// remove abstract modifier
int mods = member.getModifiers();
if (Modifier.isAbstract(mods)) mods = mods - Modifier.ABSTRACT;
LazyMethodGen ret = new LazyMethodGen(
mods,
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;
}
/**
* Create a single bridge method called 'theBridgeMethod' that bridges to 'whatToBridgeTo'
*/
private static void createBridgeMethod(BcelWorld world, LazyMethodGen whatToBridgeToMethodGen, LazyClassGen clazz,ResolvedMember theBridgeMethod) {
InstructionList body;
InstructionFactory fact;
int pos = 0;
ResolvedMember whatToBridgeTo = whatToBridgeToMethodGen.getMemberView();
if (whatToBridgeTo==null) {
whatToBridgeTo =
new ResolvedMemberImpl(Member.METHOD,
whatToBridgeToMethodGen.getEnclosingClass().getType(),
whatToBridgeToMethodGen.getAccessFlags(),
whatToBridgeToMethodGen.getName(),
whatToBridgeToMethodGen.getSignature());
}
LazyMethodGen bridgeMethod = makeBridgeMethod(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*/ );
Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType());
Type[] paramTypes = BcelWorld.makeBcelTypes(theBridgeMethod.getParameterTypes());
Type[] newParamTypes=whatToBridgeToMethodGen.getArgumentTypes();
body = bridgeMethod.getBody();
fact = clazz.getFactory();
if (!whatToBridgeToMethodGen.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 (!newParamTypes[i].equals(paramTypes[i])) {
if (debug) System.err.println("Cast "+newParamTypes[i]+" from "+paramTypes[i]);
body.append(fact.createCast(paramTypes[i],newParamTypes[i]));
}
pos+=paramType.getSize();
}
body.append(Utility.createInvoke(fact, world,whatToBridgeTo));
body.append(InstructionFactory.createReturn(returnType));
clazz.addMethodGen(bridgeMethod);
}
// ----
public boolean weave() {
if (clazz.isWoven() && !clazz.isReweavable()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()),
ty.getSourceLocation(), null);
return false;
}
Set aspectsAffectingType = null;
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType = new HashSet();
boolean isChanged = false;
// we want to "touch" all aspects
if (clazz.getType().isAspect()) isChanged = true;
// start by munging all typeMungers
for (Iterator i = typeMungers.iterator(); i.hasNext(); ) {
Object o = i.next();
if ( !(o instanceof BcelTypeMunger) ) {
//???System.err.println("surprising: " + o);
continue;
}
BcelTypeMunger munger = (BcelTypeMunger)o;
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
isChanged = true;
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName());
}
}
// Weave special half type/half shadow mungers...
isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged;
isChanged = weaveDeclareAtField(clazz) || isChanged;
// XXX do major sort of stuff
// sort according to: Major: type hierarchy
// within each list: dominates
// don't forget to sort addedThisInitialiers according to dominates
addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values());
addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList);
if (addedSuperInitializersAsList == null) {
throw new BCException("circularity in inter-types");
}
// this will create a static initializer if there isn't one
// this is in just as bad taste as NOPs
LazyMethodGen staticInit = clazz.getStaticInitializer();
staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true));
// now go through each method, and match against each method. This
// sets up each method's {@link LazyMethodGen#matchedShadows} field,
// and it also possibly adds to {@link #initializationShadows}.
List methodGens = new ArrayList(clazz.getMethodGens());
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
boolean shadowMungerMatched = match(mg);
if (shadowMungerMatched) {
// For matching mungers, add their declaring aspects to the list that affected this type
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.addAll(findAspectsForMungers(mg));
isChanged = true;
}
}
// now we weave all but the initialization shadows
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
implement(mg);
}
// if we matched any initialization shadows, we inline and weave
if (!initializationShadows.isEmpty()) {
// Repeat next step until nothing left to inline...cant go on
// infinetly as compiler will have detected and reported
// "Recursive constructor invocation"
while (inlineSelfConstructors(methodGens));
positionAndImplement(initializationShadows);
}
// now proceed with late type mungers
if (lateTypeMungers != null) {
for (Iterator i = lateTypeMungers.iterator(); i.hasNext(); ) {
BcelTypeMunger munger = (BcelTypeMunger)i.next();
if (munger.matches(clazz.getType())) {
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
isChanged = true;
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName());
}
}
}
}
//FIXME AV - see #75442, for now this is not enough to fix the bug, comment that out until we really fix it
// // flush to save some memory
// PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType());
// finally, if we changed, we add in the introduced methods.
if (isChanged) {
clazz.getOrCreateWeaverStateInfo(inReweavableMode);
weaveInAddedMethods(); // FIXME asc are these potentially affected by declare annotation?
}
if (inReweavableMode) {
WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(true);
wsi.addAspectsAffectingType(aspectsAffectingType);
wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes());
wsi.setReweavable(true);
} else {
clazz.getOrCreateWeaverStateInfo(false).setReweavable(false);
}
return isChanged;
}
// **************************** start of bridge method creation code *****************
// debug flag for bridge method creation
private static boolean debug=false;
// FIXME asc tidy this lot up !!
// FIXME asc refactor into ResolvedType or even ResolvedMember?
/**
* Check if a particular method is overriding another - refactored into this helper so it
* can be used from multiple places.
*/
private static ResolvedMember isOverriding(ResolvedType typeToCheck,ResolvedMember methodThatMightBeGettingOverridden,String mname,String mrettype,int mmods,boolean inSamePackage,UnresolvedType[] methodParamsArray) {
// Check if we can be an override...
if (methodThatMightBeGettingOverridden.isStatic()) return null; // we can't be overriding a static method
if (methodThatMightBeGettingOverridden.isPrivate()) return null; // we can't be overriding a private method
if (!methodThatMightBeGettingOverridden.getName().equals(mname)) return null; // names dont match (this will also skip <init> and <clinit> too)
if (methodThatMightBeGettingOverridden.getParameterTypes().length!=methodParamsArray.length) return null; // check same number of parameters
if (!isVisibilityOverride(mmods,methodThatMightBeGettingOverridden,inSamePackage)) return null;
if (debug) System.err.println(" Seriously considering this might be getting overridden "+methodThatMightBeGettingOverridden);
// Look at erasures of parameters (List<String> erased is List)
boolean sameParams = true;
for (int p = 0;p<methodThatMightBeGettingOverridden.getParameterTypes().length;p++) {
if (!methodThatMightBeGettingOverridden.getParameterTypes()[p].getErasureSignature().equals(methodParamsArray[p].getErasureSignature())) sameParams = false;
}
// If the 'typeToCheck' represents a parameterized type then the method will be the parameterized form of the
// generic method in the generic type. So if the method was 'void m(List<T> lt, T t)' and the parameterized type here
// is I<String> then the method we are looking at will be 'void m(List<String> lt, String t)' which when erased
// is 'void m(List lt,String t)' - so if the parameters *do* match then there is a generic method we are
// overriding
if (sameParams) {
// check for covariance
if (typeToCheck.isParameterizedType()) {
return methodThatMightBeGettingOverridden.getBackingGenericMember();
} else if (!methodThatMightBeGettingOverridden.getReturnType().getErasureSignature().equals(mrettype)) {
return methodThatMightBeGettingOverridden; // covariance
}
}
return null;
}
/**
* Looks at the visibility modifiers between two methods, and knows whether they are from classes in
* the same package, and decides whether one overrides the other.
* @return true if there is an overrides rather than a 'hides' relationship
*/
static boolean isVisibilityOverride(int methodMods, ResolvedMember inheritedMethod,boolean inSamePackage) {
if (inheritedMethod.isStatic()) return false;
if (methodMods == inheritedMethod.getModifiers()) return true;
if (inheritedMethod.isPrivate()) return false;
boolean isPackageVisible = !inheritedMethod.isPrivate() && !inheritedMethod.isProtected()
&& !inheritedMethod.isPublic();
if (isPackageVisible && !inSamePackage) return false;
return true;
}
/**
* This method recurses up a specified type looking for a method that overrides the one passed in.
*
* @return the method being overridden or null if none is found
*/
public static ResolvedMember checkForOverride(ResolvedType typeToCheck,String mname,String mparams,String mrettype,int mmods,String mpkg,UnresolvedType[] methodParamsArray) {
if (typeToCheck==null) return null;
if (typeToCheck instanceof MissingResolvedTypeWithKnownSignature) return null; // we just can't tell !
if (debug) System.err.println(" Checking for override of "+mname+" in "+typeToCheck);
String packageName = typeToCheck.getPackageName();
if (packageName==null) packageName="";
boolean inSamePackage = packageName.equals(mpkg); // used when looking at visibility rules
ResolvedMember [] methods = typeToCheck.getDeclaredMethods();
for (int ii=0;ii<methods.length;ii++) {
ResolvedMember methodThatMightBeGettingOverridden = methods[ii]; // the method we are going to check
ResolvedMember isOverriding = isOverriding(typeToCheck,methodThatMightBeGettingOverridden,mname,mrettype,mmods,inSamePackage,methodParamsArray);
if (isOverriding!=null) return isOverriding;
}
List l = typeToCheck.getInterTypeMungers();
for (Iterator iterator = l.iterator(); iterator.hasNext();) {
BcelTypeMunger element = (BcelTypeMunger) iterator.next();
if (element.getMunger() instanceof NewMethodTypeMunger) {
if (debug) System.err.println("Possible ITD candidate "+element);
ResolvedMember aMethod = element.getSignature();
ResolvedMember isOverriding = isOverriding(typeToCheck,aMethod,mname,mrettype,mmods,inSamePackage,methodParamsArray);
if (isOverriding!=null) return isOverriding;
}
}
if (typeToCheck.equals(UnresolvedType.OBJECT)) return null;
ResolvedType superclass = typeToCheck.getSuperclass();
ResolvedMember overriddenMethod = checkForOverride(superclass,mname,mparams,mrettype,mmods,mpkg,methodParamsArray);
if (overriddenMethod!=null) return overriddenMethod;
ResolvedType[] interfaces = typeToCheck.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
ResolvedType anInterface = interfaces[i];
overriddenMethod = checkForOverride(anInterface,mname,mparams,mrettype,mmods,mpkg,methodParamsArray);
if (overriddenMethod!=null) return overriddenMethod;
}
return null;
}
/**
* We need to determine if any methods in this type require bridge methods - this method should only
* be called if necessary to do this calculation, i.e. we are on a 1.5 VM (where covariance/generics exist) and
* the type hierarchy for the specified class has changed (via decp/itd).
*
* See pr108101
*/
public static boolean calculateAnyRequiredBridgeMethods(BcelWorld world,LazyClassGen clazz) {
if (!world.isInJava5Mode()) return false; // just double check... the caller should have already verified this
if (clazz.isInterface()) return false; // dont bother if we're an interface
boolean didSomething=false; // set if we build any bridge methods
// So what methods do we have right now in this class?
List /*LazyMethodGen*/ methods = clazz.getMethodGens();
// Keep a set of all methods from this type - it'll help us to check if bridge methods
// have already been created, we don't want to do it twice!
Set methodsSet = new HashSet();
for (int i = 0; i < methods.size(); i++) {
LazyMethodGen aMethod = (LazyMethodGen)methods.get(i);
methodsSet.add(aMethod.getName()+aMethod.getSignature()); // e.g. "foo(Ljava/lang/String;)V"
}
// Now go through all the methods in this type
for (int i = 0; i < methods.size(); i++) {
// This is the local method that we *might* have to bridge to
LazyMethodGen bridgeToCandidate = (LazyMethodGen)methods.get(i);
if (bridgeToCandidate.isBridgeMethod()) continue; // Doh!
String name = bridgeToCandidate.getName();
String psig = bridgeToCandidate.getParameterSignature();
String rsig = bridgeToCandidate.getReturnType().getSignature();
//if (bridgeToCandidate.isAbstract()) continue;
if (bridgeToCandidate.isStatic()) continue; // ignore static methods
if (name.endsWith("init>")) continue; // Skip constructors and static initializers
if (debug) System.err.println("Determining if we have to bridge to "+clazz.getName()+"."+name+""+bridgeToCandidate.getSignature());
// Let's take a look at the superclass
ResolvedType theSuperclass= clazz.getSuperClass();
if (debug) System.err.println("Checking supertype "+theSuperclass);
String pkgName = clazz.getPackageName();
UnresolvedType[] bm = BcelWorld.fromBcel(bridgeToCandidate.getArgumentTypes());
ResolvedMember overriddenMethod = checkForOverride(theSuperclass,name,psig,rsig,bridgeToCandidate.getAccessFlags(),pkgName,bm);
if (overriddenMethod!=null) {
boolean alreadyHaveABridgeMethod = methodsSet.contains(overriddenMethod.getName()+overriddenMethod.getSignature());
if (!alreadyHaveABridgeMethod) {
if (debug) System.err.println("Bridging to "+overriddenMethod);
createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod);
didSomething = true;
continue; // look at the next method
}
}
// Check superinterfaces
String[] interfaces = clazz.getInterfaceNames();
for (int j = 0; j < interfaces.length; j++) {
if (debug) System.err.println("Checking superinterface "+interfaces[j]);
ResolvedType interfaceType = world.resolve(interfaces[j]);
overriddenMethod = checkForOverride(interfaceType,name,psig,rsig,bridgeToCandidate.getAccessFlags(),clazz.getPackageName(),bm);
if (overriddenMethod!=null) {
boolean alreadyHaveABridgeMethod = methodsSet.contains(overriddenMethod.getName()+overriddenMethod.getSignature());
if (!alreadyHaveABridgeMethod) {
createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod);
didSomething=true;
if (debug) System.err.println("Bridging to "+overriddenMethod);
continue; // look at the next method
}
}
}
}
return didSomething;
}
// **************************** end of bridge method creation code *****************
/**
* Weave any declare @method/@ctor statements into the members of the supplied class
*/
private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) {
List reportedProblems = new ArrayList();
List allDecams = world.getDeclareAnnotationOnMethods();
if (allDecams.isEmpty()) return false; // nothing to do
boolean isChanged = false;
// deal with ITDs
List itdMethodsCtors = getITDSubset(clazz,ResolvedTypeMunger.Method);
itdMethodsCtors.addAll(getITDSubset(clazz,ResolvedTypeMunger.Constructor));
if (!itdMethodsCtors.isEmpty()) {
// Can't use the subset called 'decaMs' as it won't be right for ITDs...
isChanged = weaveAtMethodOnITDSRepeatedly(allDecams,itdMethodsCtors,reportedProblems);
}
// deal with all the other methods...
List members = clazz.getMethodGens();
List decaMs = getMatchingSubset(allDecams,clazz.getType());
if (decaMs.isEmpty()) return false; // nothing to do
if (!members.isEmpty()) {
Set unusedDecams = new HashSet();
unusedDecams.addAll(decaMs);
for (int memberCounter = 0;memberCounter<members.size();memberCounter++) {
LazyMethodGen mg = (LazyMethodGen)members.get(memberCounter);
if (!mg.getName().startsWith(NameMangler.PREFIX)) {
// Single first pass
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
for (Iterator iter = decaMs.iterator(); iter.hasNext();) {
DeclareAnnotation decaM = (DeclareAnnotation) iter.next();
if (decaM.matches(mg.getMemberView(),world)) {
if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) {
// remove the declare @method since don't want an error when
// the annotation is already there
unusedDecams.remove(decaM);
continue; // skip this one...
}
Annotation a = decaM.getAnnotationX().getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true);
Method oldMethod = mg.getMethod();
MethodGen myGen = new MethodGen(oldMethod,clazz.getClassName(),clazz.getConstantPoolGen());
myGen.addAnnotation(ag);
Method newMethod = myGen.getMethod();
mg.addAnnotation(decaM.getAnnotationX());
members.set(memberCounter,new LazyMethodGen(newMethod,clazz));
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod());
reportMethodCtorWeavingMessage(clazz, mg.getMemberView(), decaM,mg.getDeclarationLineNumber());
isChanged = true;
modificationOccured = true;
// remove the declare @method since have matched against it
unusedDecams.remove(decaM);
} else {
if (!decaM.isStarredAnnotationPattern())
worthRetrying.add(decaM); // an annotation is specified that might be put on by a subsequent decaf
}
}
// Multiple secondary passes
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
// lets have another go
List forRemoval = new ArrayList();
for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaM = (DeclareAnnotation) iter.next();
if (decaM.matches(mg.getMemberView(),world)) {
if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) {
// remove the declare @method since don't want an error when
// the annotation is already there
unusedDecams.remove(decaM);
continue; // skip this one...
}
mg.addAnnotation(decaM.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaM);
// remove the declare @method since have matched against it
unusedDecams.remove(decaM);
}
}
worthRetrying.removeAll(forRemoval);
}
}
}
checkUnusedDeclareAtTypes(unusedDecams, false);
}
return isChanged;
}
// TAG: WeavingMessage
private void reportMethodCtorWeavingMessage(LazyClassGen clazz, ResolvedMember member, DeclareAnnotation decaM,int memberLineNumber) {
if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){
StringBuffer parmString = new StringBuffer("(");
UnresolvedType[] paramTypes = member.getParameterTypes();
for (int i = 0; i < paramTypes.length; i++) {
UnresolvedType type = paramTypes[i];
String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type.getSignature());
if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1);
parmString.append(s);
if ((i+1)<paramTypes.length) parmString.append(",");
}
parmString.append(")");
String methodName = member.getName();
StringBuffer sig = new StringBuffer();
sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(member.getModifiers()));
sig.append(" ");
sig.append(member.getReturnType().toString());
sig.append(" ");
sig.append(member.getDeclaringType().toString());
sig.append(".");
sig.append(methodName.equals("<init>")?"new":methodName);
sig.append(parmString);
StringBuffer loc = new StringBuffer();
if (clazz.getFileName()==null) {
loc.append("no debug info available");
} else {
loc.append(clazz.getFileName());
if (memberLineNumber!=-1) {
loc.append(":"+memberLineNumber);
}
}
getWorld().getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES,
new String[]{
sig.toString(),
loc.toString(),
decaM.getAnnotationString(),
methodName.startsWith("<init>")?"constructor":"method",
decaM.getAspect().toString(),
Utility.beautifyLocation(decaM.getSourceLocation())
}));
}
}
/**
* Looks through a list of declare annotation statements and only returns
* those that could possibly match on a field/method/ctor in type.
*/
private List getMatchingSubset(List declareAnnotations, ResolvedType type) {
List subset = new ArrayList();
for (Iterator iter = declareAnnotations.iterator(); iter.hasNext();) {
DeclareAnnotation da = (DeclareAnnotation) iter.next();
if (da.couldEverMatch(type)) {
subset.add(da);
}
}
return subset;
}
/**
* Get a subset of all the type mungers defined on this aspect
*/
private List getITDSubset(LazyClassGen clazz,ResolvedTypeMunger.Kind wantedKind) {
List subset = new ArrayList();
Collection c = clazz.getBcelObjectType().getTypeMungers();
for (Iterator iter = c.iterator();iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger)iter.next();
if (typeMunger.getMunger().getKind()==wantedKind)
subset.add(typeMunger);
}
return subset;
}
public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz,BcelTypeMunger fieldMunger) {
NewFieldTypeMunger nftm = (NewFieldTypeMunger)fieldMunger.getMunger();
ResolvedMember lookingFor =AjcMemberMaker.interFieldInitializer(nftm.getSignature(),clazz.getType());
List meths = clazz.getMethodGens();
for (Iterator iter = meths.iterator(); iter.hasNext();) {
LazyMethodGen element = (LazyMethodGen) iter.next();
if (element.getName().equals(lookingFor.getName())) return element;
}
return null;
}
// FIXME asc refactor this to neaten it up
public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz,BcelTypeMunger methodCtorMunger) {
if (methodCtorMunger.getMunger() instanceof NewMethodTypeMunger) {
NewMethodTypeMunger nftm = (NewMethodTypeMunger)methodCtorMunger.getMunger();
ResolvedMember lookingFor = AjcMemberMaker.interMethodDispatcher(nftm.getSignature(),methodCtorMunger.getAspectType());
List meths = clazz.getMethodGens();
for (Iterator iter = meths.iterator(); iter.hasNext();) {
LazyMethodGen element = (LazyMethodGen) iter.next();
if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element;
}
return null;
} else if (methodCtorMunger.getMunger() instanceof NewConstructorTypeMunger) {
NewConstructorTypeMunger nftm = (NewConstructorTypeMunger)methodCtorMunger.getMunger();
ResolvedMember lookingFor =AjcMemberMaker.postIntroducedConstructor(methodCtorMunger.getAspectType(),nftm.getSignature().getDeclaringType(),nftm.getSignature().getParameterTypes());
List meths = clazz.getMethodGens();
for (Iterator iter = meths.iterator(); iter.hasNext();) {
LazyMethodGen element = (LazyMethodGen) iter.next();
if (element.getName().equals(lookingFor.getName()) && element.getParameterSignature().equals(lookingFor.getParameterSignature())) return element;
}
return null;
} else {
throw new RuntimeException("Not sure what this is: "+methodCtorMunger);
}
}
/**
* Applies some set of declare @field constructs (List<DeclareAnnotation>) to some bunch
* of ITDfields (List<BcelTypeMunger>. It will iterate over the fields repeatedly until
* everything has been applied.
*
*/
private boolean weaveAtFieldRepeatedly(List decaFs, List itdFields,List reportedErrors) {
boolean isChanged = false;
for (Iterator iter = itdFields.iterator(); iter.hasNext();) {
BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next();
ResolvedMember itdIsActually = fieldMunger.getSignature();
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
for (Iterator iter2 = decaFs.iterator(); iter2.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter2.next();
if (decaF.matches(itdIsActually,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger);
if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one...
annotationHolder.addAnnotation(decaF.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation());
isChanged = true;
modificationOccured = true;
} else {
if (!decaF.isStarredAnnotationPattern())
worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf
}
}
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
List forRemoval = new ArrayList();
for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter2.next();
if (decaF.matches(itdIsActually,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,fieldMunger);
if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaF,reportedErrors)) continue; // skip this one...
annotationHolder.addAnnotation(decaF.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),itdIsActually.getSourceLocation());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaF);
}
worthRetrying.removeAll(forRemoval);
}
}
}
return isChanged;
}
/**
* Applies some set of declare @method/@ctor constructs (List<DeclareAnnotation>) to some bunch
* of ITDmembers (List<BcelTypeMunger>. It will iterate over the fields repeatedly until
* everything has been applied.
*/
private boolean weaveAtMethodOnITDSRepeatedly(List decaMCs, List itdMethodsCtors,List reportedErrors) {
boolean isChanged = false;
for (Iterator iter = itdMethodsCtors.iterator(); iter.hasNext();) {
BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next();
ResolvedMember unMangledInterMethod = methodctorMunger.getSignature();
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
for (Iterator iter2 = decaMCs.iterator(); iter2.hasNext();) {
DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next();
if (decaMC.matches(unMangledInterMethod,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz,methodctorMunger);
if (annotationHolder == null || doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)){
continue; // skip this one...
}
annotationHolder.addAnnotation(decaMC.getAnnotationX());
isChanged=true;
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation());
reportMethodCtorWeavingMessage(clazz, unMangledInterMethod, decaMC,-1);
modificationOccured = true;
} else {
if (!decaMC.isStarredAnnotationPattern())
worthRetrying.add(decaMC); // an annotation is specified that might be put on by a subsequent decaf
}
}
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
List forRemoval = new ArrayList();
for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next();
if (decaMC.matches(unMangledInterMethod,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,methodctorMunger);
if (doesAlreadyHaveAnnotation(annotationHolder,unMangledInterMethod,decaMC,reportedErrors)) continue; // skip this one...
annotationHolder.addAnnotation(decaMC.getAnnotationX());
unMangledInterMethod.addAnnotation(decaMC.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),unMangledInterMethod.getSourceLocation());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaMC);
}
worthRetrying.removeAll(forRemoval);
}
}
}
return isChanged;
}
private boolean dontAddTwice(DeclareAnnotation decaF, Annotation [] dontAddMeTwice){
for (int i = 0; i < dontAddMeTwice.length; i++){
Annotation ann = dontAddMeTwice[i];
if (ann != null && decaF.getAnnotationX().getTypeName().equals(ann.getTypeName())){
dontAddMeTwice[i] = null; // incase it really has been added twice!
return true;
}
}
return false;
}
/**
* Weave any declare @field statements into the fields of the supplied class
*
* Interesting case relating to public ITDd fields. The annotations are really stored against
* the interfieldinit method in the aspect, but the public field is placed in the target
* type and then is processed in the 2nd pass over fields that occurs. I think it would be
* more expensive to avoid putting the annotation on that inserted public field than just to
* have it put there as well as on the interfieldinit method.
*/
private boolean weaveDeclareAtField(LazyClassGen clazz) {
// BUGWARNING not getting enough warnings out on declare @field ?
// There is a potential problem here with warnings not coming out - this
// will occur if they are created on the second iteration round this loop.
// We currently deactivate error reporting for the second time round.
// A possible solution is to record what annotations were added by what
// decafs and check that to see if an error needs to be reported - this
// would be expensive so lets skip it for now
List reportedProblems = new ArrayList();
List allDecafs = world.getDeclareAnnotationOnFields();
if (allDecafs.isEmpty()) return false; // nothing to do
boolean isChanged = false;
List itdFields = getITDSubset(clazz,ResolvedTypeMunger.Field);
if (itdFields!=null) {
isChanged = weaveAtFieldRepeatedly(allDecafs,itdFields,reportedProblems);
}
List decaFs = getMatchingSubset(allDecafs,clazz.getType());
if (decaFs.isEmpty()) return false; // nothing more to do
Field[] fields = clazz.getFieldGens();
if (fields!=null) {
Set unusedDecafs = new HashSet();
unusedDecafs.addAll(decaFs);
for (int fieldCounter = 0;fieldCounter<fields.length;fieldCounter++) {
BcelField aBcelField = new BcelField(clazz.getBcelObjectType(),fields[fieldCounter]);
if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) {
// Single first pass
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
Annotation [] dontAddMeTwice = fields[fieldCounter].getAnnotations();
// go through all the declare @field statements
for (Iterator iter = decaFs.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter.next();
if (decaF.matches(aBcelField,world)) {
if (!dontAddTwice(decaF,dontAddMeTwice)){
if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)){
// remove the declare @field since don't want an error when
// the annotation is already there
unusedDecafs.remove(decaF);
continue;
}
if(decaF.getAnnotationX().isRuntimeVisible()){ // isAnnotationWithRuntimeRetention(clazz.getJavaClass(world))){
//if(decaF.getAnnotationTypeX().isAnnotationWithRuntimeRetention(world)){
// it should be runtime visible, so put it on the Field
Annotation a = decaF.getAnnotationX().getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a,clazz.getConstantPoolGen(),true);
FieldGen myGen = new FieldGen(fields[fieldCounter],clazz.getConstantPoolGen());
myGen.addAnnotation(ag);
Field newField = myGen.getField();
aBcelField.addAnnotation(decaF.getAnnotationX());
clazz.replaceField(fields[fieldCounter],newField);
fields[fieldCounter]=newField;
} else{
aBcelField.addAnnotation(decaF.getAnnotationX());
}
}
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]);
reportFieldAnnotationWeavingMessage(clazz, fields, fieldCounter, decaF);
isChanged = true;
modificationOccured = true;
// remove the declare @field since have matched against it
unusedDecafs.remove(decaF);
} else {
if (!decaF.isStarredAnnotationPattern())
worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf
}
}
// Multiple secondary passes
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
// lets have another go
List forRemoval = new ArrayList();
for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter.next();
if (decaF.matches(aBcelField,world)) {
// below code is for recursive things
if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) {
// remove the declare @field since don't want an error when
// the annotation is already there
unusedDecafs.remove(decaF);
continue; // skip this one...
}
aBcelField.addAnnotation(decaF.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]);
isChanged = true;
modificationOccured = true;
forRemoval.add(decaF);
// remove the declare @field since have matched against it
unusedDecafs.remove(decaF);
}
}
worthRetrying.removeAll(forRemoval);
}
}
}
checkUnusedDeclareAtTypes(unusedDecafs,true);
}
return isChanged;
}
// bug 99191 - put out an error message if the type doesn't exist
/**
* Report an error if the reason a "declare @method/ctor/field" was not used was because the member
* specified does not exist. This method is passed some set of declare statements that didn't
* match and a flag indicating whether the set contains declare @field or declare @method/ctor
* entries.
*/
private void checkUnusedDeclareAtTypes(Set unusedDecaTs, boolean isDeclareAtField) {
for (Iterator iter = unusedDecaTs.iterator(); iter.hasNext();) {
DeclareAnnotation declA = (DeclareAnnotation) iter.next();
// Error if an exact type pattern was specified
if ((declA.isExactPattern() ||
(declA.getSignaturePattern().getDeclaringType() instanceof ExactTypePattern))
&& (!declA.getSignaturePattern().getName().isAny()
|| (declA.getKind() == DeclareAnnotation.AT_CONSTRUCTOR))) {
// Quickly check if an ITD meets supplies the 'missing' member
boolean itdMatch = false;
List lst = clazz.getType().getInterTypeMungers();
for (Iterator iterator = lst.iterator(); iterator.hasNext() && !itdMatch;) {
BcelTypeMunger element = (BcelTypeMunger) iterator.next();
if (element.getMunger() instanceof NewFieldTypeMunger) {
NewFieldTypeMunger nftm = (NewFieldTypeMunger)element.getMunger();
itdMatch = declA.getSignaturePattern().matches(nftm.getSignature(),world,false);
}else if (element.getMunger() instanceof NewMethodTypeMunger) {
NewMethodTypeMunger nmtm = (NewMethodTypeMunger)element.getMunger();
itdMatch = declA.getSignaturePattern().matches(nmtm.getSignature(),world,false);
} else if (element.getMunger() instanceof NewConstructorTypeMunger) {
NewConstructorTypeMunger nctm = (NewConstructorTypeMunger)element.getMunger();
itdMatch = declA.getSignaturePattern().matches(nctm.getSignature(),world,false);
}
}
if (!itdMatch) {
IMessage message = null;
if (isDeclareAtField) {
message = new Message(
"The field '"+ declA.getSignaturePattern().toString() +
"' does not exist", declA.getSourceLocation() , true);
} else {
message = new Message(
"The method '"+ declA.getSignaturePattern().toString() +
"' does not exist", declA.getSourceLocation() , true);
}
world.getMessageHandler().handleMessage(message);
}
}
}
}
// TAG: WeavingMessage
private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, Field[] fields, int fieldCounter, DeclareAnnotation decaF) {
if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){
Field theField = fields[fieldCounter];
world.getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES,
new String[]{
theField.toString() + "' of type '" + clazz.getName(),
clazz.getFileName(),
decaF.getAnnotationString(),
"field",
decaF.getAspect().toString(),
Utility.beautifyLocation(decaF.getSourceLocation())}));
}
}
/**
* Check if a resolved member (field/method/ctor) already has an annotation, if it
* does then put out a warning and return true
*/
private boolean doesAlreadyHaveAnnotation(ResolvedMember rm,DeclareAnnotation deca,List reportedProblems) {
if (rm.hasAnnotation(deca.getAnnotationTypeX())) {
if (world.getLint().elementAlreadyAnnotated.isEnabled()) {
Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode());
if (!reportedProblems.contains(uniqueID)) {
reportedProblems.add(uniqueID);
world.getLint().elementAlreadyAnnotated.signal(
new String[]{rm.toString(),deca.getAnnotationTypeX().toString()},
rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()});
}
}
return true;
}
return false;
}
private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm,ResolvedMember itdfieldsig,DeclareAnnotation deca,List reportedProblems) {
if (rm != null && rm.hasAnnotation(deca.getAnnotationTypeX())) {
if (world.getLint().elementAlreadyAnnotated.isEnabled()) {
Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode());
if (!reportedProblems.contains(uniqueID)) {
reportedProblems.add(uniqueID);
reportedProblems.add(new Integer(itdfieldsig.hashCode()*deca.hashCode()));
world.getLint().elementAlreadyAnnotated.signal(
new String[]{rm.toString(),deca.getAnnotationTypeX().toString()},
rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()});
}
}
return true;
}
return false;
}
private Set findAspectsForMungers(LazyMethodGen mg) {
Set aspectsAffectingType = new HashSet();
for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) {
BcelShadow aShadow = (BcelShadow) iter.next();
// Mungers in effect on that shadow
for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) {
ShadowMunger aMunger = (ShadowMunger) iter2.next();
if (aMunger instanceof BcelAdvice) {
BcelAdvice bAdvice = (BcelAdvice)aMunger;
if(bAdvice.getConcreteAspect() != null){
aspectsAffectingType.add(bAdvice.getConcreteAspect().getName());
}
} else {
// It is a 'Checker' - we don't need to remember aspects that only contributed Checkers...
}
}
}
return aspectsAffectingType;
}
private boolean inlineSelfConstructors(List methodGens) {
boolean inlinedSomething = false;
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen) i.next();
if (! mg.getName().equals("<init>")) continue;
InstructionHandle ih = findSuperOrThisCall(mg);
if (ih != null && isThisCall(ih)) {
LazyMethodGen donor = getCalledMethod(ih);
inlineMethod(donor, mg, ih);
inlinedSomething = true;
}
}
return inlinedSomething;
}
private void positionAndImplement(List initializationShadows) {
for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) {
BcelShadow s = (BcelShadow) i.next();
positionInitializationShadow(s);
//s.getEnclosingMethod().print();
s.implement();
}
}
private void positionInitializationShadow(BcelShadow s) {
LazyMethodGen mg = s.getEnclosingMethod();
InstructionHandle call = findSuperOrThisCall(mg);
InstructionList body = mg.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow((BcelShadow) s);
if (s.getKind() == Shadow.PreInitialization) {
// XXX assert first instruction is an ALOAD_0.
// a pre shadow goes from AFTER the first instruction (which we believe to
// be an ALOAD_0) to just before the call to super
r.associateWithTargets(
Range.genStart(body, body.getStart().getNext()),
Range.genEnd(body, call.getPrev()));
} else {
// assert s.getKind() == Shadow.Initialization
r.associateWithTargets(
Range.genStart(body, call.getNext()),
Range.genEnd(body));
}
}
private boolean isThisCall(InstructionHandle ih) {
INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction();
return inst.getClassName(cpg).equals(clazz.getName());
}
/** inline a particular call in bytecode.
*
* @param donor the method we want to inline
* @param recipient the method containing the call we want to inline
* @param call the instructionHandle in recipient's body holding the call we want to
* inline.
*/
public static void inlineMethod(
LazyMethodGen donor,
LazyMethodGen recipient,
InstructionHandle call)
{
// assert recipient.contains(call)
/* Implementation notes:
*
* We allocate two slots for every tempvar so we don't screw up
* longs and doubles which may share space. This could be conservatively avoided
* (no reference to a long/double instruction, don't do it) or packed later.
* Right now we don't bother to pack.
*
* Allocate a new var for each formal param of the inlined. Fill with stack
* contents. Then copy the inlined instructions in with the appropriate remap
* table. Any framelocs used by locals in inlined are reallocated to top of
* frame,
*/
final InstructionFactory fact = recipient.getEnclosingClass().getFactory();
IntMap frameEnv = new IntMap();
// this also sets up the initial environment
InstructionList argumentStores =
genArgumentStores(donor, recipient, frameEnv, fact);
InstructionList inlineInstructions =
genInlineInstructions(donor, recipient, frameEnv, fact, false);
inlineInstructions.insert(argumentStores);
recipient.getBody().append(call, inlineInstructions);
Utility.deleteInstruction(call, recipient);
}
/** generate the instructions to be inlined.
*
* @param donor the method from which we will copy (and adjust frame and jumps)
* instructions.
* @param recipient the method the instructions will go into. Used to get the frame
* size so we can allocate new frame locations for locals in donor.
* @param frameEnv an environment to map from donor frame to recipient frame,
* initially populated with argument locations.
* @param fact an instruction factory for recipient
*/
static InstructionList genInlineInstructions(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact,
boolean keepReturns)
{
InstructionList footer = new InstructionList();
InstructionHandle end = footer.append(InstructionConstants.NOP);
InstructionList ret = new InstructionList();
InstructionList sourceList = donor.getBody();
Map srcToDest = new HashMap();
ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen();
ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen();
boolean isAcrossClass = donorCpg != recipientCpg;
// first pass: copy the instructions directly, populate the srcToDest map,
// fix frame instructions
for (InstructionHandle src = sourceList.getStart();
src != null;
src = src.getNext())
{
Instruction fresh = Utility.copyInstruction(src.getInstruction());
InstructionHandle dest;
if (fresh instanceof CPInstruction) {
// need to reset index to go to new constant pool. This is totally
// a computation leak... we're testing this LOTS of times. Sigh.
if (isAcrossClass) {
CPInstruction cpi = (CPInstruction) fresh;
cpi.setIndex(
recipientCpg.addConstant(
donorCpg.getConstant(cpi.getIndex()),
donorCpg));
}
}
if (src.getInstruction() == Range.RANGEINSTRUCTION) {
dest = ret.append(Range.RANGEINSTRUCTION);
} else if (fresh instanceof ReturnInstruction) {
if (keepReturns) {
dest = ret.append(fresh);
} else {
dest =
ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end));
}
} else if (fresh instanceof BranchInstruction) {
dest = ret.append((BranchInstruction) fresh);
} else if (
fresh instanceof LocalVariableInstruction || fresh instanceof RET) {
IndexedInstruction indexed = (IndexedInstruction) fresh;
int oldIndex = indexed.getIndex();
int freshIndex;
if (!frameEnv.hasKey(oldIndex)) {
freshIndex = recipient.allocateLocal(2);
frameEnv.put(oldIndex, freshIndex);
} else {
freshIndex = frameEnv.get(oldIndex);
}
indexed.setIndex(freshIndex);
dest = ret.append(fresh);
} else {
dest = ret.append(fresh);
}
srcToDest.put(src, dest);
}
// second pass: retarget branch instructions, copy ranges and tags
Map tagMap = new HashMap();
Map shadowMap = new HashMap();
for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart();
dest != null;
dest = dest.getNext(), src = src.getNext()) {
Instruction inst = dest.getInstruction();
// retarget branches
if (inst instanceof BranchInstruction) {
BranchInstruction branch = (BranchInstruction) inst;
InstructionHandle oldTarget = branch.getTarget();
InstructionHandle newTarget =
(InstructionHandle) srcToDest.get(oldTarget);
if (newTarget == null) {
// assert this is a GOTO
// this was a return instruction we previously replaced
} else {
branch.setTarget(newTarget);
if (branch instanceof Select) {
Select select = (Select) branch;
InstructionHandle[] oldTargets = select.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
select.setTarget(
k,
(InstructionHandle) srcToDest.get(oldTargets[k]));
}
}
}
}
//copy over tags and range attributes
InstructionTargeter[] srcTargeters = src.getTargeters();
if (srcTargeters != null) {
for (int j = srcTargeters.length - 1; j >= 0; j--) {
InstructionTargeter old = srcTargeters[j];
if (old instanceof Tag) {
Tag oldTag = (Tag) old;
Tag fresh = (Tag) tagMap.get(oldTag);
if (fresh == null) {
fresh = oldTag.copy();
tagMap.put(oldTag, fresh);
}
dest.addTargeter(fresh);
} else if (old instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) old;
if (er.getStart() == src) {
ExceptionRange freshEr =
new ExceptionRange(
recipient.getBody(),
er.getCatchType(),
er.getPriority());
freshEr.associateWithTargets(
dest,
(InstructionHandle)srcToDest.get(er.getEnd()),
(InstructionHandle)srcToDest.get(er.getHandler()));
}
} else if (old instanceof ShadowRange) {
ShadowRange oldRange = (ShadowRange) old;
if (oldRange.getStart() == src) {
BcelShadow oldShadow = oldRange.getShadow();
BcelShadow freshEnclosing =
oldShadow.getEnclosingShadow() == null
? null
: (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow());
BcelShadow freshShadow =
oldShadow.copyInto(recipient, freshEnclosing);
ShadowRange freshRange = new ShadowRange(recipient.getBody());
freshRange.associateWithShadow(freshShadow);
freshRange.associateWithTargets(
dest,
(InstructionHandle) srcToDest.get(oldRange.getEnd()));
shadowMap.put(oldRange, freshRange);
//recipient.matchedShadows.add(freshShadow);
// XXX should go through the NEW copied shadow and update
// the thisVar, targetVar, and argsVar
// ??? Might want to also go through at this time and add
// "extra" vars to the shadow.
}
}
}
}
}
if (!keepReturns) ret.append(footer);
return ret;
}
/** generate the argument stores in preparation for inlining.
*
* @param donor the method we will inline from. Used to get the signature.
* @param recipient the method we will inline into. Used to get the frame size
* so we can allocate fresh locations.
* @param frameEnv an empty environment we populate with a map from donor frame to
* recipient frame.
* @param fact an instruction factory for recipient
*/
private static InstructionList genArgumentStores(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact)
{
InstructionList ret = new InstructionList();
int donorFramePos = 0;
// writing ret back to front because we're popping.
if (! donor.isStatic()) {
int targetSlot = recipient.allocateLocal(Type.OBJECT);
ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot));
frameEnv.put(donorFramePos, targetSlot);
donorFramePos += 1;
}
Type[] argTypes = donor.getArgumentTypes();
for (int i = 0, len = argTypes.length; i < len; i++) {
Type argType = argTypes[i];
int argSlot = recipient.allocateLocal(argType);
ret.insert(InstructionFactory.createStore(argType, argSlot));
frameEnv.put(donorFramePos, argSlot);
donorFramePos += argType.getSize();
}
return ret;
}
/** get a called method: Assumes the called method is in this class,
* and the reference to it is exact (a la INVOKESPECIAL).
*
* @param ih The InvokeInstruction instructionHandle pointing to the called method.
*/
private LazyMethodGen getCalledMethod(
InstructionHandle ih)
{
InvokeInstruction inst = (InvokeInstruction) ih.getInstruction();
String methodName = inst.getName(cpg);
String signature = inst.getSignature(cpg);
return clazz.getLazyMethodGen(methodName, signature);
}
private void weaveInAddedMethods() {
Collections.sort(addedLazyMethodGens,
new Comparator() {
public int compare(Object a, Object b) {
LazyMethodGen aa = (LazyMethodGen) a;
LazyMethodGen bb = (LazyMethodGen) b;
int i = aa.getName().compareTo(bb.getName());
if (i != 0) return i;
return aa.getSignature().compareTo(bb.getSignature());
}
}
);
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
clazz.addMethodGen((LazyMethodGen)i.next());
}
}
void addPerSingletonField(Member field) {
ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType());
String aspectName = field.getReturnType().getName();
LazyMethodGen clinit = clazz.getStaticInitializer();
InstructionList setup = new InstructionList();
InstructionFactory fact = clazz.getFactory();
setup.append(fact.createNew(aspectType));
setup.append(InstructionFactory.createDup(1));
setup.append(fact.createInvoke(
aspectName,
"<init>",
Type.VOID,
new Type[0],
Constants.INVOKESPECIAL));
setup.append(
fact.createFieldAccess(
aspectName,
field.getName(),
aspectType,
Constants.PUTSTATIC));
clinit.getBody().insert(setup);
}
/**
* Returns null if this is not a Java constructor, and then we won't
* weave into it at all
*/
private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) {
int depth = 1;
InstructionHandle start = mg.getBody().getStart();
while (true) {
if (start == null) return null;
Instruction inst = start.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth--;
if (depth == 0) return start;
} else if (inst instanceof NEW) {
depth++;
}
start = start.getNext();
}
}
// ----
private boolean match(LazyMethodGen mg) {
BcelShadow enclosingShadow;
List shadowAccumulator = new ArrayList();
// we want to match ajsynthetic constructors...
if (mg.getName().equals("<init>")) {
return matchInit(mg, shadowAccumulator);
} else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) {
return false;
} else {
if (mg.getName().equals("<clinit>")) {
clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg);
//System.err.println(enclosingShadow);
} else if (mg.isAdviceMethod()) {
enclosingShadow = BcelShadow.makeAdviceExecution(world, mg);
} else {
AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature();
if (effective == null) {
enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows);
} else if (effective.isWeaveBody()) {
ResolvedMember rm = effective.getEffectiveSignature();
// Annotations for things with effective signatures are never stored in the effective
// signature itself - we have to hunt for them. Storing them in the effective signature
// would mean keeping two sets up to date (no way!!)
fixAnnotationsForResolvedMember(rm,mg.getMemberView());
enclosingShadow =
BcelShadow.makeShadowForMethod(world,mg,effective.getShadowKind(),rm);
} else {
return false;
}
}
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
match(mg, h, enclosingShadow, shadowAccumulator);
}
}
// FIXME asc change from string match if we can, rather brittle. this check actually prevents field-exec jps
if (canMatch(enclosingShadow.getKind()) && !mg.getName().startsWith("ajc$interFieldInit")) {
if (match(enclosingShadow, shadowAccumulator)) {
enclosingShadow.init();
}
}
mg.matchedShadows = shadowAccumulator;
return !shadowAccumulator.isEmpty();
}
}
private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) {
BcelShadow enclosingShadow;
// XXX the enclosing join point is wrong for things before ignoreMe.
InstructionHandle superOrThisCall = findSuperOrThisCall(mg);
// we don't walk bodies of things where it's a wrong constructor thingie
if (superOrThisCall == null) return false;
enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall);
if (mg.getEffectiveSignature() != null) {
enclosingShadow.setMatchingSignature(mg.getEffectiveSignature().getEffectiveSignature());
}
// walk the body
boolean beforeSuperOrThisCall = true;
if (shouldWeaveBody(mg)) {
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
if (h == superOrThisCall) {
beforeSuperOrThisCall = false;
continue;
}
match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator);
}
}
if (canMatch(Shadow.ConstructorExecution))
match(enclosingShadow, shadowAccumulator);
}
// XXX we don't do pre-inits of interfaces
// now add interface inits
if (superOrThisCall != null && ! isThisCall(superOrThisCall)) {
InstructionHandle curr = enclosingShadow.getRange().getStart();
for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) {
IfaceInitList l = (IfaceInitList) i.next();
Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType);
BcelShadow initShadow =
BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig);
// insert code in place
InstructionList inits = genInitInstructions(l.list, false);
if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) {
initShadow.initIfaceInitializer(curr);
initShadow.getRange().insert(inits, Range.OutsideBefore);
}
}
// now we add our initialization code
InstructionList inits = genInitInstructions(addedThisInitializers, false);
enclosingShadow.getRange().insert(inits, Range.OutsideBefore);
}
// actually, you only need to inline the self constructors that are
// in a particular group (partition the constructors into groups where members
// call or are called only by those in the group). Then only inline
// constructors
// in groups where at least one initialization jp matched. Future work.
boolean addedInitialization =
match(
BcelShadow.makeUnfinishedInitialization(world, mg),
initializationShadows);
addedInitialization |=
match(
BcelShadow.makeUnfinishedPreinitialization(world, mg),
initializationShadows);
mg.matchedShadows = shadowAccumulator;
return addedInitialization || !shadowAccumulator.isEmpty();
}
private boolean shouldWeaveBody(LazyMethodGen mg) {
if (mg.isBridgeMethod()) return false;
if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>");
AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature();
if (a != null) return a.isWeaveBody();
return true;
}
/**
* first sorts the mungers, then gens the initializers in the right order
*/
private InstructionList genInitInstructions(List list, boolean isStatic) {
list = PartialOrder.sort(list);
if (list == null) {
throw new BCException("circularity in inter-types");
}
InstructionList ret = new InstructionList();
for (Iterator i = list.iterator(); i.hasNext();) {
ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next();
NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger();
ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType());
if (!isStatic) ret.append(InstructionConstants.ALOAD_0);
ret.append(Utility.createInvoke(fact, world, initMethod));
}
return ret;
}
private void match(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
Instruction i = ih.getInstruction();
if ((i instanceof FieldInstruction) &&
(canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet))
) {
FieldInstruction fi = (FieldInstruction) i;
if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) {
// check for sets of constant fields. We first check the previous
// instruction. If the previous instruction is a LD_WHATEVER (push
// constant on the stack) then we must resolve the field to determine
// if it's final. If it is final, then we don't generate a shadow.
InstructionHandle prevHandle = ih.getPrev();
Instruction prevI = prevHandle.getInstruction();
if (Utility.isConstantPushInstruction(prevI)) {
Member field = BcelWorld.makeFieldJoinPointSignature(clazz, (FieldInstruction) i);
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
} else if (Modifier.isFinal(resolvedField.getModifiers())) {
// it's final, so it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
} else {
if (canMatch(Shadow.FieldSet))
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
if (canMatch(Shadow.FieldSet))
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
if (canMatch(Shadow.FieldGet))
matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else if (i instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction) i;
if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) {
if (canMatch(Shadow.ConstructorCall))
match(
BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
} else if (ii instanceof INVOKESPECIAL) {
String onTypeName = ii.getClassName(cpg);
if (onTypeName.equals(mg.getEnclosingClass().getName())) {
// we are private
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
} else {
// we are a super call, and this is not a join point in AspectJ-1.{0,1}
}
} else {
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
}
}
// performance optimization... we only actually care about ASTORE instructions,
// since that's what every javac type thing ever uses to start a handler, but for
// now we'll do this for everybody.
if (!canMatch(Shadow.ExceptionHandler)) return;
if (Range.isRangeHandle(ih)) return;
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int j = 0; j < targeters.length; j++) {
InstructionTargeter t = targeters[j];
if (t instanceof ExceptionRange) {
// assert t.getHandler() == ih
ExceptionRange er = (ExceptionRange) t;
if (er.getCatchType() == null) continue;
if (isInitFailureHandler(ih)) return;
match(
BcelShadow.makeExceptionHandler(
world,
er,
mg, ih, enclosingShadow),
shadowAccumulator);
}
}
}
}
private boolean isInitFailureHandler(InstructionHandle ih) {
// Skip the astore_0 and aload_0 at the start of the handler and
// then check if the instruction following these is
// 'putstatic ajc$initFailureCause'. If it is then we are
// in the handler we created in AspectClinit.generatePostSyntheticCode()
InstructionHandle twoInstructionsAway = ih.getNext().getNext();
if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) {
String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg);
if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true;
}
return false;
}
private void matchSetInstruction(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (
Modifier.isFinal(resolvedField.getModifiers())
&& Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) {
// it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(
BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
BcelShadow bs = BcelShadow.makeFieldGet(world,resolvedField,mg,ih,enclosingShadow);
String cname = fi.getClassName(cpg);
if (!resolvedField.getDeclaringType().getName().equals(cname)) {
bs.setActualTargetType(cname);
}
match(bs, shadowAccumulator);
}
}
/**
* For some named resolved type, this method looks for a member with a particular name -
* it should only be used when you truly believe there is only one member with that
* name in the type as it returns the first one it finds.
*/
private ResolvedMember findResolvedMemberNamed(ResolvedType type,String methodName) {
ResolvedMember[] allMethods = type.getDeclaredMethods();
for (int i = 0; i < allMethods.length; i++) {
ResolvedMember member = allMethods[i];
if (member.getName().equals(methodName)) return member;
}
return null;
}
/**
* For a given resolvedmember, this will discover the real annotations for it.
* <b>Should only be used when the resolvedmember is the contents of an effective signature
* attribute, as thats the only time when the annotations aren't stored directly in the
* resolvedMember</b>
* @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing
* @param declaredSig the real sig 'blah.ajc$xxx'
*/
private void fixAnnotationsForResolvedMember(ResolvedMember rm,ResolvedMember declaredSig) {
try {
UnresolvedType memberHostType = declaredSig.getDeclaringType();
ResolvedType[] annotations = (ResolvedType[])mapToAnnotations.get(rm);
String methodName = declaredSig.getName();
// FIXME asc shouldnt really rely on string names !
if (annotations == null) {
if (rm.getKind()==Member.FIELD) {
if (methodName.startsWith("ajc$inlineAccessField")) {
ResolvedMember resolvedDooberry = world.resolve(rm);
annotations = resolvedDooberry.getAnnotationTypes();
} else {
ResolvedMember realthing = AjcMemberMaker.interFieldInitializer(rm,memberHostType);
ResolvedMember resolvedDooberry = world.resolve(realthing);
annotations = resolvedDooberry.getAnnotationTypes();
}
} else if (rm.getKind()==Member.METHOD && !rm.isAbstract()) {
if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) {
ResolvedMember resolvedDooberry = world.resolve(declaredSig);
annotations = resolvedDooberry.getAnnotationTypes();
} else {
ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world),memberHostType).resolve(world);
// ResolvedMember resolvedDooberry = world.resolve(realthing);
ResolvedMember theRealMember = findResolvedMemberNamed(memberHostType.resolve(world),realthing.getName());
// AMC temp guard for M4
if (theRealMember == null) {
throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified");
}
annotations = theRealMember.getAnnotationTypes();
}
} else if (rm.getKind()==Member.CONSTRUCTOR) {
ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(),rm.getParameterTypes());
ResolvedMember resolvedDooberry = world.resolve(realThing);
// AMC temp guard for M4
if (resolvedDooberry == null) {
throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified");
}
annotations = resolvedDooberry.getAnnotationTypes();
}
if (annotations == null)
annotations = new ResolvedType[0];
mapToAnnotations.put(rm,annotations);
}
rm.setAnnotationTypes(annotations);
}
catch (UnsupportedOperationException ex) {
throw ex;
} catch (Throwable t) {
//FIXME asc remove this catch after more testing has confirmed the above stuff is OK
throw new BCException("Unexpectedly went bang when searching for annotations on "+rm,t);
}
}
private void matchInvokeInstruction(LazyMethodGen mg,
InstructionHandle ih,
InvokeInstruction invoke,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
String methodName = invoke.getName(cpg);
if (methodName.startsWith(NameMangler.PREFIX)) {
Member jpSig =
world.makeJoinPointSignatureForMethodInvocation(clazz, invoke);
ResolvedMember declaredSig = jpSig.resolve(world);
//System.err.println(method + ", declaredSig: " +declaredSig);
if (declaredSig == null) return;
if (declaredSig.getKind() == Member.FIELD) {
Shadow.Kind kind;
if (jpSig.getReturnType().equals(ResolvedType.VOID)) {
kind = Shadow.FieldSet;
} else {
kind = Shadow.FieldGet;
}
if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet))
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
kind, declaredSig),
shadowAccumulator);
} else {
AjAttribute.EffectiveSignatureAttribute effectiveSig =
declaredSig.getEffectiveSignature();
if (effectiveSig == null) return;
//System.err.println("call to inter-type member: " + effectiveSig);
if (effectiveSig.isWeaveBody()) return;
ResolvedMember rm = effectiveSig.getEffectiveSignature();
fixAnnotationsForResolvedMember(rm,declaredSig); // abracadabra
if (canMatch(effectiveSig.getShadowKind()))
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
effectiveSig.getShadowKind(), rm), shadowAccumulator);
}
} else {
if (canMatch(Shadow.MethodCall))
match(
BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private boolean match(BcelShadow shadow, List shadowAccumulator) {
//System.err.println("match: " + shadow);
ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_SHADOW, shadow);
boolean isMatched = false;
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger munger = (ShadowMunger)i.next();
ContextToken mungerMatchToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MATCHING_POINTCUT, munger.getPointcut());
if (munger.match(shadow, world)) {
WeaverMetrics.recordMatchResult(true);// Could pass: munger
shadow.addMunger(munger);
isMatched = true;
if (shadow.getKind() == Shadow.StaticInitialization) {
clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation());
}
} else {
WeaverMetrics.recordMatchResult(false); // Could pass: munger
}
CompilationAndWeavingContext.leavingPhase(mungerMatchToken);
}
if (isMatched) shadowAccumulator.add(shadow);
CompilationAndWeavingContext.leavingPhase(shadowMatchToken);
return isMatched;
}
// ----
private void implement(LazyMethodGen mg) {
List shadows = mg.matchedShadows;
if (shadows == null) return;
// We depend on a partial order such that inner shadows are earlier on the list
// than outer shadows. That's fine. This order is preserved if:
// A preceeds B iff B.getStart() is LATER THAN A.getStart().
for (Iterator i = shadows.iterator(); i.hasNext(); ) {
BcelShadow shadow = (BcelShadow)i.next();
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.IMPLEMENTING_ON_SHADOW,shadow);
shadow.implement();
CompilationAndWeavingContext.leavingPhase(tok);
}
int ii = mg.getMaxLocals();
mg.matchedShadows = null;
}
// ----
public LazyClassGen getLazyClassGen() {
return clazz;
}
public List getShadowMungers() {
return shadowMungers;
}
public BcelWorld getWorld() {
return world;
}
// Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info
public static void setReweavableMode(boolean mode) {
inReweavableMode = mode;
}
public static boolean getReweavableMode() {
return inReweavableMode;
}
public String toString() {
return "BcelClassWeaver instance for : "+clazz;
}
}
|
115,204
|
Bug 115204 WildAnnotationTypePattern.java:61 NPE after renaming method-annotation class
|
Sorry I don't have a small test case. It looks like the NPE happens when the annotation refered to by a (compiled?) aspect no longer exists because it was renamed. The class being woven is the first one (alphabetically), and the method being woven does not have the annotation on it. Let me know if you need a test case. (And sorry for the late bugs - I'm just now writing the article.) ------------------------------------------------------------------ java.lang.NullPointerException at org.aspectj.weaver.patterns.WildAnnotationTypePattern.matches(WildAnnotationTypePattern.java:61) at org.aspectj.weaver.patterns.SignaturePattern.matchesAnnotations(SignaturePattern.java:321) at org.aspectj.weaver.patterns.SignaturePattern.matchesExactly(SignaturePattern.java:169) at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:131) at org.aspectj.weaver.patterns.WithincodePointcut.matchInternal(WithincodePointcut.java:73) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:143) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:143) at org.aspectj.weaver.patterns.AndPointcut.matchInternal(AndPointcut.java:55) at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:143) 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:97) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1749) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1736) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1533) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1359) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:382) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:98) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1478) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1443) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1217) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1021) 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:759) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:225) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:151) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public class com.isberg.articles.aop7.bean.ABeanTest$APlus extends java.lang.Object: TypeMungers: [(BcelTypeMunger ResolvedTypeMunger(Method, java.lang.String com.isberg.articles.aop7.bean.ABeanTest$CPlus.propertyName(java.lang.String)))] declares: [declare parents: com.isberg.articles.aop7.bean.ABeanTest$CPlus extends (com.isberg.articles.aop7.bean.ABean$IBean);] private static Throwable ajc$initFailureCause public static final com.isberg.articles.aop7.bean.ABeanTest$APlus ajc$perSingletonInstance static void <clinit>(): staticinitialization(void com.isberg.articles.aop7.bean.ABeanTest$APlus.<clinit>()) | catch java.lang.Throwable -> E0 | | INVOKESTATIC com.isberg.articles.aop7.bean.ABeanTest$APlus.ajc$postClinit ()V (line 125) | catch java.lang.Throwable -> E0 | GOTO L0 | E0: ASTORE_0 | ALOAD_0 | PUTSTATIC com.isberg.articles.aop7.bean.ABeanTest$APlus.ajc$initFailureCause Ljava/lang/Throwable; | L0: RETURN staticinitialization(void com.isberg.articles.aop7.bean.ABeanTest$APlus.<clinit>()) end static void <clinit>() void <init>(): ALOAD_0 // com.isberg.articles.aop7.bean.ABeanTest$APlus this (line 125) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void com.isberg.articles.aop7.bean.ABeanTest$APlus.<init>()) | RETURN constructor-execution(void com.isberg.articles.aop7.bean.ABeanTest$APlus.<init>()) end void <init>() void ajc$declare_parents_1() org.aspectj.weaver.MethodDeclarationLineNumber: 127:3678 : RETURN (line 127) end void ajc$declare_parents_1() public static String ajc$interMethod$com_isberg_articles_aop7_bean_ABeanTest$APlus$com_isberg_articles_aop7_bean_ABeanTest$CPlus$propertyName(com.isberg.articles.aop7.bean.ABeanTest$CPlus, String) EffectiveSignatureAttribute(java.lang.String com.isberg.articles.aop7.bean.ABeanTest$CPlus.propertyName(java.lang.String), method-execution) : method-execution(java.lang.String com.isberg.articles.aop7.bean.ABeanTest$CPlus.propertyName(java.lang.String)) | ALOAD_0 // com.isberg.articles.aop7.bean.ABeanTest$CPlus ajc$this_ (line 132) | ALOAD_1 // java.lang.String methodName | INVOKESTATIC com.isberg.articles.aop7.bean.ABean.ajc$interMethod$com_isberg_articles_aop7_bean_ABean$com_isberg_articles_aop7_bean_ABean$IBean$propertyName (Lcom/isberg/articles/aop7/bean/ABean$IBean;Ljava/lang/String;)Ljava/lang/String; | ASTORE_2 | LDC "something" (line 133) | ALOAD_2 // java.lang.String result | method-call(boolean java.lang.String.equals(java.lang.Object)) | | INVOKEVIRTUAL java.lang.String.equals (Ljava/lang/Object;)Z | method-call(boolean java.lang.String.equals(java.lang.Object)) | IFEQ L0 | LDC "a" (line 134) | ASTORE_2 // java.lang.String result | L0: ALOAD_2 // java.lang.String result (line 136) | ARETURN method-execution(java.lang.String com.isberg.articles.aop7.bean.ABeanTest$CPlus.propertyName(java.lang.String)) end public static String ajc$interMethod$com_isberg_articles_aop7_bean_ABeanTest$APlus$com_isberg_articles_aop7_bean_ABeanTest$CPlus$propertyName(com.isberg.articles.aop7.bean.ABeanTest$CPlus, String) public static String ajc$interMethodDispatch1$com_isberg_articles_aop7_bean_ABeanTest$APlus$com_isberg_articles_aop7_bean_ABeanTest$CPlus$propertyName(com.isberg.articles.aop7.bean.ABeanTest$CPlus, String) EffectiveSignatureAttribute(java.lang.String com.isberg.articles.aop7.bean.ABeanTest$CPlus.propertyName(java.lang.String), method-call) : ALOAD_0 ALOAD_1 INVOKEVIRTUAL com.isberg.articles.aop7.bean.ABeanTest$CPlus.propertyName (Ljava/lang/String;)Ljava/lang/String; ARETURN end public static String ajc$interMethodDispatch1$com_isberg_articles_aop7_bean_ABeanTest$APlus$com_isberg_articles_aop7_bean_ABeanTest$CPlus$propertyName(com.isberg.articles.aop7.bean.ABeanTest$CPlus, String) public static com.isberg.articles.aop7.bean.ABeanTest$APlus aspectOf() org.aspectj.weaver.AjAttribute$AjSynthetic@591171 : GETSTATIC com.isberg.articles.aop7.bean.ABeanTest$APlus.ajc$perSingletonInstance Lcom/isberg/articles/aop7/bean/ABeanTest$APlus; IFNONNULL L0 NEW org.aspectj.lang.NoAspectBoundException DUP LDC "com_isberg_articles_aop7_bean_ABeanTest$APlus" GETSTATIC com.isberg.articles.aop7.bean.ABeanTest$APlus.ajc$initFailureCause Ljava/lang/Throwable; INVOKESPECIAL org.aspectj.lang.NoAspectBoundException.<init> (Ljava/lang/String;Ljava/lang/Throwable;)V ATHROW L0: GETSTATIC com.isberg.articles.aop7.bean.ABeanTest$APlus.ajc$perSingletonInstance Lcom/isberg/articles/aop7/bean/ABeanTest$APlus; ARETURN end public static com.isberg.articles.aop7.bean.ABeanTest$APlus aspectOf() public static boolean hasAspect() org.aspectj.weaver.AjAttribute$AjSynthetic@16e3eb3 : GETSTATIC com.isberg.articles.aop7.bean.ABeanTest$APlus.ajc$perSingletonInstance Lcom/isberg/articles/aop7/bean/ABeanTest$APlus; IFNULL L0 ICONST_1 IRETURN L0: ICONST_0 IRETURN end public static boolean hasAspect() private static void ajc$postClinit() org.aspectj.weaver.AjAttribute$AjSynthetic@d7cf62 : NEW com.isberg.articles.aop7.bean.ABeanTest$APlus DUP INVOKESPECIAL com.isberg.articles.aop7.bean.ABeanTest$APlus.<init> ()V PUTSTATIC com.isberg.articles.aop7.bean.ABeanTest$APlus.ajc$perSingletonInstance Lcom/isberg/articles/aop7/bean/ABeanTest$APlus; RETURN end private static void ajc$postClinit() end public class com.isberg.articles.aop7.bean.ABeanTest$APlus when matching pointcut ((withincode(@(Parallel) * *(..)) && call(void *(..))) && percflow(com.isberg.articles.aop7.concurrent.ParallelMethodImpl on execution(@(Parallel) * *(..)))) when matching shadow method-call(boolean java.lang.String.equals(java.lang.Object)) when weaving type com.isberg.articles.aop7.bean.ABeanTest$APlus when weaving aspects when weaving when batch building BuildConfig[c:\home\ws\main-31\.metadata\.plugins\org.eclipse.ajdt.core\devworks-fall.generated.lst] #Files=70
|
resolved fixed
|
557f5b4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-18T10:09:32Z
| 2005-11-05T11:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/WildAnnotationTypePattern.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Map;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.AnnotatedElement;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
/**
* @author colyer
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class WildAnnotationTypePattern extends AnnotationTypePattern {
private TypePattern typePattern;
private boolean resolved = false;
/**
*
*/
public WildAnnotationTypePattern(TypePattern typePattern) {
super();
this.typePattern = typePattern;
this.setLocation(typePattern.getSourceContext(), typePattern.start, typePattern.end);
}
public TypePattern getTypePattern() {
return typePattern;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.AnnotationTypePattern#matches(org.aspectj.weaver.AnnotatedElement)
*/
public FuzzyBoolean matches(AnnotatedElement annotated) {
if (!resolved) {
throw new IllegalStateException("Can't match on an unresolved annotation type pattern");
}
// matches if the type of any of the annotations on the AnnotatedElement is
// matched by the typePattern.
ResolvedType[] annTypes = annotated.getAnnotationTypes();
for (int i = 0; i < annTypes.length; i++) {
if (typePattern.matches(annTypes[i],TypePattern.STATIC).alwaysTrue()) {
return FuzzyBoolean.YES;
}
}
return FuzzyBoolean.NO;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolve(org.aspectj.weaver.World)
*/
public void resolve(World world) {
// nothing to do...
resolved = true;
}
/**
* This can modify in place, or return a new TypePattern if the type changes.
*/
public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings,
boolean allowBinding)
{
if (!scope.getWorld().isInJava5Mode()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ANNOTATIONS_NEED_JAVA5),
getSourceLocation()));
return this;
}
if (resolved) return this;
this.typePattern = typePattern.resolveBindings(scope,bindings,false,false);
resolved = true;
if (typePattern instanceof ExactTypePattern) {
ExactTypePattern et = (ExactTypePattern)typePattern;
if (!et.getExactType().resolve(scope.getWorld()).isAnnotation()) {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE,et.getExactType().getName()),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
resolved = false;
}
ExactAnnotationTypePattern eatp = new ExactAnnotationTypePattern(et.getExactType().resolve(scope.getWorld()));
eatp.copyLocationFrom(this);
return eatp;
} else {
return this;
}
}
public AnnotationTypePattern parameterizeWith(Map typeVariableMap) {
WildAnnotationTypePattern ret = new WildAnnotationTypePattern(typePattern.parameterizeWith(typeVariableMap));
ret.copyLocationFrom(this);
ret.resolved = resolved;
return ret;
}
private static final byte VERSION = 1; // rev if ser. form changes
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(AnnotationTypePattern.WILD);
s.writeByte(VERSION);
typePattern.write(s);
writeLocation(s);
}
public static AnnotationTypePattern read(VersionedDataInputStream s,ISourceContext context) throws IOException {
AnnotationTypePattern ret;
byte version = s.readByte();
if (version > VERSION) {
throw new BCException("ExactAnnotationTypePattern was written by a newer version of AspectJ");
}
TypePattern t = TypePattern.read(s,context);
ret = new WildAnnotationTypePattern(t);
ret.readLocation(context,s);
return ret;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (!(obj instanceof WildAnnotationTypePattern)) return false;
WildAnnotationTypePattern other = (WildAnnotationTypePattern) obj;
return other.typePattern.equals(typePattern);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return 17 + 37*typePattern.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return "@(" + typePattern.toString() + ")";
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
tests/java5/ataspectj/annotationGen/RuntimePointcuts.java
|
import org.aspectj.weaver.tools.*;
import java.lang.reflect.*;
public class RuntimePointcuts {
public static void main(String[] args) throws Exception {
PointcutParser parser = new PointcutParser();
PointcutExpression pc1 = parser.parsePointcutExpression("PCLib.anyMethodExecution()");
PointcutParameter param = parser.createPointcutParameter("s",String.class);
PointcutExpression pc2 = parser.parsePointcutExpression("PCLib.joinPointWithStringArg(s)",RuntimePointcuts.class,new PointcutParameter[] {param});
Method foo = RuntimePointcuts.class.getDeclaredMethod("foo", new Class[0]);
Method bar = RuntimePointcuts.class.getDeclaredMethod("bar",new Class[] {String.class});
ShadowMatch fooMatch1 = pc1.matchesMethodExecution(foo);
if (!fooMatch1.alwaysMatches()) throw new RuntimeException("fooMatch1 should always match");
ShadowMatch fooMatch2 = pc2.matchesMethodExecution(foo);
if (!fooMatch2.neverMatches()) throw new RuntimeException("fooMatch2 should never match");
ShadowMatch barMatch1 = pc1.matchesMethodExecution(bar);
if (!barMatch1.alwaysMatches()) throw new RuntimeException("barMatch1 should always match");
ShadowMatch barMatch2 = pc2.matchesMethodExecution(bar);
if (!barMatch2.alwaysMatches()) throw new RuntimeException("barMatch2 should always match");
JoinPointMatch jpm = barMatch2.matchesJoinPoint(new Object(),new Object(),new Object[] {"hello"});
if (!jpm.matches()) throw new RuntimeException("should match at join point");
if (!jpm.getParameterBindings()[0].getBinding().toString().equals("hello"))
throw new RuntimeException("expecting s to be bound to hello");
}
public void foo() {}
public void bar(String s) {}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
tests/java5/reflection/ReflectOnAjcCompiledPointcuts.java
| |
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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");
}
/*
* 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");}
// 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);
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
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.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.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;
}
for (int i = 0; i < anns.length; i++) {
Annotation ann = anns[i];
if ("Lorg/aspectj/lang/annotation/Aspect;".equals(ann.getTypeSignature())) {
return true;
}
}
return false;
} catch (IOException e) {
// assume it is one as a best effort
return true;
}
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/src/org/aspectj/weaver/internal/tools/TypePatternMatcherImpl.java
| |
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/src/org/aspectj/weaver/ltw/LTWWorld.java
| |
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/src/org/aspectj/weaver/ltw/LTWeaver.java
| |
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/src/org/aspectj/weaver/reflect/AnnotationFinder.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.Member;
import java.util.Set;
import org.aspectj.weaver.ResolvedType;
/**
* @author colyer
* Used in 1.4 code to access annotations safely
*/
public interface AnnotationFinder {
Object getAnnotation(ResolvedType annotationType, Object onObject);
Object getAnnotationFromMember(ResolvedType annotationType, Member aMember);
Object getAnnotationFromClass(ResolvedType annotationType, Class aClass);
Set/*UnresolvedType*/ getAnnotations(Member onMember);
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/src/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegate.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.Collection;
import java.util.Collections;
import org.aspectj.weaver.AnnotationTargetKind;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.patterns.PerClause;
/**
* @author colyer
* A delegate for a resolved type that uses runtime type information (java.lang.reflect)
* to answer questions. This class uses only Java 1.4 features to answer questions.
* In a Java 1.5 environment use the Java5ReflectionBasedReferenceTypeDelegate subtype.
*/
public class ReflectionBasedReferenceTypeDelegate implements ReferenceTypeDelegate {
protected Class myClass = null;
private World world;
private ReferenceType resolvedType;
private ResolvedMember[] fields = null;
private ResolvedMember[] methods = null;
private ResolvedType[] interfaces = null;
public ReflectionBasedReferenceTypeDelegate(Class forClass, World inWorld, ReferenceType resolvedType) {
initialize(resolvedType,forClass,inWorld);
}
/** for reflective construction only */
public ReflectionBasedReferenceTypeDelegate() {}
public void initialize(ReferenceType aType, Class aClass, World aWorld) {
this.myClass = aClass;
this.resolvedType = aType;
this.world = aWorld;
}
protected Class getBaseClass() {
return this.myClass;
}
protected World getWorld() {
return this.world;
}
protected ReflectionWorld getReflectionWorld() {
return (ReflectionWorld) this.world;
}
public ReferenceType buildGenericType() {
throw new UnsupportedOperationException("Shouldn't be asking for generic type at 1.4 source level or lower");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#addAnnotation(org.aspectj.weaver.AnnotationX)
*/
public void addAnnotation(AnnotationX annotationX) {
throw new UnsupportedOperationException("Cannot add an annotation to a reflection based delegate");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#isAspect()
*/
public boolean isAspect() {
// we could do better than this in Java 5 by looking at the annotations on the type...
return false;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#isAnnotationStyleAspect()
*/
public boolean isAnnotationStyleAspect() {
// we could do better than this in Java 5 by looking at the annotations on the type...
return false;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#isInterface()
*/
public boolean isInterface() {
return this.myClass.isInterface();
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#isEnum()
*/
public boolean isEnum() {
// cant be an enum in Java 1.4 or prior
return false;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#isAnnotation()
*/
public boolean isAnnotation() {
// cant be an annotation in Java 1.4 or prior
return false;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#isAnnotationWithRuntimeRetention()
*/
public boolean isAnnotationWithRuntimeRetention() {
// cant be an annotation in Java 1.4 or prior
return false;
}
public String getRetentionPolicy() {
// cant be an annotation in Java 1.4 or prior
return null;
}
public boolean canAnnotationTargetType() {
return false;
}
public AnnotationTargetKind[] getAnnotationTargetKinds() {
return null;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#isClass()
*/
public boolean isClass() {
return !this.myClass.isInterface() && !this.myClass.isPrimitive() && !this.myClass.isArray();
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#isGeneric()
*/
public boolean isGeneric() {
// cant be generic in 1.4
return false;
}
public boolean isAnonymous() {
return false;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#isExposedToWeaver()
*/
public boolean isExposedToWeaver() {
// reflection based types are never exposed to the weaver
return false;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#hasAnnotation(org.aspectj.weaver.UnresolvedType)
*/
public boolean hasAnnotation(UnresolvedType ofType) {
// in Java 1.4 we cant have an annotation
return false;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getAnnotations()
*/
public AnnotationX[] getAnnotations() {
// no annotations in Java 1.4
return new AnnotationX[0];
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getAnnotationTypes()
*/
public ResolvedType[] getAnnotationTypes() {
// no annotations in Java 1.4
return new ResolvedType[0];
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getDeclaredFields()
*/
public ResolvedMember[] getDeclaredFields() {
if (fields == null) {
Field[] reflectFields = this.myClass.getDeclaredFields();
this.fields = new ResolvedMember[reflectFields.length];
for (int i = 0; i < reflectFields.length; i++) {
this.fields[i] =
ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(reflectFields[i], world);
}
}
return fields;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getDeclaredInterfaces()
*/
public ResolvedType[] getDeclaredInterfaces() {
if (interfaces == null) {
Class[] reflectInterfaces = this.myClass.getInterfaces();
this.interfaces = new ResolvedType[reflectInterfaces.length];
for (int i = 0; i < reflectInterfaces.length; i++) {
this.interfaces[i] = getReflectionWorld().resolve(reflectInterfaces[i]);
}
}
return interfaces;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getDeclaredMethods()
*/
public ResolvedMember[] getDeclaredMethods() {
if (methods == null) {
Method[] reflectMethods = this.myClass.getDeclaredMethods();
Constructor[] reflectCons = this.myClass.getDeclaredConstructors();
this.methods = new ResolvedMember[reflectMethods.length + reflectCons.length];
for (int i = 0; i < reflectMethods.length; i++) {
this.methods[i] =
ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(reflectMethods[i], world);
}
for (int i = 0; i < reflectCons.length; i++) {
this.methods[i + reflectMethods.length] =
ReflectionBasedReferenceTypeDelegateFactory.createResolvedMember(reflectCons[i], world);
}
}
return methods;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getDeclaredPointcuts()
*/
public ResolvedMember[] getDeclaredPointcuts() {
return new ResolvedMember[0];
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getTypeVariables()
*/
public TypeVariable[] getTypeVariables() {
// no type variables in Java 1.4
return new TypeVariable[0];
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getPerClause()
*/
public PerClause getPerClause() {
// no per clause...
return null;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getDeclares()
*/
public Collection getDeclares() {
// no declares
return Collections.EMPTY_SET;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getTypeMungers()
*/
public Collection getTypeMungers() {
// no type mungers
return Collections.EMPTY_SET;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getPrivilegedAccesses()
*/
public Collection getPrivilegedAccesses() {
// no aspect members..., not used for weaving
return Collections.EMPTY_SET;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getModifiers()
*/
public int getModifiers() {
return this.myClass.getModifiers();
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getSuperclass()
*/
public ResolvedType getSuperclass() {
if (this.myClass.getSuperclass() == null) return null;
return getReflectionWorld().resolve(this.myClass.getSuperclass());
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getWeaverState()
*/
public WeaverStateInfo getWeaverState() {
return null;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getResolvedTypeX()
*/
public ReferenceType getResolvedTypeX() {
return this.resolvedType;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#doesNotExposeShadowMungers()
*/
public boolean doesNotExposeShadowMungers() {
return false;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ReferenceTypeDelegate#getDeclaredGenericSignature()
*/
public String getDeclaredGenericSignature() {
// no generic sig in 1.4
return null;
}
public void ensureDelegateConsistent() {
// Nothing to do - a reflection based delegate can't become inconsistent...
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
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.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) {
try {
Class c = Class.forName(forReferenceType.getName());
if (LangUtil.is15VMOrGreater()) {
ReflectionBasedReferenceTypeDelegate rbrtd = create15Delegate(forReferenceType,c,inWorld);
if (rbrtd!=null) return rbrtd; // can be null if we didn't find the class the delegate logic loads
}
return new ReflectionBasedReferenceTypeDelegate(c,inWorld,forReferenceType);
} catch (ClassNotFoundException cnfEx) {
return null;
}
}
private static ReflectionBasedReferenceTypeDelegate create15Delegate(ReferenceType forReferenceType, Class forClass, World inWorld) {
try {
Class delegateClass = Class.forName("org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate");
ReflectionBasedReferenceTypeDelegate ret = (ReflectionBasedReferenceTypeDelegate) delegateClass.newInstance();
ret.initialize(forReferenceType,forClass,inWorld);
return ret;
} catch (ClassNotFoundException cnfEx) {
return null;
} catch (InstantiationException insEx) {
return null;
} catch (IllegalAccessException illAccEx) {
return null;
}
}
/**
* 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
);
return ret;
}
public static ResolvedMember createResolvedAdviceMember(Method aMethod, World inWorld) {
return 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
);
}
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) {
return new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.CONSTRUCTOR,
toResolvedType(aConstructor.getDeclaringClass(),(ReflectionWorld)inWorld),
aConstructor.getModifiers(),
toResolvedType(aConstructor.getDeclaringClass(),(ReflectionWorld)inWorld),
"init",
toResolvedTypeArray(aConstructor.getParameterTypes(),inWorld),
toResolvedTypeArray(aConstructor.getExceptionTypes(),inWorld),
aConstructor
);
}
public static ResolvedMember createResolvedField(Field aField, World inWorld) {
return 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);
}
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");
}
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;
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/src/org/aspectj/weaver/reflect/ReflectionBasedResolvedMemberImpl.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.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
/**
* Subtype of ResolvedMemberImpl used in reflection world.
* Knows how to get annotations from a java.lang.reflect.Member
*
*/
public class ReflectionBasedResolvedMemberImpl extends ResolvedMemberImpl {
private static AnnotationFinder annotationFinder = null;
static {
try {
Class java15AnnotationFinder = Class.forName("org.aspectj.weaver.reflect.Java15AnnotationFinder");
annotationFinder = (AnnotationFinder) java15AnnotationFinder.newInstance();
} catch(Exception ex) {
// must be on 1.4 or earlier
}
}
private Member reflectMember;
/**
* @param kind
* @param declaringType
* @param modifiers
* @param returnType
* @param name
* @param parameterTypes
*/
public ReflectionBasedResolvedMemberImpl(Kind kind,
UnresolvedType declaringType, int modifiers,
UnresolvedType returnType, String name,
UnresolvedType[] parameterTypes,
Member reflectMember) {
super(kind, declaringType, modifiers, returnType, name, parameterTypes);
this.reflectMember = reflectMember;
}
/**
* @param kind
* @param declaringType
* @param modifiers
* @param returnType
* @param name
* @param parameterTypes
* @param checkedExceptions
*/
public ReflectionBasedResolvedMemberImpl(Kind kind,
UnresolvedType declaringType, int modifiers,
UnresolvedType returnType, String name,
UnresolvedType[] parameterTypes, UnresolvedType[] checkedExceptions,
Member reflectMember) {
super(kind, declaringType, modifiers, returnType, name, parameterTypes,
checkedExceptions);
this.reflectMember = reflectMember;
}
/**
* @param kind
* @param declaringType
* @param modifiers
* @param returnType
* @param name
* @param parameterTypes
* @param checkedExceptions
* @param backingGenericMember
*/
public ReflectionBasedResolvedMemberImpl(Kind kind,
UnresolvedType declaringType, int modifiers,
UnresolvedType returnType, String name,
UnresolvedType[] parameterTypes,
UnresolvedType[] checkedExceptions,
ResolvedMember backingGenericMember,
Member reflectMember) {
super(kind, declaringType, modifiers, returnType, name, parameterTypes,
checkedExceptions, backingGenericMember);
this.reflectMember = reflectMember;
}
/**
* @param kind
* @param declaringType
* @param modifiers
* @param name
* @param signature
*/
public ReflectionBasedResolvedMemberImpl(Kind kind,
UnresolvedType declaringType, int modifiers, String name,
String signature, Member reflectMember) {
super(kind, declaringType, modifiers, name, signature);
this.reflectMember = reflectMember;
}
public boolean hasAnnotation(UnresolvedType ofType) {
unpackAnnotations();
return super.hasAnnotation(ofType);
}
public boolean hasAnnotations() {
unpackAnnotations();
return super.hasAnnotations();
}
public ResolvedType[] getAnnotationTypes() {
unpackAnnotations();
return super.getAnnotationTypes();
}
private void unpackAnnotations() {
if (annotationTypes == null && annotationFinder != null) {
annotationTypes = annotationFinder.getAnnotations(reflectMember);
}
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
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;
/**
* @author colyer
*
*/
public class ReflectionShadow extends Shadow {
private World world;
private ResolvedType enclosingType;
private ResolvedMember enclosingMember;
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();
public static Shadow makeExecutionShadow(World inWorld, java.lang.reflect.Member forMethod) {
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);
}
public static Shadow makeAdviceExecutionShadow(World inWorld, java.lang.reflect.Method forMethod) {
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);
}
public static Shadow makeCallShadow(World inWorld, java.lang.reflect.Member aMember, java.lang.reflect.Member withinCode) {
Shadow enclosingShadow = makeExecutionShadow(inWorld,withinCode);
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);
}
public static Shadow makeCallShadow(World inWorld, java.lang.reflect.Member aMember, Class thisClass) {
Shadow enclosingShadow = makeStaticInitializationShadow(inWorld, thisClass);
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);
}
public static Shadow makeStaticInitializationShadow(World inWorld, Class forType) {
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);
}
public static Shadow makePreInitializationShadow(World inWorld, Constructor forConstructor) {
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);
}
public static Shadow makeInitializationShadow(World inWorld, Constructor forConstructor) {
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);
}
public static Shadow makeHandlerShadow(World inWorld, Class exceptionType, Class withinType) {
Kind kind = Shadow.ExceptionHandler;
Shadow enclosingShadow = makeStaticInitializationShadow(inWorld, withinType);
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);
}
public static Shadow makeHandlerShadow(World inWorld, Class exceptionType, java.lang.reflect.Member withinCode) {
Kind kind = Shadow.ExceptionHandler;
Shadow enclosingShadow = makeExecutionShadow(inWorld, withinCode);
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);
}
public static Shadow makeFieldGetShadow(World inWorld, Field forField, Class callerType) {
Shadow enclosingShadow = makeStaticInitializationShadow(inWorld, callerType);
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);
}
public static Shadow makeFieldGetShadow(World inWorld, Field forField, java.lang.reflect.Member inMember) {
Shadow enclosingShadow = makeExecutionShadow(inWorld,inMember);
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);
}
public static Shadow makeFieldSetShadow(World inWorld, Field forField, Class callerType) {
Shadow enclosingShadow = makeStaticInitializationShadow(inWorld, callerType);
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);
}
public static Shadow makeFieldSetShadow(World inWorld, Field forField, java.lang.reflect.Member inMember) {
Shadow enclosingShadow = makeExecutionShadow(inWorld,inMember);
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);
}
public ReflectionShadow(World world, Kind kind, Member signature, Shadow enclosingShadow, ResolvedType enclosingType, ResolvedMember enclosingMember) {
super(kind,signature,enclosingShadow);
this.world = world;
this.enclosingType = enclosingType;
this.enclosingMember = enclosingMember;
}
/* (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));
}
return thisVar;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.Shadow#getTargetVar()
*/
public Var getTargetVar() {
if (targetVar == null && hasTarget()) {
targetVar = ReflectionVar.createTargetVar(getThisType().resolve(world));
}
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);
}
}
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);
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);
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);
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));
}
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));
}
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);
}
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;
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/src/org/aspectj/weaver/reflect/ReflectionVar.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.Member;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ast.Var;
/**
* A variable at a reflection shadow, used by the residual tests.
*/
public class ReflectionVar extends Var {
static final int THIS_VAR = 0;
static final int TARGET_VAR = 1;
static final int ARGS_VAR = 2;
static final int AT_THIS_VAR = 3;
static final int AT_TARGET_VAR = 4;
static final int AT_ARGS_VAR = 5;
static final int AT_WITHIN_VAR = 6;
static final int AT_WITHINCODE_VAR = 7;
static final int AT_ANNOTATION_VAR = 8;
private static AnnotationFinder annotationFinder = null;
static {
try {
Class java15AnnotationFinder = Class.forName("org.aspectj.weaver.reflect.Java15AnnotationFinder");
annotationFinder = (AnnotationFinder) java15AnnotationFinder.newInstance();
} catch(Exception ex) {
// must be on 1.4 or earlier
}
}
private int argsIndex = 0;
private int varType;
public static ReflectionVar createThisVar(ResolvedType type) {
ReflectionVar ret = new ReflectionVar(type);
ret.varType = THIS_VAR;
return ret;
}
public static ReflectionVar createTargetVar(ResolvedType type) {
ReflectionVar ret = new ReflectionVar(type);
ret.varType = TARGET_VAR;
return ret;
}
public static ReflectionVar createArgsVar(ResolvedType type, int index) {
ReflectionVar ret = new ReflectionVar(type);
ret.varType = ARGS_VAR;
ret.argsIndex = index;
return ret;
}
public static ReflectionVar createThisAnnotationVar(ResolvedType type) {
ReflectionVar ret = new ReflectionVar(type);
ret.varType = AT_THIS_VAR;
return ret;
}
public static ReflectionVar createTargetAnnotationVar(ResolvedType type) {
ReflectionVar ret = new ReflectionVar(type);
ret.varType = AT_TARGET_VAR;
return ret;
}
public static ReflectionVar createArgsAnnotationVar(ResolvedType type, int index) {
ReflectionVar ret = new ReflectionVar(type);
ret.varType = AT_ARGS_VAR;
ret.argsIndex = index;
return ret;
}
public static ReflectionVar createWithinAnnotationVar(ResolvedType annType) {
ReflectionVar ret = new ReflectionVar(annType);
ret.varType = AT_WITHIN_VAR;
return ret;
}
public static ReflectionVar createWithinCodeAnnotationVar(ResolvedType annType) {
ReflectionVar ret = new ReflectionVar(annType);
ret.varType = AT_WITHINCODE_VAR;
return ret;
}
public static ReflectionVar createAtAnnotationVar(ResolvedType annType) {
ReflectionVar ret = new ReflectionVar(annType);
ret.varType = AT_ANNOTATION_VAR;
return ret;
}
private ReflectionVar(ResolvedType type) {
super(type);
}
public Object getBindingAtJoinPoint(Object thisObject, Object targetObject, Object[] args) {
return getBindingAtJoinPoint(thisObject,targetObject,args,null,null,null);
}
/**
* At a join point with the given this, target, and args, return the object to which this
* var is bound.
* @param thisObject
* @param targetObject
* @param args
* @return
*/
public Object getBindingAtJoinPoint(
Object thisObject,
Object targetObject,
Object[] args,
Member subject,
Member withinCode,
Class withinType) {
switch( this.varType) {
case THIS_VAR: return thisObject;
case TARGET_VAR: return targetObject;
case ARGS_VAR:
if (this.argsIndex > (args.length - 1)) return null;
return args[argsIndex];
case AT_THIS_VAR:
if (annotationFinder != null) {
return annotationFinder.getAnnotation(getType(), thisObject);
} else return null;
case AT_TARGET_VAR:
if (annotationFinder != null) {
return annotationFinder.getAnnotation(getType(), targetObject);
} else return null;
case AT_ARGS_VAR:
if (this.argsIndex > (args.length - 1)) return null;
if (annotationFinder != null) {
return annotationFinder.getAnnotation(getType(), args[argsIndex]);
} else return null;
case AT_WITHIN_VAR:
if (annotationFinder != null) {
return annotationFinder.getAnnotationFromClass(getType(), withinType);
} else return null;
case AT_WITHINCODE_VAR:
if (annotationFinder != null) {
return annotationFinder.getAnnotationFromMember(getType(), withinCode);
} else return null;
case AT_ANNOTATION_VAR:
if (annotationFinder != null) {
return annotationFinder.getAnnotationFromMember(getType(), subject);
} else return null;
}
return null;
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
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.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 {
public ReflectionWorld() {
super();
this.setMessageHandler(new ExceptionBasedMessageHandler());
setBehaveInJava5Way(LangUtil.is15VMOrGreater());
}
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);
}
/* (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
}
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/src/org/aspectj/weaver/tools/PointcutParser.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.AtAjAttributes;
import org.aspectj.weaver.internal.tools.PointcutExpressionImpl;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.CflowPointcut;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.IScope;
import org.aspectj.weaver.patterns.KindedPointcut;
import org.aspectj.weaver.patterns.NotPointcut;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.ParserException;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.SimpleScope;
import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.aspectj.weaver.patterns.ThisOrTargetPointcut;
import org.aspectj.weaver.reflect.PointcutParameterImpl;
import org.aspectj.weaver.reflect.ReflectionWorld;
/**
* A PointcutParser can be used to build PointcutExpressions for a
* user-defined subset of AspectJ's pointcut language
*/
public class PointcutParser {
private static World world = new ReflectionWorld();
private Set supportedPrimitives;
/**
* @return a Set containing every PointcutPrimitive except
* if, cflow, and cflowbelow (useful for passing to
* PointcutParser constructor).
*/
public static Set getAllSupportedPointcutPrimitives() {
Set primitives = new HashSet();
primitives.add(PointcutPrimitive.ADVICE_EXECUTION);
primitives.add(PointcutPrimitive.ARGS);
primitives.add(PointcutPrimitive.CALL);
primitives.add(PointcutPrimitive.EXECUTION);
primitives.add(PointcutPrimitive.GET);
primitives.add(PointcutPrimitive.HANDLER);
primitives.add(PointcutPrimitive.INITIALIZATION);
primitives.add(PointcutPrimitive.PRE_INITIALIZATION);
primitives.add(PointcutPrimitive.SET);
primitives.add(PointcutPrimitive.STATIC_INITIALIZATION);
primitives.add(PointcutPrimitive.TARGET);
primitives.add(PointcutPrimitive.THIS);
primitives.add(PointcutPrimitive.WITHIN);
primitives.add(PointcutPrimitive.WITHIN_CODE);
primitives.add(PointcutPrimitive.AT_ANNOTATION);
primitives.add(PointcutPrimitive.AT_THIS);
primitives.add(PointcutPrimitive.AT_TARGET);
primitives.add(PointcutPrimitive.AT_ARGS);
primitives.add(PointcutPrimitive.AT_WITHIN);
primitives.add(PointcutPrimitive.AT_WITHINCODE);
primitives.add(PointcutPrimitive.REFERENCE);
return primitives;
}
/**
* Create a pointcut parser that can parse the full AspectJ pointcut
* language with the following exceptions:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
*/
public PointcutParser() {
supportedPrimitives = getAllSupportedPointcutPrimitives();
}
/**
* Create a pointcut parser that can parse pointcut expressions built
* from a user-defined subset of AspectJ's supported pointcut primitives.
* The following restrictions apply:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* @param supportedPointcutKinds a set of PointcutPrimitives this parser
* should support
* @throws UnsupportedOperationException if the set contains if, cflow, or
* cflow below
*/
public PointcutParser(Set/*<PointcutPrimitives>*/ supportedPointcutKinds) {
supportedPrimitives = supportedPointcutKinds;
for (Iterator iter = supportedPointcutKinds.iterator(); iter.hasNext();) {
PointcutPrimitive element = (PointcutPrimitive) iter.next();
if ((element == PointcutPrimitive.IF) ||
(element == PointcutPrimitive.CFLOW) ||
(element == PointcutPrimitive.CFLOW_BELOW)) {
throw new UnsupportedOperationException("Cannot handle if, cflow, and cflowbelow primitives");
}
}
}
public PointcutParameter createPointcutParameter(String name, Class type) {
return new PointcutParameterImpl(name,type);
}
/**
* Parse the given pointcut expression.
* A global scope is assumed for resolving any type references, and the pointcut
* must contain no formals (variables to be bound).
* @throws UnsupportedPointcutPrimitiveException if the parser encounters a
* primitive pointcut expression of a kind not supported by this PointcutParser.
* @throws IllegalArgumentException if the expression is not a well-formed
* pointcut expression
*/
public PointcutExpression parsePointcutExpression(String expression)
throws UnsupportedPointcutPrimitiveException, IllegalArgumentException {
return parsePointcutExpression(expression,null,new PointcutParameter[0]);
}
/**
* Parse the given pointcut expression.
* The pointcut is resolved as if it had been declared inside the inScope class
* (this allows the pointcut to contain unqualified references to other pointcuts
* declared in the same type for example).
* The pointcut may contain zero or more formal parameters to be bound at matched
* join points.
* @throws UnsupportedPointcutPrimitiveException if the parser encounters a
* primitive pointcut expression of a kind not supported by this PointcutParser.
* @throws IllegalArgumentException if the expression is not a well-formed
* pointcut expression
*/
public PointcutExpression parsePointcutExpression(
String expression,
Class inScope,
PointcutParameter[] formalParameters)
throws UnsupportedPointcutPrimitiveException, IllegalArgumentException {
PointcutExpressionImpl pcExpr = null;
try {
Pointcut pc = new PatternParser(expression).parsePointcut();
validateAgainstSupportedPrimitives(pc,expression);
IScope resolutionScope = buildResolutionScope((inScope == null ? Object.class : inScope),formalParameters);
pc = pc.resolve(resolutionScope);
ResolvedType declaringTypeForResolution = null;
if (inScope != null) {
declaringTypeForResolution = world.resolve(inScope.getName());
} else {
declaringTypeForResolution = ResolvedType.OBJECT.resolve(world);
}
IntMap arity = new IntMap(formalParameters.length);
for (int i = 0; i < formalParameters.length; i++) {
arity.put(i, i);
}
pc = pc.concretize(declaringTypeForResolution, declaringTypeForResolution, arity);
validateAgainstSupportedPrimitives(pc,expression); // again, because we have now followed any ref'd pcuts
pcExpr = new PointcutExpressionImpl(pc,expression,formalParameters,world);
} catch (ParserException pEx) {
throw new IllegalArgumentException(buildUserMessageFromParserException(expression,pEx));
} catch (ReflectionWorld.ReflectionWorldException rwEx) {
throw new IllegalArgumentException(rwEx.getMessage());
}
return pcExpr;
}
/* for testing */
Set getSupportedPrimitives() {
return supportedPrimitives;
}
/* for testing */
IMessageHandler setCustomMessageHandler(IMessageHandler aHandler) {
IMessageHandler current = world.getMessageHandler();
world.setMessageHandler(aHandler);
return current;
}
private IScope buildResolutionScope(Class inScope, PointcutParameter[] formalParameters) {
if (formalParameters == null) formalParameters = new PointcutParameter[0];
FormalBinding[] formalBindings = new FormalBinding[formalParameters.length];
for (int i = 0; i < formalBindings.length; i++) {
formalBindings[i] = new FormalBinding(UnresolvedType.forName(formalParameters[i].getType().getName()),formalParameters[i].getName(),i);
}
if (inScope == null) {
return new SimpleScope(world,formalBindings);
} else {
ResolvedType inType = world.resolve(inScope.getName());
ISourceContext sourceContext = new ISourceContext() {
public ISourceLocation makeSourceLocation(IHasPosition position) {
return new SourceLocation(new File(""),0);
}
public ISourceLocation makeSourceLocation(int line, int offset) {
return new SourceLocation(new File(""),line);
}
public int getOffset() {
return 0;
}
};
return new AtAjAttributes.BindingScope(inType,sourceContext,formalBindings);
}
}
private void validateAgainstSupportedPrimitives(Pointcut pc, String expression) {
switch(pc.getPointcutKind()) {
case Pointcut.AND:
validateAgainstSupportedPrimitives(((AndPointcut)pc).getLeft(),expression);
validateAgainstSupportedPrimitives(((AndPointcut)pc).getRight(),expression);
break;
case Pointcut.ARGS:
if (!supportedPrimitives.contains(PointcutPrimitive.ARGS))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.ARGS);
break;
case Pointcut.CFLOW:
CflowPointcut cfp = (CflowPointcut) pc;
if (cfp.isCflowBelow()) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CFLOW_BELOW);
} else {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CFLOW);
}
case Pointcut.HANDLER:
if (!supportedPrimitives.contains(PointcutPrimitive.HANDLER))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.HANDLER);
break;
case Pointcut.IF:
case Pointcut.IF_FALSE:
case Pointcut.IF_TRUE:
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.IF);
case Pointcut.KINDED:
validateKindedPointcut(((KindedPointcut)pc),expression);
break;
case Pointcut.NOT:
validateAgainstSupportedPrimitives(((NotPointcut)pc).getNegatedPointcut(),expression);
break;
case Pointcut.OR:
validateAgainstSupportedPrimitives(((OrPointcut)pc).getLeft(),expression);
validateAgainstSupportedPrimitives(((OrPointcut)pc).getRight(),expression);
break;
case Pointcut.THIS_OR_TARGET:
boolean isThis = ((ThisOrTargetPointcut)pc).isThis();
if (isThis && !supportedPrimitives.contains(PointcutPrimitive.THIS)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.THIS);
} else if (!supportedPrimitives.contains(PointcutPrimitive.TARGET)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.TARGET);
}
break;
case Pointcut.WITHIN:
if (!supportedPrimitives.contains(PointcutPrimitive.WITHIN))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.WITHIN);
break;
case Pointcut.WITHINCODE:
if (!supportedPrimitives.contains(PointcutPrimitive.WITHIN_CODE))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.WITHIN_CODE);
break;
case Pointcut.ATTHIS_OR_TARGET:
isThis = ((ThisOrTargetAnnotationPointcut)pc).isThis();
if (isThis && !supportedPrimitives.contains(PointcutPrimitive.AT_THIS)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_THIS);
} else if (!supportedPrimitives.contains(PointcutPrimitive.AT_TARGET)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_TARGET);
}
break;
case Pointcut.ATARGS:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_ARGS))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_ARGS);
break;
case Pointcut.ANNOTATION:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_ANNOTATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_ANNOTATION);
break;
case Pointcut.ATWITHIN:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_WITHIN))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_WITHIN);
break;
case Pointcut.ATWITHINCODE:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_WITHINCODE))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_WITHINCODE);
break;
case Pointcut.REFERENCE:
if (!supportedPrimitives.contains(PointcutPrimitive.REFERENCE))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.REFERENCE);
break;
case Pointcut.NONE: // deliberate fall-through
default:
throw new IllegalArgumentException("Unknown pointcut kind: " + pc.getPointcutKind());
}
}
private void validateKindedPointcut(KindedPointcut pc, String expression) {
Shadow.Kind kind = pc.getKind();
if ((kind == Shadow.MethodCall) || (kind == Shadow.ConstructorCall)) {
if (!supportedPrimitives.contains(PointcutPrimitive.CALL))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CALL);
} else if ((kind == Shadow.MethodExecution) || (kind == Shadow.ConstructorExecution)) {
if (!supportedPrimitives.contains(PointcutPrimitive.EXECUTION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.EXECUTION);
} else if (kind == Shadow.AdviceExecution) {
if (!supportedPrimitives.contains(PointcutPrimitive.ADVICE_EXECUTION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.ADVICE_EXECUTION);
} else if (kind == Shadow.FieldGet) {
if (!supportedPrimitives.contains(PointcutPrimitive.GET))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.GET);
} else if (kind == Shadow.FieldSet) {
if (!supportedPrimitives.contains(PointcutPrimitive.SET))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.SET);
} else if (kind == Shadow.Initialization) {
if (!supportedPrimitives.contains(PointcutPrimitive.INITIALIZATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.INITIALIZATION);
} else if (kind == Shadow.PreInitialization) {
if (!supportedPrimitives.contains(PointcutPrimitive.PRE_INITIALIZATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.PRE_INITIALIZATION);
} else if (kind == Shadow.StaticInitialization) {
if (!supportedPrimitives.contains(PointcutPrimitive.STATIC_INITIALIZATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.STATIC_INITIALIZATION);
}
}
private String buildUserMessageFromParserException(String pc, ParserException ex) {
StringBuffer msg = new StringBuffer();
msg.append("Pointcut is not well-formed: expecting '");
msg.append(ex.getMessage());
msg.append("'");
IHasPosition location = ex.getLocation();
msg.append(" at character position ");
msg.append(location.getStart());
msg.append("\n");
msg.append(pc);
msg.append("\n");
for (int i = 0; i < location.getStart(); i++) {
msg.append(" ");
}
for (int j=location.getStart(); j <= location.getEnd(); j++) {
msg.append("^");
}
msg.append("\n");
return msg.toString();
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/src/org/aspectj/weaver/tools/TypePatternMatcher.java
| |
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/testsrc/org/aspectj/weaver/tools/PointcutParserTest.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.util.HashSet;
import java.util.Set;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IMessage.Kind;
import junit.framework.TestCase;
/**
* Test cases for the PointcutParser class
*/
public class PointcutParserTest extends TestCase {
public void testGetAllSupportedPointcutPrimitives() {
Set s = PointcutParser.getAllSupportedPointcutPrimitives();
assertEquals("Should be 21 elements in the set",21,s.size());
assertFalse("Should not contain if pcd",s.contains(PointcutPrimitive.IF));
assertFalse("Should not contain cflow pcd",s.contains(PointcutPrimitive.CFLOW));
assertFalse("Should not contain cflowbelow pcd",s.contains(PointcutPrimitive.CFLOW_BELOW));
}
public void testEmptyConstructor() {
PointcutParser parser = new PointcutParser();
Set s = parser.getSupportedPrimitives();
assertEquals("Should be 21 elements in the set",21,s.size());
assertFalse("Should not contain if pcd",s.contains(PointcutPrimitive.IF));
assertFalse("Should not contain cflow pcd",s.contains(PointcutPrimitive.CFLOW));
assertFalse("Should not contain cflowbelow pcd",s.contains(PointcutPrimitive.CFLOW_BELOW));
}
public void testSetConstructor() {
Set p = PointcutParser.getAllSupportedPointcutPrimitives();
PointcutParser parser = new PointcutParser(p);
assertEquals("Should use the set we pass in",p,parser.getSupportedPrimitives());
Set q = new HashSet();
q.add(PointcutPrimitive.ARGS);
parser = new PointcutParser(q);
assertEquals("Should have only one element in set",1,parser.getSupportedPrimitives().size());
assertEquals("Should only have ARGS pcd",PointcutPrimitive.ARGS,
parser.getSupportedPrimitives().iterator().next());
}
public void testParsePointcutExpression() {
PointcutParser p = new PointcutParser();
IMessageHandler current = p.setCustomMessageHandler(new IgnoreWarningsMessageHandler());
try {
p.parsePointcutExpression(
"(adviceexecution() || execution(* *.*(..)) || handler(Exception) || " +
"call(Foo Bar+.*(Goo)) || get(* foo) || set(Foo+ (Goo||Moo).s*) || " +
"initialization(Foo.new(..)) || preinitialization(*.new(Foo,..)) || " +
"staticinitialization(org.xzy.abc..*)) && (this(Foo) || target(Boo) ||" +
"args(A,B,C)) && !handler(X)");
} finally {
p.setCustomMessageHandler(current);
}
try {
p.parsePointcutExpression("gobble-de-gook()");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException ex) {}
}
public void testParseExceptionErrorMessages() {
PointcutParser p = new PointcutParser();
try {
p.parsePointcutExpression("execution(int Foo.*(..) && args(Double)");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException ex) {
assertTrue("Pointcut is not well-formed message",ex.getMessage().startsWith("Pointcut is not well-formed: expecting ')' at character position 24"));
}
}
public void testParseIfPCD() {
PointcutParser p = new PointcutParser();
try {
p.parsePointcutExpression("if(true)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Should not support IF",PointcutPrimitive.IF,ex.getUnsupportedPrimitive());
}
}
public void testParseCflowPCDs() {
PointcutParser p = new PointcutParser();
try {
p.parsePointcutExpression("cflow(this(t))");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Should not support CFLOW",PointcutPrimitive.CFLOW,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("cflowbelow(this(t))");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Should not support CFLOW_BELOW",PointcutPrimitive.CFLOW_BELOW,ex.getUnsupportedPrimitive());
}
}
public void testParseReferencePCDs() {
Set pcKinds = PointcutParser.getAllSupportedPointcutPrimitives();
pcKinds.remove(PointcutPrimitive.REFERENCE);
PointcutParser p = new PointcutParser(pcKinds);
try {
p.parsePointcutExpression("bananas(String)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertTrue(ex.getUnsupportedPrimitive() == PointcutPrimitive.REFERENCE);
}
}
public void testParseUnsupportedPCDs() {
Set s = new HashSet();
PointcutParser p = new PointcutParser(s);
try {
p.parsePointcutExpression("args(x)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Args",PointcutPrimitive.ARGS,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("within(x)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Within",PointcutPrimitive.WITHIN,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("withincode(new(..))");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Withincode",PointcutPrimitive.WITHIN_CODE,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("handler(Exception)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("handler",PointcutPrimitive.HANDLER,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("this(X)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("this",PointcutPrimitive.THIS,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("target(X)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("target",PointcutPrimitive.TARGET,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("this(X) && target(Y)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("This",PointcutPrimitive.THIS,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("this(X) || target(Y)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("This",PointcutPrimitive.THIS,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("!this(X)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("This",PointcutPrimitive.THIS,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("call(* *.*(..))");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Call",PointcutPrimitive.CALL,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("execution(* *.*(..))");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Execution",PointcutPrimitive.EXECUTION,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("get(* *)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Get",PointcutPrimitive.GET,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("set(* *)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Set",PointcutPrimitive.SET,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("initialization(new(..))");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Initialization",PointcutPrimitive.INITIALIZATION,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("preinitialization(new(..))");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Prc-init",PointcutPrimitive.PRE_INITIALIZATION,ex.getUnsupportedPrimitive());
}
try {
p.parsePointcutExpression("staticinitialization(T)");
fail("Expected UnsupportedPointcutPrimitiveException");
} catch(UnsupportedPointcutPrimitiveException ex) {
assertEquals("Staticinit",PointcutPrimitive.STATIC_INITIALIZATION,ex.getUnsupportedPrimitive());
}
}
public void testFormals() {
PointcutParser parser = new PointcutParser();
PointcutParameter param = parser.createPointcutParameter("x",String.class);
PointcutExpression pc = parser.parsePointcutExpression("args(x)", null, new PointcutParameter[] {param} );
assertEquals("args(x)",pc.getPointcutExpression());
try {
pc = parser.parsePointcutExpression("args(String)", null, new PointcutParameter[] {param} );
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
assertTrue("formal unbound",ex.getMessage().indexOf("formal unbound") != -1);
}
try {
pc = parser.parsePointcutExpression("args(y)");
fail("Expecting IllegalArgumentException");
} catch(IllegalArgumentException ex) {
assertTrue("no match for type name",ex.getMessage().indexOf("warning no match for this type name: y") != -1);
}
}
private static class IgnoreWarningsMessageHandler implements IMessageHandler {
public boolean handleMessage(IMessage message) throws AbortException {
if (message.getKind() != IMessage.WARNING) throw new RuntimeException("unexpected message: " + message.toString());
return true;
}
public boolean isIgnoring(Kind kind) {
if (kind != IMessage.ERROR) return true;
return false;
}
public void dontIgnore(Kind kind) {
}
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/testsrc/org/aspectj/weaver/tools/ToolsTests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.weaver.tools;
import junit.framework.Test;
import junit.framework.TestSuite;
public class ToolsTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for org.aspectj.weaver.tools");
//$JUnit-BEGIN$
suite.addTestSuite(PointcutParserTest.class);
suite.addTestSuite(PointcutExpressionTest.class);
//$JUnit-END$
return suite;
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver/testsrc/org/aspectj/weaver/tools/TypePatternMatcherTest.java
| |
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver5/java5-src/org/aspectj/weaver/reflect/Java15AnnotationFinder.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.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.util.Repository;
import org.aspectj.apache.bcel.util.ClassLoaderRepository;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
/**
* Find the given annotation (if present) on the given object
*
*/
public class Java15AnnotationFinder implements AnnotationFinder {
private Repository bcelRepository;
public Java15AnnotationFinder() {
this.bcelRepository = new ClassLoaderRepository(getClass().getClassLoader());
}
/* (non-Javadoc)
* @see org.aspectj.weaver.reflect.AnnotationFinder#getAnnotation(org.aspectj.weaver.ResolvedType, java.lang.Object)
*/
public Object getAnnotation(ResolvedType annotationType, Object onObject) {
try {
Class annotationClass = Class.forName(annotationType.getName());
if (onObject.getClass().isAnnotationPresent(annotationClass)) {
return onObject.getClass().getAnnotation(annotationClass);
}
} catch (ClassNotFoundException ex) {
// just return null
}
return null;
}
public Object getAnnotationFromClass(ResolvedType annotationType, Class aClass) {
try {
Class annotationClass = Class.forName(annotationType.getName());
if (aClass.isAnnotationPresent(annotationClass)) {
return aClass.getAnnotation(annotationClass);
}
} catch (ClassNotFoundException ex) {
// just return null
}
return null;
}
public Object getAnnotationFromMember(ResolvedType annotationType, Member aMember) {
if (!(aMember instanceof AccessibleObject)) return null;
AccessibleObject ao = (AccessibleObject) aMember;
try {
Class annotationClass = Class.forName(annotationType.getName());
if (ao.isAnnotationPresent(annotationClass)) {
return ao.getAnnotation(annotationClass);
}
} catch (ClassNotFoundException ex) {
// just return null
}
return null;
}
public Set getAnnotations(Member onMember) {
if (!(onMember instanceof AccessibleObject)) return Collections.EMPTY_SET;
// here we really want both the runtime visible AND the class visible annotations
// so we bail out to Bcel and then chuck away the JavaClass so that we don't hog
// memory.
try {
JavaClass jc = bcelRepository.loadClass(onMember.getDeclaringClass());
org.aspectj.apache.bcel.classfile.annotation.Annotation[] anns = new org.aspectj.apache.bcel.classfile.annotation.Annotation[0];
if (onMember instanceof Method) {
org.aspectj.apache.bcel.classfile.Method bcelMethod = jc.getMethod((Method)onMember);
anns = bcelMethod.getAnnotations();
} else if (onMember instanceof Constructor) {
org.aspectj.apache.bcel.classfile.Method bcelCons = jc.getMethod((Constructor)onMember);
anns = bcelCons.getAnnotations();
} else if (onMember instanceof Field) {
org.aspectj.apache.bcel.classfile.Field bcelField = jc.getField((Field)onMember);
anns = bcelField.getAnnotations();
}
// the answer is cached and we don't want to hold on to memory
bcelRepository.clear();
if (anns == null) anns = new org.aspectj.apache.bcel.classfile.annotation.Annotation[0];
// convert to our Annotation type
Set<UnresolvedType> annSet = new HashSet<UnresolvedType>();
for (int i = 0; i < anns.length; i++) {
annSet.add(UnresolvedType.forName(anns[i].getTypeName()));
}
return annSet;
} catch (ClassNotFoundException cnfEx) {
// just use reflection then
}
AccessibleObject ao = (AccessibleObject) onMember;
Annotation[] anns = ao.getDeclaredAnnotations();
Set<UnresolvedType> annSet = new HashSet<UnresolvedType>();
for (int i = 0; i < anns.length; i++) {
annSet.add(UnresolvedType.forName(anns[i].annotationType().getName()));
}
return annSet;
}
public ResolvedType[] getAnnotations(Class forClass, World inWorld) {
// here we really want both the runtime visible AND the class visible annotations
// so we bail out to Bcel and then chuck away the JavaClass so that we don't hog
// memory.
try {
JavaClass jc = bcelRepository.loadClass(forClass);
org.aspectj.apache.bcel.classfile.annotation.Annotation[] anns =jc.getAnnotations();
bcelRepository.clear();
if (anns == null) return new ResolvedType[0];
ResolvedType[] ret = new ResolvedType[anns.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = inWorld.resolve(anns[i].getTypeName());
}
return ret;
} catch (ClassNotFoundException cnfEx) {
// just use reflection then
}
Annotation[] classAnnotations = forClass.getAnnotations();
ResolvedType[] ret = new ResolvedType[classAnnotations.length];
for (int i = 0; i < classAnnotations.length; i++) {
ret[i] = inWorld.resolve(classAnnotations[i].annotationType().getName());
}
return ret;
}
}
|
116,755
|
Bug 116755 PointcutParser is not configurable
|
I'm testing the reflection and weaver tools APIs. When I using following code: PointcutParser parse = new PointcutParser(); String expr = "call(public * main.hello(..)"; PointcutExpression pex = parse.parsePointcutExpression(expr); Whenever I use a full qualified class name in pointcut expression, an exception is throwed out: java.lang.IllegalArgumentException: warning no match for this type name: obj [Xlint:invalidAbsoluteTypeName] I try to turn off this Lint exception. But it seems I must access to world field of PointcutParser. This is inconvenient because world field is not exposed by PointcutParser. The existing PointcutParser interface implicitly creates a World and does not allow any configuration including classpath or lint. But developers may need this kind of control.
|
resolved fixed
|
522911e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-19T17:08:48Z
| 2005-11-17T01:13:20Z
|
weaver5/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.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.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.Pointcut;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.BoundedReferenceType;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.TypeFactory;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableReferenceType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.internal.tools.PointcutExpressionImpl;
import org.aspectj.weaver.tools.PointcutParameter;
import org.aspectj.weaver.tools.PointcutParser;
/**
* @author colyer
* Provides Java 5 behaviour in reflection based delegates (overriding
* 1.4 behaviour from superclass where appropriate)
*/
public class Java15ReflectionBasedReferenceTypeDelegate extends
ReflectionBasedReferenceTypeDelegate {
private AjType myType;
private ResolvedType[] annotations;
private ResolvedMember[] pointcuts;
private ResolvedMember[] methods;
private ResolvedMember[] fields;
private TypeVariable[] typeVariables;
private ResolvedType superclass;
private ResolvedType[] superInterfaces;
private String genericSignature = null;
private Java15AnnotationFinder annotationFinder = new Java15AnnotationFinder();
public Java15ReflectionBasedReferenceTypeDelegate() {}
public void initialize(ReferenceType aType, Class aClass, World aWorld) {
super.initialize(aType, aClass, aWorld);
myType = AjTypeSystem.getAjType(aClass);
}
public ReferenceType buildGenericType() {
return (ReferenceType) UnresolvedType.forGenericTypeVariables(
getResolvedTypeX().getSignature(),
getTypeVariables()).resolve(getWorld());
}
public AnnotationX[] getAnnotations() {
// AMC - we seem not to need to implement this method...
throw new UnsupportedOperationException("getAnnotations on Java15ReflectionBasedReferenceTypeDelegate is not implemented yet");
//return super.getAnnotations();
}
public ResolvedType[] getAnnotationTypes() {
if (annotations == null) {
annotations = annotationFinder.getAnnotations(getBaseClass(), getWorld());
}
return annotations;
}
public boolean hasAnnotation(UnresolvedType ofType) {
ResolvedType[] myAnns = getAnnotationTypes();
ResolvedType toLookFor = ofType.resolve(getWorld());
for (int i = 0; i < myAnns.length; i++) {
if (myAnns[i] == toLookFor) return true;
}
return false;
}
// use the MAP to ensure that any aj-synthetic fields are filtered out
public ResolvedMember[] getDeclaredFields() {
if (fields == null) {
Field[] reflectFields = this.myType.getDeclaredFields();
this.fields = new ResolvedMember[reflectFields.length];
for (int i = 0; i < reflectFields.length; i++) {
this.fields[i] = createGenericFieldMember(reflectFields[i]);
}
}
return fields;
}
public String getDeclaredGenericSignature() {
if (this.genericSignature == null && isGeneric()) {
}
return genericSignature;
}
public ResolvedType[] getDeclaredInterfaces() {
if (superInterfaces == null) {
Type[] genericInterfaces = getBaseClass().getGenericInterfaces();
this.superInterfaces = fromTypes(genericInterfaces);
}
return superInterfaces;
}
public ResolvedType getSuperclass() {
if (superclass == null)
superclass = fromType(this.getBaseClass().getGenericSuperclass());
return superclass;
}
public TypeVariable[] getTypeVariables() {
if (this.typeVariables == null) {
java.lang.reflect.TypeVariable[] tVars = this.getBaseClass().getTypeParameters();
this.typeVariables = new TypeVariable[tVars.length];
for (int i = 0; i < tVars.length; i++) {
this.typeVariables[i] = ((TypeVariableReferenceType) fromType(tVars[i])).getTypeVariable();
}
}
return this.typeVariables;
}
// overrides super method since by using the MAP we can filter out advice
// methods that really shouldn't be seen in this list
public ResolvedMember[] getDeclaredMethods() {
if (methods == null) {
Method[] reflectMethods = this.myType.getDeclaredMethods();
Constructor[] reflectCons = this.myType.getDeclaredConstructors();
this.methods = new ResolvedMember[reflectMethods.length + reflectCons.length];
for (int i = 0; i < reflectMethods.length; i++) {
this.methods[i] = createGenericMethodMember(reflectMethods[i]);
}
for (int i = 0; i < reflectCons.length; i++) {
this.methods[i + reflectMethods.length] =
createGenericConstructorMember(reflectCons[i]);
}
}
return methods;
}
private ResolvedMember createGenericMethodMember(Method forMethod) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD,
getResolvedTypeX(),
forMethod.getModifiers(),
fromType(forMethod.getGenericReturnType()),
forMethod.getName(),
fromTypes(forMethod.getGenericParameterTypes()),
fromTypes(forMethod.getGenericExceptionTypes()),
forMethod
);
return ret;
}
private ResolvedMember createGenericConstructorMember(Constructor forConstructor) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD,
getResolvedTypeX(),
forConstructor.getModifiers(),
getResolvedTypeX(),
"init",
fromTypes(forConstructor.getGenericParameterTypes()),
fromTypes(forConstructor.getGenericExceptionTypes()),
forConstructor
);
return ret;
}
private ResolvedMember createGenericFieldMember(Field forField) {
return new ReflectionBasedResolvedMemberImpl(
org.aspectj.weaver.Member.FIELD,
getResolvedTypeX(),
forField.getModifiers(),
fromType(forField.getGenericType()),
forField.getName(),
new UnresolvedType[0],
forField);
}
public ResolvedMember[] getDeclaredPointcuts() {
if (pointcuts == null) {
Pointcut[] pcs = this.myType.getDeclaredPointcuts();
pointcuts = new ResolvedMember[pcs.length];
PointcutParser parser = new PointcutParser();
for (int i = 0; i < pcs.length; i++) {
AjType<?>[] ptypes = pcs[i].getParameterTypes();
String[] pnames = pcs[i].getParameterNames();
if (pnames.length != ptypes.length) {
throw new IllegalStateException("Required parameter names not available when parsing pointcut " + pcs[i].getName() + " in type " + getResolvedTypeX().getName());
}
PointcutParameter[] parameters = new PointcutParameter[ptypes.length];
for (int j = 0; j < parameters.length; j++) {
parameters[j] = parser.createPointcutParameter(pnames[j],ptypes[j].getJavaClass());
}
String pcExpr = pcs[i].getPointcutExpression().toString();
PointcutExpressionImpl pEx = (PointcutExpressionImpl) parser.parsePointcutExpression(pcExpr,getBaseClass(),parameters);
org.aspectj.weaver.patterns.Pointcut pc = pEx.getUnderlyingPointcut();
UnresolvedType[] weaverPTypes = new UnresolvedType[ptypes.length];
for (int j = 0; j < weaverPTypes.length; j++) {
weaverPTypes[j] = UnresolvedType.forName(ptypes[j].getName());
}
pointcuts[i] = new ResolvedPointcutDefinition(getResolvedTypeX(),pcs[i].getModifiers(),pcs[i].getName(),weaverPTypes,pc);
}
}
return pointcuts;
}
public boolean isAnnotation() {
return getBaseClass().isAnnotation();
}
public boolean isAnnotationStyleAspect() {
return getBaseClass().isAnnotationPresent(Aspect.class);
}
public boolean isAnnotationWithRuntimeRetention() {
if (!isAnnotation()) return false;
if (getBaseClass().isAnnotationPresent(Retention.class)) {
Retention retention = (Retention) getBaseClass().getAnnotation(Retention.class);
RetentionPolicy policy = retention.value();
return policy == RetentionPolicy.RUNTIME;
} else {
return false;
}
}
public boolean isAspect() {
return this.myType.isAspect();
}
public boolean isEnum() {
return getBaseClass().isEnum();
}
public boolean isGeneric() {
//return false; // for now
return getBaseClass().getTypeParameters().length > 0;
}
private ResolvedType fromType(Type aType) {
if (aType instanceof Class) {
return getWorld().resolve(((Class)aType).getName());
} else if (aType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) aType;
ResolvedType baseType = fromType(pt.getRawType());
Type[] args = pt.getActualTypeArguments();
ResolvedType[] resolvedArgs = fromTypes(args);
return TypeFactory.createParameterizedType(baseType, resolvedArgs, getWorld());
} else if (aType instanceof java.lang.reflect.TypeVariable) {
java.lang.reflect.TypeVariable tv = (java.lang.reflect.TypeVariable) aType;
Type[] bounds = tv.getBounds();
ResolvedType[] resBounds = fromTypes(bounds);
ResolvedType upperBound = resBounds[0];
ResolvedType[] additionalBounds = new ResolvedType[0];
if (resBounds.length > 1) {
additionalBounds = new ResolvedType[resBounds.length - 1];
System.arraycopy(resBounds,1,additionalBounds,0,additionalBounds.length);
}
TypeVariable rt_tv = new TypeVariable(tv.getName(),upperBound,additionalBounds);
return new TypeVariableReferenceType(rt_tv,getWorld());
} else if (aType instanceof WildcardType) {
WildcardType wildType = (WildcardType) aType;
Type[] lowerBounds = wildType.getLowerBounds();
Type[] upperBounds = wildType.getUpperBounds();
ResolvedType bound = null;
boolean isExtends = lowerBounds.length == 0;
if (isExtends) {
bound = fromType(upperBounds[0]);
} else {
bound = fromType(lowerBounds[0]);
}
return new BoundedReferenceType((ReferenceType)bound,isExtends,getWorld());
} else if (aType instanceof GenericArrayType) {
GenericArrayType gt = (GenericArrayType) aType;
Type componentType = gt.getGenericComponentType();
UnresolvedType.makeArray(fromType(componentType),1);
}
return ResolvedType.MISSING;
}
private ResolvedType[] fromTypes(Type[] types) {
ResolvedType[] ret = new ResolvedType[types.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = fromType(types[i]);
}
return ret;
}
@Override
public boolean isAnonymous() {
return this.myClass.isAnonymousClass();
}
}
|
115,607
|
Bug 115607 Incorrect structure model for simple declare @type program?
|
This program: ---8<----- @interface I {} class Simple {} public aspect C { declare @type: Simple : @I; } ---8<----- (all in a file called C.java, open with the AJ editor) when built shows incorrect gutter markers, it shows a double headed arrow on Simple implying that it annotates itself - rather than something outgoing from the declare statement and something incoming on the Simple type.
|
resolved fixed
|
9ed75a1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-21T16:33:56Z
| 2005-11-09T09:53:20Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceLocation.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.lookup;
import java.io.File;
import org.aspectj.ajdt.internal.core.builder.EclipseAdapterUtils;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
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.problem.ProblemHandler;
public class EclipseSourceLocation implements ISourceLocation {
private static String NO_CONTEXT = "USE_NULL--NO_CONTEXT_AVAILABLE";
CompilationResult result;
int startPos, endPos;
// lazy but final
File file;
int startLine = -1;
int endLine = -1;
int column = -1;
String context;
public EclipseSourceLocation(CompilationResult result, int startPos, int endPos) {
super();
this.result = result;
this.startPos = startPos;
this.endPos = endPos;
}
public CompilationResult getCompilationResult() {
return result;
}
public int getOffset() {
return startPos;
}
public int getStartPos() {
return startPos;
}
public int getEndPos() {
return endPos;
}
public File getSourceFile() {
if (null == file) {
if ((null == result)
|| (null == result.fileName)
|| (0 == result.fileName.length)) {
file = ISourceLocation.NO_FILE;
} else {
file = new File(new String(result.fileName));
}
}
return file;
}
public int getLine() {
if (-1 == startLine) {
startLine = ProblemHandler.searchLineNumber(result.lineSeparatorPositions, startPos);
}
return startLine;
}
public int getColumn() {
if (-1 == column) {
int lineNumber = getLine();
// JJH added check that lineNumber is in legal range to avoid exceptions
if (0 < lineNumber && lineNumber < result.lineSeparatorPositions.length) {
int lineStart = result.lineSeparatorPositions[lineNumber];
int col = startPos - lineStart; // 1-based
if (0 <= col) {
column = col;
} else {
column = 0;
}
}
}
return column;
}
public int getEndLine() {
if (-1 == endLine) {
endLine = ProblemHandler.searchLineNumber(result.lineSeparatorPositions, endPos);
}
return endLine;
}
public String getContext() {
if (null == context) {
ICompilationUnit compilationUnit = result.compilationUnit;
IProblem[] problems = result.problems;
if ((null == compilationUnit) || (null == problems)
|| (1 != problems.length)) { // ?? which of n>1 problems?
context = NO_CONTEXT;
} else {
context = EclipseAdapterUtils.makeLocationContext(compilationUnit, problems[0]);
}
}
return (NO_CONTEXT == context ? null : context);
}
/** @return String {file:}line{:column} */
public String toString() {
StringBuffer sb = new StringBuffer();
if (getSourceFile() != ISourceLocation.NO_FILE) {
sb.append(getSourceFile().getPath());
sb.append(":");
}
sb.append("" + getLine());
if (getColumn() != 0) {
sb.append(":" + getColumn());
}
if (getOffset()>=0) { sb.append("::").append(getOffset()); }
return sb.toString();
}
}
|
115,607
|
Bug 115607 Incorrect structure model for simple declare @type program?
|
This program: ---8<----- @interface I {} class Simple {} public aspect C { declare @type: Simple : @I; } ---8<----- (all in a file called C.java, open with the AJ editor) when built shows incorrect gutter markers, it shows a double headed arrow on Simple implying that it annotates itself - rather than something outgoing from the declare statement and something incoming on the Simple type.
|
resolved fixed
|
9ed75a1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-21T16:33:56Z
| 2005-11-09T09:53:20Z
|
tests/bugs150/pr115607.java
| |
115,607
|
Bug 115607 Incorrect structure model for simple declare @type program?
|
This program: ---8<----- @interface I {} class Simple {} public aspect C { declare @type: Simple : @I; } ---8<----- (all in a file called C.java, open with the AJ editor) when built shows incorrect gutter markers, it shows a double headed arrow on Simple implying that it annotates itself - rather than something outgoing from the declare statement and something incoming on the Simple type.
|
resolved fixed
|
9ed75a1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-21T16:33:56Z
| 2005-11-09T09:53:20Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
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 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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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 testPointcutParsingOfCompiledPointcuts() {
// runTest("pointcut parsing with ajc compiled pointcut references");
// }
/*
* 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");}
// 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);
}
}
|
114,332
|
Bug 114332 Reflection API not detecting ITD method correctly in all circumstances
| null |
resolved fixed
|
735d94f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-21T22:05:46Z
| 2005-10-31T09:13:20Z
|
aspectj5rt/java5-src/org/aspectj/internal/lang/reflect/AjTypeImpl.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.internal.lang.reflect;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.aspectj.internal.lang.annotation.ajcDeclareAnnotation;
import org.aspectj.internal.lang.annotation.ajcDeclareEoW;
import org.aspectj.internal.lang.annotation.ajcDeclareParents;
import org.aspectj.internal.lang.annotation.ajcDeclarePrecedence;
import org.aspectj.internal.lang.annotation.ajcDeclareSoft;
import org.aspectj.internal.lang.annotation.ajcITD;
import org.aspectj.internal.lang.annotation.ajcPrivileged;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclareError;
import org.aspectj.lang.annotation.DeclareWarning;
import org.aspectj.lang.reflect.Advice;
import org.aspectj.lang.reflect.AdviceKind;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.DeclareAnnotation;
import org.aspectj.lang.reflect.DeclareErrorOrWarning;
import org.aspectj.lang.reflect.DeclareParents;
import org.aspectj.lang.reflect.DeclarePrecedence;
import org.aspectj.lang.reflect.DeclareSoft;
import org.aspectj.lang.reflect.InterTypeConstructorDeclaration;
import org.aspectj.lang.reflect.InterTypeFieldDeclaration;
import org.aspectj.lang.reflect.InterTypeMethodDeclaration;
import org.aspectj.lang.reflect.NoSuchAdviceException;
import org.aspectj.lang.reflect.NoSuchPointcutException;
import org.aspectj.lang.reflect.PerClause;
import org.aspectj.lang.reflect.PerClauseKind;
import org.aspectj.lang.reflect.Pointcut;
/**
* @author colyer
*
*/
public class AjTypeImpl<T> implements AjType<T> {
private static final String ajcMagic = "ajc$";
private Class<T> clazz;
private Pointcut[] declaredPointcuts = null;
private Pointcut[] pointcuts = null;
private Advice[] declaredAdvice = null;
private Advice[] advice = null;
private InterTypeMethodDeclaration[] declaredITDMethods = null;
private InterTypeMethodDeclaration[] itdMethods = null;
private InterTypeFieldDeclaration[] declaredITDFields = null;
private InterTypeFieldDeclaration[] itdFields = null;
private InterTypeConstructorDeclaration[] itdCons = null;
private InterTypeConstructorDeclaration[] declaredITDCons = null;
public AjTypeImpl(Class<T> fromClass) {
this.clazz = fromClass;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getName()
*/
public String getName() {
return clazz.getName();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getPackage()
*/
public Package getPackage() {
return clazz.getPackage();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getInterfaces()
*/
public AjType<?>[] getInterfaces() {
Class<?>[] baseInterfaces = clazz.getInterfaces();
return toAjTypeArray(baseInterfaces);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getModifiers()
*/
public int getModifiers() {
return clazz.getModifiers();
}
public Class<T> getJavaClass() {
return clazz;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getSupertype()
*/
public AjType<?> getSupertype() {
return new AjTypeImpl(clazz.getSuperclass());
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getGenericSupertype()
*/
public Type getGenericSupertype() {
return clazz.getGenericSuperclass();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getEnclosingMethod()
*/
public Method getEnclosingMethod() {
return clazz.getEnclosingMethod();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getEnclosingConstructor()
*/
public Constructor getEnclosingConstructor() {
return clazz.getEnclosingConstructor();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getEnclosingType()
*/
public AjType<?> getEnclosingType() {
Class<?> enc = clazz.getEnclosingClass();
return enc != null ? new AjTypeImpl(enc) : null;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaringType()
*/
public AjType<?> getDeclaringType() {
Class dec = clazz.getDeclaringClass();
return dec != null ? new AjTypeImpl(dec) : null;
}
public PerClause getPerClause() {
if (isAspect()) {
Aspect aspectAnn = clazz.getAnnotation(Aspect.class);
String perClause = aspectAnn.value();
if (perClause.equals("")) {
if (getSupertype().isAspect()) {
return getSupertype().getPerClause();
}
return new PerClauseImpl(PerClauseKind.SINGLETON);
} else if (perClause.startsWith("perthis(")) {
return new PointcutBasedPerClauseImpl(PerClauseKind.PERTHIS,perClause.substring("perthis(".length(),perClause.length() - 1));
} else if (perClause.startsWith("pertarget(")) {
return new PointcutBasedPerClauseImpl(PerClauseKind.PERTARGET,perClause.substring("pertarget(".length(),perClause.length() - 1));
} else if (perClause.startsWith("percflow(")) {
return new PointcutBasedPerClauseImpl(PerClauseKind.PERCFLOW,perClause.substring("percflow(".length(),perClause.length() - 1));
} else if (perClause.startsWith("percflowbelow(")) {
return new PointcutBasedPerClauseImpl(PerClauseKind.PERCFLOWBELOW,perClause.substring("percflowbelow(".length(),perClause.length() - 1));
} else if (perClause.startsWith("pertypewithin")) {
return new TypePatternBasedPerClauseImpl(PerClauseKind.PERTYPEWITHIN,perClause.substring("pertypewithin(".length(),perClause.length() - 1));
} else {
throw new IllegalStateException("Per-clause not recognized: " + perClause);
}
} else {
return null;
}
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isAnnotationPresent(java.lang.Class)
*/
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
return clazz.isAnnotationPresent(annotationType);
}
public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
return clazz.getAnnotation(annotationType);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getAnnotations()
*/
public Annotation[] getAnnotations() {
return clazz.getAnnotations();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredAnnotations()
*/
public Annotation[] getDeclaredAnnotations() {
return clazz.getDeclaredAnnotations();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getAspects()
*/
public AjType<?>[] getAjTypes() {
Class[] classes = clazz.getClasses();
return toAjTypeArray(classes);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredAspects()
*/
public AjType<?>[] getDeclaredAjTypes() {
Class[] classes = clazz.getDeclaredClasses();
return toAjTypeArray(classes);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getConstructor(java.lang.Class...)
*/
public Constructor getConstructor(AjType<?>... parameterTypes) throws NoSuchMethodException {
return clazz.getConstructor(toClassArray(parameterTypes));
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getConstructors()
*/
public Constructor[] getConstructors() {
return clazz.getConstructors();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredConstructor(java.lang.Class...)
*/
public Constructor getDeclaredConstructor(AjType<?>... parameterTypes) throws NoSuchMethodException {
return clazz.getDeclaredConstructor(toClassArray(parameterTypes));
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredConstructors()
*/
public Constructor[] getDeclaredConstructors() {
return clazz.getDeclaredConstructors();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredField(java.lang.String)
*/
public Field getDeclaredField(String name) throws NoSuchFieldException {
Field f = clazz.getDeclaredField(name);
if (f.getName().startsWith(ajcMagic)) throw new NoSuchFieldException(name);
return f;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredFields()
*/
public Field[] getDeclaredFields() {
Field[] fields = clazz.getDeclaredFields();
List<Field> filteredFields = new ArrayList<Field>();
for (Field field : fields)
if (!field.getName().startsWith(ajcMagic)
&& !field.isAnnotationPresent(DeclareWarning.class)
&& !field.isAnnotationPresent(DeclareError.class)) {
filteredFields.add(field);
}
Field[] ret = new Field[filteredFields.size()];
filteredFields.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getField(java.lang.String)
*/
public Field getField(String name) throws NoSuchFieldException {
Field f = clazz.getField(name);
if (f.getName().startsWith(ajcMagic)) throw new NoSuchFieldException(name);
return f;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getFields()
*/
public Field[] getFields() {
Field[] fields = clazz.getFields();
List<Field> filteredFields = new ArrayList<Field>();
for (Field field : fields)
if (!field.getName().startsWith(ajcMagic)
&& !field.isAnnotationPresent(DeclareWarning.class)
&& !field.isAnnotationPresent(DeclareError.class)) {
filteredFields.add(field);
}
Field[] ret = new Field[filteredFields.size()];
filteredFields.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredMethod(java.lang.String, java.lang.Class...)
*/
public Method getDeclaredMethod(String name, AjType<?>... parameterTypes) throws NoSuchMethodException {
Method m = clazz.getDeclaredMethod(name,toClassArray(parameterTypes));
if (!isReallyAMethod(m)) throw new NoSuchMethodException(name);
return m;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getMethod(java.lang.String, java.lang.Class...)
*/
public Method getMethod(String name, AjType<?>... parameterTypes) throws NoSuchMethodException {
Method m = clazz.getMethod(name,toClassArray(parameterTypes));
if (!isReallyAMethod(m)) throw new NoSuchMethodException(name);
return m;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredMethods()
*/
public Method[] getDeclaredMethods() {
Method[] methods = clazz.getDeclaredMethods();
List<Method> filteredMethods = new ArrayList<Method>();
for (Method method : methods) {
if (isReallyAMethod(method)) filteredMethods.add(method);
}
Method[] ret = new Method[filteredMethods.size()];
filteredMethods.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getMethods()
*/
public Method[] getMethods() {
Method[] methods = clazz.getMethods();
List<Method> filteredMethods = new ArrayList<Method>();
for (Method method : methods) {
if (isReallyAMethod(method)) filteredMethods.add(method);
}
Method[] ret = new Method[filteredMethods.size()];
filteredMethods.toArray(ret);
return ret;
}
private boolean isReallyAMethod(Method method) {
if (method.getName().startsWith(ajcMagic)) return false;
if (method.isAnnotationPresent(org.aspectj.lang.annotation.Pointcut.class)) return false;
if (method.isAnnotationPresent(Before.class)) return false;
if (method.isAnnotationPresent(After.class)) return false;
if (method.isAnnotationPresent(AfterReturning.class)) return false;
if (method.isAnnotationPresent(AfterThrowing.class)) return false;
if (method.isAnnotationPresent(Around.class)) return false;
return true;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredPointcut(java.lang.String)
*/
public Pointcut getDeclaredPointcut(String name) throws NoSuchPointcutException {
Pointcut[] pcs = getDeclaredPointcuts();
for (Pointcut pc : pcs)
if (pc.getName().equals(name)) return pc;
throw new NoSuchPointcutException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getPointcut(java.lang.String)
*/
public Pointcut getPointcut(String name) throws NoSuchPointcutException {
Pointcut[] pcs = getPointcuts();
for (Pointcut pc : pcs)
if (pc.getName().equals(name)) return pc;
throw new NoSuchPointcutException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredPointcuts()
*/
public Pointcut[] getDeclaredPointcuts() {
if (declaredPointcuts != null) return declaredPointcuts;
List<Pointcut> pointcuts = new ArrayList<Pointcut>();
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
Pointcut pc = asPointcut(method);
if (pc != null) pointcuts.add(pc);
}
Pointcut[] ret = new Pointcut[pointcuts.size()];
pointcuts.toArray(ret);
declaredPointcuts = ret;
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getPointcuts()
*/
public Pointcut[] getPointcuts() {
if (pointcuts != null) return pointcuts;
List<Pointcut> pcuts = new ArrayList<Pointcut>();
Method[] methods = clazz.getMethods();
for (Method method : methods) {
Pointcut pc = asPointcut(method);
if (pc != null) pcuts.add(pc);
}
Pointcut[] ret = new Pointcut[pcuts.size()];
pcuts.toArray(ret);
pointcuts = ret;
return ret;
}
private Pointcut asPointcut(Method method) {
org.aspectj.lang.annotation.Pointcut pcAnn = method.getAnnotation(org.aspectj.lang.annotation.Pointcut.class);
if (pcAnn != null) {
String name = method.getName();
if (name.startsWith(ajcMagic)) {
// extract real name
int nameStart = name.indexOf("$$");
name = name.substring(nameStart +2,name.length());
int nextDollar = name.indexOf("$");
if (nextDollar != -1) name = name.substring(0,nextDollar);
}
return new PointcutImpl(name,pcAnn.value(),method,AjTypeSystem.getAjType(method.getDeclaringClass()),pcAnn.argNames());
} else {
return null;
}
}
public Advice[] getDeclaredAdvice(AdviceKind... ofType) {
Set<AdviceKind> types;
if (ofType.length == 0) {
types = EnumSet.allOf(AdviceKind.class);
} else {
types = EnumSet.noneOf(AdviceKind.class);
types.addAll(Arrays.asList(ofType));
}
return getDeclaredAdvice(types);
}
public Advice[] getAdvice(AdviceKind... ofType) {
Set<AdviceKind> types;
if (ofType.length == 0) {
types = EnumSet.allOf(AdviceKind.class);
} else {
types = EnumSet.noneOf(AdviceKind.class);
types.addAll(Arrays.asList(ofType));
}
return getAdvice(types);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredAdvice(org.aspectj.lang.reflect.AdviceType)
*/
private Advice[] getDeclaredAdvice(Set ofAdviceTypes) {
if (declaredAdvice == null) initDeclaredAdvice();
List<Advice> adviceList = new ArrayList<Advice>();
for (Advice a : declaredAdvice) {
if (ofAdviceTypes.contains(a.getKind())) adviceList.add(a);
}
Advice[] ret = new Advice[adviceList.size()];
adviceList.toArray(ret);
return ret;
}
private void initDeclaredAdvice() {
Method[] methods = clazz.getDeclaredMethods();
List<Advice> adviceList = new ArrayList<Advice>();
for (Method method : methods) {
Advice advice = asAdvice(method);
if (advice != null) adviceList.add(advice);
}
declaredAdvice = new Advice[adviceList.size()];
adviceList.toArray(declaredAdvice);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredAdvice(org.aspectj.lang.reflect.AdviceType)
*/
private Advice[] getAdvice(Set ofAdviceTypes) {
if (advice == null) initAdvice();
List<Advice> adviceList = new ArrayList<Advice>();
for (Advice a : advice) {
if (ofAdviceTypes.contains(a.getKind())) adviceList.add(a);
}
Advice[] ret = new Advice[adviceList.size()];
adviceList.toArray(ret);
return ret;
}
private void initAdvice() {
Method[] methods = clazz.getMethods();
List<Advice> adviceList = new ArrayList<Advice>();
for (Method method : methods) {
Advice advice = asAdvice(method);
if (advice != null) adviceList.add(advice);
}
advice = new Advice[adviceList.size()];
adviceList.toArray(advice);
}
public Advice getAdvice(String name) throws NoSuchAdviceException {
if (name.equals("")) throw new IllegalArgumentException("use getAdvice(AdviceType...) instead for un-named advice");
if (advice == null) initAdvice();
for (Advice a : advice) {
if (a.getName().equals(name)) return a;
}
throw new NoSuchAdviceException(name);
}
public Advice getDeclaredAdvice(String name) throws NoSuchAdviceException {
if (name.equals("")) throw new IllegalArgumentException("use getAdvice(AdviceType...) instead for un-named advice");
if (declaredAdvice == null) initDeclaredAdvice();
for (Advice a : declaredAdvice) {
if (a.getName().equals(name)) return a;
}
throw new NoSuchAdviceException(name);
}
private Advice asAdvice(Method method) {
if (method.getAnnotations().length == 0) return null;
Before beforeAnn = method.getAnnotation(Before.class);
if (beforeAnn != null) return new AdviceImpl(method,beforeAnn.value(),AdviceKind.BEFORE);
After afterAnn = method.getAnnotation(After.class);
if (afterAnn != null) return new AdviceImpl(method,afterAnn.value(),AdviceKind.AFTER);
AfterReturning afterReturningAnn = method.getAnnotation(AfterReturning.class);
if (afterReturningAnn != null) {
String pcExpr = afterReturningAnn.pointcut();
if (pcExpr.equals("")) pcExpr = afterReturningAnn.value();
return new AdviceImpl(method,pcExpr,AdviceKind.AFTER_RETURNING,afterReturningAnn.returning());
}
AfterThrowing afterThrowingAnn = method.getAnnotation(AfterThrowing.class);
if (afterThrowingAnn != null) {
String pcExpr = afterThrowingAnn.pointcut();
if (pcExpr == null) pcExpr = afterThrowingAnn.value();
return new AdviceImpl(method,pcExpr,AdviceKind.AFTER_THROWING,afterThrowingAnn.throwing());
}
Around aroundAnn = method.getAnnotation(Around.class);
if (aroundAnn != null) return new AdviceImpl(method,aroundAnn.value(),AdviceKind.AROUND);
return null;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDMethod(java.lang.String, java.lang.Class, java.lang.Class...)
*/
public InterTypeMethodDeclaration getDeclaredITDMethod(String name,
AjType<?> target, AjType<?>... parameterTypes) throws NoSuchMethodException {
InterTypeMethodDeclaration[] itdms = getDeclaredITDMethods();
outer: for (InterTypeMethodDeclaration itdm : itdms) {
try {
if (!itdm.getName().equals(name)) continue;
AjType<?> itdTarget = itdm.getTargetType();
if (itdTarget.equals(target)) {
AjType<?>[] ptypes = itdm.getParameterTypes();
if (ptypes.length == parameterTypes.length) {
for (int i = 0; i < ptypes.length; i++) {
if (!ptypes[i].equals(parameterTypes[i]))
continue outer;
}
return itdm;
}
}
} catch (ClassNotFoundException cnf) {
// just move on to the next one
}
}
throw new NoSuchMethodException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDMethods()
*/
public InterTypeMethodDeclaration[] getDeclaredITDMethods() {
if (this.declaredITDMethods == null) {
List<InterTypeMethodDeclaration> itdms = new ArrayList<InterTypeMethodDeclaration>();
Method[] baseMethods = clazz.getDeclaredMethods();
for (Method m : baseMethods) {
if (!m.getName().contains("ajc$interMethod$")) continue;
if (m.isAnnotationPresent(ajcITD.class)) {
ajcITD ann = m.getAnnotation(ajcITD.class);
InterTypeMethodDeclaration itdm =
new InterTypeMethodDeclarationImpl(
this,ann.targetType(),ann.modifiers(),
ann.name(),m);
itdms.add(itdm);
}
}
addAnnotationStyleITDMethods(itdms,false);
this.declaredITDMethods = new InterTypeMethodDeclaration[itdms.size()];
itdms.toArray(this.declaredITDMethods);
}
return this.declaredITDMethods;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDMethod(java.lang.String, java.lang.Class, java.lang.Class...)
*/
public InterTypeMethodDeclaration getITDMethod(String name, AjType<?> target,
AjType<?>... parameterTypes)
throws NoSuchMethodException {
InterTypeMethodDeclaration[] itdms = getITDMethods();
outer: for (InterTypeMethodDeclaration itdm : itdms) {
try {
if (!itdm.getName().equals(name)) continue;
AjType<?> itdTarget = itdm.getTargetType();
if (itdTarget.equals(target)) {
AjType<?>[] ptypes = itdm.getParameterTypes();
if (ptypes.length == parameterTypes.length) {
for (int i = 0; i < ptypes.length; i++) {
if (!ptypes[i].equals(parameterTypes[i]))
continue outer;
}
return itdm;
}
}
} catch (ClassNotFoundException cnf) {
// just move on to the next one
}
}
throw new NoSuchMethodException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDMethods()
*/
public InterTypeMethodDeclaration[] getITDMethods() {
if (this.itdMethods == null) {
List<InterTypeMethodDeclaration> itdms = new ArrayList<InterTypeMethodDeclaration>();
Method[] baseMethods = clazz.getDeclaredMethods();
for (Method m : baseMethods) {
if (!m.getName().contains("ajc$interMethod$")) continue;
if (m.isAnnotationPresent(ajcITD.class)) {
ajcITD ann = m.getAnnotation(ajcITD.class);
if (!Modifier.isPublic(ann.modifiers())) continue;
InterTypeMethodDeclaration itdm =
new InterTypeMethodDeclarationImpl(
this,ann.targetType(),ann.modifiers(),
ann.name(),m);
itdms.add(itdm);
}
}
addAnnotationStyleITDMethods(itdms,true);
this.itdMethods = new InterTypeMethodDeclaration[itdms.size()];
itdms.toArray(this.itdMethods);
}
return this.itdMethods;
}
private void addAnnotationStyleITDMethods(List<InterTypeMethodDeclaration> toList, boolean publicOnly) {
if (isAspect()) {
for (Field f : clazz.getDeclaredFields()) {
if (!f.getType().isInterface()) continue;
if (!Modifier.isPublic(f.getModifiers()) || !Modifier.isStatic(f.getModifiers())) continue;
if (f.isAnnotationPresent(org.aspectj.lang.annotation.DeclareParents.class)) {
for (Method itdM : f.getType().getDeclaredMethods()) {
if (!Modifier.isPublic(itdM.getModifiers()) && publicOnly) continue;
InterTypeMethodDeclaration itdm = new InterTypeMethodDeclarationImpl(
this, AjTypeSystem.getAjType(f.getType()), itdM
);
toList.add(itdm);
}
}
}
}
}
private void addAnnotationStyleITDFields(List<InterTypeFieldDeclaration> toList, boolean publicOnly) {
return;
//AV: I think it is meaningless
//@AJ decp is interface driven ie no field
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDConstructor(java.lang.Class, java.lang.Class...)
*/
public InterTypeConstructorDeclaration getDeclaredITDConstructor(
AjType<?> target, AjType<?>... parameterTypes) throws NoSuchMethodException {
InterTypeConstructorDeclaration[] itdcs = getDeclaredITDConstructors();
outer: for (InterTypeConstructorDeclaration itdc : itdcs) {
try {
AjType<?> itdTarget = itdc.getTargetType();
if (itdTarget.equals(target)) {
AjType<?>[] ptypes = itdc.getParameterTypes();
if (ptypes.length == parameterTypes.length) {
for (int i = 0; i < ptypes.length; i++) {
if (!ptypes[i].equals(parameterTypes[i]))
continue outer;
}
return itdc;
}
}
} catch (ClassNotFoundException cnf) {
// just move on to the next one
}
}
throw new NoSuchMethodException();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDConstructors()
*/
public InterTypeConstructorDeclaration[] getDeclaredITDConstructors() {
if (this.declaredITDCons == null) {
List<InterTypeConstructorDeclaration> itdcs = new ArrayList<InterTypeConstructorDeclaration>();
Method[] baseMethods = clazz.getDeclaredMethods();
for (Method m : baseMethods) {
if (!m.getName().contains("ajc$postInterConstructor")) continue;
if (m.isAnnotationPresent(ajcITD.class)) {
ajcITD ann = m.getAnnotation(ajcITD.class);
InterTypeConstructorDeclaration itdc =
new InterTypeConstructorDeclarationImpl(this,ann.targetType(),ann.modifiers(),m);
itdcs.add(itdc);
}
}
this.declaredITDCons = new InterTypeConstructorDeclaration[itdcs.size()];
itdcs.toArray(this.declaredITDCons);
}
return this.declaredITDCons;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDConstructor(java.lang.Class, java.lang.Class...)
*/
public InterTypeConstructorDeclaration getITDConstructor(AjType<?> target,
AjType<?>... parameterTypes) throws NoSuchMethodException {
InterTypeConstructorDeclaration[] itdcs = getITDConstructors();
outer: for (InterTypeConstructorDeclaration itdc : itdcs) {
try {
AjType<?> itdTarget = itdc.getTargetType();
if (itdTarget.equals(target)) {
AjType<?>[] ptypes = itdc.getParameterTypes();
if (ptypes.length == parameterTypes.length) {
for (int i = 0; i < ptypes.length; i++) {
if (!ptypes[i].equals(parameterTypes[i]))
continue outer;
}
return itdc;
}
}
} catch (ClassNotFoundException cnf) {
// just move on to the next one
}
}
throw new NoSuchMethodException();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDConstructors()
*/
public InterTypeConstructorDeclaration[] getITDConstructors() {
if (this.itdCons == null) {
List<InterTypeConstructorDeclaration> itdcs = new ArrayList<InterTypeConstructorDeclaration>();
Method[] baseMethods = clazz.getMethods();
for (Method m : baseMethods) {
if (!m.getName().contains("ajc$postInterConstructor")) continue;
if (m.isAnnotationPresent(ajcITD.class)) {
ajcITD ann = m.getAnnotation(ajcITD.class);
if (!Modifier.isPublic(ann.modifiers())) continue;
InterTypeConstructorDeclaration itdc =
new InterTypeConstructorDeclarationImpl(this,ann.targetType(),ann.modifiers(),m);
itdcs.add(itdc);
}
}
this.itdCons = new InterTypeConstructorDeclaration[itdcs.size()];
itdcs.toArray(this.itdCons);
}
return this.itdCons; }
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDField(java.lang.String, java.lang.Class)
*/
public InterTypeFieldDeclaration getDeclaredITDField(String name,
AjType<?> target) throws NoSuchFieldException {
InterTypeFieldDeclaration[] itdfs = getDeclaredITDFields();
for (InterTypeFieldDeclaration itdf : itdfs) {
if (itdf.getName().equals(name)) {
try {
AjType<?> itdTarget = itdf.getTargetType();
if (itdTarget.equals(target)) return itdf;
} catch (ClassNotFoundException cnfEx) {
// move on to next field
}
}
}
throw new NoSuchFieldException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclaredITDFields()
*/
public InterTypeFieldDeclaration[] getDeclaredITDFields() {
List<InterTypeFieldDeclaration> itdfs = new ArrayList<InterTypeFieldDeclaration>();
if (this.declaredITDFields == null) {
Method[] baseMethods = clazz.getDeclaredMethods();
for(Method m : baseMethods) {
if (m.isAnnotationPresent(ajcITD.class)) {
if (!m.getName().contains("ajc$interFieldInit")) continue;
ajcITD ann = m.getAnnotation(ajcITD.class);
String interFieldInitMethodName = m.getName();
String interFieldGetDispatchMethodName =
interFieldInitMethodName.replace("FieldInit","FieldGetDispatch");
try {
Method dispatch = clazz.getDeclaredMethod(interFieldGetDispatchMethodName, m.getParameterTypes());
InterTypeFieldDeclaration itdf = new InterTypeFieldDeclarationImpl(
this,ann.targetType(),ann.modifiers(),ann.name(),
AjTypeSystem.getAjType(dispatch.getReturnType()),
dispatch.getGenericReturnType());
itdfs.add(itdf);
} catch (NoSuchMethodException nsmEx) {
throw new IllegalStateException("Can't find field get dispatch method for " + m.getName());
}
}
}
addAnnotationStyleITDFields(itdfs, false);
this.declaredITDFields = new InterTypeFieldDeclaration[itdfs.size()];
itdfs.toArray(this.declaredITDFields);
}
return this.declaredITDFields;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDField(java.lang.String, java.lang.Class)
*/
public InterTypeFieldDeclaration getITDField(String name, AjType<?> target)
throws NoSuchFieldException {
InterTypeFieldDeclaration[] itdfs = getITDFields();
for (InterTypeFieldDeclaration itdf : itdfs) {
if (itdf.getName().equals(name)) {
try {
AjType<?> itdTarget = itdf.getTargetType();
if (itdTarget.equals(target)) return itdf;
} catch (ClassNotFoundException cnfEx) {
// move on to next field
}
}
}
throw new NoSuchFieldException(name);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getITDFields()
*/
public InterTypeFieldDeclaration[] getITDFields() {
List<InterTypeFieldDeclaration> itdfs = new ArrayList<InterTypeFieldDeclaration>();
if (this.itdFields == null) {
Method[] baseMethods = clazz.getMethods();
for(Method m : baseMethods) {
if (m.isAnnotationPresent(ajcITD.class)) {
ajcITD ann = m.getAnnotation(ajcITD.class);
if (!m.getName().contains("ajc$interFieldInit")) continue;
if (!Modifier.isPublic(ann.modifiers())) continue;
String interFieldInitMethodName = m.getName();
String interFieldGetDispatchMethodName =
interFieldInitMethodName.replace("FieldInit","FieldGetDispatch");
try {
Method dispatch = m.getDeclaringClass().getDeclaredMethod(interFieldGetDispatchMethodName, m.getParameterTypes());
InterTypeFieldDeclaration itdf = new InterTypeFieldDeclarationImpl(
this,ann.targetType(),ann.modifiers(),ann.name(),
AjTypeSystem.getAjType(dispatch.getReturnType()),
dispatch.getGenericReturnType());
itdfs.add(itdf);
} catch (NoSuchMethodException nsmEx) {
throw new IllegalStateException("Can't find field get dispatch method for " + m.getName());
}
}
}
addAnnotationStyleITDFields(itdfs, true);
this.itdFields = new InterTypeFieldDeclaration[itdfs.size()];
itdfs.toArray(this.itdFields);
}
return this.itdFields;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclareErrorOrWarnings()
*/
public DeclareErrorOrWarning[] getDeclareErrorOrWarnings() {
List<DeclareErrorOrWarning> deows = new ArrayList<DeclareErrorOrWarning>();
for (Field field : clazz.getDeclaredFields()) {
try {
if (field.isAnnotationPresent(DeclareWarning.class)) {
DeclareWarning dw = field.getAnnotation(DeclareWarning.class);
if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
String message = (String) field.get(null);
DeclareErrorOrWarningImpl deow = new DeclareErrorOrWarningImpl(dw.value(),message,false,this);
deows.add(deow);
}
} else if (field.isAnnotationPresent(DeclareError.class)) {
DeclareError de = field.getAnnotation(DeclareError.class);
if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
String message = (String) field.get(null);
DeclareErrorOrWarningImpl deow = new DeclareErrorOrWarningImpl(de.value(),message,true,this);
deows.add(deow);
}
}
} catch (IllegalArgumentException e) {
// just move on to the next field
} catch (IllegalAccessException e) {
// just move on to the next field
}
}
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(ajcDeclareEoW.class)) {
ajcDeclareEoW deowAnn = method.getAnnotation(ajcDeclareEoW.class);
DeclareErrorOrWarning deow = new DeclareErrorOrWarningImpl(deowAnn.pointcut(),deowAnn.message(),deowAnn.isError(),this);
deows.add(deow);
}
}
DeclareErrorOrWarning[] ret = new DeclareErrorOrWarning[deows.size()];
deows.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclareParents()
*/
public DeclareParents[] getDeclareParents() {
List<DeclareParents> decps = new ArrayList<DeclareParents>();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(ajcDeclareParents.class)) {
ajcDeclareParents decPAnn = method.getAnnotation(ajcDeclareParents.class);
DeclareParentsImpl decp = new DeclareParentsImpl(
decPAnn.targetTypePattern(),
decPAnn.parentTypes(),
decPAnn.isExtends(),
this
);
decps.add(decp);
}
}
addAnnotationStyleDeclareParents(decps);
if (getSupertype().isAspect()) {
decps.addAll(Arrays.asList(getSupertype().getDeclareParents()));
}
DeclareParents[] ret = new DeclareParents[decps.size()];
decps.toArray(ret);
return ret;
}
private void addAnnotationStyleDeclareParents(List<DeclareParents> toList) {
for (Field f : clazz.getDeclaredFields()) {
if (f.isAnnotationPresent(org.aspectj.lang.annotation.DeclareImplements.class)) {
if (!f.getType().isInterface()) continue;
org.aspectj.lang.annotation.DeclareImplements ann = f.getAnnotation(org.aspectj.lang.annotation.DeclareImplements.class);
String parentType = f.getType().getName();
DeclareParentsImpl decp = new DeclareParentsImpl(
ann.value(),
parentType,
false,
this
);
toList.add(decp);
}
if (f.isAnnotationPresent(org.aspectj.lang.annotation.DeclareParents.class)
&& Modifier.isStatic(f.getModifiers())
&& Modifier.isPublic(f.getModifiers())) {
if (!f.getType().isInterface()) continue;
org.aspectj.lang.annotation.DeclareParents ann = f.getAnnotation(org.aspectj.lang.annotation.DeclareParents.class);
String parentType = f.getType().getName();
DeclareParentsImpl decp = new DeclareParentsImpl(
ann.value(),
parentType,
false,
this
);
toList.add(decp);
}
}
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclareSofts()
*/
public DeclareSoft[] getDeclareSofts() {
List<DeclareSoft> decs = new ArrayList<DeclareSoft>();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(ajcDeclareSoft.class)) {
ajcDeclareSoft decSAnn = method.getAnnotation(ajcDeclareSoft.class);
DeclareSoftImpl ds = new DeclareSoftImpl(
this,
decSAnn.pointcut(),
decSAnn.exceptionType()
);
decs.add(ds);
}
}
if (getSupertype().isAspect()) {
decs.addAll(Arrays.asList(getSupertype().getDeclareSofts()));
}
DeclareSoft[] ret = new DeclareSoft[decs.size()];
decs.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclareAnnotations()
*/
public DeclareAnnotation[] getDeclareAnnotations() {
List<DeclareAnnotation> decAs = new ArrayList<DeclareAnnotation>();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(ajcDeclareAnnotation.class)) {
ajcDeclareAnnotation decAnn = method.getAnnotation(ajcDeclareAnnotation.class);
// the target annotation is on this method...
Annotation targetAnnotation = null;
Annotation[] anns = method.getAnnotations();
for (Annotation ann: anns) {
if (ann.annotationType() != ajcDeclareAnnotation.class) {
// this must be the one...
targetAnnotation = ann;
break;
}
}
DeclareAnnotationImpl da = new DeclareAnnotationImpl(
this,
decAnn.kind(),
decAnn.pattern(),
targetAnnotation,
decAnn.annotation()
);
decAs.add(da);
}
}
if (getSupertype().isAspect()) {
decAs.addAll(Arrays.asList(getSupertype().getDeclareAnnotations()));
}
DeclareAnnotation[] ret = new DeclareAnnotation[decAs.size()];
decAs.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getDeclarePrecedence()
*/
public DeclarePrecedence[] getDeclarePrecedence() {
List<DeclarePrecedence> decps = new ArrayList<DeclarePrecedence>();
// @AspectJ Style
if (clazz.isAnnotationPresent(org.aspectj.lang.annotation.DeclarePrecedence.class)) {
org.aspectj.lang.annotation.DeclarePrecedence ann =
clazz.getAnnotation(org.aspectj.lang.annotation.DeclarePrecedence.class);
DeclarePrecedenceImpl decp = new DeclarePrecedenceImpl(
ann.value(),
this
);
decps.add(decp);
}
// annotated code-style
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(ajcDeclarePrecedence.class)) {
ajcDeclarePrecedence decPAnn = method.getAnnotation(ajcDeclarePrecedence.class);
DeclarePrecedenceImpl decp = new DeclarePrecedenceImpl(
decPAnn.value(),
this
);
decps.add(decp);
}
}
if (getSupertype().isAspect()) {
decps.addAll(Arrays.asList(getSupertype().getDeclarePrecedence()));
}
DeclarePrecedence[] ret = new DeclarePrecedence[decps.size()];
decps.toArray(ret);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getEnumConstants()
*/
public T[] getEnumConstants() {
return clazz.getEnumConstants();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#getTypeParameters()
*/
public TypeVariable<Class<T>>[] getTypeParameters() {
return clazz.getTypeParameters();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isEnum()
*/
public boolean isEnum() {
return clazz.isEnum();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isInstance(java.lang.Object)
*/
public boolean isInstance(Object o) {
return clazz.isInstance(o);
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isInterface()
*/
public boolean isInterface() {
return clazz.isInterface();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isLocalClass()
*/
public boolean isLocalClass() {
return clazz.isLocalClass() && !isAspect();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isMemberClass()
*/
public boolean isMemberClass() {
return clazz.isMemberClass() && !isAspect();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isArray()
*/
public boolean isArray() {
return clazz.isArray();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isPrimitive()
*/
public boolean isPrimitive() {
return clazz.isPrimitive();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isAspect()
*/
public boolean isAspect() {
return clazz.getAnnotation(Aspect.class) != null;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.AjType#isMemberAspect()
*/
public boolean isMemberAspect() {
return clazz.isMemberClass() && isAspect();
}
public boolean isPrivileged() {
return isAspect() && clazz.isAnnotationPresent(ajcPrivileged.class);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AjTypeImpl)) return false;
AjTypeImpl other = (AjTypeImpl) obj;
return other.clazz.equals(clazz);
}
@Override
public int hashCode() {
return clazz.hashCode();
}
private AjType<?>[] toAjTypeArray(Class<?>[] classes) {
AjType<?>[] ajtypes = new AjType<?>[classes.length];
for (int i = 0; i < ajtypes.length; i++) {
ajtypes[i] = AjTypeSystem.getAjType(classes[i]);
}
return ajtypes;
}
private Class<?>[] toClassArray(AjType<?>[] ajTypes) {
Class<?>[] classes = new Class<?>[ajTypes.length];
for (int i = 0; i < classes.length; i++) {
classes[i] = ajTypes[i].getJavaClass();
}
return classes;
}
public String toString() { return getName(); }
}
|
114,332
|
Bug 114332 Reflection API not detecting ITD method correctly in all circumstances
| null |
resolved fixed
|
735d94f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-21T22:05:46Z
| 2005-10-31T09:13:20Z
|
aspectj5rt/java5-src/org/aspectj/internal/lang/reflect/InterTypeConstructorDeclarationImpl.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.internal.lang.reflect;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.InterTypeConstructorDeclaration;
/**
* @author colyer
*
*/
public class InterTypeConstructorDeclarationImpl extends
InterTypeDeclarationImpl implements InterTypeConstructorDeclaration {
private Method baseMethod;
/**
* @param decType
* @param target
* @param mods
*/
public InterTypeConstructorDeclarationImpl(AjType<?> decType,
String target, int mods, Method baseMethod) {
super(decType, target, mods);
this.baseMethod = baseMethod;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeConstructorDeclaration#getParameters()
*/
public AjType<?>[] getParameterTypes() {
Class<?>[] baseTypes = baseMethod.getParameterTypes();
AjType<?>[] ret = new AjType<?>[baseTypes.length-1];
for (int i = 1; i < baseTypes.length; i++) {
ret[i-1] = AjTypeSystem.getAjType(baseTypes[i]);
}
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeConstructorDeclaration#getGenericParameters()
*/
public Type[] getGenericParameterTypes() {
Type[] baseTypes = baseMethod.getGenericParameterTypes();
Type[] ret = new AjType<?>[baseTypes.length-1];
for (int i = 1; i < baseTypes.length; i++) {
if (baseTypes[i] instanceof Class) {
ret[i-1] = AjTypeSystem.getAjType((Class<?>)baseTypes[i]);
} else {
ret[i-1] = baseTypes[i];
}
}
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeConstructorDeclaration#getDeclaredExceptionTypes()
*/
public AjType<?>[] getExceptionTypes() {
Class<?>[] baseTypes = baseMethod.getExceptionTypes();
AjType<?>[] ret = new AjType<?>[baseTypes.length];
for (int i = 0; i < baseTypes.length; i++) {
ret[i] = AjTypeSystem.getAjType(baseTypes[i]);
}
return ret;
}
}
|
114,332
|
Bug 114332 Reflection API not detecting ITD method correctly in all circumstances
| null |
resolved fixed
|
735d94f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-21T22:05:46Z
| 2005-10-31T09:13:20Z
|
aspectj5rt/java5-src/org/aspectj/internal/lang/reflect/InterTypeDeclarationImpl.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.internal.lang.reflect;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.InterTypeDeclaration;
/**
* @author colyer
*
*/
public class InterTypeDeclarationImpl implements InterTypeDeclaration {
private AjType<?> declaringType;
private String targetTypeName;
private AjType<?> targetType;
private int modifiers;
public InterTypeDeclarationImpl(AjType<?> decType, String target, int mods) {
this.declaringType = decType;
this.targetTypeName = target;
this.modifiers = mods;
try {
this.targetType = (AjType<?>) StringToType.stringToType(target, decType.getJavaClass());
} catch (ClassNotFoundException cnf) {
// we'll only report this later if the user asks for the target type.
}
}
public InterTypeDeclarationImpl(AjType<?> decType, AjType<?> targetType, int mods) {
this.declaringType = decType;
this.targetType = targetType;
this.targetTypeName = targetType.getName();
this.modifiers = mods;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeDeclaration#getDeclaringType()
*/
public AjType<?> getDeclaringType() {
return this.declaringType;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeDeclaration#getTargetType()
*/
public AjType<?> getTargetType() throws ClassNotFoundException {
if (this.targetType == null) throw new ClassNotFoundException(this.targetTypeName);
return this.targetType;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeDeclaration#getModifiers()
*/
public int getModifiers() {
return this.modifiers;
}
}
|
114,332
|
Bug 114332 Reflection API not detecting ITD method correctly in all circumstances
| null |
resolved fixed
|
735d94f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-21T22:05:46Z
| 2005-10-31T09:13:20Z
|
aspectj5rt/java5-src/org/aspectj/internal/lang/reflect/InterTypeFieldDeclarationImpl.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.internal.lang.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.InterTypeFieldDeclaration;
/**
* @author colyer
*
*/
public class InterTypeFieldDeclarationImpl extends InterTypeDeclarationImpl
implements InterTypeFieldDeclaration {
private String name;
private AjType<?> type;
private Type genericType;
/**
* @param decType
* @param target
* @param mods
*/
public InterTypeFieldDeclarationImpl(AjType<?> decType, String target,
int mods, String name, AjType<?> type, Type genericType) {
super(decType, target, mods);
this.name = name;
this.type = type;
this.genericType = genericType;
}
public InterTypeFieldDeclarationImpl(AjType<?> decType, AjType<?> targetType, Field base) {
super(decType,targetType,base.getModifiers());
this.name = base.getName();
this.type = AjTypeSystem.getAjType(base.getType());
Type gt = base.getGenericType();
if (gt instanceof Class) {
this.genericType = AjTypeSystem.getAjType((Class<?>)gt);
} else {
this.genericType = gt;
}
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeFieldDeclaration#getName()
*/
public String getName() {
return this.name;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeFieldDeclaration#getType()
*/
public AjType<?> getType() {
return this.type;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeFieldDeclaration#getGenericType()
*/
public Type getGenericType() {
return this.genericType;
}
}
|
114,332
|
Bug 114332 Reflection API not detecting ITD method correctly in all circumstances
| null |
resolved fixed
|
735d94f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-21T22:05:46Z
| 2005-10-31T09:13:20Z
|
aspectj5rt/java5-src/org/aspectj/internal/lang/reflect/InterTypeMethodDeclarationImpl.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.internal.lang.reflect;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.InterTypeMethodDeclaration;
/**
* @author colyer
*
*/
public class InterTypeMethodDeclarationImpl extends InterTypeDeclarationImpl
implements InterTypeMethodDeclaration {
private String name;
private Method baseMethod;
private int parameterAdjustmentFactor = 1; // no of fake params at start of baseMethod
private AjType<?>[] parameterTypes;
private Type[] genericParameterTypes;
private AjType<?> returnType;
private Type genericReturnType;
private AjType<?>[] exceptionTypes;
/**
* @param decType
* @param target
* @param mods
*/
public InterTypeMethodDeclarationImpl(AjType<?> decType, String target,
int mods, String name, Method itdInterMethod) {
super(decType, target, mods);
this.name = name;
this.baseMethod = itdInterMethod;
}
public InterTypeMethodDeclarationImpl(AjType<?> decType, AjType<?> targetType, Method base) {
super(decType,targetType,base.getModifiers());
this.parameterAdjustmentFactor = 0;
this.name = base.getName();
this.baseMethod = base;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeMethodDeclaration#getName()
*/
public String getName() {
return this.name;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeMethodDeclaration#getReturnType()
*/
public AjType<?> getReturnType() {
return AjTypeSystem.getAjType(baseMethod.getReturnType());
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeMethodDeclaration#getGenericReturnType()
*/
public Type getGenericReturnType() {
Type gRet = baseMethod.getGenericReturnType();
if (gRet instanceof Class) {
return AjTypeSystem.getAjType((Class<?>)gRet);
}
return gRet;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeMethodDeclaration#getParameters()
*/
public AjType<?>[] getParameterTypes() {
Class<?>[] baseTypes = baseMethod.getParameterTypes();
AjType<?>[] ret = new AjType<?>[baseTypes.length -parameterAdjustmentFactor];
for (int i = parameterAdjustmentFactor; i < baseTypes.length; i++) {
ret[i-parameterAdjustmentFactor] = AjTypeSystem.getAjType(baseTypes[i]);
}
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeMethodDeclaration#getGenericParameters()
*/
public Type[] getGenericParameterTypes() {
Type[] baseTypes = baseMethod.getGenericParameterTypes();
Type[] ret = new AjType<?>[baseTypes.length-parameterAdjustmentFactor];
for (int i = parameterAdjustmentFactor; i < baseTypes.length; i++) {
if (baseTypes[i] instanceof Class) {
ret[i-parameterAdjustmentFactor] = AjTypeSystem.getAjType((Class<?>)baseTypes[i]);
} else {
ret[i-parameterAdjustmentFactor] = baseTypes[i];
}
}
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.InterTypeMethodDeclaration#getTypeParameters()
*/
public TypeVariable<Method>[] getTypeParameters() {
return baseMethod.getTypeParameters();
}
public AjType<?>[] getExceptionTypes() {
Class<?>[] baseTypes = baseMethod.getExceptionTypes();
AjType<?>[] ret = new AjType<?>[baseTypes.length];
for (int i = 0; i < baseTypes.length; i++) {
ret[i] = AjTypeSystem.getAjType(baseTypes[i]);
}
return ret;
}
}
|
114,332
|
Bug 114332 Reflection API not detecting ITD method correctly in all circumstances
| null |
resolved fixed
|
735d94f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-21T22:05:46Z
| 2005-10-31T09:13:20Z
|
tests/java5/reflection/ReflectBilling.java
| |
114,332
|
Bug 114332 Reflection API not detecting ITD method correctly in all circumstances
| null |
resolved fixed
|
735d94f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-21T22:05:46Z
| 2005-10-31T09:13:20Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
// public void testSelfBoundGenerics_pr117296() { runTest("self bounding generic types");}
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 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");
}
/*
* 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);
}
// 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);
}
}
|
103,051
|
Bug 103051 Declare Soft not Affecting Explicit Adviceexecution
|
The following aspect should compile successfully: import java.io.IOException; public aspect SoftenAdvice { declare soft: IOException: within(SoftenAdvice) && adviceexecution(); before() : execution(* main(..)) { throw new IOException("test"); } public static void main(String args[]) { } } But both 1.5.0M2 and HEAD (from 2 days ago) give this output: C:\devel\scratch\err>ajc SoftenAdvice.aj C:\devel\scratch\err\SoftenAdvice.aj:7 [error] Unhandled exception type IOExcept ion throw new IOException("test"); ^^^^^^^^^^^^^^^^^^^^ 1 error However if you change the declare soft to be the following, it correctly softens at the advice execution join point. declare soft: IOException: within(SoftenAdvice) && !withincode(* *(..));
|
resolved fixed
|
554e733
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-22T09:28:09Z
| 2005-07-07T18:13:20Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten 2004-07-26 extended to allow overloading of
* hierarchy builder
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding;
import org.aspectj.weaver.BoundedReferenceType;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeFactory;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableDeclaringElement;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.UnresolvedTypeVariableReferenceType;
import org.aspectj.weaver.World;
/**
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
private AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private boolean xSerializableAspects;
private World world;
private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap();
public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) {
AjLookupEnvironment aenv = (AjLookupEnvironment)env;
return aenv.factory;
}
public static EclipseFactory fromScopeLookupEnvironment(Scope scope) {
return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment);
}
public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) {
this.lookupEnvironment = lookupEnvironment;
this.buildManager = buildManager;
this.world = buildManager.getWorld();
this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects();
}
public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) {
this.lookupEnvironment = lookupEnvironment;
this.world = world;
this.xSerializableAspects = xSer;
this.buildManager = null;
}
public World getWorld() {
return world;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedType fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedType.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedType ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedType fromTypeBindingToRTX(TypeBinding tb) {
if (tb == null) return ResolvedType.MISSING;
ResolvedType ret = getWorld().resolve(fromBinding(tb));
return ret;
}
public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedType.NONE;
}
int len = bindings.length;
ResolvedType[] ret = new ResolvedType[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
public static String getName(TypeBinding binding) {
if (binding instanceof TypeVariableBinding) {
// The first bound may be null - so default to object?
TypeVariableBinding tvb = (TypeVariableBinding)binding;
if (tvb.firstBound!=null) {
return getName(tvb.firstBound);
} else {
return getName(tvb.superclass);
}
}
if (binding instanceof ReferenceBinding) {
return new String(
CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.'));
}
String packageName = new String(binding.qualifiedPackageName());
String className = new String(binding.qualifiedSourceName()).replace('.', '$');
if (packageName.length() > 0) {
className = packageName + "." + className;
}
//XXX doesn't handle arrays correctly (or primitives?)
return new String(className);
}
/**
* Some generics notes:
*
* Andy 6-May-05
* We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we
* see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not
* sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back
* the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to
* remember the type variable.
* Adrian 10-July-05
* When we forget it's a type variable we come unstuck when getting the declared members of a parameterized
* type - since we don't know it's a type variable we can't replace it with the type parameter.
*/
//??? going back and forth between strings and bindings is a waste of cycles
public UnresolvedType fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedType.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tb = (TypeVariableBinding) binding;
UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb);
return utvrt;
}
// handle arrays since the component type may need special treatment too...
if (binding instanceof ArrayBinding) {
ArrayBinding aBinding = (ArrayBinding) binding;
UnresolvedType componentType = fromBinding(aBinding.leafComponentType);
return UnresolvedType.makeArray(componentType, aBinding.dimensions);
}
if (binding instanceof WildcardBinding) {
WildcardBinding eWB = (WildcardBinding) binding;
UnresolvedType theType = TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature()));
// Repair the bound
// e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then
// the type variable in the unresolvedtype will be correct only in name. In that
// case let's set it correctly based on the one in the eclipse WildcardBinding
UnresolvedType theBound = null;
if (eWB.bound instanceof TypeVariableBinding) {
theBound = fromTypeVariableBinding((TypeVariableBinding)eWB.bound);
} else {
theBound = fromBinding(eWB.bound);
}
if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound);
if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound);
return theType;
}
if (binding instanceof ParameterizedTypeBinding) {
if (binding instanceof RawTypeBinding) {
// special case where no parameters are specified!
return UnresolvedType.forRawTypeName(getName(binding));
}
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
UnresolvedType[] arguments = null;
if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227)
arguments = new UnresolvedType[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = fromBinding(ptb.arguments[i]);
}
}
String baseTypeSignature = null;
ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true);
if (baseType != ResolvedType.MISSING) {
// can legitimately be missing if a bound refers to a type we haven't added to the world yet...
if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType();
baseTypeSignature = baseType.getErasureSignature();
} else {
baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature();
}
// Create an unresolved parameterized type. We can't create a resolved one as the
// act of resolution here may cause recursion problems since the parameters may
// be type variables that we haven't fixed up yet.
if (arguments==null) arguments=new UnresolvedType[0];
String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1);
return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments);
}
// Convert the source type binding for a generic type into a generic UnresolvedType
// notice we can easily determine the type variables from the eclipse object
// and we can recover the generic signature from it too - so we pass those
// to the forGenericType() method.
if (binding.isGenericType() &&
!binding.isParameterizedType() &&
!binding.isRawType()) {
TypeVariableBinding[] tvbs = binding.typeVariables();
TypeVariable[] tVars = new TypeVariable[tvbs.length];
for (int i = 0; i < tvbs.length; i++) {
TypeVariableBinding eclipseV = tvbs[i];
String name = CharOperation.charToString(eclipseV.sourceName);
tVars[i] = new TypeVariable(name,fromBinding(eclipseV.superclass()),fromBindings(eclipseV.superInterfaces()));
}
//TODO asc generics - temporary guard....
if (!(binding instanceof SourceTypeBinding))
throw new RuntimeException("Cant get the generic sig for "+binding.debugName());
return UnresolvedType.forGenericType(getName(binding),tVars,
CharOperation.charToString(((SourceTypeBinding)binding).genericSignature()));
}
// LocalTypeBinding have a name $Local$, we can get the real name by using the signature....
if (binding instanceof LocalTypeBinding) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
return UnresolvedType.forSignature(new String(binding.signature()));
} else {
// we're reporting a problem and don't have a resolved name for an
// anonymous local type yet, report the issue on the enclosing type
return UnresolvedType.forSignature(new String(ltb.enclosingType.signature()));
}
}
return UnresolvedType.forName(getName(binding));
}
/**
* Some type variables refer to themselves recursively, this enables us to avoid
* recursion problems.
*/
private static Map typeVariableBindingsInProgress = new HashMap();
/**
* Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ
* form (TypeVariable).
*/
private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) {
// first, check for recursive call to this method for the same tvBinding
if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) {
return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding);
}
// Check if its a type variable binding that we need to recover to an alias...
if (typeVariablesForAliasRecovery!=null) {
String aliasname = (String)typeVariablesForAliasRecovery.get(aTypeVariableBinding);
if (aliasname!=null) {
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
ret.setTypeVariable(new TypeVariable(aliasname));
return ret;
}
}
if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) {
return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName));
}
// Create the UnresolvedTypeVariableReferenceType for the type variable
String name = CharOperation.charToString(aTypeVariableBinding.sourceName());
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
typeVariableBindingsInProgress.put(aTypeVariableBinding,ret);
// Dont set any bounds here, you'll get in a recursive mess
// TODO -- what about lower bounds??
UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass());
UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length];
for (int i = 0; i < superinterfaces.length; i++) {
superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]);
}
TypeVariable tv = new TypeVariable(name,superclassType,superinterfaces);
tv.setUpperBound(superclassType);
tv.setAdditionalInterfaceBounds(superinterfaces);
tv.setRank(aTypeVariableBinding.rank);
if (aTypeVariableBinding.declaringElement instanceof MethodBinding) {
tv.setDeclaringElementKind(TypeVariable.METHOD);
// tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement);
} else {
tv.setDeclaringElementKind(TypeVariable.TYPE);
// // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement));
}
ret.setTypeVariable(tv);
if (aTypeVariableBinding.declaringElement instanceof MethodBinding)
typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret);
typeVariableBindingsInProgress.remove(aTypeVariableBinding);
return ret;
}
public UnresolvedType[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return UnresolvedType.NONE;
int len = bindings.length;
UnresolvedType[] ret = new UnresolvedType[len];
for (int i=0; i<len; i++) {
ret[i] = fromBinding(bindings[i]);
}
return ret;
}
public static ASTNode astForLocation(IHasPosition location) {
return new EmptyStatement(location.getStart(), location.getEnd());
}
public Collection getDeclareParents() {
return getWorld().getDeclareParents();
}
public Collection getDeclareAnnotationOnTypes() {
return getWorld().getDeclareAnnotationOnTypes();
}
public Collection getDeclareAnnotationOnFields() {
return getWorld().getDeclareAnnotationOnFields();
}
public Collection getDeclareAnnotationOnMethods() {
return getWorld().getDeclareAnnotationOnMethods();
}
public Collection finishedTypeMungers = null;
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers();
// XXX by Andy: why do we mix up the mungers here? it means later we know about two sets
// and the late ones are a subset of the complete set? (see pr114436)
baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers());
for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next();
EclipseTypeMunger etm = makeEclipseTypeMunger(munger);
if (etm != null) ret.add(etm);
}
finishedTypeMungers = ret;
}
public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) {
//System.err.println("make munger: " + concrete);
//!!! can't do this if we want incremental to work right
//if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete;
//System.err.println(" was not eclipse");
if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) {
AbstractMethodDeclaration method = null;
if (concrete instanceof EclipseTypeMunger) {
method = ((EclipseTypeMunger)concrete).getSourceMethod();
}
EclipseTypeMunger ret =
new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method);
if (ret.getSourceLocation() == null) {
ret.setSourceLocation(concrete.getSourceLocation());
}
return ret;
} else {
return null;
}
}
public Collection getTypeMungers() {
//??? assert finishedTypeMungers != null
return finishedTypeMungers;
}
public ResolvedMember makeResolvedMember(MethodBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
/**
* Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done
* in the scope of some type variables. Before converting the parts of a methodbinding
* (params, return type) we store the type variables in this structure, then should any
* component of the method binding refer to them, we grab them from the map.
*/
private Map typeVariablesForThisMember = new HashMap();
/**
* This is a map from typevariablebindings (eclipsey things) to the names the user
* originally specified in their ITD. For example if the target is 'interface I<N extends Number> {}'
* and the ITD was 'public void I<X>.m(List<X> lxs) {}' then this map would contain a pointer
* from the eclipse type 'N extends Number' to the letter 'X'.
*/
private Map typeVariablesForAliasRecovery;
/**
* Construct a resolvedmember from a methodbinding. The supplied map tells us about any
* typevariablebindings that replaced typevariables whilst the compiler was resolving types -
* this only happens if it is a generic itd that shares type variables with its target type.
*/
public ResolvedMember makeResolvedMemberForITD(MethodBinding binding,TypeBinding declaringType,
Map /*TypeVariableBinding > original alias name*/ recoveryAliases) {
ResolvedMember result = null;
try {
typeVariablesForAliasRecovery = recoveryAliases;
result = makeResolvedMember(binding,declaringType);
} finally {
typeVariablesForAliasRecovery = null;
}
return result;
}
public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
// Convert the type variables and store them
UnresolvedType[] ajTypeRefs = null;
typeVariablesForThisMember.clear();
// This is the set of type variables available whilst building the resolved member...
if (binding.typeVariables!=null) {
ajTypeRefs = new UnresolvedType[binding.typeVariables.length];
for (int i = 0; i < binding.typeVariables.length; i++) {
ajTypeRefs[i] = fromBinding(binding.typeVariables[i]);
typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]);
}
}
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
ResolvedMemberImpl ret = new ResolvedMemberImpl(
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD,
realDeclaringType,
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions)
);
if (binding.isVarargs()) {
ret.setVarargsMethod();
}
if (ajTypeRefs!=null) {
TypeVariable[] tVars = new TypeVariable[ajTypeRefs.length];
for (int i=0;i<ajTypeRefs.length;i++) {
tVars[i]=((TypeVariableReference)ajTypeRefs[i]).getTypeVariable();
}
ret.setTypeVariables(tVars);
}
typeVariablesForThisMember.clear();
ret.resolve(world);
return ret;
}
public ResolvedMember makeResolvedMember(FieldBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) {
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
return new ResolvedMemberImpl(
Member.FIELD,
realDeclaringType,
binding.modifiers,
world.resolve(fromBinding(binding.type)),
new String(binding.name),
UnresolvedType.NONE);
}
public TypeBinding makeTypeBinding(UnresolvedType typeX) {
TypeBinding ret = null;
// looking up type variables can get us into trouble
if (!typeX.isTypeVariableReference())
ret = (TypeBinding)typexToBinding.get(typeX);
if (ret == null) {
ret = makeTypeBinding1(typeX);
// FIXME asc keep type variables *out* of the map for now, they go in typeVariableToTypeBinding
if (!(typeX instanceof BoundedReferenceType) && !(typeX instanceof UnresolvedTypeVariableReferenceType))
typexToBinding.put(typeX, ret);
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
// When converting a parameterized type from our world to the eclipse world, these get set so that
// resolution of the type parameters may known in what context it is occurring (pr114744)
private ReferenceBinding baseTypeForParameterizedType;
private int indexOfTypeParameterBeingConverted;
private TypeBinding makeTypeBinding1(UnresolvedType typeX) {
if (typeX.isPrimitiveType()) {
if (typeX == ResolvedType.BOOLEAN) return BaseTypes.BooleanBinding;
if (typeX == ResolvedType.BYTE) return BaseTypes.ByteBinding;
if (typeX == ResolvedType.CHAR) return BaseTypes.CharBinding;
if (typeX == ResolvedType.DOUBLE) return BaseTypes.DoubleBinding;
if (typeX == ResolvedType.FLOAT) return BaseTypes.FloatBinding;
if (typeX == ResolvedType.INT) return BaseTypes.IntBinding;
if (typeX == ResolvedType.LONG) return BaseTypes.LongBinding;
if (typeX == ResolvedType.SHORT) return BaseTypes.ShortBinding;
if (typeX == ResolvedType.VOID) return BaseTypes.VoidBinding;
throw new RuntimeException("weird primitive type " + typeX);
} else if (typeX.isArray()) {
int dim = 0;
while (typeX.isArray()) {
dim++;
typeX = typeX.getComponentType();
}
return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim);
} else if (typeX.isParameterizedType()) {
// Converting back to a binding from a UnresolvedType
UnresolvedType[] typeParameters = typeX.getTypeParameters();
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length];
baseTypeForParameterizedType = baseTypeBinding;
for (int i = 0; i < argumentBindings.length; i++) {
indexOfTypeParameterBeingConverted = i;
argumentBindings[i] = makeTypeBinding(typeParameters[i]);
}
indexOfTypeParameterBeingConverted = 0;
baseTypeForParameterizedType = null;
ParameterizedTypeBinding ptb =
lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType());
return ptb;
} else if (typeX.isTypeVariableReference()) {
// return makeTypeVariableBinding((TypeVariableReference)typeX);
return makeTypeVariableBindingFromAJTypeVariable(((TypeVariableReference)typeX).getTypeVariable());
} else if (typeX.isRawType()) {
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType());
return rtb;
} else if (typeX.isGenericWildcard()) {
// translate from boundedreferencetype to WildcardBinding
BoundedReferenceType brt = (BoundedReferenceType)typeX;
// Work out 'kind' for the WildcardBinding
int boundkind = Wildcard.UNBOUND;
TypeBinding bound = null;
if (brt.isExtends()) {
boundkind = Wildcard.EXTENDS;
bound = makeTypeBinding(brt.getUpperBound());
} else if (brt.isSuper()) {
boundkind = Wildcard.SUPER;
bound = makeTypeBinding(brt.getLowerBound());
}
TypeBinding[] otherBounds = null;
if (brt.getAdditionalBounds()!=null && brt.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(brt.getAdditionalBounds());
WildcardBinding wb = lookupEnvironment.createWildcard(baseTypeForParameterizedType,indexOfTypeParameterBeingConverted,bound,otherBounds,boundkind);
return wb;
} else {
return lookupBinding(typeX.getName());
}
}
private ReferenceBinding lookupBinding(String sname) {
char[][] name = CharOperation.splitOn('.', sname.toCharArray());
ReferenceBinding rb = lookupEnvironment.getType(name);
return rb;
}
public TypeBinding[] makeTypeBindings(UnresolvedType[] types) {
int len = types.length;
TypeBinding[] ret = new TypeBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeBinding(types[i]);
}
return ret;
}
// just like the code above except it returns an array of ReferenceBindings
private ReferenceBinding[] makeReferenceBindings(UnresolvedType[] types) {
int len = types.length;
ReferenceBinding[] ret = new ReferenceBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = (ReferenceBinding)makeTypeBinding(types[i]);
}
return ret;
}
// field related
public FieldBinding makeFieldBinding(NewFieldTypeMunger nftm) {
return internalMakeFieldBinding(nftm.getSignature(),nftm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member,List aliases) {
return internalMakeFieldBinding(member,aliases);
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member) {
return internalMakeFieldBinding(member,null);
}
/**
* Take a normal AJ member and convert it into an eclipse fieldBinding.
* Taking into account any aliases that it may include due to being
* a generic itd. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* fieldbinding.
*/
public FieldBinding internalMakeFieldBinding(ResolvedMember member,List aliases) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()>0) {
int i =0;
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,declaringType.typeVariables()[i++]);
}
}
currentType = declaringType;
FieldBinding fb = new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
currentType,
Constant.NotAConstant);
typeVariableToTypeBinding.clear();
currentType = null;
return fb;
}
private ReferenceBinding currentType = null;
// method binding related
public MethodBinding makeMethodBinding(NewMethodTypeMunger nmtm) {
return internalMakeMethodBinding(nmtm.getSignature(),nmtm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases);
}
/**
* Creates a method binding for a resolvedmember taking into account type variable aliases -
* this variant can take an aliasTargetType and should be used when the alias target type
* cannot be retrieved from the resolvedmember.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
return internalMakeMethodBinding(member,aliases,aliasTargetType);
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member) {
return internalMakeMethodBinding(member,null); // there are no aliases
}
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases,member.getDeclaringType());
}
/**
* Take a normal AJ member and convert it into an eclipse methodBinding.
* Taking into account any aliases that it may include due to being a
* generic ITD. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* methodbinding
*/
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
if (member.getTypeVariables()!=null) {
if (member.getTypeVariables().length==0) {
tvbs = MethodBinding.NoTypeVariables;
} else {
tvbs = makeTypeVariableBindingsFromAJTypeVariables(member.getTypeVariables());
// QQQ do we need to bother fixing up the declaring element here?
}
}
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()!=0) {
int i=0;
ReferenceBinding aliasTarget = (ReferenceBinding)makeTypeBinding(aliasTargetType);
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,aliasTarget.typeVariables()[i++]);
}
}
currentType = declaringType;
MethodBinding mb = new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
declaringType);
if (tvbs!=null) mb.typeVariables = tvbs;
typeVariableToTypeBinding.clear();
currentType = null;
return mb;
}
/**
* Convert a bunch of type variables in one go, from AspectJ form to Eclipse form.
*/
// private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) {
// int len = typeVariables.length;
// TypeVariableBinding[] ret = new TypeVariableBinding[len];
// for (int i = 0; i < len; i++) {
// ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]);
// }
// return ret;
// }
private TypeVariableBinding[] makeTypeVariableBindingsFromAJTypeVariables(TypeVariable[] typeVariables) {
int len = typeVariables.length;
TypeVariableBinding[] ret = new TypeVariableBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeVariableBindingFromAJTypeVariable(typeVariables[i]);
}
return ret;
}
// only accessed through private methods in this class. Ensures all type variables we encounter
// map back to the same type binding - this is important later when Eclipse code is processing
// a methodbinding trying to come up with possible bindings for the type variables.
// key is currently the name of the type variable...is that ok?
private Map typeVariableToTypeBinding = new HashMap();
/**
* Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference
* in AspectJ world holds a TypeVariable and it is this type variable that is converted
* to the TypeVariableBinding.
*/
private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) {
TypeVariable tv = tvReference.getTypeVariable();
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
private TypeVariableBinding makeTypeVariableBindingFromAJTypeVariable(TypeVariable tv) {
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
public MethodBinding makeMethodBindingForCall(Member member) {
return new MethodBinding(member.getCallsiteModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
new ReferenceBinding[0],
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public void finishedCompilationUnit(CompilationUnitDeclaration unit) {
if ((buildManager != null) && buildManager.doGenerateModel()) {
AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig);
}
}
public void addTypeBinding(TypeBinding binding) {
typexToBinding.put(fromBinding(binding), binding);
}
public Shadow makeShadow(ASTNode location, ReferenceContext context) {
return EclipseShadow.makeShadow(this, location, context);
}
public Shadow makeShadow(ReferenceContext context) {
return EclipseShadow.makeShadow(this, (ASTNode) context, context);
}
public void addSourceTypeBinding(SourceTypeBinding binding, CompilationUnitDeclaration unit) {
TypeDeclaration decl = binding.scope.referenceContext;
// Deal with the raw/basic type to give us an entry in the world type map
UnresolvedType simpleTx = null;
if (binding.isGenericType()) {
simpleTx = UnresolvedType.forRawTypeName(getName(binding));
} else if (binding.isLocalType()) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
simpleTx = UnresolvedType.forSignature(new String(binding.signature()));
} else {
simpleTx = UnresolvedType.forName(getName(binding));
}
}else {
simpleTx = UnresolvedType.forName(getName(binding));
}
ReferenceType name = getWorld().lookupOrCreateName(simpleTx);
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl, unit);
// For generics, go a bit further - build a typex for the generic type
// give it the same delegate and link it to the raw type
if (binding.isGenericType()) {
UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info
ReferenceType complexName = new ReferenceType(complexTx,world);//getWorld().lookupOrCreateName(complexTx);
name.setGenericType(complexName);
complexName.setDelegate(t);
complexName.setSourceContext(t.getResolvedTypeX().getSourceContext());
}
name.setDelegate(t);
if (decl instanceof AspectDeclaration) {
((AspectDeclaration)decl).typeX = name;
((AspectDeclaration)decl).concreteName = t;
}
ReferenceBinding[] memberTypes = binding.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit);
}
}
// XXX this doesn't feel like it belongs here, but it breaks a hard dependency on
// exposing AjBuildManager (needed by AspectDeclaration).
public boolean isXSerializableAspects() {
return xSerializableAspects;
}
public ResolvedMember fromBinding(MethodBinding binding) {
return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers,
fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters));
}
public TypeVariableDeclaringElement fromBinding(Binding declaringElement) {
if (declaringElement instanceof TypeBinding) {
return fromBinding(((TypeBinding)declaringElement));
} else {
return fromBinding((MethodBinding)declaringElement);
}
}
}
|
103,051
|
Bug 103051 Declare Soft not Affecting Explicit Adviceexecution
|
The following aspect should compile successfully: import java.io.IOException; public aspect SoftenAdvice { declare soft: IOException: within(SoftenAdvice) && adviceexecution(); before() : execution(* main(..)) { throw new IOException("test"); } public static void main(String args[]) { } } But both 1.5.0M2 and HEAD (from 2 days ago) give this output: C:\devel\scratch\err>ajc SoftenAdvice.aj C:\devel\scratch\err\SoftenAdvice.aj:7 [error] Unhandled exception type IOExcept ion throw new IOException("test"); ^^^^^^^^^^^^^^^^^^^^ 1 error However if you change the declare soft to be the following, it correctly softens at the advice execution join point. declare soft: IOException: within(SoftenAdvice) && !withincode(* *(..));
|
resolved fixed
|
554e733
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-22T09:28:09Z
| 2005-07-07T18:13:20Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseShadow.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.lookup;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.*;
import org.aspectj.weaver.ast.Var;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
/**
* This is only used for declare soft right now.
*
* It might be used for other compile-time matching, but in all such cases
* this and target pcds can't be used. We might not behave correctly in
* such cases.
*/
public class EclipseShadow extends Shadow {
EclipseFactory world;
ASTNode astNode;
ReferenceContext context;
//AbstractMethodDeclaration enclosingMethod;
public EclipseShadow(EclipseFactory world, Kind kind, Member signature, ASTNode astNode,
ReferenceContext context)
{
super(kind, signature, null);
this.world = world;
this.astNode = astNode;
this.context = context;
}
public World getIWorld() {
return world.getWorld();
}
public UnresolvedType getEnclosingType() {
if (context instanceof TypeDeclaration) {
return world.fromBinding(((TypeDeclaration)context).binding);
} else if (context instanceof AbstractMethodDeclaration) {
return world.fromBinding(((AbstractMethodDeclaration)context).binding.declaringClass);
} else {
return ResolvedType.MISSING;
}
}
public ISourceLocation getSourceLocation() {
//XXX need to fill this in ASAP
return null;
}
public Member getEnclosingCodeSignature() {
if (context instanceof TypeDeclaration) {
return new MemberImpl(Member.STATIC_INITIALIZATION, getEnclosingType(), 0,
ResolvedType.VOID, "<clinit>", UnresolvedType.NONE);
} else if (context instanceof AbstractMethodDeclaration) {
return world.makeResolvedMember(((AbstractMethodDeclaration)context).binding);
} else {
return null;
}
}
// -- all below here are only used for implementing, not in matching
// -- we should probably pull out a super-interface to capture this in type system
public Var getThisVar() {
throw new RuntimeException("unimplemented");
}
public Var getTargetVar() {
throw new RuntimeException("unimplemented");
}
public Var getArgVar(int i) {
throw new RuntimeException("unimplemented");
}
public Var getThisJoinPointVar() {
throw new RuntimeException("unimplemented");
}
public Var getThisJoinPointStaticPartVar() {
throw new RuntimeException("unimplemented");
}
public Var getThisEnclosingJoinPointStaticPartVar() {
throw new RuntimeException("unimplemented");
}
public Var getArgAnnotationVar(int i, UnresolvedType annotationType) {
throw new RuntimeException("unimplemented");
}
public Var getKindedAnnotationVar(UnresolvedType annotationType) {
throw new RuntimeException("unimplemented");
}
public Var getTargetAnnotationVar(UnresolvedType annotationType) {
throw new RuntimeException("unimplemented");
}
public Var getThisAnnotationVar(UnresolvedType annotationType) {
throw new RuntimeException("unimplemented");
}
public Var getWithinAnnotationVar(UnresolvedType annotationType) {
throw new RuntimeException("unimplemented");
}
public Var getWithinCodeAnnotationVar(UnresolvedType annotationType) {
throw new RuntimeException("unimplemented");
}
// --- factory methods
public static EclipseShadow makeShadow(EclipseFactory world, ASTNode astNode,
ReferenceContext context)
{
//XXX make sure we're getting the correct declaring type at call-site
if (astNode instanceof AllocationExpression) {
AllocationExpression e = (AllocationExpression)astNode;
return new EclipseShadow(world, Shadow.ConstructorCall,
world.makeResolvedMember(e.binding), astNode, context);
} else if (astNode instanceof MessageSend) {
MessageSend e = (MessageSend)astNode;
if (e.isSuperAccess()) return null; // super calls don't have shadows
return new EclipseShadow(world, Shadow.MethodCall,
world.makeResolvedMember(e.binding), astNode, context);
} else if (astNode instanceof ExplicitConstructorCall) {
//??? these should be ignored, they don't have shadows
return null;
} else if (astNode instanceof AbstractMethodDeclaration) {
AbstractMethodDeclaration e = (AbstractMethodDeclaration)astNode;
Shadow.Kind kind;
if (e instanceof AdviceDeclaration) {
kind = Shadow.AdviceExecution;
} else if (e instanceof InterTypeMethodDeclaration) {
return new EclipseShadow(world, Shadow.MethodExecution,
((InterTypeDeclaration)e).getSignature(), astNode, context);
} else if (e instanceof InterTypeConstructorDeclaration) {
return new EclipseShadow(world, Shadow.ConstructorExecution,
((InterTypeDeclaration)e).getSignature(), astNode, context);
} else if (e instanceof InterTypeFieldDeclaration) {
return null;
} else if (e instanceof MethodDeclaration) {
kind = Shadow.MethodExecution;
} else if (e instanceof ConstructorDeclaration) {
kind = Shadow.ConstructorExecution;
} else if (e instanceof Clinit) {
kind = Shadow.StaticInitialization;
} else {
return null;
//throw new RuntimeException("unimplemented: " + e);
}
return new EclipseShadow(world, kind,
world.makeResolvedMember(e.binding), astNode, context);
} else if (astNode instanceof TypeDeclaration) {
return new EclipseShadow(world, Shadow.StaticInitialization,
new MemberImpl(Member.STATIC_INITIALIZATION,
world.fromBinding(((TypeDeclaration)astNode).binding), 0,
ResolvedType.VOID, "<clinit>", UnresolvedType.NONE),
astNode, context);
} else {
return null;
//throw new RuntimeException("unimplemented: " + astNode);
}
}
}
|
103,051
|
Bug 103051 Declare Soft not Affecting Explicit Adviceexecution
|
The following aspect should compile successfully: import java.io.IOException; public aspect SoftenAdvice { declare soft: IOException: within(SoftenAdvice) && adviceexecution(); before() : execution(* main(..)) { throw new IOException("test"); } public static void main(String args[]) { } } But both 1.5.0M2 and HEAD (from 2 days ago) give this output: C:\devel\scratch\err>ajc SoftenAdvice.aj C:\devel\scratch\err\SoftenAdvice.aj:7 [error] Unhandled exception type IOExcept ion throw new IOException("test"); ^^^^^^^^^^^^^^^^^^^^ 1 error However if you change the declare soft to be the following, it correctly softens at the advice execution join point. declare soft: IOException: within(SoftenAdvice) && !withincode(* *(..));
|
resolved fixed
|
554e733
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-22T09:28:09Z
| 2005-07-07T18:13:20Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
// public void testSelfBoundGenerics_pr117296() { runTest("self bounding generic types");}
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 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)");
}
/*
* 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);
}
// 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);
}
}
|
117,189
|
Bug 117189 Contribution: reduce overhead when no aspects define
|
This patch to the ClassLoaderWeavingAdaptor adds two optimizations when enabled is false for the adaptor: it immediately returns false for accept and it also avoids the overhead of constructing a weaver or world. It also contains commented out code that was letting me improve performance by loading reflective proxies instead of creating BCEL objects for a resolution loader (which is currently broken since reflective proxies now require a ReflectionWorld...)
|
resolved fixed
|
a5ac5af
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T09:01:53Z
| 2005-11-19T17:06:40Z
|
loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
* David Knibb weaving context enhancments
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.Lint;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.Lint.Kind;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.Utility;
import org.aspectj.weaver.bcel.BcelObjectType;
import org.aspectj.weaver.loadtime.definition.Definition;
import org.aspectj.weaver.loadtime.definition.DocumentParser;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.tools.GeneratedClassHandler;
import org.aspectj.weaver.tools.WeavingAdaptor;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class ClassLoaderWeavingAdaptor extends WeavingAdaptor {
private final static String AOP_XML = "META-INF/aop.xml";
private List m_dumpTypePattern = new ArrayList();
private List m_includeTypePattern = new ArrayList();
private List m_excludeTypePattern = new ArrayList();
private List m_includeStartsWith = new ArrayList();
private List m_excludeStartsWith = new ArrayList();
private List m_aspectExcludeTypePattern = new ArrayList();
private List m_aspectExcludeStartsWith = new ArrayList();
private List m_aspectIncludeTypePattern = new ArrayList();
private List m_aspectIncludeStartsWith = new ArrayList();
private StringBuffer namespace;
private IWeavingContext weavingContext;
public ClassLoaderWeavingAdaptor(final ClassLoader loader, IWeavingContext wContext) {
this.weavingContext = wContext;
}
void initialize(final ClassLoader loader, IWeavingContext wContext) {
//super(null);// at this stage we don't have yet a generatedClassHandler to define to the VM the closures
this.generatedClassHandler = new GeneratedClassHandler() {
/**
* Callback when we need to define a Closure in the JVM
*
* @param name
* @param bytes
*/
public void acceptClass(String name, byte[] bytes) {
try {
if (shouldDump(name.replace('/', '.'))) {
Aj.dump(name, bytes);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
Aj.defineClass(loader, name, bytes);// could be done lazily using the hook
}
};
if(wContext==null){
weavingContext = new DefaultWeavingContext(loader);
}else{
weavingContext = wContext ;
}
bcelWorld = new BcelWorld(
loader, messageHandler, new ICrossReferenceHandler() {
public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) {
;// for tools only
}
}
);
// //TODO this AJ code will call
// //org.aspectj.apache.bcel.Repository.setRepository(this);
// //ie set some static things
// //==> bogus as Bcel is expected to be
// org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader));
weaver = new BcelWeaver(bcelWorld);
// register the definitions
registerDefinitions(weaver, loader);
// AV - see #113511 - not sure it is good to skip message handler
if (enabled) {
messageHandler = bcelWorld.getMessageHandler();
// after adding aspects
weaver.prepareForWeave();
}
}
/**
* Load and cache the aop.xml/properties according to the classloader visibility rules
*
* @param weaver
* @param loader
*/
private void registerDefinitions(final BcelWeaver weaver, final ClassLoader loader) {
try {
MessageUtil.info(messageHandler, "register classloader " + getClassLoaderName(loader));
//TODO av underoptimized: we will parse each XML once per CL that see it
List definitions = new ArrayList();
//TODO av dev mode needed ? TBD -Daj5.def=...
if (ClassLoader.getSystemClassLoader().equals(loader)) {
String file = System.getProperty("aj5.def", null);
if (file != null) {
MessageUtil.info(messageHandler, "using (-Daj5.def) " + file);
definitions.add(DocumentParser.parse((new File(file)).toURL()));
}
}
String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration",AOP_XML);
StringTokenizer st = new StringTokenizer(resourcePath,";");
while(st.hasMoreTokens()){
Enumeration xmls = weavingContext.getResources(st.nextToken());
// System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader);
while (xmls.hasMoreElements()) {
URL xml = (URL) xmls.nextElement();
MessageUtil.info(messageHandler, "using " + xml.getFile());
definitions.add(DocumentParser.parse(xml));
}
}
// still go thru if definitions is empty since we will configure
// the default message handler in there
registerOptions(weaver, loader, definitions);
// AV - see #113511
if (!definitions.isEmpty()) {
registerAspectExclude(weaver, loader, definitions);
registerAspectInclude(weaver, loader, definitions);
registerAspects(weaver, loader, definitions);
registerIncludeExclude(weaver, loader, definitions);
registerDump(weaver, loader, definitions);
} else {
enabled = false;// will allow very fast skip in shouldWeave()
info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader));
}
} catch (Exception e) {
enabled = false;// will allow very fast skip in shouldWeave()
warn("register definition failed",e);
}
}
private String getClassLoaderName (ClassLoader loader) {
return weavingContext.getClassLoaderName();
}
/**
* Configure the weaver according to the option directives
* TODO av - don't know if it is that good to reuse, since we only allow a small subset of options in LTW
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
StringBuffer allOptions = new StringBuffer();
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
allOptions.append(definition.getWeaverOptions()).append(' ');
}
Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, messageHandler);
// configure the weaver and world
// AV - code duplicates AspectJBuilder.initWorldAndWeaver()
World world = weaver.getWorld();
world.setMessageHandler(weaverOption.messageHandler);
world.setXlazyTjp(weaverOption.lazyTjp);
world.setXHasMemberSupportEnabled(weaverOption.hasMember);
world.setPinpointMode(weaverOption.pinpoint);
weaver.setReweavableMode(weaverOption.notReWeavable);
world.setXnoInline(weaverOption.noInline);
// AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable
world.setBehaveInJava5Way(LangUtil.is15VMOrGreater());
//-Xlintfile: first so that lint wins
if (weaverOption.lintFile != null) {
InputStream resource = null;
try {
resource = loader.getResourceAsStream(weaverOption.lintFile);
Exception failure = null;
if (resource != null) {
try {
Properties properties = new Properties();
properties.load(resource);
world.getLint().setFromProperties(properties);
} catch (IOException e) {
failure = e;
}
}
if (failure != null || resource == null) {
world.getMessageHandler().handleMessage(new Message(
"Cannot access resource for -Xlintfile:"+weaverOption.lintFile,
IMessage.WARNING,
failure,
null));
}
} finally {
try { resource.close(); } catch (Throwable t) {;}
}
}
if (weaverOption.lint == null) {
bcelWorld.getLint().loadDefaultProperties();
bcelWorld.getLint().adviceDidNotMatch.setKind(IMessage.INFO);
} else {
if (weaverOption.lint.equals("default")) {//FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps..
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(weaverOption.lint);
}
}
//TODO proceedOnError option
}
private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_aspectExcludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_aspectExcludeStartsWith.add(fastMatchInfo);
}
}
}
}
private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_aspectIncludeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_aspectIncludeStartsWith.add(fastMatchInfo);
}
}
}
}
protected void lint (String name, String[] infos) {
Lint lint = bcelWorld.getLint();
Kind kind = lint.getLintKind(name);
kind.signal(infos,null,null);
}
/**
* Register the aspect, following include / exclude rules
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
//TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
// if not, review the getResource so that we track which resource is defined by which CL
//iterate aspectClassNames
//exclude if in any of the exclude list
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) {
String aspectClassName = (String) aspects.next();
if (acceptAspect(aspectClassName)) {
info("register aspect " + aspectClassName);
ResolvedType aspect = weaver.addLibraryAspect(aspectClassName);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(aspectClassName);
}else{
namespace = namespace.append(";"+aspectClassName);
}
}
else {
// warn("aspect excluded: " + aspectClassName);
lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) });
}
}
}
//iterate concreteAspects
//exclude if in any of the exclude list - note that the user defined name matters for that to happen
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getConcreteAspects().iterator(); aspects.hasNext();) {
Definition.ConcreteAspect concreteAspect = (Definition.ConcreteAspect) aspects.next();
if (acceptAspect(concreteAspect.name)) {
ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld());
if (!gen.validate()) {
error("Concrete-aspect '"+concreteAspect.name+"' could not be registered");
break;
}
this.generatedClassHandler.acceptClass(
concreteAspect.name,
gen.getBytes()
);
ResolvedType aspect = weaver.addLibraryAspect(concreteAspect.name);
//generate key for SC
if(namespace==null){
namespace=new StringBuffer(concreteAspect.name);
}else{
namespace = namespace.append(";"+concreteAspect.name);
}
}
}
}
}
/**
* Register the include / exclude filters
* We duplicate simple patterns in startWith filters that will allow faster matching without ResolvedType
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
String fastMatchInfo = null;
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_includeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_includeStartsWith.add(fastMatchInfo);
}
}
for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_excludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_excludeStartsWith.add(fastMatchInfo);
}
}
}
}
/**
* Checks if the type pattern can be handled as a startswith check
*
* TODO AV - enhance to support "char.sss" ie FQN direclty (match iff equals)
* we could also add support for "*..*charss" endsWith style?
*
* @param typePattern
* @return null if not possible, or the startWith sequence to test against
*/
private String looksLikeStartsWith(String typePattern) {
if (typePattern.indexOf('@') >= 0
|| typePattern.indexOf('+') >= 0
|| typePattern.indexOf(' ') >= 0
|| typePattern.charAt(typePattern.length()-1) != '*') {
return null;
}
// now must looks like with "charsss..*" or "cha.rss..*" etc
// note that "*" and "*..*" won't be fast matched
// and that "charsss.*" will not neither
int length = typePattern.length();
if (typePattern.endsWith("..*") && length > 3) {
if (typePattern.indexOf("..") == length-3 // no ".." before last sequence
&& typePattern.indexOf('*') == length-1) { // no "*" before last sequence
return typePattern.substring(0, length-2).replace('$', '.');
// ie "charsss." or "char.rss." etc
}
}
return null;
}
/**
* Register the dump filter
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) {
String dump = (String) iterator1.next();
TypePattern pattern = new PatternParser(dump).parseTypePattern();
m_dumpTypePattern.add(pattern);
}
}
}
protected boolean accept(String className, byte[] bytes) {
// avoid ResolvedType if not needed
if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
String fastClassName = className.replace('/', '.').replace('$', '.');
for (int i = 0; i < m_excludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_excludeStartsWith.get(i))) {
return false;
}
}
boolean fastAccept = false;//defaults to false if no fast include
for (int i = 0; i < m_includeStartsWith.size(); i++) {
fastAccept = fastClassName.startsWith((String)m_includeStartsWith.get(i));
if (fastAccept) {
break;
}
}
if (fastAccept) {
return true;
}
// needs further analysis
// TODO AV - needs refactoring
// during LTW this calling resolve at that stage is BAD as we do have the bytecode from the classloader hook
// but still go thru resolve that will do a getResourcesAsStream on disk
// this is also problematic for jit stub which are not on disk - as often underlying infra
// does returns null or some other info for getResourceAsStream (f.e. WLS 9 CR248491)
// Instead I parse the given bytecode. But this also means it will be parsed again in
// new WeavingClassFileProvider() from WeavingAdaptor.getWovenBytes()...
BcelObjectType bct = ((BcelWorld)weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(null, bytes));
ResolvedType classInfo = bct.getResolvedTypeX();//BAD: weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//exclude are "AND"ed
for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
//FIXME we don't use include/exclude of others aop.xml
//this can be nice but very dangerous as well to change that
private boolean acceptAspect(String aspectClassName) {
// avoid ResolvedType if not needed
if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
// EXCLUDE: if one match then reject
String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectExcludeStartsWith.get(i))) {
return false;
}
}
//INCLUDE: if one match then accept
for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) {
if (fastClassName.startsWith((String)m_aspectIncludeStartsWith.get(i))) {
return true;
}
}
// needs further analysis
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
//exclude are "AND"ed
for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
//include are "OR"ed
boolean accept = true;//defaults to true if no include
for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
public boolean shouldDump(String className) {
// avoid ResolvedType if not needed
if (m_dumpTypePattern.isEmpty()) {
return false;
}
//TODO AV - optimize for className.startWith only
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true);
//dump
for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// dump match
return true;
}
}
return false;
}
/*
* shared classes methods
*/
/**
* @return Returns the key.
*/
public String getNamespace() {
if(namespace==null) return "";
else return new String(namespace);
}
/**
* Check to see if any classes are stored in the generated classes cache.
* Then flush the cache if it is not empty
* @return true if a class has been generated and is stored in the cache
*/
public boolean generatedClassesExist(){
if(generatedClasses.size()>0) {
return true;
}
return false;
}
/**
* Flush the generated classes cache
*/
public void flushGeneratedClasses(){
generatedClasses = new HashMap();
}
}
|
117,189
|
Bug 117189 Contribution: reduce overhead when no aspects define
|
This patch to the ClassLoaderWeavingAdaptor adds two optimizations when enabled is false for the adaptor: it immediately returns false for accept and it also avoids the overhead of constructing a weaver or world. It also contains commented out code that was letting me improve performance by loading reflective proxies instead of creating BCEL objects for a resolution loader (which is currently broken since reflective proxies now require a ReflectionWorld...)
|
resolved fixed
|
a5ac5af
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T09:01:53Z
| 2005-11-19T17:06:40Z
|
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.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
*
* Contributors:
* Matthew Webster, Adrian Colyer,
* Martin Lippert initial implementation
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.MessageWriter;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
/**
* This adaptor allows the AspectJ compiler to be embedded in an existing
* system to facilitate load-time weaving. It provides an interface for a
* weaving class loader to provide a classpath to be woven by a set of
* aspects. A callback is supplied to allow a class loader to define classes
* generated by the compiler during the weaving process.
* <p>
* A weaving class loader should create a <code>WeavingAdaptor</code> before
* any classes are defined, typically during construction. The set of aspects
* passed to the adaptor is fixed for the lifetime of the adaptor although the
* classpath can be augmented. A system property can be set to allow verbose
* weaving messages to be written to the console.
*
*/
public class WeavingAdaptor {
/**
* System property used to turn on verbose weaving messages
*/
public static final String WEAVING_ADAPTOR_VERBOSE = "aj.weaving.verbose";
public static final String SHOW_WEAVE_INFO_PROPERTY = "org.aspectj.weaver.showWeaveInfo";
protected boolean enabled = true;
protected boolean verbose = getVerbose();
protected BcelWorld bcelWorld = null;
protected BcelWeaver weaver = null;
protected IMessageHandler/*WeavingAdaptorMessageHandler*/ messageHandler = null;
protected GeneratedClassHandler generatedClassHandler;
protected Map generatedClasses = new HashMap(); /* String -> UnwovenClassFile */
protected WeavingAdaptor () {
createMessageHandler();
}
/**
* Construct a WeavingAdaptor with a reference to a weaving class loader. The
* adaptor will automatically search the class loader hierarchy to resolve
* classes. The adaptor will also search the hierarchy for WeavingClassLoader
* instances to determine the set of aspects to be used ofr weaving.
* @param loader instance of <code>ClassLoader</code>
*/
public WeavingAdaptor (WeavingClassLoader loader) {
// System.err.println("? WeavingAdaptor.<init>(" + loader +"," + aspectURLs.length + ")");
generatedClassHandler = loader;
init(getFullClassPath((ClassLoader)loader),getFullAspectPath((ClassLoader)loader/*,aspectURLs*/));
}
/**
* Construct a WeavingAdator with a reference to a
* <code>GeneratedClassHandler</code>, a full search path for resolving
* classes and a complete set of aspects. The search path must include
* classes loaded by the class loader constructing the WeavingAdaptor and
* all its parents in the hierarchy.
* @param handler <code>GeneratedClassHandler</code>
* @param classURLs the URLs from which to resolve classes
* @param aspectURLs the aspects used to weave classes defined by this class loader
*/
public WeavingAdaptor (GeneratedClassHandler handler, URL[] classURLs, URL[] aspectURLs) {
// System.err.println("? WeavingAdaptor.<init>()");
generatedClassHandler = handler;
init(FileUtil.makeClasspath(classURLs),FileUtil.makeClasspath(aspectURLs));
}
private List getFullClassPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader)loader).getURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
else {
warn("cannot determine classpath");
}
}
list.addAll(0,makeClasspath(System.getProperty("sun.boot.class.path")));
return list;
}
private List getFullAspectPath (ClassLoader loader) {
List list = new LinkedList();
for (; loader != null; loader = loader.getParent()) {
if (loader instanceof WeavingClassLoader) {
URL[] urls = ((WeavingClassLoader)loader).getAspectURLs();
list.addAll(0,FileUtil.makeClasspath(urls));
}
}
return list;
}
private static boolean getVerbose () {
return Boolean.getBoolean(WEAVING_ADAPTOR_VERBOSE);
}
private void init(List classPath, List aspectPath) {
createMessageHandler();
info("using classpath: " + classPath);
info("using aspectpath: " + aspectPath);
bcelWorld = new BcelWorld(classPath,messageHandler,null);
bcelWorld.setXnoInline(false);
bcelWorld.getLint().loadDefaultProperties();
if (LangUtil.is15VMOrGreater()) {
bcelWorld.setBehaveInJava5Way(true);
}
weaver = new BcelWeaver(bcelWorld);
registerAspectLibraries(aspectPath);
}
private void createMessageHandler() {
messageHandler = new WeavingAdaptorMessageHandler(new PrintWriter(System.err));
if (verbose) messageHandler.dontIgnore(IMessage.INFO);
if (Boolean.getBoolean(SHOW_WEAVE_INFO_PROPERTY)) messageHandler.dontIgnore(IMessage.WEAVEINFO);
}
/**
* Appends URL to path used by the WeavingAdptor to resolve classes
* @param url to be appended to search path
*/
public void addURL(URL url) {
File libFile = new File(url.getPath());
try {
weaver.addLibraryJarFile(libFile);
}
catch (IOException ex) {
warn("bad library: '" + libFile + "'");
}
}
/**
* Weave a class using aspects previously supplied to the adaptor.
* @param name the name of the class
* @param bytes the class bytes
* @return the woven bytes
* @exception IOException weave failed
*/
public byte[] weaveClass (String name, byte[] bytes) throws IOException {
if (shouldWeave(name, bytes)) {
//System.out.println("WeavingAdaptor.weaveClass " + name);
info("weaving '" + name + "'");
bytes = getWovenBytes(name, bytes);
} else if (shouldWeaveAnnotationStyleAspect(name, bytes)) {
// an @AspectJ aspect needs to be at least munged by the aspectOf munger
info("weaving '" + name + "'");
bytes = getAtAspectJAspectBytes(name, bytes);
}
return bytes;
}
/**
* @param name
* @return true if should weave (but maybe we still need to munge it for @AspectJ aspectof support)
*/
private boolean shouldWeave (String name, byte[] bytes) {
name = name.replace('/','.');
boolean b = enabled && !generatedClasses.containsKey(name) && shouldWeaveName(name);
return b && accept(name, bytes);
// && shouldWeaveAnnotationStyleAspect(name);
// // we recall shouldWeaveAnnotationStyleAspect as we need to add aspectOf methods for @Aspect anyway
// //FIXME AV - this is half ok as the aspect will be weaved by others. In theory if the aspect
// // is excluded from include/exclude config we should only weave late type mungers for aspectof
// return b && (accept(name) || shouldWeaveAnnotationStyleAspect(name));
}
//ATAJ
protected boolean accept(String name, byte[] bytes) {
return true;
}
public boolean shouldDump(String name) {
return false;
}
private boolean shouldWeaveName (String name) {
return !((/*(name.startsWith("org.apache.bcel.")//FIXME AV why ? bcel is wrapped in org.aspectj.
||*/ name.startsWith("org.aspectj.")
|| name.startsWith("java.")
|| name.startsWith("javax."))
//|| name.startsWith("$Proxy")//JDK proxies//FIXME AV is that 1.3 proxy ? fe. ataspect.$Proxy0 is a java5 proxy...
|| name.startsWith("sun.reflect."));//JDK reflect
}
/**
* We allow @AJ aspect weaving so that we can add aspectOf() as part of the weaving
* (and not part of the source compilation)
*
* @param name
* @param bytes bytecode (from classloader), allow to NOT lookup stuff on disk again during resolve
* @return true if @Aspect
*/
private boolean shouldWeaveAnnotationStyleAspect(String name, byte[] bytes) {
// AV: instead of doing resolve that would lookup stuff on disk thru BCEL ClassLoaderRepository
// we reuse bytes[] here to do a fast lookup for @Aspect annotation
return bcelWorld.isAnnotationStyleAspect(name, bytes);
}
/**
* Weave a set of bytes defining a class.
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getWovenBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
weaver.weave(wcp);
return wcp.getBytes();
}
/**
* Weave a set of bytes defining a class for only what is needed to turn @AspectJ aspect
* in a usefull form ie with aspectOf method - see #113587
* @param name the name of the class being woven
* @param bytes the bytes that define the class
* @return byte[] the woven bytes for the class
* @throws IOException
*/
private byte[] getAtAspectJAspectBytes(String name, byte[] bytes) throws IOException {
WeavingClassFileProvider wcp = new WeavingClassFileProvider(name,bytes);
wcp.setApplyAtAspectJMungersOnly();
weaver.weave(wcp);
return wcp.getBytes();
}
private void registerAspectLibraries(List aspectPath) {
// System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")");
for (Iterator i = aspectPath.iterator(); i.hasNext();) {
String libName = (String)i.next();
addAspectLibrary(libName);
}
weaver.prepareForWeave();
}
/*
* Register an aspect library with this classloader for use during
* weaving. This class loader will also return (unmodified) any of the
* classes in the library in response to a <code>findClass()</code> request.
* The library is not required to be on the weavingClasspath given when this
* classloader was constructed.
* @param aspectLibraryJarFile a jar file representing an aspect library
* @throws IOException
*/
private void addAspectLibrary(String aspectLibraryName) {
File aspectLibrary = new File(aspectLibraryName);
if (aspectLibrary.isDirectory()
|| (aspectLibrary.isFile()
&& FileUtil.hasZipSuffix(aspectLibraryName))) {
try {
info("adding aspect library: '" + aspectLibrary + "'");
weaver.addLibraryJarFile(aspectLibrary);
} catch (IOException ex) {
error("exception adding aspect library: '" + ex + "'");
}
} else {
error("bad aspect library: '" + aspectLibrary + "'");
}
}
private static List makeClasspath(String cp) {
List ret = new ArrayList();
if (cp != null) {
StringTokenizer tok = new StringTokenizer(cp,File.pathSeparator);
while (tok.hasMoreTokens()) {
ret.add(tok.nextToken());
}
}
return ret;
}
protected boolean info (String message) {
return MessageUtil.info(messageHandler,message);
}
protected boolean warn (String message) {
return MessageUtil.warn(messageHandler,message);
}
protected boolean warn (String message, Throwable th) {
return messageHandler.handleMessage(new Message("Register definition failed", IMessage.WARNING, th, null));
}
protected boolean error (String message) {
return MessageUtil.error(messageHandler,message);
}
/**
* Processes messages arising from weaver operations.
* Tell weaver to abort on any message more severe than warning.
*/
protected class WeavingAdaptorMessageHandler extends MessageWriter {
private Set ignoring = new HashSet();
private IMessage.Kind failKind;
public WeavingAdaptorMessageHandler (PrintWriter writer) {
super(writer,true);
ignore(IMessage.WEAVEINFO);
ignore(IMessage.INFO);
this.failKind = IMessage.ERROR;
}
public boolean handleMessage(IMessage message) throws AbortException {
boolean result = super.handleMessage(message);
if (0 <= message.getKind().compareTo(failKind)) {
throw new AbortException(message);
}
return true;
}
public boolean isIgnoring (Kind kind) {
return ((null != kind) && (ignoring.contains(kind)));
}
/**
* Set a message kind to be ignored from now on
*/
public void ignore (IMessage.Kind kind) {
if ((null != kind) && (!ignoring.contains(kind))) {
ignoring.add(kind);
}
}
/**
* Remove a message kind from the list of those ignored from now on.
*/
public void dontIgnore (IMessage.Kind kind) {
if (null != kind) {
ignoring.remove(kind);
}
}
}
private class WeavingClassFileProvider implements IClassFileProvider {
private UnwovenClassFile unwovenClass;
private List unwovenClasses = new ArrayList(); /* List<UnovenClassFile> */
private UnwovenClassFile wovenClass;
private boolean isApplyAtAspectJMungersOnly = false;
public WeavingClassFileProvider (String name, byte[] bytes) {
this.unwovenClass = new UnwovenClassFile(name,bytes);
this.unwovenClasses.add(unwovenClass);
bcelWorld.addSourceObjectType(unwovenClass.getJavaClass());
}
public void setApplyAtAspectJMungersOnly() {
isApplyAtAspectJMungersOnly = true;
}
public boolean isApplyAtAspectJMungersOnly() {
return isApplyAtAspectJMungersOnly;
}
public byte[] getBytes () {
if (wovenClass != null) return wovenClass.getBytes();
else return unwovenClass.getBytes();
}
public Iterator getClassFileIterator() {
return unwovenClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(UnwovenClassFile result) {
if (wovenClass == null) {
wovenClass = result;
}
/* Classes generated by weaver e.g. around closure advice */
else {
String className = result.getClassName();
generatedClasses.put(className,result);
generatedClassHandler.acceptClass(className,result.getBytes());
}
}
public void processingReweavableState() { }
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {}
};
}
}
}
|
103,157
|
Bug 103157 after returning should not bind "null" as return value
|
Today I found out the following. When writing an advice as... after() returning(Object o): staticinitialization(*) { System.out.println(o); } This advice is indeed executed every time a type returns from staticinitialization. However, since there is no returned object, o is bound to "null". I think this is inconsistent with the fact where we have something like: after() returning(T o): call(Object Foo.bar()) { System.out.println(o); } Here, AFAIK the advice would not execute in cases where the returned object is not an instance of T. Thus, I would propose that the first advice should only execute at joinpoints where a return value is available.
|
resolved fixed
|
8b294d9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:52:27Z
| 2005-07-08T13:40:00Z
|
tests/new/AfterReturningParam.java
|
import org.aspectj.testing.Tester;
public class AfterReturningParam {
public static void main(String[] args) {
AfterReturningParam p = new AfterReturningParam();
Tester.checkAndClearEvents(new String[] { "constr exec as Object null" });
p.mInt();
Tester.checkAndClearEvents(new String[] { "int as Object 2" });
p.mObject();
Tester.checkAndClearEvents(new String[] { "Object as Object ning",
"Object (that is String) as String ning" });
p.mVoid();
Tester.checkAndClearEvents(new String[] { "void as Object null" });
}
public int mInt() { return 2; }
public Object mObject() { return "ning"; }
public void mVoid() { return; }
AfterReturningParam() {
}
}
aspect A {
private void callEvent(String s, Object o) {
Tester.event(s + " " + o);
}
after() returning (AfterReturningParam o) : execution(AfterReturningParam.new()) { // CW 35 in 1.0.4, no match
callEvent("constr exec as constd object", o);
}
after() returning (Object o) : execution(AfterReturningParam.new()) { // CW 38 in 1.0.4, does match
callEvent("constr exec as Object", o);
}
after() returning (String o) : execution(AfterReturningParam.new()) { // CW 41 in 1.0.4, no match
callEvent("constr exec as String", o);
}
after() returning (Object o) : execution(int AfterReturningParam.mInt()) { // match
callEvent("int as Object", o);
}
after() returning (String o) : execution(int AfterReturningParam.mInt()) { // no match
callEvent("int as String", o);
}
after() returning (Integer o) : execution(int AfterReturningParam.mInt()) { // no match
callEvent("int as Integer", o);
}
after() returning (Object o) : execution(Object AfterReturningParam.mObject()) { // match
callEvent("Object as Object", o);
}
after() returning (String o) : execution(Object AfterReturningParam.mObject()) { // match (interesting, matching by instanceof)
callEvent("Object (that is String) as String", o);
}
after() returning (Object o) : execution(void AfterReturningParam.mVoid()) { // match
callEvent("void as Object", o);
}
after() returning (String o) : execution(void AfterReturningParam.mVoid()) { // CW 65 warning in 1.0.4 no match
callEvent("void as String", o);
}
}
|
103,157
|
Bug 103157 after returning should not bind "null" as return value
|
Today I found out the following. When writing an advice as... after() returning(Object o): staticinitialization(*) { System.out.println(o); } This advice is indeed executed every time a type returns from staticinitialization. However, since there is no returned object, o is bound to "null". I think this is inconsistent with the fact where we have something like: after() returning(T o): call(Object Foo.bar()) { System.out.println(o); } Here, AFAIK the advice would not execute in cases where the returned object is not an instance of T. Thus, I would propose that the first advice should only execute at joinpoints where a return value is available.
|
resolved fixed
|
8b294d9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:52:27Z
| 2005-07-08T13:40:00Z
|
tests/new/ConstructorExecInit.java
|
import org.aspectj.testing.*;
/**
* -usejavac mode: no error
* not -usejavac mode: VerifyError
*/
public class ConstructorExecInit {
public static void main(String[] args) {
new ConstructorExecInit();
Tester.checkAllEvents();
}
static {
Tester.expectEvent("execution");
Tester.expectEvent("initialization");
}
}
/** @testcase after returning from initialization and after executing constructor */
aspect A {
after (Object target) : execution(*.new(..)) && target(target) && !within(A) {
Tester.event("execution");
}
after () returning (Object target) : initialization(new(..)) && !this(A) {
Tester.event("initialization");
}
}
|
103,157
|
Bug 103157 after returning should not bind "null" as return value
|
Today I found out the following. When writing an advice as... after() returning(Object o): staticinitialization(*) { System.out.println(o); } This advice is indeed executed every time a type returns from staticinitialization. However, since there is no returned object, o is bound to "null". I think this is inconsistent with the fact where we have something like: after() returning(T o): call(Object Foo.bar()) { System.out.println(o); } Here, AFAIK the advice would not execute in cases where the returned object is not an instance of T. Thus, I would propose that the first advice should only execute at joinpoints where a return value is available.
|
resolved fixed
|
8b294d9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:52:27Z
| 2005-07-08T13:40:00Z
|
tests/new/OddConstructors.java
|
import java.lang.reflect.*;
import org.aspectj.testing.Tester;
public class OddConstructors {
public static void main(String[] args) throws Exception { test(); }
public static void test() throws Exception {
new OddConstructors().go();
Tester.check("advised default constructor");
Tester.checkEqual(B.aspectOf().count, 1, "new'd once");
}
void go() throws Exception {
// new C();
// use reflection instead of new to create this class to tickle the bug
Constructor c = Class.forName("C").getConstructor(new Class[0]);
I i = (I)c.newInstance(new Object[0]);
}
static aspect B extends A issingleton() { //of eachJVM() {
pointcut i(): target(I);
}
}
abstract aspect A {
abstract pointcut i();
pointcut j():
i()
// 2001.08.01 (palm)
// Had to change this to I.new from new
// because of the change to the meaning
// of initialization
//&& initialization(new(..)) ;
&& initialization(I.new(..)) ;
after() returning(Object o): j() {
Tester.note("advised default constructor");
count++;
}
int count = 0;
}
class C implements I { public C() {} }
interface I {}
|
103,157
|
Bug 103157 after returning should not bind "null" as return value
|
Today I found out the following. When writing an advice as... after() returning(Object o): staticinitialization(*) { System.out.println(o); } This advice is indeed executed every time a type returns from staticinitialization. However, since there is no returned object, o is bound to "null". I think this is inconsistent with the fact where we have something like: after() returning(T o): call(Object Foo.bar()) { System.out.println(o); } Here, AFAIK the advice would not execute in cases where the returned object is not an instance of T. Thus, I would propose that the first advice should only execute at joinpoints where a return value is available.
|
resolved fixed
|
8b294d9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:52:27Z
| 2005-07-08T13:40:00Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
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 testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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");
}
/*
* 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);
}
// 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);
}
}
|
103,157
|
Bug 103157 after returning should not bind "null" as return value
|
Today I found out the following. When writing an advice as... after() returning(Object o): staticinitialization(*) { System.out.println(o); } This advice is indeed executed every time a type returns from staticinitialization. However, since there is no returned object, o is bound to "null". I think this is inconsistent with the fact where we have something like: after() returning(T o): call(Object Foo.bar()) { System.out.println(o); } Here, AFAIK the advice would not execute in cases where the returned object is not an instance of T. Thus, I would propose that the first advice should only execute at joinpoints where a return value is available.
|
resolved fixed
|
8b294d9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:52:27Z
| 2005-07-08T13:40: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);
if (matches && resolvedExtraParameterType.isParameterizedType()) {
maybeIssueUncheckedMatchWarning(resolvedExtraParameterType,shadowReturnType,shadow,world);
}
return matches;
} else if (kind == AdviceKind.PerTargetEntry) {
return shadow.hasTarget();
} else if (kind == AdviceKind.PerThisEntry) {
return shadow.hasThis();
} else if (kind == AdviceKind.Around) {
if (shadow.getKind() == Shadow.PreInitialization) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.AROUND_ON_PREINIT),
getSourceLocation(), shadow.getSourceLocation());
return false;
} else if (shadow.getKind() == Shadow.Initialization) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.AROUND_ON_INIT),
getSourceLocation(), shadow.getSourceLocation());
return false;
} else if (shadow.getKind() == Shadow.StaticInitialization &&
shadow.getEnclosingType().resolve(world).isInterface())
{
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.AROUND_ON_INTERFACE_STATICINIT,shadow.getEnclosingType().getName()),
getSourceLocation(), shadow.getSourceLocation());
return false;
} else {
//System.err.println(getSignature().getReturnType() + " from " + shadow.getReturnType());
if (getSignature().getReturnType() == ResolvedType.VOID) {
if (shadow.getReturnType() != ResolvedType.VOID) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.NON_VOID_RETURN,shadow),
getSourceLocation(), shadow.getSourceLocation());
return false;
}
} else if (getSignature().getReturnType().equals(UnresolvedType.OBJECT)) {
return true;
} else {
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;
}
}
|
103,157
|
Bug 103157 after returning should not bind "null" as return value
|
Today I found out the following. When writing an advice as... after() returning(Object o): staticinitialization(*) { System.out.println(o); } This advice is indeed executed every time a type returns from staticinitialization. However, since there is no returned object, o is bound to "null". I think this is inconsistent with the fact where we have something like: after() returning(T o): call(Object Foo.bar()) { System.out.println(o); } Here, AFAIK the advice would not execute in cases where the returned object is not an instance of T. Thus, I would propose that the first advice should only execute at joinpoints where a return value is available.
|
resolved fixed
|
8b294d9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:52:27Z
| 2005-07-08T13:40:00Z
|
weaver/src/org/aspectj/weaver/Shadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.lang.JoinPoint;
import org.aspectj.util.PartialOrder;
import org.aspectj.util.TypeSafeEnum;
import org.aspectj.weaver.ast.Var;
import org.aspectj.weaver.bcel.BcelAdvice;
/*
* The superclass of anything representing a the shadow of a join point. A shadow represents
* some bit of code, and encompasses both entry and exit from that code. All shadows have a kind
* and a signature.
*/
public abstract class Shadow {
// every Shadow has a unique id, doesn't matter if it wraps...
private static int nextShadowID = 100; // easier to spot than zero.
private final Kind kind;
private final Member signature;
private Member matchingSignature;
private ResolvedMember resolvedSignature;
protected final Shadow enclosingShadow;
protected List mungers = new ArrayList(1);
public int shadowId = nextShadowID++; // every time we build a shadow, it gets a new id
// ----
protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) {
this.kind = kind;
this.signature = signature;
this.enclosingShadow = enclosingShadow;
}
// ----
public abstract World getIWorld();
public List /*ShadowMunger*/ getMungers() {
return mungers;
}
/**
* could this(*) pcd ever match
*/
public final boolean hasThis() {
if (getKind().neverHasThis()) {
return false;
} else if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
return false;
} else {
return enclosingShadow.hasThis();
}
}
/**
* the type of the this object here
*
* @throws IllegalStateException if there is no this here
*/
public final UnresolvedType getThisType() {
if (!hasThis()) throw new IllegalStateException("no this");
if (getKind().isEnclosingKind()) {
return getSignature().getDeclaringType();
} else {
return enclosingShadow.getThisType();
}
}
/**
* a var referencing this
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getThisVar();
/**
* could target(*) pcd ever match
*/
public final boolean hasTarget() {
if (getKind().neverHasTarget()) {
return false;
} else if (getKind().isTargetSameAsThis()) {
return hasThis();
} else {
return !getSignature().isStatic();
}
}
/**
* the type of the target object here
*
* @throws IllegalStateException if there is no target here
*/
public final UnresolvedType getTargetType() {
if (!hasTarget()) throw new IllegalStateException("no target");
return getSignature().getDeclaringType();
}
/**
* a var referencing the target
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getTargetVar();
public UnresolvedType[] getArgTypes() {
if (getKind() == FieldSet) return new UnresolvedType[] { getSignature().getReturnType() };
return getSignature().getParameterTypes();
}
public UnresolvedType[] getGenericArgTypes() {
if (getKind() == FieldSet) return new UnresolvedType[] { getResolvedSignature().getGenericReturnType() };
return getResolvedSignature().getGenericParameterTypes();
}
public UnresolvedType getArgType(int arg) {
if (getKind() == FieldSet) return getSignature().getReturnType();
return getSignature().getParameterTypes()[arg];
}
public int getArgCount() {
if (getKind() == FieldSet) return 1;
return getSignature()
.getParameterTypes().length;
}
public abstract UnresolvedType getEnclosingType();
public abstract Var getArgVar(int i);
public abstract Var getThisJoinPointVar();
public abstract Var getThisJoinPointStaticPartVar();
public abstract Var getThisEnclosingJoinPointStaticPartVar();
// annotation variables
public abstract Var getKindedAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getWithinAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getThisAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getTargetAnnotationVar(UnresolvedType forAnnotationType);
public abstract Var getArgAnnotationVar(int i, UnresolvedType forAnnotationType);
public abstract Member getEnclosingCodeSignature();
/** returns the kind of shadow this is, representing what happens under this shadow
*/
public Kind getKind() {
return kind;
}
/** returns the signature of the thing under this shadow
*/
public Member getSignature() {
return signature;
}
/**
* returns the signature of the thing under this shadow, with
* any synthetic arguments removed
*/
public Member getMatchingSignature() {
return matchingSignature != null ? matchingSignature : signature;
}
public void setMatchingSignature(Member member) {
this.matchingSignature = member;
}
/**
* returns the resolved signature of the thing under this shadow
*
*/
public ResolvedMember getResolvedSignature() {
if (resolvedSignature == null) {
resolvedSignature = signature.resolve(getIWorld());
}
return resolvedSignature;
}
public UnresolvedType getReturnType() {
if (kind == ConstructorCall) return getSignature().getDeclaringType();
else if (kind == FieldSet) return ResolvedType.VOID;
return getResolvedSignature().getGenericReturnType();
}
/**
* These names are the ones that will be returned by thisJoinPoint.getKind()
* Those need to be documented somewhere
*/
public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true);
public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true);
public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false);
public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false);
public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true);
public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true);
public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false);
public static final Kind PreInitialization = new Kind(JoinPoint.PREINTIALIZATION, 8, false);
public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false);
public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false);
public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true);
public static final int MAX_SHADOW_KIND = 11;
public static final Kind[] SHADOW_KINDS = new Kind[] {
MethodCall, ConstructorCall, MethodExecution, ConstructorExecution,
FieldGet, FieldSet, StaticInitialization, PreInitialization,
AdviceExecution, Initialization, ExceptionHandler,
};
public static final Set ALL_SHADOW_KINDS;
static {
HashSet aSet = new HashSet();
for (int i = 0; i < SHADOW_KINDS.length; i++) {
aSet.add(SHADOW_KINDS[i]);
}
ALL_SHADOW_KINDS = Collections.unmodifiableSet(aSet);
}
/** A type-safe enum representing the kind of shadows
*/
public static final class Kind extends TypeSafeEnum {
private boolean argsOnStack; //XXX unused
public Kind(String name, int key, boolean argsOnStack) {
super(name, key);
this.argsOnStack = argsOnStack;
}
public String toLegalJavaIdentifier() {
return getName().replace('-', '_');
}
public boolean argsOnStack() {
return !isTargetSameAsThis();
}
// !!! this is false for handlers!
public boolean allowsExtraction() {
return true;
}
// XXX revisit along with removal of priorities
public boolean hasHighPriorityExceptions() {
return !isTargetSameAsThis();
}
/**
* These are all the shadows that contains other shadows within them and
* are often directly associated with methods.
*/
public boolean isEnclosingKind() {
return this == MethodExecution || this == ConstructorExecution ||
this == AdviceExecution || this == StaticInitialization
|| this == Initialization;
}
public boolean isTargetSameAsThis() {
return this == MethodExecution
|| this == ConstructorExecution
|| this == StaticInitialization
|| this == PreInitialization
|| this == AdviceExecution
|| this == Initialization;
}
public boolean neverHasTarget() {
return this == ConstructorCall
|| this == ExceptionHandler
|| this == PreInitialization
|| this == StaticInitialization;
}
public boolean neverHasThis() {
return this == PreInitialization
|| this == StaticInitialization;
}
public String getSimpleName() {
int dash = getName().lastIndexOf('-');
if (dash == -1) return getName();
else return getName().substring(dash+1);
}
public static Kind read(DataInputStream s) throws IOException {
int key = s.readByte();
switch(key) {
case 1: return MethodCall;
case 2: return ConstructorCall;
case 3: return MethodExecution;
case 4: return ConstructorExecution;
case 5: return FieldGet;
case 6: return FieldSet;
case 7: return StaticInitialization;
case 8: return PreInitialization;
case 9: return AdviceExecution;
case 10: return Initialization;
case 11: return ExceptionHandler;
}
throw new BCException("unknown kind: " + key);
}
}
/**
* Only does the check if the munger requires it (@AJ aspects don't)
*
* @param munger
* @return
*/
protected boolean checkMunger(ShadowMunger munger) {
if (munger.mustCheckExceptions()) {
for (Iterator i = munger.getThrownExceptions().iterator(); i.hasNext(); ) {
if (!checkCanThrow(munger, (ResolvedType)i.next() )) return false;
}
}
return true;
}
protected boolean checkCanThrow(ShadowMunger munger, ResolvedType resolvedTypeX) {
if (getKind() == ExceptionHandler) {
//XXX much too lenient rules here, need to walk up exception handlers
return true;
}
if (!isDeclaredException(resolvedTypeX, getSignature())) {
getIWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CANT_THROW_CHECKED,resolvedTypeX,this), // from advice in \'" + munger. + "\'",
getSourceLocation(), munger.getSourceLocation());
}
return true;
}
private boolean isDeclaredException(
ResolvedType resolvedTypeX,
Member member)
{
ResolvedType[] excs = getIWorld().resolve(member.getExceptions(getIWorld()));
for (int i=0, len=excs.length; i < len; i++) {
if (excs[i].isAssignableFrom(resolvedTypeX)) return true;
}
return false;
}
public void addMunger(ShadowMunger munger) {
if (checkMunger(munger)) this.mungers.add(munger);
}
public final void implement() {
sortMungers();
if (mungers == null) return;
prepareForMungers();
implementMungers();
}
private void sortMungers() {
List sorted = PartialOrder.sort(mungers);
if (sorted == null) {
// this means that we have circular dependencies
for (Iterator i = mungers.iterator(); i.hasNext(); ) {
ShadowMunger m = (ShadowMunger)i.next();
getIWorld().getMessageHandler().handleMessage(
MessageUtil.error(
WeaverMessages.format(WeaverMessages.CIRCULAR_DEPENDENCY,this), m.getSourceLocation()));
}
}
mungers = sorted;
}
/** Prepare the shadow for implementation. After this is done, the shadow
* should be in such a position that each munger simply needs to be implemented.
*/
protected void prepareForMungers() {
throw new RuntimeException("Generic shadows cannot be prepared");
}
/*
* Ensure we report a nice source location - particular in the case
* where the source info is missing (binary weave).
*/
private String beautifyLocation(ISourceLocation isl) {
StringBuffer nice = new StringBuffer();
if (isl==null || isl.getSourceFile()==null || isl.getSourceFile().getName().indexOf("no debug info available")!=-1) {
nice.append("no debug info available");
} else {
// can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa
int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/');
if (takeFrom == -1) {
takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\');
}
nice.append(isl.getSourceFile().getPath().substring(takeFrom +1));
if (isl.getLine()!=0) nice.append(":").append(isl.getLine());
}
return nice.toString();
}
/*
* Report a message about the advice weave that has occurred. Some messing about
* to make it pretty ! This code is just asking for an NPE to occur ...
*/
private void reportWeavingMessage(ShadowMunger munger) {
Advice advice = (Advice)munger;
AdviceKind aKind = advice.getKind();
// Only report on interesting advice kinds ...
if (aKind == null || advice.getConcreteAspect()==null) {
// We suspect someone is programmatically driving the weaver
// (e.g. IdWeaveTestCase in the weaver testcases)
return;
}
if (!( aKind.equals(AdviceKind.Before) ||
aKind.equals(AdviceKind.After) ||
aKind.equals(AdviceKind.AfterReturning) ||
aKind.equals(AdviceKind.AfterThrowing) ||
aKind.equals(AdviceKind.Around) ||
aKind.equals(AdviceKind.Softener))) return;
String description = advice.getKind().toString();
String advisedType = this.getEnclosingType().getName();
String advisingType= advice.getConcreteAspect().getName();
Message msg = null;
if (advice.getKind().equals(AdviceKind.Softener)) {
msg = WeaveMessage.constructWeavingMessage(
WeaveMessage.WEAVEMESSAGE_SOFTENS,
new String[]{advisedType,beautifyLocation(getSourceLocation()),
advisingType,beautifyLocation(munger.getSourceLocation())},
advisedType,
advisingType);
} else {
boolean runtimeTest = ((BcelAdvice)advice).hasDynamicTests();
String joinPointDescription = this.toString();
msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES,
new String[]{ joinPointDescription, advisedType, beautifyLocation(getSourceLocation()),
description,
advisingType,beautifyLocation(munger.getSourceLocation()),
(runtimeTest?" [with runtime test]":"")},
advisedType,
advisingType);
// Boolean.toString(runtimeTest)});
}
getIWorld().getMessageHandler().handleMessage(msg);
}
public IRelationship.Kind determineRelKind(ShadowMunger munger) {
AdviceKind ak = ((Advice)munger).getKind();
if (ak.getKey()==AdviceKind.Before.getKey())
return IRelationship.Kind.ADVICE_BEFORE;
else if (ak.getKey()==AdviceKind.After.getKey())
return IRelationship.Kind.ADVICE_AFTER;
else if (ak.getKey()==AdviceKind.AfterThrowing.getKey())
return IRelationship.Kind.ADVICE_AFTERTHROWING;
else if (ak.getKey()==AdviceKind.AfterReturning.getKey())
return IRelationship.Kind.ADVICE_AFTERRETURNING;
else if (ak.getKey()==AdviceKind.Around.getKey())
return IRelationship.Kind.ADVICE_AROUND;
else if (ak.getKey()==AdviceKind.CflowEntry.getKey() ||
ak.getKey()==AdviceKind.CflowBelowEntry.getKey() ||
ak.getKey()==AdviceKind.InterInitializer.getKey() ||
ak.getKey()==AdviceKind.PerCflowEntry.getKey() ||
ak.getKey()==AdviceKind.PerCflowBelowEntry.getKey() ||
ak.getKey()==AdviceKind.PerThisEntry.getKey() ||
ak.getKey()==AdviceKind.PerTargetEntry.getKey() ||
ak.getKey()==AdviceKind.Softener.getKey() ||
ak.getKey()==AdviceKind.PerTypeWithinEntry.getKey()) {
//System.err.println("Dont want a message about this: "+ak);
return null;
}
throw new RuntimeException("Shadow.determineRelKind: What the hell is it? "+ak);
}
/** Actually implement the (non-empty) mungers associated with this shadow */
private void implementMungers() {
World world = getIWorld();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.implementOn(this);
if (world.getCrossReferenceHandler() != null) {
world.getCrossReferenceHandler().addCrossReference(
munger.getSourceLocation(), // What is being applied
this.getSourceLocation(), // Where is it being applied
determineRelKind(munger), // What kind of advice?
((BcelAdvice)munger).hasDynamicTests() // Is a runtime test being stuffed in the code?
);
}
// TAG: WeavingMessage
if (!getIWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
reportWeavingMessage(munger);
}
if (world.getModel() != null) {
//System.err.println("munger: " + munger + " on " + this);
AsmRelationshipProvider.getDefault().adviceMunger(world.getModel(), this, munger);
}
}
}
public String makeReflectiveFactoryString() {
return null; //XXX
}
public abstract ISourceLocation getSourceLocation();
// ---- utility
public String toString() {
return getKind() + "(" + getSignature() + ")"; // + getSourceLines();
}
public String toResolvedString(World world) {
return getKind() + "(" + world.resolve(getSignature()).toGenericString() + ")";
}
}
|
117,681
|
Bug 117681 VerifyError when using annotations to define inter-type annotation
|
Using Sun JDK1.5.0_04 Audit.java public interface Audit { public String getLastUpdatedBy(); public void setLastUpdatedBy(String un); } AuditImpl.java public class AuditImpl implements Audit { private String lastUpdatedBy; public String getLastUpdatedBy() { return lastUpdatedBy; } public void setLastUpdatedBy(String un) { lastUpdatedBy = un; } } TestAspect.java import org.aspectj.lang.annotation.*; Test.java @Aspect public class TestAspect { @DeclareParents("Test") public static Audit introduced = new AuditImpl(); } public class Test { public static void main(String[] args) { Test t = new Test(); Audit a = (Audit)t; a.setLastUpdatedBy("username"); System.out.println("Username ="+a.getLastUpdatedBy()); } } files.lst Audit.java AuditImpl.java TestAspect.java Test.java Compiled using the following command d:\aspectj1.5\bin\ajc -classpath "d:\aspectj1.5\lib\aspectjrt.jar" -argfi le files.lst -1.5 d:\aspectj1.5\bin\aj5 Test Exception in thread "main" java.lang.VerifyError: (class: Test, method: setLastUpdatedBy signature: (Ljava/lang/String;)V) Incompatible argument to function d:\aspectj1.5\bin\aj5 -noverify Test Username=
|
resolved fixed
|
11ab99f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:54:02Z
| 2005-11-23T10:00:00Z
|
tests/bugs150/pr117681/Audit.java
| |
117,681
|
Bug 117681 VerifyError when using annotations to define inter-type annotation
|
Using Sun JDK1.5.0_04 Audit.java public interface Audit { public String getLastUpdatedBy(); public void setLastUpdatedBy(String un); } AuditImpl.java public class AuditImpl implements Audit { private String lastUpdatedBy; public String getLastUpdatedBy() { return lastUpdatedBy; } public void setLastUpdatedBy(String un) { lastUpdatedBy = un; } } TestAspect.java import org.aspectj.lang.annotation.*; Test.java @Aspect public class TestAspect { @DeclareParents("Test") public static Audit introduced = new AuditImpl(); } public class Test { public static void main(String[] args) { Test t = new Test(); Audit a = (Audit)t; a.setLastUpdatedBy("username"); System.out.println("Username ="+a.getLastUpdatedBy()); } } files.lst Audit.java AuditImpl.java TestAspect.java Test.java Compiled using the following command d:\aspectj1.5\bin\ajc -classpath "d:\aspectj1.5\lib\aspectjrt.jar" -argfi le files.lst -1.5 d:\aspectj1.5\bin\aj5 Test Exception in thread "main" java.lang.VerifyError: (class: Test, method: setLastUpdatedBy signature: (Ljava/lang/String;)V) Incompatible argument to function d:\aspectj1.5\bin\aj5 -noverify Test Username=
|
resolved fixed
|
11ab99f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:54:02Z
| 2005-11-23T10:00:00Z
|
tests/bugs150/pr117681/AuditImpl.java
| |
117,681
|
Bug 117681 VerifyError when using annotations to define inter-type annotation
|
Using Sun JDK1.5.0_04 Audit.java public interface Audit { public String getLastUpdatedBy(); public void setLastUpdatedBy(String un); } AuditImpl.java public class AuditImpl implements Audit { private String lastUpdatedBy; public String getLastUpdatedBy() { return lastUpdatedBy; } public void setLastUpdatedBy(String un) { lastUpdatedBy = un; } } TestAspect.java import org.aspectj.lang.annotation.*; Test.java @Aspect public class TestAspect { @DeclareParents("Test") public static Audit introduced = new AuditImpl(); } public class Test { public static void main(String[] args) { Test t = new Test(); Audit a = (Audit)t; a.setLastUpdatedBy("username"); System.out.println("Username ="+a.getLastUpdatedBy()); } } files.lst Audit.java AuditImpl.java TestAspect.java Test.java Compiled using the following command d:\aspectj1.5\bin\ajc -classpath "d:\aspectj1.5\lib\aspectjrt.jar" -argfi le files.lst -1.5 d:\aspectj1.5\bin\aj5 Test Exception in thread "main" java.lang.VerifyError: (class: Test, method: setLastUpdatedBy signature: (Ljava/lang/String;)V) Incompatible argument to function d:\aspectj1.5\bin\aj5 -noverify Test Username=
|
resolved fixed
|
11ab99f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:54:02Z
| 2005-11-23T10:00:00Z
|
tests/bugs150/pr117681/MoodIndicator.java
| |
117,681
|
Bug 117681 VerifyError when using annotations to define inter-type annotation
|
Using Sun JDK1.5.0_04 Audit.java public interface Audit { public String getLastUpdatedBy(); public void setLastUpdatedBy(String un); } AuditImpl.java public class AuditImpl implements Audit { private String lastUpdatedBy; public String getLastUpdatedBy() { return lastUpdatedBy; } public void setLastUpdatedBy(String un) { lastUpdatedBy = un; } } TestAspect.java import org.aspectj.lang.annotation.*; Test.java @Aspect public class TestAspect { @DeclareParents("Test") public static Audit introduced = new AuditImpl(); } public class Test { public static void main(String[] args) { Test t = new Test(); Audit a = (Audit)t; a.setLastUpdatedBy("username"); System.out.println("Username ="+a.getLastUpdatedBy()); } } files.lst Audit.java AuditImpl.java TestAspect.java Test.java Compiled using the following command d:\aspectj1.5\bin\ajc -classpath "d:\aspectj1.5\lib\aspectjrt.jar" -argfi le files.lst -1.5 d:\aspectj1.5\bin\aj5 Test Exception in thread "main" java.lang.VerifyError: (class: Test, method: setLastUpdatedBy signature: (Ljava/lang/String;)V) Incompatible argument to function d:\aspectj1.5\bin\aj5 -noverify Test Username=
|
resolved fixed
|
11ab99f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:54:02Z
| 2005-11-23T10:00:00Z
|
tests/bugs150/pr117681/Test.java
| |
117,681
|
Bug 117681 VerifyError when using annotations to define inter-type annotation
|
Using Sun JDK1.5.0_04 Audit.java public interface Audit { public String getLastUpdatedBy(); public void setLastUpdatedBy(String un); } AuditImpl.java public class AuditImpl implements Audit { private String lastUpdatedBy; public String getLastUpdatedBy() { return lastUpdatedBy; } public void setLastUpdatedBy(String un) { lastUpdatedBy = un; } } TestAspect.java import org.aspectj.lang.annotation.*; Test.java @Aspect public class TestAspect { @DeclareParents("Test") public static Audit introduced = new AuditImpl(); } public class Test { public static void main(String[] args) { Test t = new Test(); Audit a = (Audit)t; a.setLastUpdatedBy("username"); System.out.println("Username ="+a.getLastUpdatedBy()); } } files.lst Audit.java AuditImpl.java TestAspect.java Test.java Compiled using the following command d:\aspectj1.5\bin\ajc -classpath "d:\aspectj1.5\lib\aspectjrt.jar" -argfi le files.lst -1.5 d:\aspectj1.5\bin\aj5 Test Exception in thread "main" java.lang.VerifyError: (class: Test, method: setLastUpdatedBy signature: (Ljava/lang/String;)V) Incompatible argument to function d:\aspectj1.5\bin\aj5 -noverify Test Username=
|
resolved fixed
|
11ab99f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:54:02Z
| 2005-11-23T10:00:00Z
|
tests/bugs150/pr117681/TestAspect.java
| |
117,681
|
Bug 117681 VerifyError when using annotations to define inter-type annotation
|
Using Sun JDK1.5.0_04 Audit.java public interface Audit { public String getLastUpdatedBy(); public void setLastUpdatedBy(String un); } AuditImpl.java public class AuditImpl implements Audit { private String lastUpdatedBy; public String getLastUpdatedBy() { return lastUpdatedBy; } public void setLastUpdatedBy(String un) { lastUpdatedBy = un; } } TestAspect.java import org.aspectj.lang.annotation.*; Test.java @Aspect public class TestAspect { @DeclareParents("Test") public static Audit introduced = new AuditImpl(); } public class Test { public static void main(String[] args) { Test t = new Test(); Audit a = (Audit)t; a.setLastUpdatedBy("username"); System.out.println("Username ="+a.getLastUpdatedBy()); } } files.lst Audit.java AuditImpl.java TestAspect.java Test.java Compiled using the following command d:\aspectj1.5\bin\ajc -classpath "d:\aspectj1.5\lib\aspectjrt.jar" -argfi le files.lst -1.5 d:\aspectj1.5\bin\aj5 Test Exception in thread "main" java.lang.VerifyError: (class: Test, method: setLastUpdatedBy signature: (Ljava/lang/String;)V) Incompatible argument to function d:\aspectj1.5\bin\aj5 -noverify Test Username=
|
resolved fixed
|
11ab99f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:54:02Z
| 2005-11-23T10:00:00Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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");
}
/*
* 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);
}
// 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);
}
}
|
117,681
|
Bug 117681 VerifyError when using annotations to define inter-type annotation
|
Using Sun JDK1.5.0_04 Audit.java public interface Audit { public String getLastUpdatedBy(); public void setLastUpdatedBy(String un); } AuditImpl.java public class AuditImpl implements Audit { private String lastUpdatedBy; public String getLastUpdatedBy() { return lastUpdatedBy; } public void setLastUpdatedBy(String un) { lastUpdatedBy = un; } } TestAspect.java import org.aspectj.lang.annotation.*; Test.java @Aspect public class TestAspect { @DeclareParents("Test") public static Audit introduced = new AuditImpl(); } public class Test { public static void main(String[] args) { Test t = new Test(); Audit a = (Audit)t; a.setLastUpdatedBy("username"); System.out.println("Username ="+a.getLastUpdatedBy()); } } files.lst Audit.java AuditImpl.java TestAspect.java Test.java Compiled using the following command d:\aspectj1.5\bin\ajc -classpath "d:\aspectj1.5\lib\aspectjrt.jar" -argfi le files.lst -1.5 d:\aspectj1.5\bin\aj5 Test Exception in thread "main" java.lang.VerifyError: (class: Test, method: setLastUpdatedBy signature: (Ljava/lang/String;)V) Incompatible argument to function d:\aspectj1.5\bin\aj5 -noverify Test Username=
|
resolved fixed
|
11ab99f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T12:54:02Z
| 2005-11-23T10:00: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.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.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 {
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();
// getstatic field from aspect
body.append(Utility.createGet(fact, munger.getDelegate()));
int pos = 0;
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 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();
}
}
|
116,254
|
Bug 116254 AjTypeSystem interface cannot be used in LTW environment
| null |
resolved fixed
|
81e6b60
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T13:14:22Z
| 2005-11-14T17:40:00Z
|
aspectj5rt/java5-src/org/aspectj/internal/lang/reflect/DeclareSoftImpl.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.internal.lang.reflect;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.DeclareSoft;
import org.aspectj.lang.reflect.PointcutExpression;
/**
* @author colyer
*
*/
public class DeclareSoftImpl implements DeclareSoft {
private AjType<?> declaringType;
private PointcutExpression pointcut;
private AjType<?> exceptionType;
private String missingTypeName;
public DeclareSoftImpl(AjType declaringType, String pcut, String exceptionTypeName) {
this.declaringType = declaringType;
this.pointcut = new PointcutExpressionImpl(pcut);
try {
this.exceptionType = AjTypeSystem.getAjType(Class.forName(exceptionTypeName));
} catch (ClassNotFoundException ex) {
this.missingTypeName = exceptionTypeName;
}
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.DeclareSoft#getDeclaringType()
*/
public AjType getDeclaringType() {
return this.declaringType;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.DeclareSoft#getSoftenedExceptionType()
*/
public AjType getSoftenedExceptionType() throws ClassNotFoundException {
if (this.missingTypeName != null) throw new ClassNotFoundException(this.missingTypeName);
return this.exceptionType;
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.DeclareSoft#getPointcutExpression()
*/
public PointcutExpression getPointcutExpression() {
return this.pointcut;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("declare soft : ");
if (this.missingTypeName != null) {
sb.append(this.exceptionType.getName());
} else {
sb.append(this.missingTypeName);
}
sb.append(" : ");
sb.append(getPointcutExpression().asString());
return sb.toString();
}
}
|
116,254
|
Bug 116254 AjTypeSystem interface cannot be used in LTW environment
| null |
resolved fixed
|
81e6b60
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T13:14:22Z
| 2005-11-14T17:40:00Z
|
aspectj5rt/java5-src/org/aspectj/internal/lang/reflect/StringToType.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.internal.lang.reflect;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.StringTokenizer;
import org.aspectj.lang.reflect.AjTypeSystem;
/**
* @author colyer
* Helper class for converting type representations in Strings into java.lang.reflect.Types.
*/
public class StringToType {
public static Type[] commaSeparatedListToTypeArray(String typeNames, Class classScope)
throws ClassNotFoundException {
StringTokenizer strTok = new StringTokenizer(typeNames,",");
Type[] ret = new Type[strTok.countTokens()];
int index = 0;
outer: while (strTok.hasMoreTokens()) {
String typeName = strTok.nextToken().trim();
ret[index++] = stringToType(typeName, classScope);
}
return ret;
}
public static Type stringToType(String typeName, Class classScope)
throws ClassNotFoundException {
try {
if (typeName.indexOf("<") == -1) {
return AjTypeSystem.getAjType(Class.forName(typeName));
} else {
return makeParameterizedType(typeName,classScope);
}
} catch (ClassNotFoundException e) {
// could be a type variable
TypeVariable[] tVars = classScope.getTypeParameters();
for (int i = 0; i < tVars.length; i++) {
if (tVars[i].getName().equals(typeName)) {
return tVars[i];
}
}
throw new ClassNotFoundException(typeName);
}
}
private static Type makeParameterizedType(String typeName, Class classScope)
throws ClassNotFoundException {
int paramStart = typeName.indexOf('<');
String baseName = typeName.substring(0, paramStart);
final Class baseClass = Class.forName(baseName);
int paramEnd = typeName.lastIndexOf('>');
String params = typeName.substring(paramStart+1,paramEnd);
final Type[] typeParams = commaSeparatedListToTypeArray(params,classScope);
return new ParameterizedType() {
public Type[] getActualTypeArguments() {
return typeParams;
}
public Type getRawType() {
return baseClass;
}
public Type getOwnerType() {
return baseClass.getEnclosingClass();
}
};
}
}
|
114,054
|
Bug 114054 NPE in CContentOutlinePage.createContentProvider()
|
CUIPlugin.getActiveWorkbenchWindow().getActivePage() can return null.
|
resolved fixed
|
a4caeb9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T16:20:19Z
| 2005-10-28T03:26:40Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
public void testAtDeclareParents_pr117681() { runTest("at declare parents");}
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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");
}
/*
* 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);
}
// 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);
}
}
|
114,054
|
Bug 114054 NPE in CContentOutlinePage.createContentProvider()
|
CUIPlugin.getActiveWorkbenchWindow().getActivePage() can return null.
|
resolved fixed
|
a4caeb9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T16:20:19Z
| 2005-10-28T03:26:40Z
|
weaver/src/org/aspectj/weaver/patterns/PerThisOrTargetPointcutVisitor.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.patterns;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
/**
* A visitor that turns a pointcut into a type pattern equivalent for a perthis or pertarget matching:
* - pertarget(target(Foo)) => Foo+ (this one is a special case..)
* - pertarget(execution(* Foo.do()) => Foo
* - perthis(call(* Foo.do()) => *
* - perthis(!call(* Foo.do()) => * (see how the ! has been absorbed here..)
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class PerThisOrTargetPointcutVisitor extends IdentityPointcutVisitor {
/** A maybe marker */
private final static TypePattern MAYBE = new TypePatternMayBe();
private final boolean m_isTarget;
private final ResolvedType m_fromAspectType;
public PerThisOrTargetPointcutVisitor(boolean isTarget, ResolvedType fromAspectType) {
m_isTarget = isTarget;
m_fromAspectType = fromAspectType;
}
public TypePattern getPerTypePointcut(Pointcut perClausePointcut) {
return (TypePattern) perClausePointcut.accept(this, perClausePointcut);
}
//-- visitor methods, all is like Identity visitor except when it comes to transform pointcuts
public Object visit(WithinPointcut node, Object data) {
if (m_isTarget) {
//pertarget(.. && within(Foo)) => true
//pertarget(.. && !within(Foo)) => true as well !
return MAYBE;
} else {
return node.getTypePattern();
}
}
public Object visit(WithincodePointcut node, Object data) {
if (m_isTarget) {
//pertarget(.. && withincode(* Foo.do())) => true
//pertarget(.. && !withincode(* Foo.do())) => true as well !
return MAYBE;
} else {
return node.getSignature().getDeclaringType();
}
}
public Object visit(WithinAnnotationPointcut node, Object data) {
if (m_isTarget) {
return MAYBE;
} else {
return node.getAnnotationTypePattern();
}
}
public Object visit(WithinCodeAnnotationPointcut node, Object data) {
if (m_isTarget) {
return MAYBE;
} else {
return MAYBE;//FIXME AV - can we optimize ? perthis(@withincode(Foo)) = hasmethod(..)
}
}
public Object visit(KindedPointcut node, Object data) {
if (node.getKind().equals(Shadow.AdviceExecution)) {
return MAYBE;//TODO AV - can we do better ?
} else if (node.getKind().equals(Shadow.ConstructorExecution)
|| node.getKind().equals(Shadow.Initialization)
|| node.getKind().equals(Shadow.MethodExecution)
|| node.getKind().equals(Shadow.PreInitialization)
|| node.getKind().equals(Shadow.StaticInitialization)) {
return node.getSignature().getDeclaringType();
} else if (node.getKind().equals(Shadow.ConstructorCall)
|| node.getKind().equals(Shadow.FieldGet)
|| node.getKind().equals(Shadow.FieldSet)
|| node.getKind().equals(Shadow.MethodCall)) {
if (m_isTarget) {
return node.getSignature().getDeclaringType();
} else {
return MAYBE;
}
} else if (node.getKind().equals(Shadow.ExceptionHandler)) {
return MAYBE;
} else {
throw new ParserException("Undetermined - should not happen: " + node.getKind().getSimpleName(), null);
}
}
public Object visit(AndPointcut node, Object data) {
return new AndTypePattern(getPerTypePointcut(node.left), getPerTypePointcut(node.right));
}
public Object visit(OrPointcut node, Object data) {
return new OrTypePattern(getPerTypePointcut(node.left), getPerTypePointcut(node.right));
}
public Object visit(NotPointcut node, Object data) {
TypePattern negated = getPerTypePointcut(node.getNegatedPointcut());
if (MAYBE.equals(negated)) {
return MAYBE;
}
return new NotTypePattern(negated);
}
public Object visit(ThisOrTargetAnnotationPointcut node, Object data) {
if (m_isTarget && !node.isThis()) {
return node.getAnnotationTypePattern();
} else if (!m_isTarget && node.isThis()) {
return node.getAnnotationTypePattern();
} else {
// perthis(@target(Foo))
return MAYBE;
}
}
public Object visit(ThisOrTargetPointcut node, Object data) {
if ((m_isTarget && !node.isThis())
|| (!m_isTarget && node.isThis())) {
String pointcutString = node.getType().toString();
// see pr115788 "<nothing>" means there was a problem resolving types - that will be reported so dont blow up
// the parser here..
if (pointcutString.equals("<nothing>")) {
return new NoTypePattern();
}
//pertarget(target(Foo)) => Foo+ for type pattern matching
//perthis(this(Foo)) => Foo+ for type pattern matching
// TODO AV - we do like a deep copy by parsing it again.. quite dirty, would need a clean deep copy
TypePattern copy = new PatternParser(pointcutString.replace('$', '.')).parseTypePattern();
// TODO AV - see dirty replace from $ to . here as inner classes are with $ instead (#108488)
copy.includeSubtypes = true;
return copy;
} else {
// perthis(target(Foo)) => maybe
return MAYBE;
}
}
public Object visit(ReferencePointcut node, Object data) {
// && pc_ref()
// we know there is no support for binding in perClause: perthis(pc_ref(java.lang.String))
// TODO AV - may need some work for generics..
ResolvedPointcutDefinition pointcutDec;
ResolvedType searchStart = m_fromAspectType;
if (node.onType != null) {
searchStart = node.onType.resolve(m_fromAspectType.getWorld());
if (searchStart == ResolvedType.MISSING) {
return MAYBE;// this should not happen since concretize will fails but just in case..
}
}
pointcutDec = searchStart.findPointcut(node.name);
return getPerTypePointcut(pointcutDec.getPointcut());
}
public Object visit(IfPointcut node, Object data) {
return TypePattern.ANY;
}
public Object visit(HandlerPointcut node, Object data) {
// quiet unexpected since a KindedPointcut but do as if...
return MAYBE;
}
public Object visit(CflowPointcut node, Object data) {
return MAYBE;
}
public Object visit(ConcreteCflowPointcut node, Object data) {
return MAYBE;
}
public Object visit(ArgsPointcut node, Object data) {
return MAYBE;
}
public Object visit(ArgsAnnotationPointcut node, Object data) {
return MAYBE;
}
public Object visit(AnnotationPointcut node, Object data) {
return MAYBE;
}
public Object visit(Pointcut.MatchesNothingPointcut node, Object data) {
// a small hack since the usual MatchNothing has its toString = "<nothing>" which is not parseable back
// while I use back parsing for check purpose.
return new NoTypePattern() {
public String toString() {
return "false";
}
};
}
/**
* A MayBe type pattern that acts as ANY except that !MAYBE = MAYBE
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
private static class TypePatternMayBe extends AnyTypePattern {
}
}
|
114,495
|
Bug 114495 unqualified superaspect<T> pointcut sortafunny in subaspect
| null |
resolved fixed
|
86880f7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T19:21:03Z
| 2005-11-01T10:13:20Z
|
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
/*
public void testBrokenDispatchByITD_pr72834() { runTest("broken dispatch");}
public void testMissingAccessor_pr73856() { runTest("missing accessor");}
public void testCunningDeclareParents_pr92311() { runTest("cunning declare parents");}
public void testGenericITDsAndAbstractMethodError_pr102357() { runTest("generic itds and abstract method error");}
*/
public void testAtDeclareParents_pr117681() { runTest("at declare parents");}
public void testPrivilegeProblem_pr87525() { runTest("privilege problem with switch");}
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 testBadDecp_pr110788_1() { runTest("bad generic decp - 1");}
public void testBadDecp_pr110788_2() { runTest("bad generic decp - 2");}
public void testBadDecp_pr110788_3() { runTest("bad generic decp - 3");}
public void testBadDecp_pr110788_4() { runTest("bad generic decp - 4");}
public void testVarargsITD_pr110906() { runTest("ITD varargs problem");}
public void testBadRenderer_pr86903() { runTest("bcelrenderer bad");}
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 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");
}
/*
* 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);
}
// 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);
}
}
|
114,495
|
Bug 114495 unqualified superaspect<T> pointcut sortafunny in subaspect
| null |
resolved fixed
|
86880f7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T19:21:03Z
| 2005-11-01T10:13:20Z
|
weaver/src/org/aspectj/weaver/ReferenceType.java
|
/* *******************************************************************
* Copyright (c) 2002 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Andy Clement - June 2005 - separated out from ResolvedType
* ******************************************************************/
package org.aspectj.weaver;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.PerClause;
/**
* A reference type represents some 'real' type, not a primitive, not an array - but
* a real type, for example java.util.List. Each ReferenceType has a delegate
* that is the underlying artifact - either an eclipse artifact or a
* bcel artifact. If the type represents a raw type (i.e. there is
* a generic form) then the genericType field is set to point to the
* generic type. If it is for a parameterized type then the generic type
* is also set to point to the generic form.
*/
public class ReferenceType extends ResolvedType {
/**
* For parameterized types (or the raw type) - this field points to the actual
* reference type from which they are derived.
*/
ReferenceType genericType = null;
ReferenceTypeDelegate delegate = null;
ISourceContext sourceContext = null;
int startPos = 0;
int endPos = 0;
public static ReferenceType fromTypeX(UnresolvedType tx, World world) {
ReferenceType rt = new ReferenceType(tx.getErasureSignature(),world);
rt.typeKind = tx.typeKind;
return rt;
}
// cached values for members
ResolvedMember[] parameterizedMethods = null;
ResolvedMember[] parameterizedFields = null;
ResolvedMember[] parameterizedPointcuts = null;
ResolvedType[] parameterizedInterfaces = null;
Collection parameterizedDeclares = null;
//??? should set delegate before any use
public ReferenceType(String signature, World world) {
super(signature, world);
}
/**
* Constructor used when creating a parameterized type.
*/
public ReferenceType(
ResolvedType theGenericType,
ResolvedType[] theParameters,
World aWorld) {
super(makeParameterizedSignature(theGenericType,theParameters),
theGenericType.signatureErasure,
aWorld);
ReferenceType genericReferenceType = (ReferenceType) theGenericType;
this.typeParameters = theParameters;
this.genericType = genericReferenceType;
this.typeKind = TypeKind.PARAMETERIZED;
this.delegate = genericReferenceType.getDelegate();
}
/**
* Constructor used when creating a raw type.
*/
public ReferenceType(
ResolvedType theGenericType,
World aWorld) {
super(theGenericType.getErasureSignature(),
theGenericType.getErasureSignature(),
aWorld);
ReferenceType genericReferenceType = (ReferenceType) theGenericType;
this.typeParameters = null;
this.genericType = genericReferenceType;
this.typeKind = TypeKind.RAW;
this.delegate = genericReferenceType.getDelegate();
}
public String getSignatureForAttribute() {
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 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
parameterizedInterfaces[i] =
parameterizedInterfaces[i].parameterizedWith(paramTypes);
}
}
return parameterizedInterfaces;
}
return delegate.getDeclaredInterfaces();
}
public ResolvedMember[] getDeclaredMethods() {
if (parameterizedMethods != null) return parameterizedMethods;
if (isParameterizedType() || isRawType()) {
ResolvedMember[] delegateMethods = delegate.getDeclaredMethods();
UnresolvedType[] parameters = getTypesForMemberParameterization();
parameterizedMethods = new ResolvedMember[delegateMethods.length];
for (int i = 0; i < delegateMethods.length; i++) {
parameterizedMethods[i] = delegateMethods[i].parameterizedWith(parameters,this,isParameterizedType());
}
return parameterizedMethods;
} else {
return delegate.getDeclaredMethods();
}
}
public ResolvedMember[] getDeclaredPointcuts() {
if (parameterizedPointcuts != null) return parameterizedPointcuts;
if (isParameterizedType()) {
ResolvedMember[] delegatePointcuts = delegate.getDeclaredPointcuts();
parameterizedPointcuts = new ResolvedMember[delegatePointcuts.length];
for (int i = 0; i < delegatePointcuts.length; i++) {
parameterizedPointcuts[i] = delegatePointcuts[i].parameterizedWith(getTypesForMemberParameterization(),this,isParameterizedType());
}
return parameterizedPointcuts;
} else {
return delegate.getDeclaredPointcuts();
}
}
private UnresolvedType[] getTypesForMemberParameterization() {
UnresolvedType[] parameters = null;
if (isParameterizedType()) {
parameters = getTypeParameters();
} else if (isRawType()){
// raw type, use upper bounds of type variables on generic type
TypeVariable[] tvs = getGenericType().getTypeVariables();
parameters = new UnresolvedType[tvs.length];
for (int i = 0; i < tvs.length; i++) {
parameters[i] = tvs[i].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() { return delegate.getPerClause(); }
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;
}
private boolean ajMembersNeedParameterization() {
if (isParameterizedType()) return true;
if (getSuperclass() != null) return ((ReferenceType)getSuperclass()).ajMembersNeedParameterization();
return false;
}
private Map getAjMemberParameterizationMap() {
Map myMap = getMemberParameterizationMap();
if (myMap.size() == 0) {
// might extend a parameterized aspect that we also need to consider...
if (getSuperclass() != null) return ((ReferenceType)getSuperclass()).getAjMemberParameterizationMap();
}
return myMap;
}
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;
// If we are raw, we have a generic type - we should ensure it uses the
// same delegate
if (isRawType() && getGenericType()!=null) {
((ReferenceType)getGenericType()).setDelegate(delegate);
}
clearParameterizationCaches();
}
private void clearParameterizationCaches() {
parameterizedFields = null;
parameterizedInterfaces = null;
parameterizedMethods = null;
parameterizedPointcuts = null;
}
public int getEndPos() {
return endPos;
}
public int getStartPos() {
return startPos;
}
public void setEndPos(int endPos) {
this.endPos = endPos;
}
public void setSourceContext(ISourceContext sourceContext) {
this.sourceContext = sourceContext;
}
public void setStartPos(int startPos) {
this.startPos = startPos;
}
public boolean doesNotExposeShadowMungers() {
return delegate.doesNotExposeShadowMungers();
}
public String getDeclaredGenericSignature() {
return delegate.getDeclaredGenericSignature();
}
public void setGenericType(ReferenceType rt) {
genericType = rt;
// Should we 'promote' this reference type from simple to raw?
// makes sense if someone is specifying that it has a generic form
if ( typeKind == TypeKind.SIMPLE ) {
typeKind = TypeKind.RAW;
signatureErasure = signature;
}
}
public ResolvedType getGenericType() {
if (isGenericType()) return this;
return genericType;
}
/**
* a parameterized signature starts with a "P" in place of the "L",
* see the comment on signatures in UnresolvedType.
* @param aGenericType
* @param someParameters
* @return
*/
private static String makeParameterizedSignature(ResolvedType aGenericType, ResolvedType[] someParameters) {
String rawSignature = aGenericType.getErasureSignature();
String prefix = PARAMETERIZED_TYPE_IDENTIFIER + rawSignature.substring(1,rawSignature.length()-1);
StringBuffer ret = new StringBuffer();
ret.append(prefix);
ret.append("<");
for (int i = 0; i < someParameters.length; i++) {
ret.append(someParameters[i].getSignature());
}
ret.append(">;");
return ret.toString();
}
private static String makeDeclaredSignature(ResolvedType aGenericType, UnresolvedType[] someParameters) {
StringBuffer ret = new StringBuffer();
String rawSig = aGenericType.getErasureSignature();
ret.append(rawSig.substring(0,rawSig.length()-1));
ret.append("<");
for (int i = 0; i < someParameters.length; i++) {
ret.append(someParameters[i].getSignature());
}
ret.append(">;");
return ret.toString();
}
}
|
114,495
|
Bug 114495 unqualified superaspect<T> pointcut sortafunny in subaspect
| null |
resolved fixed
|
86880f7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T19:21:03Z
| 2005-11-01T10:13:20Z
|
weaver/src/org/aspectj/weaver/ResolvedType.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur @AspectJ ITDs
* ******************************************************************/
package org.aspectj.weaver;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.PerClause;
public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement {
private static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0];
public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P";
private ResolvedType[] resolvedTypeParams;
protected World world;
protected ResolvedType(String signature, World world) {
super(signature);
this.world = world;
}
protected ResolvedType(String signature, String signatureErasure, World world) {
super(signature,signatureErasure);
this.world = world;
}
// ---- things that don't require a world
/**
* Returns an iterator through ResolvedType objects representing all the direct
* supertypes of this type. That is, through the superclass, if any, and
* all declared interfaces.
*/
public final Iterator getDirectSupertypes() {
Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces());
ResolvedType superclass = getSuperclass();
if (superclass == null) {
return ifacesIterator;
} else {
return Iterators.snoc(ifacesIterator, superclass);
}
}
public abstract ResolvedMember[] getDeclaredFields();
public abstract ResolvedMember[] getDeclaredMethods();
public abstract ResolvedType[] getDeclaredInterfaces();
public abstract ResolvedMember[] getDeclaredPointcuts();
/**
* Returns a ResolvedType object representing the superclass of this type, or null.
* If this represents a java.lang.Object, a primitive type, or void, this
* method returns null.
*/
public abstract ResolvedType getSuperclass();
/**
* Returns the modifiers for this type.
* <p/>
* See {@link Class#getModifiers()} for a description
* of the weirdness of this methods on primitives and arrays.
*
* @param world the {@link World} in which the lookup is made.
* @return an int representing the modifiers for this type
* @see java.lang.reflect.Modifier
*/
public abstract int getModifiers();
// return true if this resolved type couldn't be found (but we know it's name maybe)
public boolean isMissing() {
return false;
}
public ResolvedType[] getAnnotationTypes() {
return EMPTY_RESOLVED_TYPE_ARRAY;
}
public final UnresolvedType getSuperclass(World world) {
return getSuperclass();
}
// This set contains pairs of types whose signatures are concatenated
// together, this means with a fast lookup we can tell if two types
// are equivalent.
static Set validBoxing = new HashSet();
static {
validBoxing.add("Ljava/lang/Byte;B");
validBoxing.add("Ljava/lang/Character;C");
validBoxing.add("Ljava/lang/Double;D");
validBoxing.add("Ljava/lang/Float;F");
validBoxing.add("Ljava/lang/Integer;I");
validBoxing.add("Ljava/lang/Long;J");
validBoxing.add("Ljava/lang/Short;S");
validBoxing.add("Ljava/lang/Boolean;Z");
validBoxing.add("BLjava/lang/Byte;");
validBoxing.add("CLjava/lang/Character;");
validBoxing.add("DLjava/lang/Double;");
validBoxing.add("FLjava/lang/Float;");
validBoxing.add("ILjava/lang/Integer;");
validBoxing.add("JLjava/lang/Long;");
validBoxing.add("SLjava/lang/Short;");
validBoxing.add("ZLjava/lang/Boolean;");
}
// utilities
public ResolvedType getResolvedComponentType() {
return null;
}
public World getWorld() {
return world;
}
// ---- things from object
public final boolean equals(Object other) {
if (other instanceof ResolvedType) {
return this == other;
} else {
return super.equals(other);
}
}
// ---- difficult things
/**
* returns an iterator through all of the fields of this type, in order
* for checking from JVM spec 2ed 5.4.3.2. This means that the order is
* <p/>
* <ul><li> fields from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getFields() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterators.Getter fieldGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedType)o).getDeclaredFields());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
fieldGetter);
}
/**
* returns an iterator through all of the methods of this type, in order
* for checking from JVM spec 2ed 5.4.3.3. This means that the order is
* <p/>
* <ul><li> methods from current class </li>
* <li> recur into superclass, all the way up, not touching interfaces </li>
* <li> recur into all superinterfaces, in some unspecified order </li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
* NOTE: Take a look at the javadoc on getMethodsWithoutIterator() to see if
* you are sensitive to a quirk in getMethods()
*/
public Iterator getMethods() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter ifaceGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
Iterators.array(((ResolvedType)o).getDeclaredInterfaces())
);
}
};
Iterators.Getter methodGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedType)o).getDeclaredMethods());
}
};
return
Iterators.mapOver(
Iterators.append(
new Iterator() {
ResolvedType curr = ResolvedType.this;
public boolean hasNext() {
return curr != null;
}
public Object next() {
ResolvedType ret = curr;
curr = curr.getSuperclass();
return ret;
}
public void remove() {
throw new UnsupportedOperationException();
}
},
Iterators.recur(this, ifaceGetter)),
methodGetter);
}
/**
* Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those declared
* on the superinterfaces. The getMethods() call above doesn't quite work the same as it will (through the iterator) return methods
* declared on *this* class twice, once at the start and once at the end - I couldn't debug that problem, so created this alternative.
*/
public List getMethodsWithoutIterator(boolean includeITDs, boolean allowMissing) {
List methods = new ArrayList();
Set knowninterfaces = new HashSet();
addAndRecurse(knowninterfaces,methods,this,includeITDs,allowMissing);
return methods;
}
private void addAndRecurse(Set knowninterfaces,List collector, ResolvedType rtx, boolean includeITDs, boolean allowMissing) {
collector.addAll(Arrays.asList(rtx.getDeclaredMethods())); // Add the methods declared on this type
// now add all the inter-typed members too
if (includeITDs && rtx.interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
ResolvedMember rm = tm.getSignature();
if (rm != null) { // new parent type munger can have null signature...
collector.add(tm.getSignature());
}
}
}
if (!rtx.equals(ResolvedType.OBJECT)) {
ResolvedType superType = rtx.getSuperclass();
if (superType != null && !superType.isMissing()) {
addAndRecurse(knowninterfaces,collector,superType,includeITDs,allowMissing); // Recurse if we aren't at the top
}
}
ResolvedType[] interfaces = rtx.getDeclaredInterfaces(); // Go through the interfaces on the way back down
for (int i = 0; i < interfaces.length; i++) {
ResolvedType iface = interfaces[i];
// we need to know if it is an interface from Parent kind munger
// as those are used for @AJ ITD and we precisely want to skip those
boolean shouldSkip = false;
for (int j = 0; j < rtx.interTypeMungers.size(); j++) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j);
if (munger.getMunger().getKind() == ResolvedTypeMunger.Parent) {
shouldSkip = true;
break;
}
}
if (!shouldSkip && !knowninterfaces.contains(iface)) { // Dont do interfaces more than once
knowninterfaces.add(iface);
if (allowMissing && iface.isMissing()) {
if (iface instanceof MissingResolvedTypeWithKnownSignature) {
((MissingResolvedTypeWithKnownSignature)iface).raiseWarningOnMissingInterfaceWhilstFindingMethods();
}
} else {
addAndRecurse(knowninterfaces,collector,iface,includeITDs,allowMissing);
}
}
}
}
public ResolvedType[] getResolvedTypeParameters() {
if (resolvedTypeParams == null) {
resolvedTypeParams = world.resolve(typeParameters);
}
return resolvedTypeParams;
}
/**
* described in JVM spec 2ed 5.4.3.2
*/
public ResolvedMember lookupField(Member m) {
return lookupMember(m, getFields());
}
/**
* described in JVM spec 2ed 5.4.3.3.
* Doesnt check ITDs.
*/
public ResolvedMember lookupMethod(Member m) {
return lookupMember(m, getMethods());
}
public ResolvedMember lookupMethodInITDs(Member m) {
if (interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
if (matches(tm.getSignature(), m)) {
return tm.getSignature();
}
}
}
return null;
}
/**
* return null if not found
*/
private ResolvedMember lookupMember(Member m, Iterator i) {
while (i.hasNext()) {
ResolvedMember f = (ResolvedMember) i.next();
if (matches(f, m)) return f;
}
return null; //ResolvedMember.Missing;
//throw new BCException("can't find " + m);
}
/**
* return null if not found
*/
private ResolvedMember lookupMember(Member m, ResolvedMember[] a) {
for (int i = 0; i < a.length; i++) {
ResolvedMember f = a[i];
if (matches(f, m)) return f;
}
return null;
}
/**
* Looks for the first member in the hierarchy matching aMember. This method
* differs from lookupMember(Member) in that it takes into account parameters
* which are type variables - which clearly an unresolved Member cannot do since
* it does not know anything about type variables.
*/
public ResolvedMember lookupResolvedMember(ResolvedMember aMember,boolean allowMissing) {
Iterator toSearch = null;
ResolvedMember found = null;
if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) {
toSearch = getMethodsWithoutIterator(true,allowMissing).iterator();
} else {
if (aMember.getKind() != Member.FIELD)
throw new IllegalStateException("I didn't know you would look for members of kind " + aMember.getKind());
toSearch = getFields();
}
while(toSearch.hasNext()) {
ResolvedMemberImpl candidate = (ResolvedMemberImpl) toSearch.next();
if (candidate.matches(aMember)) {
found = candidate;
break;
}
}
return found;
}
public static boolean matches(Member m1, Member m2) {
if (m1 == null) return m2 == null;
if (m2 == null) return false;
// Check the names
boolean equalNames = m1.getName().equals(m2.getName());
if (!equalNames) return false;
// Check the signatures
boolean equalSignatures = m1.getSignature().equals(m2.getSignature());
if (equalSignatures) return true;
// If they aren't the same, we need to allow for covariance ... where one sig might be ()LCar; and
// the subsig might be ()LFastCar; - where FastCar is a subclass of Car
boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature());
if (equalCovariantSignatures) return true;
return false;
}
public static boolean conflictingSignature(Member m1, Member m2) {
if (m1 == null || m2 == null) return false;
if (!m1.getName().equals(m2.getName())) {
return false;
}
if (m1.getKind() != m2.getKind()) {
return false;
}
if (m1.getKind() == Member.FIELD) {
return m1.getDeclaringType().equals(m2.getDeclaringType());
} else if (m1.getKind() == Member.POINTCUT) {
return true;
}
UnresolvedType[] p1 = m1.getParameterTypes();
UnresolvedType[] p2 = m2.getParameterTypes();
int n = p1.length;
if (n != p2.length) return false;
for (int i=0; i < n; i++) {
if (!p1[i].equals(p2[i])) return false;
}
return true;
}
/**
* returns an iterator through all of the pointcuts of this type, in order
* for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is
* <p/>
* <ul><li> pointcuts from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getPointcuts() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
// same order as fields
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterators.Getter pointcutGetter = new Iterators.Getter() {
public Iterator get(Object o) {
//System.err.println("getting for " + o);
return Iterators.array(((ResolvedType)o).getDeclaredPointcuts());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
pointcutGetter);
}
public ResolvedPointcutDefinition findPointcut(String name) {
//System.err.println("looking for pointcuts " + this);
for (Iterator i = getPointcuts(); i.hasNext(); ) {
ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next();
//System.err.println(f);
if (name.equals(f.getName())) {
return f;
}
}
return null; // should we throw an exception here?
}
// all about collecting CrosscuttingMembers
//??? collecting data-structure, shouldn't really be a field
public CrosscuttingMembers crosscuttingMembers;
public CrosscuttingMembers collectCrosscuttingMembers() {
crosscuttingMembers = new CrosscuttingMembers(this);
crosscuttingMembers.setPerClause(getPerClause());
crosscuttingMembers.addShadowMungers(collectShadowMungers());
crosscuttingMembers.addTypeMungers(getTypeMungers());
//FIXME AV - skip but needed ?? or ?? crosscuttingMembers.addLateTypeMungers(getLateTypeMungers());
crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers()));
crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses());
//System.err.println("collected cc members: " + this + ", " + collectDeclares());
return crosscuttingMembers;
}
public final Collection collectDeclares(boolean includeAdviceLike) {
if (! this.isAspect() ) return Collections.EMPTY_LIST;
ArrayList ret = new ArrayList();
//if (this.isAbstract()) {
// for (Iterator i = getDeclares().iterator(); i.hasNext();) {
// Declare dec = (Declare) i.next();
// if (!dec.isAdviceLike()) ret.add(dec);
// }
//
// if (!includeAdviceLike) return ret;
if (!this.isAbstract()) {
//ret.addAll(getDeclares());
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedType ty = (ResolvedType) typeIterator.next();
//System.out.println("super: " + ty + ", " + );
for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) {
Declare dec = (Declare) i.next();
if (dec.isAdviceLike()) {
if (includeAdviceLike) ret.add(dec);
} else {
ret.add(dec);
}
}
}
}
return ret;
}
private final Collection collectShadowMungers() {
if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST;
ArrayList acc = new ArrayList();
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedType ty = (ResolvedType) typeIterator.next();
acc.addAll(ty.getDeclaredShadowMungers());
}
return acc;
}
protected boolean doesNotExposeShadowMungers() {
return false;
}
public PerClause getPerClause() {
return null;
}
protected Collection getDeclares() {
return Collections.EMPTY_LIST;
}
protected Collection getTypeMungers() {
return Collections.EMPTY_LIST;
}
protected Collection getPrivilegedAccesses() {
return Collections.EMPTY_LIST;
}
// ---- useful things
public final boolean isInterface() {
return Modifier.isInterface(getModifiers());
}
public final boolean isAbstract() {
return Modifier.isAbstract(getModifiers());
}
public boolean isClass() {
return false;
}
public boolean isAspect() {
return false;
}
public boolean isAnnotationStyleAspect() {
return false;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isEnum() {
return false;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isAnnotation() {
return false;
}
public boolean isAnonymous() {
return false;
}
/**
* Note: Only overridden by Name subtype
*/
public void addAnnotation(AnnotationX annotationX) {
throw new RuntimeException("ResolvedType.addAnnotation() should never be called");
}
/**
* Note: Only overridden by Name subtype
*/
public AnnotationX[] getAnnotations() {
throw new RuntimeException("ResolvedType.getAnnotations() should never be called");
}
/**
* Note: Only overridden by ReferenceType subtype
*/
public boolean canAnnotationTargetType() {
return false;
}
/**
* Note: Only overridden by ReferenceType subtype
*/
public AnnotationTargetKind[] getAnnotationTargetKinds() {
return null;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isAnnotationWithRuntimeRetention() {
return false;
}
public boolean isSynthetic() {
return signature.indexOf("$ajc") != -1;
}
public final boolean isFinal() {
return Modifier.isFinal(getModifiers());
}
protected Map /*Type variable name -> UnresolvedType*/ getMemberParameterizationMap() {
if (!isParameterizedType()) return Collections.EMPTY_MAP;
TypeVariable[] tvs = getGenericType().getTypeVariables();
Map parameterizationMap = new HashMap();
for (int i = 0; i < tvs.length; i++) {
parameterizationMap.put(tvs[i].getName(), typeParameters[i]);
}
return parameterizationMap;
}
public Collection getDeclaredAdvice() {
List l = new ArrayList();
ResolvedMember[] methods = getDeclaredMethods();
if (isParameterizedType()) methods = getGenericType().getDeclaredMethods();
Map typeVariableMap = getMemberParameterizationMap();
for (int i=0, len = methods.length; i < len; i++) {
ShadowMunger munger = methods[i].getAssociatedShadowMunger();
if (munger != null) {
if (this.isParameterizedType()) {
//munger.setPointcut(munger.getPointcut().parameterizeWith(typeVariableMap));
munger = munger.parameterizeWith(this,typeVariableMap);
if (munger instanceof Advice) {
Advice advice = (Advice) munger;
// update to use the parameterized signature...
UnresolvedType[] ptypes = methods[i].getGenericParameterTypes() ;
UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length];
for (int j = 0; j < ptypes.length; j++) {
if (ptypes[j] instanceof TypeVariableReferenceType) {
TypeVariableReferenceType tvrt = (TypeVariableReferenceType) ptypes[j];
if (typeVariableMap.containsKey(tvrt.getTypeVariable().getName())) {
newPTypes[j] = (UnresolvedType) typeVariableMap.get(tvrt.getTypeVariable().getName());
} else {
newPTypes[j] = ptypes[j];
}
} else {
newPTypes[j] = ptypes[j];
}
}
advice.setBindingParameterTypes(newPTypes);
}
}
munger.setDeclaringType(this);
l.add(munger);
}
}
return l;
}
public Collection getDeclaredShadowMungers() {
Collection c = getDeclaredAdvice();
return c;
}
// ---- only for testing!
public ResolvedMember[] getDeclaredJavaFields() {
return filterInJavaVisible(getDeclaredFields());
}
public ResolvedMember[] getDeclaredJavaMethods() {
return filterInJavaVisible(getDeclaredMethods());
}
public ShadowMunger[] getDeclaredShadowMungersArray() {
List l = (List) getDeclaredShadowMungers();
return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]);
}
private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) {
List l = new ArrayList();
for (int i=0, len = ms.length; i < len; i++) {
if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) {
l.add(ms[i]);
}
}
return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]);
}
public abstract ISourceContext getSourceContext();
// ---- fields
public static final ResolvedType[] NONE = new ResolvedType[0];
public static final Primitive BYTE = new Primitive("B", 1, 0);
public static final Primitive CHAR = new Primitive("C", 1, 1);
public static final Primitive DOUBLE = new Primitive("D", 2, 2);
public static final Primitive FLOAT = new Primitive("F", 1, 3);
public static final Primitive INT = new Primitive("I", 1, 4);
public static final Primitive LONG = new Primitive("J", 2, 5);
public static final Primitive SHORT = new Primitive("S", 1, 6);
public static final Primitive VOID = new Primitive("V", 0, 8);
public static final Primitive BOOLEAN = new Primitive("Z", 1, 7);
public static final Missing MISSING = new Missing();
// ---- types
public static ResolvedType makeArray(ResolvedType type, int dim) {
if (dim == 0) return type;
ResolvedType array = new Array("[" + type.getSignature(),"["+type.getErasureSignature(),type.getWorld(),type);
return makeArray(array,dim-1);
}
static class Array extends ResolvedType {
ResolvedType componentType;
// Sometimes the erasure is different, eg. [TT; and [Ljava/lang/Object;
Array(String sig, String erasureSig,World world, ResolvedType componentType) {
super(sig,erasureSig, world);
this.componentType = componentType;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
// ??? should this return clone? Probably not...
// If it ever does, here is the code:
// ResolvedMember cloneMethod =
// new ResolvedMember(Member.METHOD,this,Modifier.PUBLIC,UnresolvedType.OBJECT,"clone",new UnresolvedType[]{});
// return new ResolvedMember[]{cloneMethod};
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return
new ResolvedType[] {
world.getCoreType(CLONEABLE),
world.getCoreType(SERIALIZABLE)
};
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final ResolvedType getSuperclass() {
return world.getCoreType(OBJECT);
}
public final boolean isAssignableFrom(ResolvedType o) {
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitiveType()) {
return o.equals(this);
} else {
return getComponentType().resolve(world).isAssignableFrom(o.getComponentType().resolve(world));
}
}
public boolean isAssignableFrom(ResolvedType o, boolean allowMissing) {
return isAssignableFrom(o);
}
public final boolean isCoerceableFrom(ResolvedType o) {
if (o.equals(UnresolvedType.OBJECT) ||
o.equals(UnresolvedType.SERIALIZABLE) ||
o.equals(UnresolvedType.CLONEABLE)) {
return true;
}
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitiveType()) {
return o.equals(this);
} else {
return getComponentType().resolve(world).isCoerceableFrom(o.getComponentType().resolve(world));
}
}
public final int getModifiers() {
int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
return (componentType.getModifiers() & mask) | Modifier.FINAL;
}
public UnresolvedType getComponentType() {
return componentType;
}
public ResolvedType getResolvedComponentType() {
return componentType;
}
public ISourceContext getSourceContext() {
return getResolvedComponentType().getSourceContext();
}
}
static class Primitive extends ResolvedType {
private int size;
private int index;
Primitive(String signature, int size, int index) {
super(signature, null);
this.size = size;
this.index = index;
this.typeKind=TypeKind.PRIMITIVE;
}
public final int getSize() {
return size;
}
public final int getModifiers() {
return Modifier.PUBLIC | Modifier.FINAL;
}
public final boolean isPrimitiveType() {
return true;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final boolean isAssignableFrom(ResolvedType other) {
if (!other.isPrimitiveType()) {
if (!world.isInJava5Mode()) return false;
return validBoxing.contains(this.getSignature()+other.getSignature());
}
return assignTable[((Primitive)other).index][index];
}
public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) {
return isAssignableFrom(other);
}
public final boolean isCoerceableFrom(ResolvedType other) {
if (this == other) return true;
if (! other.isPrimitiveType()) return false;
if (index > 6 || ((Primitive)other).index > 6) return false;
return true;
}
public ResolvedType resolve(World world) {
this.world = world;
return super.resolve(world);
}
public final boolean needsNoConversionFrom(ResolvedType other) {
if (! other.isPrimitiveType()) return false;
return noConvertTable[((Primitive)other).index][index];
}
private static final boolean[][] assignTable =
{// to: B C D F I J S V Z from
{ true , true , true , true , true , true , true , false, false }, // B
{ false, true , true , true , true , true , false, false, false }, // C
{ false, false, true , false, false, false, false, false, false }, // D
{ false, false, true , true , false, false, false, false, false }, // F
{ false, false, true , true , true , true , false, false, false }, // I
{ false, false, true , true , false, true , false, false, false }, // J
{ false, false, true , true , true , true , true , false, false }, // S
{ false, false, false, false, false, false, false, true , false }, // V
{ false, false, false, false, false, false, false, false, true }, // Z
};
private static final boolean[][] noConvertTable =
{// to: B C D F I J S V Z from
{ true , true , false, false, true , false, true , false, false }, // B
{ false, true , false, false, true , false, false, false, false }, // C
{ false, false, true , false, false, false, false, false, false }, // D
{ false, false, false, true , false, false, false, false, false }, // F
{ false, false, false, false, true , false, false, false, false }, // I
{ false, false, false, false, false, true , false, false, false }, // J
{ false, false, false, false, true , false, true , false, false }, // S
{ false, false, false, false, false, false, false, true , false }, // V
{ false, false, false, false, false, false, false, false, true }, // Z
};
// ----
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return ResolvedType.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedType getSuperclass() {
return null;
}
public ISourceContext getSourceContext() {
return null;
}
}
static class Missing extends ResolvedType {
Missing() {
super(MISSING_NAME, null);
}
// public final String toString() {
// return "<missing>";
// }
public final String getName() {
return MISSING_NAME;
}
public final boolean isMissing() {
return true;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return ResolvedType.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedType getSuperclass() {
return null;
}
public final int getModifiers() {
return 0;
}
public final boolean isAssignableFrom(ResolvedType other) {
return false;
}
public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) {
return false;
}
public final boolean isCoerceableFrom(ResolvedType other) {
return false;
}
public boolean needsNoConversionFrom(ResolvedType other) {
return false;
}
public ISourceContext getSourceContext() {
return null;
}
}
/**
* Look up a member, takes into account any ITDs on this type.
* return null if not found
*/
public ResolvedMember lookupMemberNoSupers(Member member) {
ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member);
if (ret == null && interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
if (matches(tm.getSignature(), member)) {
return tm.getSignature();
}
}
}
return ret;
}
public ResolvedMember lookupMemberWithSupersAndITDs(Member member) {
ResolvedMember ret = lookupMemberNoSupers(member);
if (ret != null) return ret;
ResolvedType supert = getSuperclass();
if (supert != null) {
ret = supert.lookupMemberNoSupers(member);
}
return ret;
}
/**
* as lookupMemberNoSupers, but does not include ITDs
*
* @param member
* @return
*/
public ResolvedMember lookupDirectlyDeclaredMemberNoSupers(Member member) {
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = lookupMember(member, getDeclaredFields());
} else {
// assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR
ret = lookupMember(member, getDeclaredMethods());
}
return ret;
}
/**
* This lookup has specialized behaviour - a null result tells the
* EclipseTypeMunger that it should make a default implementation of a
* method on this type.
*
* @param member
* @return
*/
public ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member) {
return lookupMemberIncludingITDsOnInterfaces(member, this);
}
private ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member, ResolvedType onType) {
ResolvedMember ret = onType.lookupMemberNoSupers(member);
if (ret != null) {
return ret;
} else {
ResolvedType superType = onType.getSuperclass();
if (superType != null) {
ret = lookupMemberIncludingITDsOnInterfaces(member,superType);
}
if (ret == null) {
// try interfaces then, but only ITDs now...
ResolvedType[] superInterfaces = onType.getDeclaredInterfaces();
for (int i = 0; i < superInterfaces.length; i++) {
ret = superInterfaces[i].lookupMethodInITDs(member);
if (ret != null) return ret;
}
}
}
return ret;
}
protected List interTypeMungers = new ArrayList(0);
public List getInterTypeMungers() {
return interTypeMungers;
}
public List getInterTypeParentMungers() {
List l = new ArrayList();
for (Iterator iter = interTypeMungers.iterator(); iter.hasNext();) {
ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next();
if (element.getMunger() instanceof NewParentTypeMunger) l.add(element);
}
return l;
}
/**
* ??? This method is O(N*M) where N = number of methods and M is number of
* inter-type declarations in my super
*/
public List getInterTypeMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeMungers(ret);
return ret;
}
public List getInterTypeParentMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeParentMungers(ret);
return ret;
}
private void collectInterTypeParentMungers(List collector) {
for (Iterator iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedType superType = (ResolvedType) iter.next();
superType.collectInterTypeParentMungers(collector);
}
collector.addAll(getInterTypeParentMungers());
}
protected void collectInterTypeMungers(List collector) {
for (Iterator iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedType superType = (ResolvedType) iter.next();
superType.collectInterTypeMungers(collector);
}
outer:
for (Iterator iter1 = collector.iterator(); iter1.hasNext();) {
ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next();
if ( superMunger.getSignature() == null) continue;
if ( !superMunger.getSignature().isAbstract()) continue;
for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) {
ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next();
if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
if (!superMunger.getSignature().isPublic()) continue;
for (Iterator iter = getMethods(); iter.hasNext(); ) {
ResolvedMember method = (ResolvedMember)iter.next();
if (conflictingSignature(method, superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
}
collector.addAll(getInterTypeMungers());
}
/**
* Check:
* 1) That we don't have any abstract type mungers unless this type is abstract.
* 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794)
*/
public void checkInterTypeMungers() {
if (isAbstract()) return;
boolean itdProblem = false;
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next();
itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2
}
if (itdProblem) return; // If the rules above are broken, return right now
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next();
if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1
if (munger.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate) {
;//ignore for @AJ ITD as munger.getSignature() is the interface method hence abstract
} else {
world.getMessageHandler().handleMessage(
new Message("must implement abstract inter-type declaration: " + munger.getSignature(),
"", IMessage.ERROR, getSourceLocation(), null,
new ISourceLocation[] { getMungerLocation(munger) }));
}
}
}
}
/**
* See PR70794. This method checks that if an abstract inter-type method declaration is made on
* an interface then it must also be public.
* This is a compiler limitation that could be made to work in the future (if someone
* provides a worthwhile usecase)
*
* @return indicates if the munger failed the check
*/
private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) {
if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) {
ResolvedMember itdMember = munger.getSignature();
ResolvedType onType = itdMember.getDeclaringType().resolve(world);
if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) {
world.getMessageHandler().handleMessage(
new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"",
Message.ERROR,getSourceLocation(),null,
new ISourceLocation[]{getMungerLocation(munger)})
);
return true;
}
}
return false;
}
/**
* Get a source location for the munger.
* Until intertype mungers remember where they came from, the source location
* for the munger itself is null. In these cases use the
* source location for the aspect containing the ITD.
*/
private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) {
ISourceLocation sloc = munger.getSourceLocation();
if (sloc == null) {
sloc = munger.getAspectType().getSourceLocation();
}
return sloc;
}
/**
* Returns a ResolvedType object representing the declaring type of this type, or
* null if this type does not represent a non-package-level-type.
* <p/>
* <strong>Warning</strong>: This is guaranteed to work for all member types.
* For anonymous/local types, the only guarantee is given in JLS 13.1, where
* it guarantees that if you call getDeclaringType() repeatedly, you will eventually
* get the top-level class, but it does not say anything about classes in between.
*
* @return the declaring UnresolvedType object, or null.
*/
public ResolvedType getDeclaringType() {
if (isArray()) return null;
String name = getName();
int lastDollar = name.lastIndexOf('$');
while (lastDollar != -1) {
ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true);
if (ret != ResolvedType.MISSING) return ret;
lastDollar = name.lastIndexOf('$', lastDollar-1);
}
return null;
}
public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) {
//System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType);
if (Modifier.isPublic(modifiers)) {
return true;
} else if (Modifier.isPrivate(modifiers)) {
return targetType.getOutermostType().equals(fromType.getOutermostType());
} else if (Modifier.isProtected(modifiers)) {
return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType);
} else { // package-visible
return samePackage(targetType, fromType);
}
}
public static boolean hasBridgeModifier(int modifiers) {
return (modifiers & Constants.ACC_BRIDGE)!=0;
}
private static boolean samePackage(
ResolvedType targetType,
ResolvedType fromType) {
String p1 = targetType.getPackageName();
String p2 = fromType.getPackageName();
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
/**
* Checks if the generic type for 'this' and the generic type for 'other' are the same -
* it can be passed raw or parameterized versions and will just compare the underlying
* generic type.
*/
private boolean genericTypeEquals(ResolvedType other) {
ResolvedType rt = other;
if (rt.isParameterizedType() || rt.isRawType()) rt.getGenericType();
if (( (isParameterizedType() || isRawType()) && getGenericType().equals(rt)) ||
(this.equals(other))) return true;
return false;
}
/**
* Look up the actual occurence of a particular type in the hierarchy for
* 'this' type. The input is going to be a generic type, and the caller
* wants to know if it was used in its RAW or a PARAMETERIZED form in this
* hierarchy.
*
* returns null if it can't be found.
*/
public ResolvedType discoverActualOccurrenceOfTypeInHierarchy(ResolvedType lookingFor) {
if (!lookingFor.isGenericType())
throw new BCException("assertion failed: method should only be called with generic type, but "+lookingFor+" is "+lookingFor.typeKind);
if (this.equals(ResolvedType.OBJECT)) return null;
if (genericTypeEquals(lookingFor)) return this;
ResolvedType superT = getSuperclass();
if (superT.genericTypeEquals(lookingFor)) return superT;
ResolvedType[] superIs = getDeclaredInterfaces();
for (int i = 0; i < superIs.length; i++) {
ResolvedType superI = superIs[i];
if (superI.genericTypeEquals(lookingFor)) return superI;
ResolvedType checkTheSuperI = superI.discoverActualOccurrenceOfTypeInHierarchy(lookingFor);
if (checkTheSuperI!=null) return checkTheSuperI;
}
return superT.discoverActualOccurrenceOfTypeInHierarchy(lookingFor);
}
/**
* Called for all type mungers but only does something if they share type variables
* with a generic type which they target. When this happens this routine will check
* for the target type in the target hierarchy and 'bind' any type parameters as
* appropriate. For example, for the ITD "List<T> I<T>.x" against a type like this:
* "class A implements I<String>" this routine will return a parameterized form of
* the ITD "List<String> I.x"
*/
public ConcreteTypeMunger fillInAnyTypeParameters(ConcreteTypeMunger munger) {
boolean debug = false;
ResolvedMember member = munger.getSignature();
if (munger.isTargetTypeParameterized()) {
if (debug) System.err.println("Processing attempted parameterization of "+munger+" targetting type "+this);
if (debug) System.err.println(" This type is "+this+" ("+typeKind+")");
// need to tailor this munger instance for the particular target...
if (debug) System.err.println(" Signature that needs parameterizing: "+member);
// Retrieve the generic type
ResolvedType onType = world.resolve(member.getDeclaringType()).getGenericType();
member.resolve(world); // Ensure all parts of the member are resolved
if (debug) System.err.println(" Actual target ontype: "+onType+" ("+onType.typeKind+")");
// quickly find the targettype in the type hierarchy for this type (it will be either RAW or PARAMETERIZED)
ResolvedType actualTarget = discoverActualOccurrenceOfTypeInHierarchy(onType);
if (actualTarget==null)
throw new BCException("assertion failed: asked "+this+" for occurrence of "+onType+" in its hierarchy??");
// only bind the tvars if its a parameterized type or the raw type (in which case they collapse to bounds) - don't do it for generic types ;)
if (!actualTarget.isGenericType()) {
if (debug) System.err.println("Occurrence in "+this+" is actually "+actualTarget+" ("+actualTarget.typeKind+")");
// parameterize the signature
// ResolvedMember newOne = member.parameterizedWith(actualTarget.getTypeParameters(),onType,actualTarget.isParameterizedType());
}
//if (!actualTarget.isRawType())
munger = munger.parameterizedFor(actualTarget);
if (debug) System.err.println("New sig: "+munger.getSignature());
if (debug) System.err.println("=====================================");
}
return munger;
}
public void addInterTypeMunger(ConcreteTypeMunger munger) {
ResolvedMember sig = munger.getSignature();
if (sig == null || munger.getMunger() == null ||
munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess)
{
interTypeMungers.add(munger);
return;
}
ConcreteTypeMunger originalMunger = munger;
// we will use the 'parameterized' ITD for all the comparisons but we say the original
// one passed in actually matched as it will be added to the intertype member finder
// for the target type. It is possible we only want to do this if a generic type
// is discovered and the tvar is collapsed to a bound?
munger = fillInAnyTypeParameters(munger);
sig = munger.getSignature(); // possibly changed when type parms filled in
//System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers);
if (sig.getKind() == Member.METHOD) {
if (!compareToExistingMembers(munger, getMethodsWithoutIterator(false,true) /*getMethods()*/)) return;
if (this.isInterface()) {
if (!compareToExistingMembers(munger,
Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return;
}
} else if (sig.getKind() == Member.FIELD) {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return;
} else {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return;
}
// now compare to existingMungers
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next();
if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) {
//System.err.println("match " + munger + " with " + existingMunger);
if (isVisible(munger.getSignature().getModifiers(),
munger.getAspectType(), existingMunger.getAspectType()))
{
//System.err.println(" is visible");
int c = compareMemberPrecedence(sig, existingMunger.getSignature());
if (c == 0) {
c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType());
}
//System.err.println(" compare: " + c);
if (c < 0) {
// the existing munger dominates the new munger
checkLegalOverride(munger.getSignature(), existingMunger.getSignature());
return;
} else if (c > 0) {
// the new munger dominates the existing one
checkLegalOverride(existingMunger.getSignature(), munger.getSignature());
i.remove();
break;
} else {
interTypeConflictError(munger, existingMunger);
interTypeConflictError(existingMunger, munger);
return;
}
}
}
}
//System.err.println("adding: " + munger + " to " + this);
// we are adding the parameterized form of the ITD to the list of
// mungers. Within it, the munger knows the original declared
// signature for the ITD so it can be retrieved.
interTypeMungers.add(munger);
}
private boolean compareToExistingMembers(ConcreteTypeMunger munger, List existingMembersList) {
return compareToExistingMembers(munger,existingMembersList.iterator());
}
//??? returning too soon
private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) {
ResolvedMember sig = munger.getSignature();
while (existingMembers.hasNext()) {
ResolvedMember existingMember = (ResolvedMember)existingMembers.next();
// don't worry about clashing with bridge methods
if (existingMember.isBridgeMethod()) continue;
//System.err.println("Comparing munger: "+sig+" with member "+existingMember);
if (conflictingSignature(existingMember, munger.getSignature())) {
//System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger);
//System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation());
if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) {
int c = compareMemberPrecedence(sig, existingMember);
//System.err.println(" c: " + c);
if (c < 0) {
// existingMember dominates munger
checkLegalOverride(munger.getSignature(), existingMember);
return false;
} else if (c > 0) {
// munger dominates existingMember
checkLegalOverride(existingMember, munger.getSignature());
//interTypeMungers.add(munger);
//??? might need list of these overridden abstracts
continue;
} else {
// bridge methods can differ solely in return type.
// FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it
// could do with a rewrite !
boolean sameReturnTypes = (existingMember.getReturnType().equals(sig.getReturnType()));
if (sameReturnTypes)
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(),
existingMember),
munger.getSourceLocation())
);
}
} else if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) {
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(),
existingMember),
munger.getSourceLocation())
);
;
}
//return;
}
}
return true;
}
// we know that the member signature matches, but that the member in the target type is not visible to the aspect.
// this may still be disallowed if it would result in two members within the same declaring type with the same
// signature AND more than one of them is concrete AND they are both visible within the target type.
private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType,ResolvedMember itdMember) {
if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false;
UnresolvedType declaringType = existingMember.getDeclaringType();
if (!targetType.equals(declaringType)) return false;
// now have to test that itdMember is visible from targetType
if (itdMember.isPrivate()) return false;
if (itdMember.isPublic()) return true;
// must be in same package to be visible then...
if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) return false;
// trying to put two members with the same signature into the exact same type..., and both visible in that type.
return true;
}
/**
* @return true if the override is legal
* note: calling showMessage with two locations issues TWO messages, not ONE message
* with an additional source location.
*/
public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) {
//System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType());
if (Modifier.isFinal(parent.getModifiers())) {
world.showMessage(Message.ERROR,
WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER,parent),
child.getSourceLocation(),null);
return false;
}
boolean incompatibleReturnTypes = false;
// In 1.5 mode, allow for covariance on return type
if (world.isInJava5Mode() && parent.getKind()==Member.METHOD) {
// Look at the generic types when doing this comparison
ResolvedType rtParentReturnType = parent.getGenericReturnType().resolve(world);
ResolvedType rtChildReturnType = child.getGenericReturnType().resolve(world);
incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType);
if (incompatibleReturnTypes) {
incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType);
}
} else {
incompatibleReturnTypes =!parent.getReturnType().equals(child.getReturnType());
}
if (incompatibleReturnTypes) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
if (parent.getKind() == Member.POINTCUT) {
UnresolvedType[] pTypes = parent.getParameterTypes();
UnresolvedType[] cTypes = child.getParameterTypes();
if (!Arrays.equals(pTypes, cTypes)) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
}
//System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers());
if (isMoreVisible(parent.getModifiers(), child.getModifiers())) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
// check declared exceptions
ResolvedType[] childExceptions = world.resolve(child.getExceptions());
ResolvedType[] parentExceptions = world.resolve(parent.getExceptions());
ResolvedType runtimeException = world.resolve("java.lang.RuntimeException");
ResolvedType error = world.resolve("java.lang.Error");
outer:
for (int i = 0, leni = childExceptions.length; i < leni; i++) {
//System.err.println("checking: " + childExceptions[i]);
if (runtimeException.isAssignableFrom(childExceptions[i])) continue;
if (error.isAssignableFrom(childExceptions[i])) continue;
for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) {
if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer;
}
// this message is now better handled my MethodVerifier in JDT core.
// world.showMessage(IMessage.ERROR,
// WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()),
// child.getSourceLocation(), null);
return false;
}
if (parent.isStatic() && !child.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent),
child.getSourceLocation(),null);
return false;
} else if (child.isStatic() && !parent.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent),
child.getSourceLocation(),null);
return false;
}
return true;
}
private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) {
//if (!m1.getReturnType().equals(m2.getReturnType())) return 0;
// need to allow for the special case of 'clone' - which is like abstract but is
// not marked abstract. The code below this next line seems to make assumptions
// about what will have gotten through the compiler based on the normal
// java rules. clone goes against these...
if (m2.isProtected() && m2.isNative() && m2.getName().equals("clone")) return +1;
if (Modifier.isAbstract(m1.getModifiers())) return -1;
if (Modifier.isAbstract(m2.getModifiers())) return +1;
if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0;
ResolvedType t1 = m1.getDeclaringType().resolve(world);
ResolvedType t2 = m2.getDeclaringType().resolve(world);
if (t1.isAssignableFrom(t2)) {
return -1;
}
if (t2.isAssignableFrom(t1)) {
return +1;
}
return 0;
}
public static boolean isMoreVisible(int m1, int m2) {
if (Modifier.isPrivate(m1)) return false;
if (isPackage(m1)) return Modifier.isPrivate(m2);
if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2));
if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2);
throw new RuntimeException("bad modifier: " + m1);
}
private static boolean isPackage(int i) {
return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED)));
}
private void interTypeConflictError(
ConcreteTypeMunger m1,
ConcreteTypeMunger m2) {
//XXX this works only if we ignore separate compilation issues
//XXX dual errors possible if (this instanceof BcelObjectType) return;
//System.err.println("conflict at " + m2.getSourceLocation());
getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_CONFLICT,m1.getAspectType().getName(),
m2.getSignature(),m2.getAspectType().getName()),
m2.getSourceLocation(), getSourceLocation());
}
public ResolvedMember lookupSyntheticMember(Member member) {
//??? horribly inefficient
//for (Iterator i =
//System.err.println("lookup " + member + " in " + interTypeMungers);
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
ResolvedMember ret = m.getMatchingSyntheticMember(member);
if (ret != null) {
//System.err.println(" found: " + ret);
return ret;
}
}
// if (this.getSuperclass() != ResolvedType.OBJECT && this.getSuperclass() != null) {
// return getSuperclass().lookupSyntheticMember(member);
// }
return null;
}
public void clearInterTypeMungers() {
if (isRawType()) getGenericType().clearInterTypeMungers();
interTypeMungers = new ArrayList();
}
public boolean isTopmostImplementor(ResolvedType interfaceType) {
if (isInterface()) return false;
if (!interfaceType.isAssignableFrom(this,true)) return false;
// check that I'm truly the topmost implementor
if (this.getSuperclass().isMissing()) return true; // we don't know anything about supertype, and it can't be exposed to weaver
if (interfaceType.isAssignableFrom(this.getSuperclass(),true)) {
return false;
}
return true;
}
public ResolvedType getTopmostImplementor(ResolvedType interfaceType) {
if (isInterface()) return null;
if (!interfaceType.isAssignableFrom(this)) return null;
// Check if my super class is an implementor?
ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType);
if (higherType!=null) return higherType;
return this;
}
private ResolvedType findHigher(ResolvedType other) {
if (this == other) return this;
for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) {
ResolvedType rtx = (ResolvedType)i.next();
boolean b = this.isAssignableFrom(rtx);
if (b) return rtx;
}
return null;
}
public List getExposedPointcuts() {
List ret = new ArrayList();
if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts());
for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) {
ResolvedType t = (ResolvedType)i.next();
addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false);
}
addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true);
for (Iterator i = ret.iterator(); i.hasNext(); ) {
ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next();
// System.err.println("looking at: " + inherited + " in " + this);
// System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract());
if (inherited.isAbstract()) {
if (!this.isAbstract()) {
getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()),
inherited.getSourceLocation(), this.getSourceLocation());
}
}
}
return ret;
}
private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) {
for (Iterator i = added.iterator(); i.hasNext();) {
ResolvedPointcutDefinition toAdd =
(ResolvedPointcutDefinition) i.next();
//System.err.println("adding: " + toAdd);
for (Iterator j = acc.iterator(); j.hasNext();) {
ResolvedPointcutDefinition existing =
(ResolvedPointcutDefinition) j.next();
if (existing == toAdd) continue;
if (!isVisible(existing.getModifiers(),
existing.getDeclaringType().resolve(getWorld()),
this)) {
continue;
}
if (conflictingSignature(existing, toAdd)) {
if (isOverriding) {
checkLegalOverride(existing, toAdd);
j.remove();
} else {
getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()),
existing.getSourceLocation(),
toAdd.getSourceLocation());
j.remove();
}
}
}
acc.add(toAdd);
}
}
public ISourceLocation getSourceLocation() {
return null;
}
public boolean isExposedToWeaver() {
return false;
}
public WeaverStateInfo getWeaverState() {
return null;
}
/**
* Overridden by ReferenceType to return a sensible answer for parameterized and raw types.
*
* @return
*/
public ResolvedType getGenericType() {
if (!(isParameterizedType() || isRawType()))
throw new BCException("The type "+getBaseName()+" is not parameterized or raw - it has no generic type");
return null;
}
public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) {
if (!(isGenericType() || isParameterizedType())) return this;
return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld());
}
/**
* Iff I am a parameterized type, and any of my parameters are type variable
* references, return a version with those type parameters replaced in accordance
* with the passed bindings.
*/
public UnresolvedType parameterize(Map typeBindings) {
if (!isParameterizedType()) throw new IllegalStateException("Can't parameterize a type that is not a parameterized type");
boolean workToDo = false;
for (int i = 0; i < typeParameters.length; i++) {
if (typeParameters[i].isTypeVariableReference()) {
workToDo = true;
}
}
if (!workToDo) {
return this;
} else {
UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length];
for (int i = 0; i < newTypeParams.length; i++) {
newTypeParams[i] = typeParameters[i];
if (newTypeParams[i].isTypeVariableReference()) {
TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i];
UnresolvedType binding = (UnresolvedType) typeBindings.get(tvrt.getTypeVariable().getName());
if (binding != null) newTypeParams[i] = binding;
}
}
return TypeFactory.createParameterizedType(getGenericType(), newTypeParams, getWorld());
}
}
public boolean hasParameterizedSuperType() {
getParameterizedSuperTypes();
return parameterizedSuperTypes.length > 0;
}
public boolean hasGenericSuperType() {
ResolvedType[] superTypes = getDeclaredInterfaces();
for (int i = 0; i < superTypes.length; i++) {
if (superTypes[i].isGenericType()) return true;
}
return false;
}
private ResolvedType[] parameterizedSuperTypes = null;
/**
* Similar to the above method, but accumulates the super types
*
* @return
*/
public ResolvedType[] getParameterizedSuperTypes() {
if (parameterizedSuperTypes != null) return parameterizedSuperTypes;
List accumulatedTypes = new ArrayList();
accumulateParameterizedSuperTypes(this,accumulatedTypes);
ResolvedType[] ret = new ResolvedType[accumulatedTypes.size()];
parameterizedSuperTypes = (ResolvedType[]) accumulatedTypes.toArray(ret);
return parameterizedSuperTypes;
}
private void accumulateParameterizedSuperTypes(ResolvedType forType, List parameterizedTypeList) {
if (forType.isParameterizedType()) {
parameterizedTypeList.add(forType);
}
if (forType.getSuperclass() != null) {
accumulateParameterizedSuperTypes(forType.getSuperclass(), parameterizedTypeList);
}
ResolvedType[] interfaces = forType.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
accumulateParameterizedSuperTypes(interfaces[i], parameterizedTypeList);
}
}
/**
* Types may have pointcuts just as they have methods and fields.
*/
public ResolvedPointcutDefinition findPointcut(String name, World world) {
throw new UnsupportedOperationException("Not yet implemenented");
}
/**
* Determines if variables of this type could be assigned values of another
* with lots of help.
* java.lang.Object is convertable from all types.
* A primitive type is convertable from X iff it's assignable from X.
* A reference type is convertable from X iff it's coerceable from X.
* In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y
* could be assignable to a variable of type X without loss of precision.
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other with possible conversion
*/
public final boolean isConvertableFrom(ResolvedType other) {
// // version from TypeX
// if (this.equals(OBJECT)) return true;
// if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other);
// return this.isCoerceableFrom(other);
//
// version from ResolvedTypeX
if (this.equals(OBJECT)) return true;
if (world.isInJava5Mode()) {
if (this.isPrimitiveType()^other.isPrimitiveType()) { // If one is primitive and the other isnt
if (validBoxing.contains(this.getSignature()+other.getSignature())) return true;
}
}
if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other);
return this.isCoerceableFrom(other);
}
/**
* Determines if the variables of this type could be assigned values
* of another type without casting. This still allows for assignment conversion
* as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER).
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other without casting
* @throws NullPointerException if other is null
*/
public abstract boolean isAssignableFrom(ResolvedType other);
public abstract boolean isAssignableFrom(ResolvedType other, boolean allowMissing);
/**
* Determines if values of another type could possibly be cast to
* this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion".
* <p/>
* <p> This method should be commutative, i.e., for all UnresolvedType a, b and all World w:
* <p/>
* <blockquote><pre>
* a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w)
* </pre></blockquote>
*
* @param other the other type
* @param world the {@link World} in which the possible coersion should be checked.
* @return true iff values of other could possibly be cast to this type.
* @throws NullPointerException if other is null.
*/
public abstract boolean isCoerceableFrom(ResolvedType other);
public boolean needsNoConversionFrom(ResolvedType o) {
return isAssignableFrom(o);
}
/**
* Implemented by ReferenceTypes
*/
public String getSignatureForAttribute() {
throw new RuntimeException("Cannot ask this type "+this+" for a generic sig attribute");
}
private FuzzyBoolean parameterizedWithAMemberTypeVariable = FuzzyBoolean.MAYBE;
/**
* return true if the parameterization of this type includes a member type variable. Member
* type variables occur in generic methods/ctors.
*/
public boolean isParameterizedWithAMemberTypeVariable() {
// MAYBE means we haven't worked it out yet...
if (parameterizedWithAMemberTypeVariable==FuzzyBoolean.MAYBE) {
// if there are no type parameters then we cant be...
if (typeParameters==null || typeParameters.length==0) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.NO;
return false;
}
for (int i = 0; i < typeParameters.length; i++) {
UnresolvedType aType = (ResolvedType)typeParameters[i];
if (aType.isTypeVariableReference() &&
// assume the worst - if its definetly not a type declared one, it could be anything
((TypeVariableReference)aType).getTypeVariable().getDeclaringElementKind()!=TypeVariable.TYPE) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
if (aType.isParameterizedType()) {
boolean b = aType.isParameterizedWithAMemberTypeVariable();
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
}
if (aType.isGenericWildcard()) {
if (aType.isExtends()) {
boolean b = false;
UnresolvedType upperBound = aType.getUpperBound();
if (upperBound.isParameterizedType()) {
b = upperBound.isParameterizedWithAMemberTypeVariable();
} else if (upperBound.isTypeVariableReference() && ((TypeVariableReference)upperBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) {
b = true;
}
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
// FIXME asc need to check additional interface bounds
}
if (aType.isSuper()) {
boolean b = false;
UnresolvedType lowerBound = aType.getLowerBound();
if (lowerBound.isParameterizedType()) {
b = lowerBound.isParameterizedWithAMemberTypeVariable();
} else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference)lowerBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) {
b = true;
}
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
}
}
}
parameterizedWithAMemberTypeVariable=FuzzyBoolean.NO;
}
return parameterizedWithAMemberTypeVariable.alwaysTrue();
}
}
|
114,495
|
Bug 114495 unqualified superaspect<T> pointcut sortafunny in subaspect
| null |
resolved fixed
|
86880f7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-23T19:21:03Z
| 2005-11-01T10:13:20Z
|
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
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.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.patterns.ExactTypePattern;
import org.aspectj.weaver.patterns.ExposedState;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* Advice implemented for bcel.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class BcelAdvice extends Advice {
private Test pointcutTest;
private ExposedState exposedState;
private boolean hasMatchedAtLeastOnce = false;
public BcelAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature,
ResolvedType concreteAspect)
{
super(attribute, pointcut, signature);
this.concreteAspect = concreteAspect;
}
// !!! must only be used for testing
public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature,
int extraArgumentFlags,
int start, int end, ISourceContext sourceContext, ResolvedType concreteAspect)
{
this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext),
pointcut, signature, concreteAspect);
thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests
}
// ---- implementations of ShadowMunger's methods
public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) {
suppressLintWarnings(world);
ShadowMunger ret = super.concretize(fromType, world, clause);
clearLintSuppressions(world);
return ret;
}
public ShadowMunger parameterizeWith(ResolvedType declaringType,Map typeVariableMap) {
Pointcut pc = getPointcut().parameterizeWith(typeVariableMap);
BcelAdvice ret = null;
Member adviceSignature = signature;
// allows for around advice where the return value is a type variable (see pr115250)
if (signature instanceof ResolvedMember) {
adviceSignature = ((ResolvedMember)signature).parameterizedWith(declaringType.getTypeParameters(),declaringType,declaringType.isParameterizedType());
}
ret = new BcelAdvice(this.attribute,pc,adviceSignature,this.concreteAspect);
return ret;
}
public boolean match(Shadow shadow, World world) {
suppressLintWarnings(world);
boolean ret = super.match(shadow, world);
clearLintSuppressions(world);
return ret;
}
public void specializeOn(Shadow shadow) {
if (getKind() == AdviceKind.Around) {
((BcelShadow)shadow).initializeForAroundClosure();
}
//XXX this case is just here for supporting lazy test code
if (getKind() == null) {
exposedState = new ExposedState(0);
return;
}
if (getKind().isPerEntry()) {
exposedState = new ExposedState(0);
} else if (getKind().isCflow()) {
exposedState = new ExposedState(nFreeVars);
} else if (getSignature() != null) {
exposedState = new ExposedState(getSignature());
} else {
exposedState = new ExposedState(0);
return; //XXX this case is just here for supporting lazy test code
}
World world = shadow.getIWorld();
suppressLintWarnings(world);
pointcutTest = getPointcut().findResidue(shadow, exposedState);
clearLintSuppressions(world);
// these initializations won't be performed by findResidue, but need to be
// so that the joinpoint is primed for weaving
if (getKind() == AdviceKind.PerThisEntry) {
shadow.getThisVar();
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.getTargetVar();
}
// make sure thisJoinPoint parameters are initialized
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
boolean hasGuardTest = pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around;
boolean isAround = getKind() == AdviceKind.Around;
((BcelShadow)shadow).requireThisJoinPoint(hasGuardTest,isAround);
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
if (!hasGuardTest && world.getLint().multipleAdviceStoppingLazyTjp.isEnabled()) {
// collect up the problematic advice
((BcelShadow)shadow).addAdvicePreventingLazyTjp(this);
}
if (!isAround && !hasGuardTest && world.getLint().noGuardForLazyTjp.isEnabled()) {
// can't build tjp lazily, no suitable test...
world.getLint().noGuardForLazyTjp.signal(
new String[] {shadow.toString()},
getSourceLocation(),
new ISourceLocation[] { ((BcelShadow)shadow).getSourceLocation() }
);
}
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
}
private boolean canInline(Shadow s) {
if (attribute.isProceedInInners()) return false;
//XXX this guard seems to only be needed for bad test cases
if (concreteAspect == null || concreteAspect == ResolvedType.MISSING) return false;
if (concreteAspect.getWorld().isXnoInline()) return false;
//System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState());
return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven();
}
public void implementOn(Shadow s) {
hasMatchedAtLeastOnce=true;
BcelShadow shadow = (BcelShadow) s;
//FIXME AV - see #75442, this logic is not enough so for now comment it out until we fix the bug
// // callback for perObject AJC MightHaveAspect postMunge (#75442)
// if (getConcreteAspect() != null
// && getConcreteAspect().getPerClause() != null
// && PerClause.PEROBJECT.equals(getConcreteAspect().getPerClause().getKind())) {
// final PerObject clause;
// if (getConcreteAspect().getPerClause() instanceof PerFromSuper) {
// clause = (PerObject)((PerFromSuper) getConcreteAspect().getPerClause()).lookupConcretePerClause(getConcreteAspect());
// } else {
// clause = (PerObject) getConcreteAspect().getPerClause();
// }
// if (clause.isThis()) {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getThisVar().getType(), getConcreteAspect());
// } else {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getTargetVar().getType(), getConcreteAspect());
// }
// }
if (getKind() == AdviceKind.Before) {
shadow.weaveBefore(this);
} else if (getKind() == AdviceKind.AfterReturning) {
shadow.weaveAfterReturning(this);
} else if (getKind() == AdviceKind.AfterThrowing) {
UnresolvedType catchType =
hasExtraParameter()
? getExtraParameterType()
: UnresolvedType.THROWABLE;
shadow.weaveAfterThrowing(this, catchType);
} else if (getKind() == AdviceKind.After) {
shadow.weaveAfter(this);
} else if (getKind() == AdviceKind.Around) {
// Note: under regular LTW the aspect is usually loaded after the first use of any class affecteted by it
// This means that as long as the aspect has not been thru the LTW, it's woven state is unknown
// and thus canInline(s) will return false.
// To force inlining (test), ones can do Class aspect = FQNAspect.class in the clinit of the target class
// FIXME AV : for AJC compiled @AJ aspect (or any code style aspect), the woven state can never be known
// if the aspect belongs to a parent classloader. In that case the aspect will never be inlined.
// It might be dangerous to change that especially for @AJ aspect non compiled with AJC since if those
// are not weaved (f.e. use of some limiteed LTW etc) then they cannot be prepared for inlining.
// One solution would be to flag @AJ aspect with an annotation as "prepared" and query that one.
if (!canInline(s)) {
shadow.weaveAroundClosure(this, hasDynamicTests());
} else {
shadow.weaveAroundInline(this, hasDynamicTests());
}
} else if (getKind() == AdviceKind.InterInitializer) {
shadow.weaveAfterReturning(this);
} else if (getKind().isCflow()) {
shadow.weaveCflowEntry(this, getSignature());
} else if (getKind() == AdviceKind.PerThisEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar());
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar());
} else if (getKind() == AdviceKind.Softener) {
shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType());
} else if (getKind() == AdviceKind.PerTypeWithinEntry) {
// PTWIMPL Entry to ptw is the static initialization of a type that matched the ptw type pattern
shadow.weavePerTypeWithinAspectInitialization(this,shadow.getEnclosingType());
} else {
throw new BCException("unimplemented kind: " + getKind());
}
}
// ---- implementations
private Collection collectCheckedExceptions(UnresolvedType[] excs) {
if (excs == null || excs.length == 0) return Collections.EMPTY_LIST;
Collection ret = new ArrayList();
World world = concreteAspect.getWorld();
ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION);
ResolvedType error = world.getCoreType(UnresolvedType.ERROR);
for (int i=0, len=excs.length; i < len; i++) {
ResolvedType t = world.resolve(excs[i],true);
if (t == ResolvedType.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
"",IMessage.ERROR,getSourceLocation(),null,null);
world.getMessageHandler().handleMessage(msg);
}
if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) {
ret.add(t);
}
}
return ret;
}
private Collection thrownExceptions = null;
public Collection getThrownExceptions() {
if (thrownExceptions == null) {
//??? can we really lump in Around here, how does this interact with Throwable
if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness
(getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around))
{
World world = concreteAspect.getWorld();
ResolvedMember m = world.resolve(signature);
if (m == null) {
thrownExceptions = Collections.EMPTY_LIST;
} else {
thrownExceptions = collectCheckedExceptions(m.getExceptions());
}
} else {
thrownExceptions = Collections.EMPTY_LIST;
}
}
return thrownExceptions;
}
/**
* The munger must not check for the advice exceptions to be declared by the shadow in the case
* of @AJ aspects so that around can throws Throwable
*
* @return
*/
public boolean mustCheckExceptions() {
if (getConcreteAspect() == null) {
return true;
}
return !getConcreteAspect().isAnnotationStyleAspect();
}
// only call me after prepare has been called
public boolean hasDynamicTests() {
// if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
// UnresolvedType extraParameterType = getExtraParameterType();
// if (! extraParameterType.equals(UnresolvedType.OBJECT)
// && ! extraParameterType.isPrimitive())
// return true;
// }
return pointcutTest != null &&
!(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST);
}
/**
* get the instruction list for the really simple version of this advice.
* Is broken apart
* for other advice, but if you want it in one block, this is the method to call.
*
* @param s The shadow around which these instructions will eventually live.
* @param extraArgVar The var that will hold the return value or thrown exception
* for afterX advice
* @param ifNoAdvice The instructionHandle to jump to if the dynamic
* tests for this munger fails.
*/
InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice)
{
BcelShadow shadow = (BcelShadow) s;
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// we test to see if we have the right kind of thing...
// after throwing does this just by the exception mechanism.
if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
UnresolvedType extraParameterType = getExtraParameterType();
if (! extraParameterType.equals(UnresolvedType.OBJECT)
&& ! extraParameterType.isPrimitiveType()) {
il.append(
BcelRenderer.renderTest(
fact,
world,
Test.makeInstanceof(
extraArgVar, getExtraParameterType().resolve(world)),
null,
ifNoAdvice,
null));
}
}
il.append(getAdviceArgSetup(shadow, extraArgVar, null));
il.append(getNonTestAdviceInstructions(shadow));
InstructionHandle ifYesAdvice = il.getStart();
il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice));
return il;
}
public InstructionList getAdviceArgSetup(
BcelShadow shadow,
BcelVar extraVar,
InstructionList closureInstantiation)
{
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// if (targetAspectField != null) {
// il.append(fact.createFieldAccess(
// targetAspectField.getDeclaringType().getName(),
// targetAspectField.getName(),
// BcelWorld.makeBcelType(targetAspectField.getType()),
// Constants.GETSTATIC));
// }
//
//System.err.println("BcelAdvice: " + exposedState);
if (exposedState.getAspectInstance() != null) {
il.append(BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance()));
}
final boolean isAnnotationStyleAspect = getConcreteAspect()!=null && getConcreteAspect().isAnnotationStyleAspect();
boolean previousIsClosure = false;
for (int i = 0, len = exposedState.size(); i < len; i++) {
if (exposedState.isErroneousVar(i)) continue; // Erroneous vars have already had error msgs reported!
BcelVar v = (BcelVar) exposedState.get(i);
if (v == null) {
// if not @AJ aspect, go on with the regular binding handling
if (!isAnnotationStyleAspect) {
;
} else {
// ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint
//if (getKind() == AdviceKind.Around) {
// previousIsClosure = true;
// il.append(closureInstantiation);
if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
//make sure we are in an around, since we deal with the closure, not the arg here
if (getKind() != AdviceKind.Around) {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
} else {
if (previousIsClosure) {
il.append(InstructionConstants.DUP);
} else {
previousIsClosure = true;
il.append(closureInstantiation.copy());
}
}
} else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
} else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if (hasExtraParameter()) {
previousIsClosure = false;
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
} else {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
}
}
} else {
UnresolvedType desiredTy = getBindingParameterTypes()[i];
v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
}
}
// ATAJ: for code style aspect, handles the extraFlag as usual ie not
// in the middle of the formal bindings but at the end, in a rock solid ordering
if (!isAnnotationStyleAspect) {
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
// handle thisJoinPoint parameters
// these need to be in that same order as parameters in
// org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
}
return il;
}
public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
return new InstructionList(
Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getOriginalSignature()));
}
public Member getOriginalSignature() {
Member sig = getSignature();
if (sig instanceof ResolvedMember) {
ResolvedMember rsig = (ResolvedMember)sig;
if (rsig.hasBackingGenericMember()) return rsig.getBackingGenericMember();
}
return sig;
}
public InstructionList getTestInstructions(
BcelShadow shadow,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
//System.err.println("test: " + pointcutTest);
return BcelRenderer.renderTest(
shadow.getFactory(),
shadow.getWorld(),
pointcutTest,
sk,
fk,
next);
}
public int compareTo(Object other) {
if (!(other instanceof BcelAdvice)) return 0;
BcelAdvice o = (BcelAdvice)other;
//System.err.println("compareTo: " + this + ", " + o);
if (kind.getPrecedence() != o.kind.getPrecedence()) {
if (kind.getPrecedence() > o.kind.getPrecedence()) return +1;
else return -1;
}
if (kind.isCflow()) {
// System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
// System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1;
else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1;
else return 0;
}
if (kind.isPerEntry() || kind == AdviceKind.Softener) {
return 0;
}
//System.out.println("compare: " + this + " with " + other);
World world = concreteAspect.getWorld();
int ret =
concreteAspect.getWorld().compareByPrecedence(
concreteAspect,
o.concreteAspect);
if (ret != 0) return ret;
ResolvedType declaringAspect = getDeclaringAspect().resolve(world);
ResolvedType o_declaringAspect = o.getDeclaringAspect().resolve(world);
if (declaringAspect == o_declaringAspect) {
if (kind.isAfter() || o.kind.isAfter()) {
return this.getStart() < o.getStart() ? -1: +1;
} else {
return this.getStart()< o.getStart() ? +1: -1;
}
} else if (declaringAspect.isAssignableFrom(o_declaringAspect)) {
return -1;
} else if (o_declaringAspect.isAssignableFrom(declaringAspect)) {
return +1;
} else {
return 0;
}
}
public BcelVar[] getExposedStateAsBcelVars() {
// ATAJ aspect
// the closure instantiation has the same mapping as the extracted method from wich it is called
if (getConcreteAspect()!= null && getConcreteAspect().isAnnotationStyleAspect()) {
return BcelVar.NONE;
}
//System.out.println("vars: " + Arrays.asList(exposedState.vars));
if (exposedState == null) return BcelVar.NONE;
int len = exposedState.vars.length;
BcelVar[] ret = new BcelVar[len];
for (int i=0; i < len; i++) {
ret[i] = (BcelVar)exposedState.vars[i];
}
return ret; //(BcelVar[]) exposedState.vars;
}
public boolean hasMatchedSomething() {
return hasMatchedAtLeastOnce;
}
protected void suppressLintWarnings(World inWorld) {
if (suppressedLintKinds == null) {
if (signature instanceof BcelMethod) {
this.suppressedLintKinds = Utility.getSuppressedWarnings(signature.getAnnotations(), inWorld.getLint());
} else {
this.suppressedLintKinds = Collections.EMPTY_LIST;
}
}
inWorld.getLint().suppressKinds(suppressedLintKinds);
}
protected void clearLintSuppressions(World inWorld) {
inWorld.getLint().clearSuppressions();
}
}
|
116,899
|
Bug 116899 Using -verbose in aop.xml does not yield info messages
|
The interpretation of the -verbose option for LTW is not consistent with other uses in AspectJ e.g. ajc, iajc. It should allow info as well as warining and error messages to be output. The option parser and testcase need to be updated.
|
resolved fixed
|
76d7e83
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T09:27:06Z
| 2005-11-17T17:53:20Z
|
loadtime/src/org/aspectj/weaver/loadtime/Options.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.Message;
import org.aspectj.util.LangUtil;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* A class that hanldes LTW options.
* Note: AV - I choosed to not reuse AjCompilerOptions and alike since those implies too many dependancies on
* jdt and ajdt modules.
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class Options {
private final static String OPTION_15 = "-1.5";
private final static String OPTION_lazyTjp = "-XlazyTjp";
private final static String OPTION_noWarn = "-nowarn";
private final static String OPTION_noWarnNone = "-warn:none";
private final static String OPTION_proceedOnError = "-proceedOnError";
private final static String OPTION_verbose = "-verbose";
private final static String OPTION_reweavable = "-Xreweavable";//notReweavable is default for LTW
private final static String OPTION_noinline = "-Xnoinline";
private final static String OPTION_hasMember = "-XhasMember";
private final static String OPTION_pinpoint = "-Xdev:pinpoint";
private final static String OPTION_showWeaveInfo = "-showWeaveInfo";
private final static String OPTIONVALUED_messageHandler = "-XmessageHandlerClass:";
private static final String OPTIONVALUED_Xlintfile = "-Xlintfile:";
private static final String OPTIONVALUED_Xlint = "-Xlint:";
public static WeaverOption parse(String options, ClassLoader laoder, IMessageHandler imh) {
WeaverOption weaverOption = new WeaverOption(imh);
if (LangUtil.isEmpty(options)) {
return weaverOption;
}
// the first option wins
List flags = LangUtil.anySplit(options, " ");
Collections.reverse(flags);
// do a first round on the message handler since it will report the options themselves
for (Iterator iterator = flags.iterator(); iterator.hasNext();) {
String arg = (String) iterator.next();
if (arg.startsWith(OPTIONVALUED_messageHandler)) {
if (arg.length() > OPTIONVALUED_messageHandler.length()) {
String handlerClass = arg.substring(OPTIONVALUED_messageHandler.length()).trim();
try {
Class handler = Class.forName(handlerClass, false, laoder);
weaverOption.messageHandler = ((IMessageHandler) handler.newInstance());
} catch (Throwable t) {
weaverOption.messageHandler.handleMessage(
new Message(
"Cannot instantiate message handler " + handlerClass,
IMessage.ERROR,
t,
null
)
);
}
}
}
}
// configure the other options
for (Iterator iterator = flags.iterator(); iterator.hasNext();) {
String arg = (String) iterator.next();
if (arg.equals(OPTION_15)) {
weaverOption.java5 = true;
} else if (arg.equalsIgnoreCase(OPTION_lazyTjp)) {
weaverOption.lazyTjp = true;
} else if (arg.equalsIgnoreCase(OPTION_noinline)) {
weaverOption.noInline = true;
} else if (arg.equalsIgnoreCase(OPTION_noWarn) || arg.equalsIgnoreCase(OPTION_noWarnNone)) {
weaverOption.noWarn = true;
} else if (arg.equalsIgnoreCase(OPTION_proceedOnError)) {
weaverOption.proceedOnError = true;
} else if (arg.equalsIgnoreCase(OPTION_reweavable)) {
weaverOption.notReWeavable = false;
} else if (arg.equalsIgnoreCase(OPTION_showWeaveInfo)) {
weaverOption.showWeaveInfo = true;
} else if (arg.equalsIgnoreCase(OPTION_hasMember)) {
weaverOption.hasMember = true;
} else if (arg.equalsIgnoreCase(OPTION_verbose)) {
weaverOption.verbose = true;
} else if (arg.equalsIgnoreCase(OPTION_pinpoint)) {
weaverOption.pinpoint = true;
} else if (arg.startsWith(OPTIONVALUED_messageHandler)) {
;// handled in first round
} else if (arg.startsWith(OPTIONVALUED_Xlintfile)) {
if (arg.length() > OPTIONVALUED_Xlintfile.length()) {
weaverOption.lintFile = arg.substring(OPTIONVALUED_Xlintfile.length()).trim();
}
} else if (arg.startsWith(OPTIONVALUED_Xlint)) {
if (arg.length() > OPTIONVALUED_Xlint.length()) {
weaverOption.lint = arg.substring(OPTIONVALUED_Xlint.length()).trim();
}
} else {
weaverOption.messageHandler.handleMessage(
new Message(
"Cannot configure weaver with option '" + arg + "': unknown option",
IMessage.WARNING,
null,
null
)
);
}
}
// refine message handler configuration
if (weaverOption.noWarn) {
weaverOption.messageHandler.dontIgnore(IMessage.WARNING);
}
if (weaverOption.verbose) {
weaverOption.messageHandler.dontIgnore(IMessage.DEBUG);
}
if (weaverOption.showWeaveInfo) {
weaverOption.messageHandler.dontIgnore(IMessage.WEAVEINFO);
}
return weaverOption;
}
public static class WeaverOption {
boolean java5;
boolean lazyTjp;
boolean hasMember;
boolean noWarn;
boolean proceedOnError;
boolean verbose;
boolean notReWeavable = true;//default to notReweavable for LTW (faster)
boolean noInline;
boolean showWeaveInfo;
boolean pinpoint;
IMessageHandler messageHandler;
String lint;
String lintFile;
public WeaverOption(IMessageHandler imh) {
// messageHandler = new DefaultMessageHandler();//default
this.messageHandler = imh;
}
}
}
|
116,899
|
Bug 116899 Using -verbose in aop.xml does not yield info messages
|
The interpretation of the -verbose option for LTW is not consistent with other uses in AspectJ e.g. ajc, iajc. It should allow info as well as warining and error messages to be output. The option parser and testcase need to be updated.
|
resolved fixed
|
76d7e83
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T09:27:06Z
| 2005-11-17T17:53:20Z
|
tests/java5/ataspectj/ataspectj/ltwlog/Main.java
| |
116,899
|
Bug 116899 Using -verbose in aop.xml does not yield info messages
|
The interpretation of the -verbose option for LTW is not consistent with other uses in AspectJ e.g. ajc, iajc. It should allow info as well as warining and error messages to be output. The option parser and testcase need to be updated.
|
resolved fixed
|
76d7e83
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T09:27:06Z
| 2005-11-17T17:53:20Z
|
tests/java5/ataspectj/ataspectj/ltwlog/MessageHolder.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package ataspectj.ltwlog;
import org.aspectj.bridge.IMessageHolder;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.AbortException;
import org.aspectj.weaver.loadtime.DefaultMessageHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class MessageHolder extends DefaultMessageHandler {
static List s_messages = new ArrayList();
public MessageHolder() {
}
public boolean handleMessage(IMessage message) throws AbortException {
if (isIgnoring(message.getKind())) {
return false;
} else {
s_messages.add(message.toString());
return true;
}
}
public static boolean startsAs(List messages) {
if (s_messages.size() < messages.size())
return false;
int i = 0;
for (Iterator iterator = messages.iterator(); iterator.hasNext();) {
String s = (String) iterator.next();
if (!((String)s_messages.get(i)).startsWith(s)) {
return false;
}
i++;
}
return true;
}
public static int size() {
return s_messages.size();
}
public static void dump() {
for (Iterator iterator = s_messages.iterator(); iterator.hasNext();) {
String s = (String) iterator.next();
System.err.println("Holds:" + s);
}
}
}
|
116,899
|
Bug 116899 Using -verbose in aop.xml does not yield info messages
|
The interpretation of the -verbose option for LTW is not consistent with other uses in AspectJ e.g. ajc, iajc. It should allow info as well as warining and error messages to be output. The option parser and testcase need to be updated.
|
resolved fixed
|
76d7e83
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T09:27:06Z
| 2005-11-17T17:53:20Z
|
tests/src/org/aspectj/systemtest/ajc150/ataspectj/AtAjLTWTests.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150.ataspectj;
import org.aspectj.testing.XMLBasedAjcTestCase;
import junit.framework.Test;
import java.io.File;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class AtAjLTWTests extends XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(org.aspectj.systemtest.ajc150.ataspectj.AtAjLTWTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ataspectj/ltw.xml");
}
public void testRunThemAllWithJavacCompiledAndLTW() {
runTest("RunThemAllWithJavacCompiledAndLTW");
}
public void testAjcLTWPerClauseTest_XnoWeave() {
runTest("AjcLTW PerClauseTest -XnoWeave");
}
public void testAjcLTWPerClauseTest_Xreweavable() {
runTest("AjcLTW PerClauseTest -Xreweavable");
}
public void testJavaCAjcLTWPerClauseTest() {
runTest("JavaCAjcLTW PerClauseTest");
}
public void testAjcLTWAroundInlineMungerTest_XnoWeave() {
runTest("AjcLTW AroundInlineMungerTest -XnoWeave");
}
public void testAjcLTWAroundInlineMungerTest_Xreweavable() {
runTest("AjcLTW AroundInlineMungerTest");
}
public void testAjcLTWAroundInlineMungerTest() {
runTest("AjcLTW AroundInlineMungerTest");
}
public void testAjcLTWAroundInlineMungerTest_XnoInline_Xreweavable() {
runTest("AjcLTW AroundInlineMungerTest -XnoInline -Xreweavable");
}
public void testAjcLTWAroundInlineMungerTest2() {
runTest("AjcLTW AroundInlineMungerTest2");
}
public void testLTWDump() {
runTest("LTW DumpTest");
}
public void testAjcAspect1LTWAspect2_Xreweavable() {
runTest("Ajc Aspect1 LTW Aspect2 -Xreweavable");
}
public void testLTWLog() {
runTest("LTW Log");
}
public void testLTWUnweavable() {
// actually test that we do LTW proxy and jit classes
runTest("LTW Unweavable");
}
public void testLTWDecp() {
runTest("LTW Decp");
}
public void testLTWDecp2() {
runTest("LTW Decp2");
}
public void testCompileTimeAspectsDeclaredToLTWWeaver() {
runTest("Compile time aspects declared to ltw weaver");
}
public void testConcreteAtAspect() {
runTest("Concrete@Aspect");
}
public void testConcreteAspect() {
runTest("ConcreteAspect");
}
public void testConcretePrecedenceAspect() {
runTest("ConcretePrecedenceAspect");
}
public void testAspectOfWhenAspectNotInInclude() {
runTest("AspectOfWhenAspectNotInInclude");
}
public void testAppContainer() {
runTest("AppContainer");
}
}
|
117,614
|
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z
| 2005-11-23T01:40:00Z
|
tests/src/org/aspectj/systemtest/ajc150/GenericsTests.java
|
package org.aspectj.systemtest.ajc150;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.tools.ajc.Ajc;
import org.aspectj.util.LangUtil;
public class GenericsTests extends XMLBasedAjcTestCase {
/*==========================================
* Generics test plan for pointcuts.
*
* handler PASS
* - does not permit type var spec
* - does not permit generic type (fail with type not found)
* - does not permit parameterized types
* if PASS
* - does not permit type vars
* cflow PASS
* - does not permit type vars
* cflowbelow PASS
* - does not permit type vars
* @this PASS
* - does not permit type vars PASS
* - does not permit parameterized type PASS
* @target PASS
* - does not permit type vars PASS
* - does not permit parameterized type PASS
* @args PASS
* - does not permit type vars PASS
* - does not permit parameterized type PASS
* @annotation PASS
* - does not permit type vars PASS
* - does not permit parameterized type PASS
* @within, @within code - as above PASS
* annotation type pattern with generic and parameterized types PASS
* - just make sure that annotation interfaces can never be generic first! VERIFIED
* - @Foo<T> should fail PASS
* - @Foo<String> should fail PASS
* - @(Foo || Bar<T>) should fail DEFERRED (not critical)
* staticinitialization PASS
* - error on parameterized type PASS N/A
* - permit parameterized type + PASS N/A
* - matching with parameterized type + N/A
* - wrong number of parameters in parameterized type PASS N/A
* - generic type with one type parameter N/A
* - generic type with n type parameters N/A
* - generic type with bounds [extends, extends + i/f's] N/A
* - generic type with wrong number of type params N/A
* - wildcards in bounds N/A
* within PASS
* - as above, but allows parameterized type (disallowed in simplified plan)
* - wildcards in type parameters N/A
* this PASS
* - no type vars
* - parameterized types - disallowed in simplification plan
* - implements
* - instanceof
* target PASS
* - as this
* args
* - args(List) matches List, List<T>, List<String> PASS
* - args(List<T>) -> invalid absolute type T
* - args(List<String>) matches List<String> but not List<Number> PASS
* - args(List<String>) matches List with unchecked warning PASS
* - args(List<String>) matches List<?> with unchecked warning PASS
* - args(List<Double>) matches List, List<?>, List<? extends Number> with unchecked warning PASS
* matches List<Double> PASS, List<? extends Double> PASS(with warning)
* - args(List<?>) matches List, List<String>, List<?>, ... PASS
* - args(List<? extends Number) matches List<Number>, List<Double>, not List<String> PASS
* matches List, List<?> with unchecked warning PASS
* - args(List<? super Number>) matches List<Object>, List<Number>
* does not match List<Double>
* matches List, List<?> with unchecked warning
* matches List<? super Number>
* matches List<? extends Object> with unchecked warning
* matches List<? extends Number> with unchecked warning
* get & set PASS
* - parameterized declaring type PASS
* - generic declaring type PASS
* - field type is type variable PASS
* - field type is parameterized PASS
* initialization, preinitialization PASS
* - generic declaring type PASS
* - type variables as params PASS
* - parameterized types as params PASS
* - no join points for init, preinit of parameterized types (as per staticinit) PASS
* withincode PASS
* - no generic or parameterized declaring type patterns PASS
* - no parameterized throws patterns PASS
* - return type as type variable PASS
* - return type as parameterized type PASS
* - parameter as type variable PASS
* - parameter as parameterized type PASS
* - no join points within bridge methods PASS
* execution PASS
* - no generic or parameterized declaring type patterns PASS
* - no parameterized throws patterns PASS
* - return type as type variable PASS
* - return type as parameterized type PASS
* - parameter as type variable PASS
* - parameter as parameterized type PASS
* - no join points for bridge methods PASS
* call PASS
* - no generic or parameterized declaring type patterns PASS
* - no parameterized throws patterns PASS
* - return type as type variable PASS
* - return type as parameterized type PASS
* - parameter as type variable PASS
* - parameter as parameterized type PASS
* - calls to a bridge methods PASS
* after throwing - can't use parameterized type pattern
* after returning - same as for args
*/
/* ==========================================
* Generics test plan for ITDs.
*
* think about:
* - 'visibility' default/private/public
* - static/nonstatic
* - parameterized ITDs (methods/ctors/fields)
* - ITD target: interface/class/aspect
* - multiple type variables
* - constructor ITDs, method ITDs
* - ITDs sharing type variables with generic types
* - relating to above point, this makes generic ITD fields possible
* - signature attributes for generic ITDs (required? required only for public ITDs?)
* - binary weaving when target type changes over time (might start out 'simple' then sometime later be 'generic')
* - bridge methods - when to create them
* - multiple 'separate' ITDs in a file that share a type variable by 'name'
* - wildcards '?' 'extends' 'super' '&'
* - do type variables assigned to members need to persist across serialization
* - recursive type variable definitions eg. <R extends Comparable<? super R>>
* - super/extends with parameterized types <? extends List<String>>
* - multiple ITDs defined in one type that reuse type variable letters, specifying different bounds
* - generic aspects
*
* PASS parsing generic ITDs
* PASS generic methods
* PASS generic constructors
* PASS ITD visibility
* PASS static/nonstatic
* PASS parameterizedITDs
* PASS differing targets (interface/class/aspect)
* PASS multiple type variables in an ITD
* PASS parsing ITDs that share type variables with target type
* PASS using type variables from the target type in your field ITD
* PASS using type variables from the target type in your method ITD (but no type vars of your own)
* PASS using type variables from the target type in your ctor ITD (but no type vars of your own)
* PASS using type variables from the target type and having your own too (methods)
* PASS using type variables from the target type and having your own too (ctors)
* PASS reusing type variable letter but differing spec across multiple ITDs in one aspect
* PASS wildcards
* PASS recursive type variable definitions
* PASS generic aspects
* PASS parameterizing ITDs with type variables
* PASS using type variables from the target type in your *STATIC* ITD (field/method/ctor) (error scenario)
* PASS basic binary weaving of generic itds
*
* TODO generic aspect binary weaving (or at least multi source file weaving)
* TODO binary weaving with changing types (moving between generic and simple)
* TODO bridge method creation (also relates to covariance overrides..)
* TODO exotic class/interface bounds ('? extends List<String>','? super anything')
* TODO signature attributes for generic ITDs (public only?)
*
*/
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(GenericsTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void testITDReturningParameterizedType() {
runTest("ITD with parameterized type");
}
public void testPR91267_1() {
runTest("NPE using generic methods in aspects 1");
}
public void testParameterizedTypeAndAroundAdvice_PR115250() {
runTest("parameterized type and around advice");
}
public void testParameterizedTypeAndAroundAdvice_PR115250_2() {
runTest("parameterized type and around advice - 2");
}
public void testPR91267_2() {
runTest("NPE using generic methods in aspects 2");
}
public void testPR91053() {
runTest("Generics problem with Set");
}
public void testPR87282() {
runTest("Compilation error on generic member introduction");
}
public void testGenericsOverrides_1() { runTest("generics and ITD overrides - 1"); }
public void testGenericsOverrides_2() { runTest("generics and ITD overrides - 2"); }
public void testGenericsOverrides_3() { runTest("generics and ITD overrides - 3"); }
public void testGenericsOverrides_4() { runTest("generics and ITD overrides - 4"); }
public void testSelfBoundGenerics_pr117296() {
runTest("self bounding generic types");
}
public void testPR88606() {
runTest("Parameterized types on introduced fields not correctly recognized");
}
public void testPR97763() {
runTest("ITD method with generic arg");
}
public void testGenericsBang_pr95993() {
runTest("NPE at ClassScope.java:660 when compiling generic class");
}
// generic aspects
public void testPR96220_GenericAspects1() {runTest("generic aspects - 1");}
public void testPR96220_GenericAspects2() {runTest("generic aspects - 2");}
public void testPR96220_GenericAspects3() {runTest("generic aspects - 3");}
public void testGenericAspects4() {runTest("generic aspects - 4");}
public void testGenericAspects5() {runTest("generic aspects - 5 (ajdk)");} // in separate files
public void testGenericAspects6() {runTest("generic aspects - 6 (ajdk)");} // all in one file
public void testTypeVariablesInDeclareWarning() { runTest("generic aspect with declare warning using type vars");}
public void testTypeVariablesInExecutionAdvice() { runTest("generic aspect with execution advice using type vars");}
public void testTypeVariablesInAnonymousPointcut() { runTest("generic aspect with anonymous pointcut");}
public void testDeclareParentWithParameterizedInterface() {
runTest("generic aspect declare parents");
}
public void testDeclareSoftInGenericAspect() {
runTest("generic aspect declare soft");
}
//////////////////////////////////////////////////////////////////////////////
// Generic/Parameterized ITDs - includes scenarios from developers notebook //
//////////////////////////////////////////////////////////////////////////////
// parsing of generic ITD members
public void testParseItdNonStaticMethod() {runTest("Parsing generic ITDs - 1");}
public void testParseItdStaticMethod() {runTest("Parsing generic ITDs - 2");}
public void testParseItdCtor() {runTest("Parsing generic ITDs - 3");}
public void testParseItdComplexMethod() {runTest("Parsing generic ITDs - 4");}
public void testParseItdSharingVars1() {runTest("Parsing generic ITDs - 5");}
public void testParseItdSharingVars2() {runTest("Parsing generic ITDs - 6");}
// non static
public void testGenericMethodITD1() {runTest("generic method itd - 1");} // <E> ... (List<? extends E>)
public void testGenericMethodITD2() {runTest("generic method itd - 2");} // <E extends Number> ... (List<? extends E>) called incorrectly
public void testGenericMethodITD3() {runTest("generic method itd - 3");} // <E> ... (List<E>,List<E>)
public void testGenericMethodITD4() {runTest("generic method itd - 4");} // <A,B> ... (List<A>,List<B>)
public void testGenericMethodITD5() {runTest("generic method itd - 5");} // <E> ... (List<E>,List<E>) called incorrectly
public void testGenericMethodITD6() {runTest("generic method itd - 6");} // <E extends Number> ... (List<? extends E>)
public void testGenericMethodITD7() {runTest("generic method itd - 7"); } // <E> ... (List<E>,List<? extends E>)
public void testGenericMethodITD8() {runTest("generic method itd - 8"); } // <E> ... (List<E>,List<? extends E>) called incorrectly
public void testGenericMethodITD9() {runTest("generic method itd - 9"); } // <R extends Comparable<? super R>> ... (List<R>)
public void testGenericMethodITD10() {runTest("generic method itd - 10");} // <R extends Comparable<? super R>> ... (List<R>) called incorrectly
public void testGenericMethodITD11() {runTest("generic method itd - 11");} // <R extends Comparable<? extends R>> ... (List<R>)
public void testGenericMethodITD12() {runTest("generic method itd - 12");} // <R extends Comparable<? extends R>> ... (List<R>) called incorrectly
public void testGenericMethodITD13() {runTest("generic method itd - 13");} // <R extends Comparable<? extends R>> ... (List<R>) called correctly in a clever way ;)
public void testGenericMethodITD14() {runTest("generic method itd - 14");} // <R extends Comparable<? super R>> ... (List<R>) called incorrectly in a clever way
public void testGenericMethodITD15() {runTest("generic method itd - 15");} // <R extends Comparable<? super R>> ... (List<R>) called correctly in a clever way
// generic ctors
public void testGenericCtorITD1() {runTest("generic ctor itd - 1");} // <T> new(List<T>)
public void testGenericCtorITD2() {runTest("generic ctor itd - 2");} // <T> new(List<T>,List<? extends T>)
public void testGenericCtorITD3() {runTest("generic ctor itd - 3");} // <T> new(List<T>,Comparator<? super T>)
// parameterized ITDs
public void testParameterizedMethodITD1() {runTest("parameterized method itd - 1");} // (List<? extends Super>)
public void testParameterizedMethodITD2() {runTest("parameterized method itd - 2");} // (List<? extends Number>) called incorrectly
public void testParameterizedMethodITD3() {runTest("parameterized method itd - 3");} // (List<? super A>) called incorrectly
public void testParameterizedMethodITD4() {runTest("parameterized method itd - 4");} // (List<? super B>)
// differing visibilities
public void testPublicITDs() {runTest("public itds");}
public void testPublicITDsErrors() {runTest("public itds with errors");}
public void testPrivateITDs() {runTest("private itds");}
public void testPackageITDs() {runTest("package itds");}
// targetting different types (interface/class/aspect)
public void testTargettingInterface() {runTest("targetting interface");}
public void testTargettingAspect() {runTest("targetting aspect");}
public void testTargettingClass() {runTest("targetting class");}
// using a type variable from the target generic type in your ITD
public void testFieldITDsUsingTargetTypeVars1() {runTest("field itd using type variable from target type - 1");}
public void testFieldITDsUsingTargetTypeVars2() {runTest("field itd using type variable from target type - 2");}
public void testFieldITDsUsingTargetTypeVars3() {runTest("field itd using type variable from target type - 3");}
public void testFieldITDsUsingTargetTypeVars4() {runTest("field itd using type variable from target type - 4");}
public void testFieldITDsUsingTargetTypeVars5() {runTest("field itd using type variable from target type - 5");}
public void testFieldITDsUsingTargetTypeVars6() {runTest("field itd using type variable from target type - 6");}
public void testFieldITDsUsingTargetTypeVars7() {runTest("field itd using type variable from target type - 7");}
public void testFieldITDsUsingTargetTypeVars8() {runTest("field itd using type variable from target type - 8");}
public void testFieldITDsUsingTargetTypeVars9() {runTest("field itd using type variable from target type - 9");}
public void testFieldITDsUsingTargetTypeVars10(){runTest("field itd using type variable from target type -10");}
public void testFieldITDsUsingTargetTypeVars11(){runTest("field itd using type variable from target type -11");}
public void testFieldITDsUsingTargetTypeVars12(){runTest("field itd using type variable from target type -12");}
public void testFieldITDsUsingTargetTypeVars13(){runTest("field itd using type variable from target type -13");}
public void testFieldITDsUsingTargetTypeVars14(){runTest("field itd using type variable from target type -14");}
public void testFieldITDsUsingTargetTypeVars15(){runTest("field itd using type variable from target type -15");}
public void testFieldITDsUsingTargetTypeVars16(){runTest("field itd using type variable from target type -16");}
public void testFieldITDsUsingTargetTypeVars17(){runTest("field itd using type variable from target type -17");}
public void testMethodITDsUsingTargetTypeVarsA1() {runTest("method itd using type variable from target type - A1");}
public void testMethodITDsUsingTargetTypeVarsA2() {runTest("method itd using type variable from target type - A2");}
public void testMethodITDsUsingTargetTypeVarsA3() {runTest("method itd using type variable from target type - A3");}
public void testMethodITDsUsingTargetTypeVarsA4() {runTest("method itd using type variable from target type - A4");}
public void testMethodITDsUsingTargetTypeVarsB1() {runTest("method itd using type variable from target type - B1");}
public void testMethodITDsUsingTargetTypeVarsC1() {runTest("method itd using type variable from target type - C1");}
public void testMethodITDsUsingTargetTypeVarsD1() {runTest("method itd using type variable from target type - D1");}
public void testMethodITDsUsingTargetTypeVarsE1() {runTest("method itd using type variable from target type - E1");}
public void testMethodITDsUsingTargetTypeVarsF1() {runTest("method itd using type variable from target type - F1");}
public void testMethodITDsUsingTargetTypeVarsG1() {runTest("method itd using type variable from target type - G1");}
public void testMethodITDsUsingTargetTypeVarsH1() {runTest("method itd using type variable from target type - H1");}
public void testMethodITDsUsingTargetTypeVarsI1() {runTest("method itd using type variable from target type - I1");}
public void testMethodITDsUsingTargetTypeVarsI2() {runTest("method itd using type variable from target type - I2");}
public void testMethodITDsUsingTargetTypeVarsJ1() {runTest("method itd using type variable from target type - J1");}
public void testMethodITDsUsingTargetTypeVarsK1() {runTest("method itd using type variable from target type - K1");}
public void testMethodITDsUsingTargetTypeVarsL1() {runTest("method itd using type variable from target type - L1");}
public void testMethodITDsUsingTargetTypeVarsM1() {runTest("method itd using type variable from target type - M1");}
public void testMethodITDsUsingTargetTypeVarsM2() {runTest("method itd using type variable from target type - M2");}
public void testMethodITDsUsingTargetTypeVarsN1() {runTest("method itd using type variable from target type - N1");}
public void testMethodITDsUsingTargetTypeVarsO1() {runTest("method itd using type variable from target type - O1");}
public void testMethodITDsUsingTargetTypeVarsO2() {runTest("method itd using type variable from target type - O2");}
public void testMethodITDsUsingTargetTypeVarsP1() {runTest("method itd using type variable from target type - P1");}
public void testMethodITDsUsingTargetTypeVarsQ1() {runTest("method itd using type variable from target type - Q1");}
public void testCtorITDsUsingTargetTypeVarsA1() {runTest("ctor itd using type variable from target type - A1");}
public void testCtorITDsUsingTargetTypeVarsB1() {runTest("ctor itd using type variable from target type - B1");}
public void testCtorITDsUsingTargetTypeVarsC1() {runTest("ctor itd using type variable from target type - C1");}
public void testCtorITDsUsingTargetTypeVarsD1() {runTest("ctor itd using type variable from target type - D1");}
public void testCtorITDsUsingTargetTypeVarsE1() {runTest("ctor itd using type variable from target type - E1");}
public void testCtorITDsUsingTargetTypeVarsF1() {runTest("ctor itd using type variable from target type - F1");}
public void testCtorITDsUsingTargetTypeVarsG1() {runTest("ctor itd using type variable from target type - G1");}
public void testCtorITDsUsingTargetTypeVarsH1() {runTest("ctor itd using type variable from target type - H1");}
public void testCtorITDsUsingTargetTypeVarsI1() {runTest("ctor itd using type variable from target type - I1");}
public void testSophisticatedAspectsA() {runTest("uberaspects - A");}
public void testSophisticatedAspectsB() {runTest("uberaspects - B");}
public void testSophisticatedAspectsC() {runTest("uberaspects - C");}
public void testSophisticatedAspectsD() {runTest("uberaspects - D");}
public void testSophisticatedAspectsE() {runTest("uberaspects - E");}
public void testSophisticatedAspectsF() {runTest("uberaspects - F");}
public void testSophisticatedAspectsG() {runTest("uberaspects - G");}
public void testSophisticatedAspectsH() {runTest("uberaspects - H");}
public void testSophisticatedAspectsI() {runTest("uberaspects - I");}
public void testSophisticatedAspectsJ() {runTest("uberaspects - J");}
//public void testSophisticatedAspectsK() {runTest("uberaspects - K");} // FIXME asc bounds testing is tough!
public void testSophisticatedAspectsK2(){runTest("uberaspects - K2");}
public void testSophisticatedAspectsL() {runTest("uberaspects - L");}
public void testSophisticatedAspectsM() {runTest("uberaspects - M");}
public void testSophisticatedAspectsN() {runTest("uberaspects - N");}
public void testSophisticatedAspectsO() {runTest("uberaspects - O");}
public void testSophisticatedAspectsP() {runTest("uberaspects - P");}
public void testSophisticatedAspectsQ() {runTest("uberaspects - Q");}
public void testSophisticatedAspectsR() {runTest("uberaspects - R");}
public void testSophisticatedAspectsS() {runTest("uberaspects - S");}
public void testSophisticatedAspectsT() {runTest("uberaspects - T");}
public void testSophisticatedAspectsU() {runTest("uberaspects - U");} // includes nasty casts
public void testSophisticatedAspectsV() {runTest("uberaspects - V");} // casts are gone
public void testSophisticatedAspectsW() {runTest("uberaspects - W");}
public void testSophisticatedAspectsX() {runTest("uberaspects - X");} // from the AJDK
// public void testSophisticatedAspectsY() {runTest("uberaspects - Y");} // pointcut matching
// FIXME asc these two tests have peculiar error messages - generic aspect related
// public void testItdUsingTypeParameter() {runTest("itd using type parameter");}
// public void testItdIncorrectlyUsingTypeParameter() {runTest("itd incorrectly using type parameter");}
public void testUsingSameTypeVariable() {runTest("using same type variable in ITD");}
public void testBinaryWeavingITDsA() {runTest("binary weaving ITDs - A");}
public void testBinaryWeavingITDsB() {runTest("binary weaving ITDs - B");}
public void testBinaryWeavingITDs1() {runTest("binary weaving ITDs - 1");}
public void testBinaryWeavingITDs2() {runTest("binary weaving ITDs - 2");}
public void testBinaryWeavingITDs3() {runTest("binary weaving ITDs - 3");}
public void testGenericITFSharingTypeVariable() {runTest("generic intertype field declaration, sharing type variable");}
// general tests ... usually just more complex scenarios
public void testReusingTypeVariableLetters() {runTest("reusing type variable letters");}
public void testMultipleGenericITDsInOneFile() {runTest("multiple generic itds in one file");}
public void testItdNonStaticMember() {runTest("itd of non static member");}
public void testItdStaticMember() {runTest("itd of static member");}
public void testStaticGenericMethodITD() {runTest("static generic method itd");}
public void testAtOverride0() {runTest("atOverride used with ITDs");}
public void testAtOverride1() {runTest("atOverride used with ITDs - 1");}
public void testAtOverride2() {runTest("atOverride used with ITDs - 2");}
public void testAtOverride3() {runTest("atOverride used with ITDs - 3");}
public void testAtOverride4() {runTest("atOverride used with ITDs - 4");}
public void testAtOverride5() {runTest("atOverride used with ITDs - 5");}
public void testAtOverride6() {runTest("atOverride used with ITDs - 6");}
public void testAtOverride7() {runTest("atOverride used with ITDs - 7");}
// bridge methods
public void testITDBridgeMethodsCovariance1() {runTest("bridging with covariance 1 - normal");}
public void testITDBridgeMethodsCovariance2() {runTest("bridging with covariance 1 - itd");}
public void testITDBridgeMethods1Normal() {runTest("basic bridging with type vars - 1 - normal");}
public void testITDBridgeMethods1Itd() {runTest("basic bridging with type vars - 1 - itd");}
public void testITDBridgeMethods2Normal() {runTest("basic bridging with type vars - 2 - normal");}
public void testITDBridgeMethods2Itd() {runTest("basic bridging with type vars - 2 - itd");}
public void testITDBridgeMethodsPr91381() {runTest("Abstract intertype method and covariant returns");}
// Just normal source compile of two types with a method override between them
public void testGenericITDsBridgeMethods1() {
runTest("bridge methods - 1");
checkMethodsExist("Sub1",new String[]{
"java.lang.Integer Sub1.m()",
"java.lang.Object Sub1.m() [BridgeMethod]"});
}
// Now the same thing but the aspect (which doesn't do much!) is binary woven in.
public void testGenericITDsBridgeMethods1binary() {
runTest("bridge methods - 1 - binary");
checkMethodsExist("Sub1",new String[]{
"java.lang.Integer Sub1.m()",
"java.lang.Object Sub1.m() [BridgeMethod]"});
}
// Now the method is put into the superclass via ITD - there should be a bridge method in the subclass
public void testGenericITDsBridgeMethods2() {
runTest("bridge methods - 2");
checkMethodsExist("Sub2",new String[]{
"java.lang.Integer Sub2.m()",
"java.lang.Object Sub2.m() [BridgeMethod]"});
}
// Now the superclass ITD is done with binary weaving so the weaver (rather than compiler) has to create the bridge method
public void testGenericITDsBridgeMethods2binary() {
runTest("bridge methods - 2 - binary");
checkMethodsExist("Sub2",new String[]{
"java.lang.Integer Sub2.m()",
"java.lang.Object Sub2.m() [BridgeMethod]"});
}
// Now the method is put into the subclass via ITD - there should be a bridge method alongside it in the subclass
public void testGenericITDsBridgeMethods3() {
runTest("bridge methods - 3");
checkMethodsExist("Sub3",new String[]{
"java.lang.Integer Sub3.m()",
"java.lang.Object Sub3.m() [BridgeMethod]"});
}
// Now the subclass ITD is done with binary weaving - the weaver should create the necessary bridge method
public void testGenericITDsBridgeMethods3binary() {
runTest("bridge methods - 3 - binary");
checkMethodsExist("Sub3",new String[]{
"java.lang.Integer Sub3.m()",
"java.lang.Object Sub3.m() [BridgeMethod]"});
}
// Now the two types are disconnected until the aspect supplies a declare parents relationship -
// the bridge method should still be created in the subtype
public void testGenericITDSBridgeMethods4() {
runTest("bridge methods - 4");
checkMethodsExist("Sub4",new String[]{
"java.lang.Integer Sub4.m()",
"java.lang.Object Sub4.m() [BridgeMethod]"});
}
// now the aspect doing the decp between the types is applied via binary weaving - weaver should create the bridge method
public void testGenericITDSBridgeMethods4binary() {
runTest("bridge methods - 4 - binary");
checkMethodsExist("Sub4",new String[]{
"java.lang.Integer Sub4.m()",
"java.lang.Object Sub4.m() [BridgeMethod]"});
}
public void testBinaryBridgeMethodsOne() {
runTest("binary bridge methods - one");
checkMethodsExist("OneB",new String[]{
"java.lang.Number OneB.firstMethod() [BridgeMethod]",
"java.lang.Integer OneB.firstMethod()",
"void OneB.secondMethod(java.lang.Number) [BridgeMethod]",
"void OneB.secondMethod(java.lang.Integer)",
"void OneB.thirdMethod(java.lang.Number,java.lang.Number) [BridgeMethod]",
"void OneB.thirdMethod(java.lang.Integer,java.lang.Integer)",
"void OneB.fourthMethod(java.util.List)",
"java.lang.Number OneB.fifthMethod(java.lang.Number,java.util.List) [BridgeMethod]",
"java.lang.Integer OneB.fifthMethod(java.lang.Integer,java.util.List)"
});
}
public void testBinaryBridgeMethodsTwo() {
runTest("binary bridge methods - two");
checkMethodsExist("TwoB",new String[]{
"java.lang.Number TwoB.firstMethod(java.io.Serializable) [BridgeMethod]",
"java.lang.Integer TwoB.firstMethod(java.lang.String)"
});
}
public void testBinaryBridgeMethodsThree() {
runTest("binary bridge methods - three");
checkMethodsExist("ThreeB",new String[]{
"java.lang.Number ThreeB.m() [BridgeMethod]",
"java.lang.Double ThreeB.m()"
});
}
public void testGenericITDsBridgeMethodsPR91381() {runTest("abstract intertype methods and covariant returns");}
public void testGenericITDsBridgeMethodsPR91381_2() {runTest("abstract intertype methods and covariant returns - error");}
// ----------------------------------------------------------------------------------------
// generic declare parents tests
// ----------------------------------------------------------------------------------------
public void testPR96220_GenericDecp() {
runTest("generic decp - simple");
verifyClassSignature(ajc,"Basic","Ljava/lang/Object;LJ<Ljava/lang/Double;>;LI<Ljava/lang/Double;>;");
}
// Both the existing type decl and the one adding via decp are parameterized
public void testGenericDecpMultipleVariantsOfAParameterizedType1() {
runTest("generic decp - implementing two variants #1");
}
// Existing type decl is raw and the one added via decp is parameterized
public void testGenericDecpMultipleVariantsOfAParameterizedType2() {
runTest("generic decp - implementing two variants #2");
}
// Existing type decl is parameterized and the one added via decp is raw
public void testGenericDecpMultipleVariantsOfAParameterizedType3() {
runTest("generic decp - implementing two variants #3");
}
// decp is parameterized but it does match the one already on the type
public void testGenericDecpMultipleVariantsOfAParameterizedType4() {
runTest("generic decp - implementing two variants #4");
}
// same as above four tests for binary weaving
public void testGenericDecpMultipleVariantsOfAParameterizedType1_binaryWeaving() {
runTest("generic decp binary - implementing two variants #1");
}
public void testGenericDecpMultipleVariantsOfAParameterizedType2_binaryWeaving() {
runTest("generic decp binary - implementing two variants #2");
}
// Existing type decl is parameterized and the one added via decp is raw
public void testGenericDecpMultipleVariantsOfAParameterizedType3_binaryWeaving() {
runTest("generic decp binary - implementing two variants #3");
}
// decp is parameterized but it does match the one already on the type
public void testGenericDecpMultipleVariantsOfAParameterizedType4_binaryWeaving() {
runTest("generic decp binary - implementing two variants #4");
}
public void testGenericDecpParameterized() {
runTest("generic decp - with parameterized on the target");
verifyClassSignature(ajc,"Basic6","<J:Ljava/lang/Object;>Ljava/lang/Object;LI<TJ;>;LK<Ljava/lang/Integer;>;");
}
public void testGenericDecpIncorrectNumberOfTypeParams() {
runTest("generic decp - incorrect number of type parameters");
}
public void testGenericDecpSpecifyingBounds() {
runTest("generic decp - specifying bounds");
}
public void testGenericDecpViolatingBounds() {
runTest("generic decp - specifying bounds but breaking them");
}
// need separate compilation test to verify signatures are ok
//
// public void testIllegalGenericDecp() {
// runTest("illegal generic decp");
// }
//
// public void testPR95992_TypeResolvingProblemWithGenerics() {
// runTest("Problems resolving type name inside generic class");
// }
// -- Pointcut tests...
public void testHandlerWithGenerics() {
runTest("handler pcd and generics / type vars");
}
public void testPointcutsThatDontAllowTypeVars() {
runTest("pointcuts that dont allow type vars");
}
public void testParameterizedTypesInAtPCDs() {
runTest("annotation pcds with parameterized types");
}
public void testAnnotationPatternsWithParameterizedTypes() {
runTest("annotation patterns with parameterized types");
}
public void testStaticInitializationWithParameterizedTypes() {
runTest("staticinitialization and parameterized types");
}
// no longer a valid test with generics simplication
// public void testStaticInitializationMatchingWithParameterizedTypes() {
// runTest("staticinitialization and parameterized type matching");
// }
// no longer a valid test in simplified design
// public void testStaticInitializationWithGenericTypes() {
// runTest("staticinitialization with generic types");
// }
// no longer a valid test in simplified design
// public void testStaticInitializationWithGenericTypesAdvanced() {
// runTest("staticinitialization with generic types - advanced");
// }
public void testWithinPointcutErrors() {
runTest("within pcd with various parameterizations and generic types - errors");
}
public void testWithinPointcutWarnings() {
runTest("within pcd with various parameterizations and generic types - warnings");
}
public void testThisTargetPointcutErrors() {
runTest("this and target with various parameterizations and generic types - errors");
}
public void testThisTargetPointcutRuntime() {
runTest("this and target with various parameterizations and generic types - runtime");
}
public void testInitAndPreInitPointcutErrors() {
runTest("init and preinit with parameterized declaring types");
}
public void testInitAndPreInitPointcutMatchingWithGenericDeclaringTypes() {
runTest("init and preinit with raw declaring type pattern");
}
public void testInitAndPreInitPointcutMatchingWithParameterizedParameterTypes() {
runTest("init and preinit with parameterized parameter types");
}
public void testWithinCodePointcutErrors() {
runTest("withincode with various parameterizations and generic types - errors");
}
public void testWithinCodeMatching() {
runTest("withincode with various parameterizations and generic types - matching");
}
public void testWithinCodeOverrideMatchingWithGenericMembers() {
runTest("withincode with overriding of inherited generic members");
}
public void testExecutionWithRawType() {
runTest("execution pcd with raw type matching");
}
public void testExecutionWithRawSignature() {
runTest("execution pcd with raw signature matching");
}
public void testExecutionPointcutErrors() {
runTest("execution with various parameterizations and generic types - errors");
}
public void testExecutionMatching() {
runTest("execution with various parameterizations and generic types - matching");
}
public void testExecutionOverrideMatchingWithGenericMembers() {
runTest("execution with overriding of inherited generic members");
}
public void testCallPointcutErrors() {
runTest("call with various parameterizations and generic types - errors");
}
public void testCallMatching() {
runTest("call with various parameterizations and generic types - matching");
}
public void testCallOverrideMatchingWithGenericMembers() {
runTest("call with overriding of inherited generic members");
}
public void testCallWithBridgeMethods() {
runTest("call with bridge methods");
}
public void testGetAndSetPointcutErrors() {
runTest("get and set with various parameterizations and generic types - errors");
}
public void testGetAndSetPointcutMatchingWithGenericAndParameterizedTypes() {
runTest("get and set with various parameterizations and generic declaring types");
}
public void testGetAndSetPointcutMatchingWithGenericAndParameterizedFieldTypes() {
runTest("get and set with various parameterizations and generic field types");
}
public void testArgsWithRawType() {
runTest("args with raw type and generic / parameterized sigs");
}
public void testArgsParameterizedType() {
runTest("args with parameterized type and generic / parameterized sigs");
}
public void testArgsParameterizedAndWildcards() {
runTest("args with parameterized type and wildcards");
}
public void testArgsWithWildcardVar() {
runTest("args with generic wildcard");
}
public void testArgsWithWildcardExtendsVar() {
runTest("args with generic wildcard extends");
}
public void testArgsWithWildcardSuperVar() {
runTest("args with generic wildcard super");
}
public void testGenericMethodMatching() {
runTest("generic method matching");
}
public void testGenericWildcardsInSignatureMatching() {
runTest("generic wildcards in signature matching");
}
public void testAfterThrowing() {
runTest("after throwing with parameterized throw type");
}
public void testAfterReturningWithRawType() {
runTest("after returning with raw type and generic / parameterized sigs");
}
public void testAfterReturningParameterizedType() {
runTest("after returning with parameterized type and generic / parameterized sigs");
}
public void testAfterReturningParameterizedAndWildcards() {
runTest("after returning with parameterized type and wildcards");
}
public void testAfterReturningWithWildcardVar() {
runTest("after returning with generic wildcard");
}
public void testAfterReturningWithWildcardExtendsVar() {
runTest("after returning with generic wildcard extends");
}
public void testAfterReturningWithWildcardSuperVar() {
runTest("after returning with generic wildcard super");
}
public void testAJDKErasureMatchingExamples() {
runTest("ajdk notebook: erasure matching examples");
}
public void testAJDKParameterizedMatchingSimpleExamples() {
runTest("ajdk notebook: simple parameterized type matching examples");
}
public void testAJDKMixedTypeVarsAndParametersExample() {
runTest("ajdk notebook: mixed parameterized types and generic methods");
}
public void testAJDKSignatureAndWildcardExamples() {
runTest("ajdk notebook: signature matching with generic wildcards");
}
public void testAJDKBridgeMethodExamples() {
runTest("ajdk notebook: bridge method examples");
}
public void testAJDKArgsExamples() {
runTest("ajdk notebook: args examples");
}
public void testAJDKArgsAndWildcardsExamples() {
runTest("ajdk notebook: args and wildcards examples");
}
public void testAJDKAfterReturningExamples() {
runTest("ajdk notebook: after returning examples");
}
public void testAJDKPointcutInGenericClassExample() {
runTest("ajdk notebook: pointcut in generic class example");
}
// TESTS for generic abstract aspects that get extended and parameterized...
public void testStaticPointcutParameterization() {
runTest("static pointcut parameterization suite");
}
public void testDynamicPointcutParameterization() {
runTest("dynamic pointcut parameterization suite");
}
public void testReferenceToPointcutInGenericClass() {
runTest("reference to pointcut in generic class");
}
public void testReferenceToPointcutInGenericClass2() {
runTest("reference to non-parameterized pointcut in generic class");
}
public void testDeclareParentsParameterized() {
runTest("declare parents parameterized");
}
public void testDeclarePrecedenceParameterized() {
runTest("declare precedence parameterized");
}
public void testDeclareAnnotationParameterized() {
runTest("declare annotation parameterized");
}
public void testMultiLevelGenericAspects() {
runTest("multi-level generic abstract aspects");
}
// --- helpers
/**
* When a class has been written to the sandbox directory, you can ask this method to
* verify it contains a particular set of methods. Typically this is used to verify that
* bridge methods have been created.
*/
public void checkMethodsExist(String classname,String[] methods) {
Set methodsFound = new HashSet();
StringBuffer debugString = new StringBuffer();
try {
ClassLoader cl = new URLClassLoader(new URL[]{ajc.getSandboxDirectory().toURL()});
Class clz = Class.forName(classname,false,cl);
java.lang.reflect.Method[] ms = clz.getDeclaredMethods();
if (ms!=null) {
for (int i =0;i<ms.length;i++) {
String methodString = ms[i].getReturnType().getName()+" "+ms[i].getDeclaringClass().getName()+"."+
ms[i].getName()+"("+stringify(ms[i].getParameterTypes())+")"+
(isBridge(ms[i])?" [BridgeMethod]":"");
methodsFound.add(methodString);
debugString.append("\n[").append(methodString).append("]");
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
// check the methods specified do exist
for (int i = 0; i < methods.length; i++) {
String string = methods[i];
if (!methodsFound.remove(string)) {
fail("Couldn't find ["+string+"] in the set of methods in "+classname+" => "+debugString);
}
}
StringBuffer unexpectedMethods = new StringBuffer();
if (!methodsFound.isEmpty()) {
for (Iterator iter = methodsFound.iterator(); iter.hasNext();) {
String element = (String) iter.next();
unexpectedMethods.append("[").append(element).append("]");
}
fail("These methods weren't expected: "+unexpectedMethods);
}
}
/**
* Use 1.5 API isBridge if available.
* See JLS3 15.12.4.5 Create Frame, Synchronize, Transfer Control
*/
public static boolean isBridge(java.lang.reflect.Method m) {
// why not importing java.lang.reflect.Method? No BCEL clash?
if (!LangUtil.is15VMOrGreater()) {
return false;
}
try {
final Class[] noparms = new Class[0];
java.lang.reflect.Method isBridge
= java.lang.reflect.Method.class.getMethod("isBridge", noparms);
Boolean result = (Boolean) isBridge.invoke(m, new Object[0]);
return result.booleanValue();
} catch (Throwable t) {
return false;
}
}
public static JavaClass getClass(Ajc ajc, String classname) {
try {
ClassPath cp =
new ClassPath(ajc.getSandboxDirectory() + File.pathSeparator + System.getProperty("java.class.path"));
SyntheticRepository sRepos = SyntheticRepository.getInstance(cp);
JavaClass clazz = sRepos.loadClass(classname);
return clazz;
} catch (ClassNotFoundException e) {
fail("Couldn't find class "+classname+" in the sandbox directory.");
}
return null;
}
public static Signature getClassSignature(Ajc ajc,String classname) {
JavaClass clazz = getClass(ajc,classname);
Signature sigAttr = null;
Attribute[] attrs = clazz.getAttributes();
for (int i = 0; i < attrs.length; i++) {
Attribute attribute = attrs[i];
if (attribute.getName().equals("Signature")) sigAttr = (Signature)attribute;
}
return sigAttr;
}
// Check the signature attribute on a class is correct
public static void verifyClassSignature(Ajc ajc,String classname,String sig) {
Signature sigAttr = getClassSignature(ajc,classname);
assertTrue("Failed to find signature attribute for class "+classname,sigAttr!=null);
assertTrue("Expected signature to be '"+sig+"' but was '"+sigAttr.getSignature()+"'",
sigAttr.getSignature().equals(sig));
}
private static String stringify(Class[] clazzes) {
if (clazzes==null) return "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < clazzes.length; i++) {
if (i>0) sb.append(",");
sb.append(clazzes[i].getName());
}
return sb.toString();
}
}
|
117,614
|
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z
| 2005-11-23T01:40:00Z
|
weaver/src/org/aspectj/weaver/Lint.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
public class Lint {
/* private */ Map kinds = new HashMap();
/* private */ World world;
public final Kind invalidAbsoluteTypeName =
new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}");
public final Kind invalidWildcardTypeName =
new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}");
public final Kind unresolvableMember =
new Kind("unresolvableMember", "can not resolve this member: {0}");
public final Kind typeNotExposedToWeaver =
new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}");
public final Kind shadowNotInStructure =
new Kind("shadowNotInStructure", "the shadow for this join point is not exposed in the structure model: {0}");
public final Kind unmatchedSuperTypeInCall =
new Kind("unmatchedSuperTypeInCall", "does not match because declaring type is {0}, if match desired use target({1})");
public final Kind unmatchedTargetKind =
new Kind("unmatchedTargetKind", "does not match because annotation {0} has @Target{1}");
public final Kind canNotImplementLazyTjp =
new Kind("canNotImplementLazyTjp", "can not implement lazyTjp on this joinpoint {0} because around advice is used");
public final Kind multipleAdviceStoppingLazyTjp =
new Kind("multipleAdviceStoppingLazyTjp", "can not implement lazyTjp at joinpoint {0} because of advice conflicts, see secondary locations to find conflicting advice");
public final Kind needsSerialVersionUIDField =
new Kind("needsSerialVersionUIDField", "serialVersionUID of type {0} needs to be set because of {1}");
public final Kind serialVersionUIDBroken =
new Kind("brokeSerialVersionCompatibility", "serialVersionUID of type {0} is broken because of added field {1}");
public final Kind noInterfaceCtorJoinpoint =
new Kind("noInterfaceCtorJoinpoint","no interface constructor-execution join point - use {0}+ for implementing classes");
public final Kind noJoinpointsForBridgeMethods =
new Kind("noJoinpointsForBridgeMethods","pointcut did not match on the method call to a bridge method. Bridge methods are generated by the compiler and have no join points");
public final Kind enumAsTargetForDecpIgnored =
new Kind("enumAsTargetForDecpIgnored","enum type {0} matches a declare parents type pattern but is being ignored");
public final Kind annotationAsTargetForDecpIgnored =
new Kind("annotationAsTargetForDecpIgnored","annotation type {0} matches a declare parents type pattern but is being ignored");
public final Kind cantMatchArrayTypeOnVarargs =
new Kind("cantMatchArrayTypeOnVarargs","an array type as the last parameter in a signature does not match on the varargs declared method: {0}");
public final Kind adviceDidNotMatch =
new Kind("adviceDidNotMatch","advice defined in {0} has not been applied");
public final Kind invalidTargetForAnnotation =
new Kind("invalidTargetForAnnotation","{0} is not a valid target for annotation {1}, this annotation can only be applied to {2}");
public final Kind elementAlreadyAnnotated =
new Kind("elementAlreadyAnnotated","{0} - already has an annotation of type {1}, cannot add a second instance");
public final Kind runtimeExceptionNotSoftened =
new Kind("runtimeExceptionNotSoftened","{0} will not be softened as it is already a RuntimeException");
public final Kind uncheckedArgument =
new Kind("uncheckedArgument","unchecked match of {0} with {1} when argument is an instance of {2} at join point {3}");
public final Kind uncheckedAdviceConversion =
new Kind("uncheckedAdviceConversion","unchecked conversion when advice applied at shadow {0}, expected {1} but advice uses {2}");
public final Kind noGuardForLazyTjp =
new Kind("noGuardForLazyTjp","can not build thisJoinPoint lazily for this advice since it has no suitable guard. The advice applies at {0}");
public final Kind noExplicitConstructorCall =
new Kind("noExplicitConstructorCall","inter-type constructor does not contain explicit constructor call: field initializers in the target type will not be executed");
public final Kind aspectExcludedByConfiguration =
new Kind("aspectExcludedByConfiguration","aspect {0} exluded for class loader {1}");
public Lint(World world) {
this.world = world;
}
public void setAll(String messageKind) {
setAll(getMessageKind(messageKind));
}
private void setAll(IMessage.Kind messageKind) {
for (Iterator i = kinds.values().iterator(); i.hasNext(); ) {
Kind kind = (Kind)i.next();
kind.setKind(messageKind);
}
}
public void setFromProperties(File file) {
try {
InputStream s = new FileInputStream(file);
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINT_LOAD_ERROR,file.getPath(),ioe.getMessage()));
}
}
public void loadDefaultProperties() {
InputStream s = getClass().getResourceAsStream("XlintDefault.properties");
if (s == null) {
MessageUtil.warn(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_ERROR));
return;
}
try {
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_PROBLEM,ioe.getMessage()));
}
}
private void setFromProperties(InputStream s) throws IOException {
Properties p = new Properties();
p.load(s);
setFromProperties(p);
}
public void setFromProperties(Properties properties) {
for (Iterator i = properties.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
Kind kind = (Kind)kinds.get(entry.getKey());
if (kind == null) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINT_KEY_ERROR,entry.getKey()));
} else {
kind.setKind(getMessageKind((String)entry.getValue()));
}
}
}
public Collection allKinds() {
return kinds.values();
}
public Kind getLintKind(String name) {
return (Kind) kinds.get(name);
}
// temporarily suppress the given lint messages
public void suppressKinds(Collection lintKind) {
for (Iterator iter = lintKind.iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(true);
}
}
// remove any suppression of lint warnings in place
public void clearSuppressions() {
for (Iterator iter = kinds.values().iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(false);
}
}
private IMessage.Kind getMessageKind(String v) {
if (v.equals("ignore")) return null;
else if (v.equals("warning")) return IMessage.WARNING;
else if (v.equals("error")) return IMessage.ERROR;
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINT_VALUE_ERROR,v));
return null;
}
public class Kind {
private String name;
private String message;
private IMessage.Kind kind = IMessage.WARNING;
private boolean isSupressed = false; // by SuppressAjWarnings
public Kind(String name, String message) {
this.name = name;
this.message = message;
kinds.put(this.name, this);
}
public void setSuppressed(boolean shouldBeSuppressed) {
this.isSupressed = shouldBeSuppressed;
}
public boolean isEnabled() {
return (kind != null) && !isSupressed();
}
private boolean isSupressed() {
// can't suppress errors!
return isSupressed && (kind != IMessage.ERROR);
}
public String getName() {
return name;
}
public IMessage.Kind getKind() {
return kind;
}
public void setKind(IMessage.Kind kind) {
this.kind = kind;
}
public void signal(String info, ISourceLocation location) {
if (kind == null) return;
String text = MessageFormat.format(message, new Object[] {info} );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(new Message(text, kind, null, location));
}
public void signal(String[] infos, ISourceLocation location, ISourceLocation[] extraLocations) {
if (kind == null) return;
String text = MessageFormat.format(message, infos );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(
new Message(text, "", kind, location, null, extraLocations));
}
}
}
|
117,614
|
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z
| 2005-11-23T01:40:00Z
|
weaver/src/org/aspectj/weaver/MissingResolvedTypeWithKnownSignature.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.util.Collections;
import java.util.List;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
/**
* When we try to resolve a type in the world that we require to be present,
* and then fail to find it, we return an instance of this class. This class
* defers the production of the "can't find type error" until the first time
* that someone asks a question that can't be answered solely from the signature.
* This enables the weaver to be more tolerant of missing types.
*
*/
public class MissingResolvedTypeWithKnownSignature extends ResolvedType {
private static ResolvedMember[] NO_MEMBERS = new ResolvedMember[0];
private static ResolvedType[] NO_TYPES = new ResolvedType[0];
private boolean issuedCantFindTypeError = false;
private boolean issuedJoinPointWarning = false;
private boolean issuedMissingInterfaceWarning = false;
/**
* @param signature
* @param world
*/
public MissingResolvedTypeWithKnownSignature(String signature, World world) {
super(signature, world);
}
public boolean isMissing() { return true; }
/**
* @param signature
* @param signatureErasure
* @param world
*/
public MissingResolvedTypeWithKnownSignature(String signature,
String signatureErasure, World world) {
super(signature, signatureErasure, world);
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ResolvedType#getDeclaredFields()
*/
public ResolvedMember[] getDeclaredFields() {
raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_FIELDS);
return NO_MEMBERS;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ResolvedType#getDeclaredMethods()
*/
public ResolvedMember[] getDeclaredMethods() {
raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_METHODS);
return NO_MEMBERS;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ResolvedType#getDeclaredInterfaces()
*/
public ResolvedType[] getDeclaredInterfaces() {
raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_INTERFACES);
return NO_TYPES;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ResolvedType#getDeclaredPointcuts()
*/
public ResolvedMember[] getDeclaredPointcuts() {
raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_POINTCUTS);
return NO_MEMBERS;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ResolvedType#getSuperclass()
*/
public ResolvedType getSuperclass() {
raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_SUPERCLASS);
return ResolvedType.MISSING;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ResolvedType#getModifiers()
*/
public int getModifiers() {
raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_MODIFIERS);
return 0;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ResolvedType#getSourceContext()
*/
public ISourceContext getSourceContext() {
return new ISourceContext() {
public ISourceLocation makeSourceLocation(IHasPosition position) {
return null;
}
public ISourceLocation makeSourceLocation(int line, int offset) {
return null;
}
public int getOffset() {
return 0;
}
};
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ResolvedType#isAssignableFrom(org.aspectj.weaver.ResolvedType)
*/
public boolean isAssignableFrom(ResolvedType other) {
raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_ASSIGNABLE,other.getName());
return false;
}
public boolean isAssignableFrom(ResolvedType other, boolean allowMissing) {
if (allowMissing) return false;
else return isAssignableFrom(other);
}
/* (non-Javadoc)
* @see org.aspectj.weaver.ResolvedType#isCoerceableFrom(org.aspectj.weaver.ResolvedType)
*/
public boolean isCoerceableFrom(ResolvedType other) {
raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_COERCEABLE,other.getName());
return false;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.AnnotatedElement#hasAnnotation(org.aspectj.weaver.UnresolvedType)
*/
public boolean hasAnnotation(UnresolvedType ofType) {
raiseCantFindType(WeaverMessages.CANT_FIND_TYPE_ANNOTATION);
return false;
}
public List getInterTypeMungers() {
return Collections.EMPTY_LIST;
}
public List getInterTypeMungersIncludingSupers() {
return Collections.EMPTY_LIST;
}
public List getInterTypeParentMungers() {
return Collections.EMPTY_LIST;
}
public List getInterTypeParentMungersIncludingSupers() {
return Collections.EMPTY_LIST;
}
protected void collectInterTypeMungers(List collector) {
return;
}
public void raiseWarningOnJoinPointSignature(String signature) {
if (issuedJoinPointWarning) return;
String message = WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_JOINPOINT,getName(),signature);
message += "\n" + CompilationAndWeavingContext.getCurrentContext();
MessageUtil.warn(world.getMessageHandler(),message);
issuedJoinPointWarning = true;
}
public void raiseWarningOnMissingInterfaceWhilstFindingMethods() {
if (issuedMissingInterfaceWarning) return;
String message = WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_INTERFACE_METHODS,getName(),signature);
message += "\n" + CompilationAndWeavingContext.getCurrentContext();
MessageUtil.warn(world.getMessageHandler(),message);
issuedMissingInterfaceWarning = true;
}
private void raiseCantFindType(String key) {
if (issuedCantFindTypeError) return;
String message = WeaverMessages.format(key,getName());
message += "\n" + CompilationAndWeavingContext.getCurrentContext();
MessageUtil.error(world.getMessageHandler(),message);
issuedCantFindTypeError = true;
}
private void raiseCantFindType(String key,String insert) {
if (issuedCantFindTypeError) return;
String message = WeaverMessages.format(key,getName(),insert);
message += "\n" + CompilationAndWeavingContext.getCurrentContext();
MessageUtil.error(world.getMessageHandler(),message);
issuedCantFindTypeError = true;
}
}
|
117,614
|
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z
| 2005-11-23T01:40:00Z
|
weaver/src/org/aspectj/weaver/World.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* 2005 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Adrian Colyer, Andy Clement, overhaul for generics
* ******************************************************************/
package org.aspectj.weaver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import org.aspectj.asm.IHierarchy;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.bridge.context.PinpointingMessageHandler;
import org.aspectj.weaver.UnresolvedType.TypeKind;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* A World is a collection of known types and crosscutting members.
*/
public abstract class World implements Dump.INode {
/** handler for any messages produced during resolution etc. */
private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
/** handler for cross-reference information produced during the weaving process */
private ICrossReferenceHandler xrefHandler = null;
/** Currently 'active' scope in which to lookup (resolve) typevariable references */
private TypeVariableDeclaringElement typeVariableLookupScope;
/** The heart of the world, a map from type signatures to resolved types */
protected TypeMap typeMap = new TypeMap(); // Signature to ResolvedType
/** Calculator for working out aspect precedence */
private AspectPrecedenceCalculator precedenceCalculator;
/** All of the type and shadow mungers known to us */
private CrosscuttingMembersSet crosscuttingMembersSet =
new CrosscuttingMembersSet(this);
/** Model holds ASM relationships */
private IHierarchy model = null;
/** for processing Xlint messages */
private Lint lint = new Lint(this);
/** XnoInline option setting passed down to weaver */
private boolean XnoInline;
/** XlazyTjp option setting passed down to weaver */
private boolean XlazyTjp;
/** XhasMember option setting passed down to weaver */
private boolean XhasMember = false;
/** Xpinpoint controls whether we put out developer info showing the source of messages */
private boolean Xpinpoint = false;
/** When behaving in a Java 5 way autoboxing is considered */
private boolean behaveInJava5Way = false;
/**
* A list of RuntimeExceptions containing full stack information for every
* type we couldn't find.
*/
private List dumpState_cantFindTypeExceptions = null;
/**
* Play God.
* On the first day, God created the primitive types and put them in the type
* map.
*/
protected World() {
super();
Dump.registerNode(this.getClass(),this);
typeMap.put("B", ResolvedType.BYTE);
typeMap.put("S", ResolvedType.SHORT);
typeMap.put("I", ResolvedType.INT);
typeMap.put("J", ResolvedType.LONG);
typeMap.put("F", ResolvedType.FLOAT);
typeMap.put("D", ResolvedType.DOUBLE);
typeMap.put("C", ResolvedType.CHAR);
typeMap.put("Z", ResolvedType.BOOLEAN);
typeMap.put("V", ResolvedType.VOID);
precedenceCalculator = new AspectPrecedenceCalculator(this);
}
/**
* Dump processing when a fatal error occurs
*/
public void accept (Dump.IVisitor visitor) {
visitor.visitString("Shadow mungers:");
visitor.visitList(crosscuttingMembersSet.getShadowMungers());
visitor.visitString("Type mungers:");
visitor.visitList(crosscuttingMembersSet.getTypeMungers());
visitor.visitString("Late Type mungers:");
visitor.visitList(crosscuttingMembersSet.getLateTypeMungers());
if (dumpState_cantFindTypeExceptions!=null) {
visitor.visitString("Cant find type problems:");
visitor.visitList(dumpState_cantFindTypeExceptions);
dumpState_cantFindTypeExceptions = null;
}
}
// =============================================================================
// T Y P E R E S O L U T I O N
// =============================================================================
/**
* Resolve a type that we require to be present in the world
*/
public ResolvedType resolve(UnresolvedType ty) {
return resolve(ty, false);
}
/**
* Attempt to resolve a type - the source location gives you some context in which
* resolution is taking place. In the case of an error where we can't find the
* type - we can then at least report why (source location) we were trying to resolve it.
*/
public ResolvedType resolve(UnresolvedType ty,ISourceLocation isl) {
ResolvedType ret = resolve(ty,true);
if (ty == ResolvedType.MISSING) {
IMessage msg = null;
if (isl!=null) {
msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
} else {
msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
}
messageHandler.handleMessage(msg);
}
return ret;
}
/**
* Convenience method for resolving an array of unresolved types
* in one hit. Useful for e.g. resolving type parameters in signatures.
*/
public ResolvedType[] resolve(UnresolvedType[] types) {
if (types == null) return new ResolvedType[0];
ResolvedType[] ret = new ResolvedType[types.length];
for (int i=0; i<types.length; i++) {
ret[i] = resolve(types[i]);
}
return ret;
}
/**
* Resolve a type. This the hub of type resolution. The resolved type is added
* to the type map by signature.
*/
public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) {
// special resolution processing for already resolved types.
if (ty instanceof ResolvedType) {
ResolvedType rty = (ResolvedType) ty;
rty = resolve(rty);
return rty;
}
// dispatch back to the type variable reference to resolve its constituent parts
// don't do this for other unresolved types otherwise you'll end up in a loop
if (ty.isTypeVariableReference()) {
return ty.resolve(this);
}
// if we've already got a resolved type for the signature, just return it
// after updating the world
String signature = ty.getSignature();
ResolvedType ret = typeMap.get(signature);
if (ret != null) {
ret.world = this; // Set the world for the RTX
return ret;
} else if ( signature.equals("?") || signature.equals("*")) {
// might be a problem here, not sure '?' should make it to here as a signature, the
// proper signature for wildcard '?' is '*'
// fault in generic wildcard, can't be done earlier because of init issues
ResolvedType something = new BoundedReferenceType("?",this);
typeMap.put("?",something);
return something;
}
// no existing resolved type, create one
if (ty.isArray()) {
ResolvedType componentType = resolve(ty.getComponentType(),allowMissing);
String brackets = signature.substring(0,signature.lastIndexOf("[")+1);
ret = new ResolvedType.Array(signature, brackets+componentType.getErasureSignature(),
this,
componentType);
} else {
ret = resolveToReferenceType(ty);
if (!allowMissing && ret == ResolvedType.MISSING) {
ret = handleRequiredMissingTypeDuringResolution(ty);
}
}
// Pulling in the type may have already put the right entry in the map
if (typeMap.get(signature)==null && ret != ResolvedType.MISSING) {
typeMap.put(signature, ret);
}
return ret;
}
/**
* We tried to resolve a type and couldn't find it...
*/
private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) {
// defer the message until someone asks a question of the type that we can't answer
// just from the signature.
// MessageUtil.error(messageHandler,
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
if (dumpState_cantFindTypeExceptions==null) {
dumpState_cantFindTypeExceptions = new ArrayList();
}
dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type "+ty.getName()));
return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),this);
}
/**
* Some TypeFactory operations create resolved types directly, but these won't be
* in the typeMap - this resolution process puts them there. Resolved types are
* also told their world which is needed for the special autoboxing resolved types.
*/
public ResolvedType resolve(ResolvedType ty) {
if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs...
ResolvedType resolved = typeMap.get(ty.getSignature());
if (resolved == null) {
typeMap.put(ty.getSignature(), ty);
resolved = ty;
}
resolved.world = this;
return resolved;
}
/**
* Convenience method for finding a type by name and resolving it in one step.
*/
public ResolvedType resolve(String name) {
return resolve(UnresolvedType.forName(name));
}
public ResolvedType resolve(String name,boolean allowMissing) {
return resolve(UnresolvedType.forName(name),allowMissing);
}
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);
if (delegate == null) return ResolvedType.MISSING;
if (delegate.isGeneric() && behaveInJava5Way) {
// ======== raw type ===========
simpleOrRawType.typeKind = TypeKind.RAW;
ReferenceType genericType = makeGenericTypeFrom(delegate,simpleOrRawType);
// name = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(ty.getName()),this);
simpleOrRawType.setDelegate(delegate);
genericType.setDelegate(delegate);
simpleOrRawType.setGenericType(genericType);
return simpleOrRawType;
} else {
// ======== simple type =========
simpleOrRawType.setDelegate(delegate);
return simpleOrRawType;
}
}
}
/**
* Attempt to resolve a type that should be a generic type.
*/
public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) {
// Look up the raw type by signature
String rawSignature = anUnresolvedType.getRawType().getSignature();
ResolvedType rawType = (ResolvedType) typeMap.get(rawSignature);
if (rawType==null) {
rawType = resolve(UnresolvedType.forSignature(rawSignature),false);
typeMap.put(rawSignature,rawType);
}
// Does the raw type know its generic form? (It will if we created the
// raw type from a source type, it won't if its been created just through
// being referenced, e.g. java.util.List
ResolvedType genericType = rawType.getGenericType();
// There is a special case to consider here (testGenericsBang_pr95993 highlights it)
// You may have an unresolvedType for a parameterized type but it
// is backed by a simple type rather than a generic type. This occurs for
// inner types of generic types that inherit their enclosing types
// type variables.
if (rawType.isSimpleType() && (anUnresolvedType.typeParameters==null || anUnresolvedType.typeParameters.length==0)) {
rawType.world = this;
return rawType;
}
if (genericType != null) {
genericType.world = this;
return genericType;
} else {
// Fault in the generic that underpins the raw type ;)
ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType)rawType);
ReferenceType genericRefType = makeGenericTypeFrom(delegate,((ReferenceType)rawType));
((ReferenceType)rawType).setGenericType(genericRefType);
genericRefType.setDelegate(delegate);
((ReferenceType)rawType).setDelegate(delegate);
return genericRefType;
}
}
private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) {
String genericSig = delegate.getDeclaredGenericSignature();
if (genericSig != null) {
return new ReferenceType(
UnresolvedType.forGenericTypeSignature(rawType.getSignature(),delegate.getDeclaredGenericSignature()),this);
} else {
return new ReferenceType(
UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),this);
}
}
/**
* Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType).
*/
private ReferenceType resolveGenericWildcardFor(UnresolvedType aType) {
BoundedReferenceType ret = null;
// FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?)
if (aType.isExtends()) {
ReferenceType upperBound = (ReferenceType)resolve(aType.getUpperBound());
ret = new BoundedReferenceType(upperBound,true,this);
} else if (aType.isSuper()) {
ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound());
ret = new BoundedReferenceType(lowerBound,false,this);
} else {
// must be ? on its own!
}
return ret;
}
/**
* Find the ReferenceTypeDelegate behind this reference type so that it can
* fulfill its contract.
*/
protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty);
/**
* Special resolution for "core" types like OBJECT. These are resolved just like
* any other type, but if they are not found it is more serious and we issue an
* error message immediately.
*/
public ResolvedType getCoreType(UnresolvedType tx) {
ResolvedType coreTy = resolve(tx,true);
if (coreTy == ResolvedType.MISSING) {
MessageUtil.error(messageHandler,
WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName()));
}
return coreTy;
}
/**
* Lookup a type by signature, if not found then build one and put it in the
* map.
*/
public ReferenceType lookupOrCreateName(UnresolvedType ty) {
String signature = ty.getSignature();
ReferenceType ret = lookupBySignature(signature);
if (ret == null) {
ret = ReferenceType.fromTypeX(ty, this);
typeMap.put(signature, ret);
}
return ret;
}
/**
* Lookup a reference type in the world by its signature. Returns
* null if not found.
*/
public ReferenceType lookupBySignature(String signature) {
return (ReferenceType) typeMap.get(signature);
}
// =============================================================================
// T Y P E R E S O L U T I O N -- E N D
// =============================================================================
/**
* Member resolution is achieved by resolving the declaring type and then
* looking up the member in the resolved declaring type.
*/
public ResolvedMember resolve(Member member) {
ResolvedType declaring = member.getDeclaringType().resolve(this);
if (declaring.isRawType()) declaring = declaring.getGenericType();
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = declaring.lookupField(member);
} else {
ret = declaring.lookupMethod(member);
}
if (ret != null) return ret;
return declaring.lookupSyntheticMember(member);
}
// Methods for creating various cross-cutting members...
// ===========================================================
/**
* Create an advice shadow munger from the given advice attribute
*/
public abstract Advice createAdviceMunger(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature);
/**
* Create an advice shadow munger for the given advice kind
*/
public final Advice createAdviceMunger(
AdviceKind kind,
Pointcut p,
Member signature,
int extraParameterFlags,
IHasSourceLocation loc)
{
AjAttribute.AdviceAttribute attribute =
new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext());
return createAdviceMunger(attribute, p, signature);
}
public abstract ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField);
public abstract ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField);
/**
* Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed
* @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind)
*/
public abstract ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind);
public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType);
/**
* Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
*/
public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedence(aspect1, aspect2);
}
/**
* compares by precedence with the additional rule that a super-aspect is
* sorted before its sub-aspects
*/
public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2);
}
// simple property getter and setters
// ===========================================================
/**
* Nobody should hold onto a copy of this message handler, or setMessageHandler won't
* work right.
*/
public IMessageHandler getMessageHandler() {
return messageHandler;
}
public void setMessageHandler(IMessageHandler messageHandler) {
if (this.isInPinpointMode()) {
this.messageHandler = new PinpointingMessageHandler(messageHandler);
} else {
this.messageHandler = messageHandler;
}
}
/**
* convenenience method for creating and issuing messages via the message handler -
* if you supply two locations you will get two messages.
*/
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
if (loc1 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc1));
if (loc2 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
} else {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
}
public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) {
this.xrefHandler = xrefHandler;
}
/**
* Get the cross-reference handler for the world, may be null.
*/
public ICrossReferenceHandler getCrossReferenceHandler() {
return this.xrefHandler;
}
public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) {
this.typeVariableLookupScope = scope;
}
public TypeVariableDeclaringElement getTypeVariableLookupScope() {
return typeVariableLookupScope;
}
public List getDeclareParents() {
return crosscuttingMembersSet.getDeclareParents();
}
public List getDeclareAnnotationOnTypes() {
return crosscuttingMembersSet.getDeclareAnnotationOnTypes();
}
public List getDeclareAnnotationOnFields() {
return crosscuttingMembersSet.getDeclareAnnotationOnFields();
}
public List getDeclareAnnotationOnMethods() {
return crosscuttingMembersSet.getDeclareAnnotationOnMethods();
}
public List getDeclareSoft() {
return crosscuttingMembersSet.getDeclareSofts();
}
public CrosscuttingMembersSet getCrosscuttingMembersSet() {
return crosscuttingMembersSet;
}
public IHierarchy getModel() {
return model;
}
public void setModel(IHierarchy model) {
this.model = model;
}
public Lint getLint() {
return lint;
}
public void setLint(Lint lint) {
this.lint = lint;
}
public boolean isXnoInline() {
return XnoInline;
}
public void setXnoInline(boolean xnoInline) {
XnoInline = xnoInline;
}
public boolean isXlazyTjp() {
return XlazyTjp;
}
public void setXlazyTjp(boolean b) {
XlazyTjp = b;
}
public boolean isHasMemberSupportEnabled() {
return XhasMember;
}
public void setXHasMemberSupportEnabled(boolean b) {
XhasMember = b;
}
public boolean isInPinpointMode() {
return Xpinpoint;
}
public void setPinpointMode(boolean b) {
this.Xpinpoint = b;
}
public void setBehaveInJava5Way(boolean b) {
behaveInJava5Way = b;
}
public boolean isInJava5Mode() {
return behaveInJava5Way;
}
/*
* Map of types in the world, with soft links to expendable ones.
* An expendable type is a reference type that is not exposed to the weaver (ie
* just pulled in for type resolution purposes).
*/
protected static class TypeMap {
/** Map of types that never get thrown away */
private Map tMap = new HashMap();
/** Map of types that may be ejected from the cache if we need space */
private Map expendableMap = new WeakHashMap();
private static final boolean debug = false;
/**
* Add a new type into the map, the key is the type signature.
* Some types do *not* go in the map, these are ones involving
* *member* type variables. The reason is that when all you have is the
* signature which gives you a type variable name, you cannot
* guarantee you are using the type variable in the same way
* as someone previously working with a similarly
* named type variable. So, these do not go into the map:
* - TypeVariableReferenceType.
* - ParameterizedType where a member type variable is involved.
* - BoundedReferenceType when one of the bounds is a type variable.
*
* definition: "member type variables" - a tvar declared on a generic
* method/ctor as opposed to those you see declared on a generic type.
*/
public ResolvedType put(String key, ResolvedType type) {
if (type.isParameterizedType() && type.isParameterizedWithAMemberTypeVariable()) {
if (debug)
System.err.println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="+key+" type="+type);
return type;
}
if (type.isTypeVariableReference()) {
if (debug)
System.err.println("Not putting a type variable reference type into the typemap: key="+key+" type="+type);
return type;
}
// this test should be improved - only avoid putting them in if one of the
// bounds is a member type variable
if (type instanceof BoundedReferenceType) {
if (debug)
System.err.println("Not putting a bounded reference type into the typemap: key="+key+" type="+type);
return type;
}
if (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 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) { }
}
|
117,614
|
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z
| 2005-11-23T01:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
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.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.patterns.ExactTypePattern;
import org.aspectj.weaver.patterns.ExposedState;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* Advice implemented for bcel.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class BcelAdvice extends Advice {
private Test pointcutTest;
private ExposedState exposedState;
private boolean hasMatchedAtLeastOnce = false;
public BcelAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature,
ResolvedType concreteAspect)
{
super(attribute, pointcut, signature);
this.concreteAspect = concreteAspect;
}
// !!! must only be used for testing
public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature,
int extraArgumentFlags,
int start, int end, ISourceContext sourceContext, ResolvedType concreteAspect)
{
this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext),
pointcut, signature, concreteAspect);
thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests
}
// ---- implementations of ShadowMunger's methods
public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) {
suppressLintWarnings(world);
ShadowMunger ret = super.concretize(fromType, world, clause);
clearLintSuppressions(world);
return ret;
}
public ShadowMunger parameterizeWith(ResolvedType declaringType,Map typeVariableMap) {
Pointcut pc = getPointcut().parameterizeWith(typeVariableMap);
BcelAdvice ret = null;
Member adviceSignature = signature;
// allows for around advice where the return value is a type variable (see pr115250)
if (signature instanceof ResolvedMember && signature.getDeclaringType().isGenericType()) {
adviceSignature = ((ResolvedMember)signature).parameterizedWith(declaringType.getTypeParameters(),declaringType,declaringType.isParameterizedType());
}
ret = new BcelAdvice(this.attribute,pc,adviceSignature,this.concreteAspect);
return ret;
}
public boolean match(Shadow shadow, World world) {
suppressLintWarnings(world);
boolean ret = super.match(shadow, world);
clearLintSuppressions(world);
return ret;
}
public void specializeOn(Shadow shadow) {
if (getKind() == AdviceKind.Around) {
((BcelShadow)shadow).initializeForAroundClosure();
}
//XXX this case is just here for supporting lazy test code
if (getKind() == null) {
exposedState = new ExposedState(0);
return;
}
if (getKind().isPerEntry()) {
exposedState = new ExposedState(0);
} else if (getKind().isCflow()) {
exposedState = new ExposedState(nFreeVars);
} else if (getSignature() != null) {
exposedState = new ExposedState(getSignature());
} else {
exposedState = new ExposedState(0);
return; //XXX this case is just here for supporting lazy test code
}
World world = shadow.getIWorld();
suppressLintWarnings(world);
pointcutTest = getPointcut().findResidue(shadow, exposedState);
clearLintSuppressions(world);
// these initializations won't be performed by findResidue, but need to be
// so that the joinpoint is primed for weaving
if (getKind() == AdviceKind.PerThisEntry) {
shadow.getThisVar();
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.getTargetVar();
}
// make sure thisJoinPoint parameters are initialized
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
boolean hasGuardTest = pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around;
boolean isAround = getKind() == AdviceKind.Around;
((BcelShadow)shadow).requireThisJoinPoint(hasGuardTest,isAround);
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
if (!hasGuardTest && world.getLint().multipleAdviceStoppingLazyTjp.isEnabled()) {
// collect up the problematic advice
((BcelShadow)shadow).addAdvicePreventingLazyTjp(this);
}
if (!isAround && !hasGuardTest && world.getLint().noGuardForLazyTjp.isEnabled()) {
// can't build tjp lazily, no suitable test...
world.getLint().noGuardForLazyTjp.signal(
new String[] {shadow.toString()},
getSourceLocation(),
new ISourceLocation[] { ((BcelShadow)shadow).getSourceLocation() }
);
}
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
}
private boolean canInline(Shadow s) {
if (attribute.isProceedInInners()) return false;
//XXX this guard seems to only be needed for bad test cases
if (concreteAspect == null || concreteAspect == ResolvedType.MISSING) return false;
if (concreteAspect.getWorld().isXnoInline()) return false;
//System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState());
return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven();
}
public void implementOn(Shadow s) {
hasMatchedAtLeastOnce=true;
BcelShadow shadow = (BcelShadow) s;
//FIXME AV - see #75442, this logic is not enough so for now comment it out until we fix the bug
// // callback for perObject AJC MightHaveAspect postMunge (#75442)
// if (getConcreteAspect() != null
// && getConcreteAspect().getPerClause() != null
// && PerClause.PEROBJECT.equals(getConcreteAspect().getPerClause().getKind())) {
// final PerObject clause;
// if (getConcreteAspect().getPerClause() instanceof PerFromSuper) {
// clause = (PerObject)((PerFromSuper) getConcreteAspect().getPerClause()).lookupConcretePerClause(getConcreteAspect());
// } else {
// clause = (PerObject) getConcreteAspect().getPerClause();
// }
// if (clause.isThis()) {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getThisVar().getType(), getConcreteAspect());
// } else {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getTargetVar().getType(), getConcreteAspect());
// }
// }
if (getKind() == AdviceKind.Before) {
shadow.weaveBefore(this);
} else if (getKind() == AdviceKind.AfterReturning) {
shadow.weaveAfterReturning(this);
} else if (getKind() == AdviceKind.AfterThrowing) {
UnresolvedType catchType =
hasExtraParameter()
? getExtraParameterType()
: UnresolvedType.THROWABLE;
shadow.weaveAfterThrowing(this, catchType);
} else if (getKind() == AdviceKind.After) {
shadow.weaveAfter(this);
} else if (getKind() == AdviceKind.Around) {
// Note: under regular LTW the aspect is usually loaded after the first use of any class affecteted by it
// This means that as long as the aspect has not been thru the LTW, it's woven state is unknown
// and thus canInline(s) will return false.
// To force inlining (test), ones can do Class aspect = FQNAspect.class in the clinit of the target class
// FIXME AV : for AJC compiled @AJ aspect (or any code style aspect), the woven state can never be known
// if the aspect belongs to a parent classloader. In that case the aspect will never be inlined.
// It might be dangerous to change that especially for @AJ aspect non compiled with AJC since if those
// are not weaved (f.e. use of some limiteed LTW etc) then they cannot be prepared for inlining.
// One solution would be to flag @AJ aspect with an annotation as "prepared" and query that one.
if (!canInline(s)) {
shadow.weaveAroundClosure(this, hasDynamicTests());
} else {
shadow.weaveAroundInline(this, hasDynamicTests());
}
} else if (getKind() == AdviceKind.InterInitializer) {
shadow.weaveAfterReturning(this);
} else if (getKind().isCflow()) {
shadow.weaveCflowEntry(this, getSignature());
} else if (getKind() == AdviceKind.PerThisEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar());
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar());
} else if (getKind() == AdviceKind.Softener) {
shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType());
} else if (getKind() == AdviceKind.PerTypeWithinEntry) {
// PTWIMPL Entry to ptw is the static initialization of a type that matched the ptw type pattern
shadow.weavePerTypeWithinAspectInitialization(this,shadow.getEnclosingType());
} else {
throw new BCException("unimplemented kind: " + getKind());
}
}
// ---- implementations
private Collection collectCheckedExceptions(UnresolvedType[] excs) {
if (excs == null || excs.length == 0) return Collections.EMPTY_LIST;
Collection ret = new ArrayList();
World world = concreteAspect.getWorld();
ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION);
ResolvedType error = world.getCoreType(UnresolvedType.ERROR);
for (int i=0, len=excs.length; i < len; i++) {
ResolvedType t = world.resolve(excs[i],true);
if (t == ResolvedType.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
"",IMessage.ERROR,getSourceLocation(),null,null);
world.getMessageHandler().handleMessage(msg);
}
if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) {
ret.add(t);
}
}
return ret;
}
private Collection thrownExceptions = null;
public Collection getThrownExceptions() {
if (thrownExceptions == null) {
//??? can we really lump in Around here, how does this interact with Throwable
if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness
(getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around))
{
World world = concreteAspect.getWorld();
ResolvedMember m = world.resolve(signature);
if (m == null) {
thrownExceptions = Collections.EMPTY_LIST;
} else {
thrownExceptions = collectCheckedExceptions(m.getExceptions());
}
} else {
thrownExceptions = Collections.EMPTY_LIST;
}
}
return thrownExceptions;
}
/**
* The munger must not check for the advice exceptions to be declared by the shadow in the case
* of @AJ aspects so that around can throws Throwable
*
* @return
*/
public boolean mustCheckExceptions() {
if (getConcreteAspect() == null) {
return true;
}
return !getConcreteAspect().isAnnotationStyleAspect();
}
// only call me after prepare has been called
public boolean hasDynamicTests() {
// if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
// UnresolvedType extraParameterType = getExtraParameterType();
// if (! extraParameterType.equals(UnresolvedType.OBJECT)
// && ! extraParameterType.isPrimitive())
// return true;
// }
return pointcutTest != null &&
!(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST);
}
/**
* get the instruction list for the really simple version of this advice.
* Is broken apart
* for other advice, but if you want it in one block, this is the method to call.
*
* @param s The shadow around which these instructions will eventually live.
* @param extraArgVar The var that will hold the return value or thrown exception
* for afterX advice
* @param ifNoAdvice The instructionHandle to jump to if the dynamic
* tests for this munger fails.
*/
InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice)
{
BcelShadow shadow = (BcelShadow) s;
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// we test to see if we have the right kind of thing...
// after throwing does this just by the exception mechanism.
if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
UnresolvedType extraParameterType = getExtraParameterType();
if (! extraParameterType.equals(UnresolvedType.OBJECT)
&& ! extraParameterType.isPrimitiveType()) {
il.append(
BcelRenderer.renderTest(
fact,
world,
Test.makeInstanceof(
extraArgVar, getExtraParameterType().resolve(world)),
null,
ifNoAdvice,
null));
}
}
il.append(getAdviceArgSetup(shadow, extraArgVar, null));
il.append(getNonTestAdviceInstructions(shadow));
InstructionHandle ifYesAdvice = il.getStart();
il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice));
return il;
}
public InstructionList getAdviceArgSetup(
BcelShadow shadow,
BcelVar extraVar,
InstructionList closureInstantiation)
{
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// if (targetAspectField != null) {
// il.append(fact.createFieldAccess(
// targetAspectField.getDeclaringType().getName(),
// targetAspectField.getName(),
// BcelWorld.makeBcelType(targetAspectField.getType()),
// Constants.GETSTATIC));
// }
//
//System.err.println("BcelAdvice: " + exposedState);
if (exposedState.getAspectInstance() != null) {
il.append(BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance()));
}
final boolean isAnnotationStyleAspect = getConcreteAspect()!=null && getConcreteAspect().isAnnotationStyleAspect();
boolean previousIsClosure = false;
for (int i = 0, len = exposedState.size(); i < len; i++) {
if (exposedState.isErroneousVar(i)) continue; // Erroneous vars have already had error msgs reported!
BcelVar v = (BcelVar) exposedState.get(i);
if (v == null) {
// if not @AJ aspect, go on with the regular binding handling
if (!isAnnotationStyleAspect) {
;
} else {
// ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint
//if (getKind() == AdviceKind.Around) {
// previousIsClosure = true;
// il.append(closureInstantiation);
if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
//make sure we are in an around, since we deal with the closure, not the arg here
if (getKind() != AdviceKind.Around) {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
} else {
if (previousIsClosure) {
il.append(InstructionConstants.DUP);
} else {
previousIsClosure = true;
il.append(closureInstantiation.copy());
}
}
} else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
} else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if (hasExtraParameter()) {
previousIsClosure = false;
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
} else {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
}
}
} else {
UnresolvedType desiredTy = getBindingParameterTypes()[i];
v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
}
}
// ATAJ: for code style aspect, handles the extraFlag as usual ie not
// in the middle of the formal bindings but at the end, in a rock solid ordering
if (!isAnnotationStyleAspect) {
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
// handle thisJoinPoint parameters
// these need to be in that same order as parameters in
// org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
}
return il;
}
public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
return new InstructionList(
Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getOriginalSignature()));
}
public Member getOriginalSignature() {
Member sig = getSignature();
if (sig instanceof ResolvedMember) {
ResolvedMember rsig = (ResolvedMember)sig;
if (rsig.hasBackingGenericMember()) return rsig.getBackingGenericMember();
}
return sig;
}
public InstructionList getTestInstructions(
BcelShadow shadow,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
//System.err.println("test: " + pointcutTest);
return BcelRenderer.renderTest(
shadow.getFactory(),
shadow.getWorld(),
pointcutTest,
sk,
fk,
next);
}
public int compareTo(Object other) {
if (!(other instanceof BcelAdvice)) return 0;
BcelAdvice o = (BcelAdvice)other;
//System.err.println("compareTo: " + this + ", " + o);
if (kind.getPrecedence() != o.kind.getPrecedence()) {
if (kind.getPrecedence() > o.kind.getPrecedence()) return +1;
else return -1;
}
if (kind.isCflow()) {
// System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
// System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1;
else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1;
else return 0;
}
if (kind.isPerEntry() || kind == AdviceKind.Softener) {
return 0;
}
//System.out.println("compare: " + this + " with " + other);
World world = concreteAspect.getWorld();
int ret =
concreteAspect.getWorld().compareByPrecedence(
concreteAspect,
o.concreteAspect);
if (ret != 0) return ret;
ResolvedType declaringAspect = getDeclaringAspect().resolve(world);
ResolvedType o_declaringAspect = o.getDeclaringAspect().resolve(world);
if (declaringAspect == o_declaringAspect) {
if (kind.isAfter() || o.kind.isAfter()) {
return this.getStart() < o.getStart() ? -1: +1;
} else {
return this.getStart()< o.getStart() ? +1: -1;
}
} else if (declaringAspect.isAssignableFrom(o_declaringAspect)) {
return -1;
} else if (o_declaringAspect.isAssignableFrom(declaringAspect)) {
return +1;
} else {
return 0;
}
}
public BcelVar[] getExposedStateAsBcelVars() {
// ATAJ aspect
// the closure instantiation has the same mapping as the extracted method from wich it is called
if (getConcreteAspect()!= null && getConcreteAspect().isAnnotationStyleAspect()) {
return BcelVar.NONE;
}
//System.out.println("vars: " + Arrays.asList(exposedState.vars));
if (exposedState == null) return BcelVar.NONE;
int len = exposedState.vars.length;
BcelVar[] ret = new BcelVar[len];
for (int i=0; i < len; i++) {
ret[i] = (BcelVar)exposedState.vars[i];
}
return ret; //(BcelVar[]) exposedState.vars;
}
public boolean hasMatchedSomething() {
return hasMatchedAtLeastOnce;
}
protected void suppressLintWarnings(World inWorld) {
if (suppressedLintKinds == null) {
if (signature instanceof BcelMethod) {
this.suppressedLintKinds = Utility.getSuppressedWarnings(signature.getAnnotations(), inWorld.getLint());
} else {
this.suppressedLintKinds = Collections.EMPTY_LIST;
}
}
inWorld.getLint().suppressKinds(suppressedLintKinds);
}
protected void clearLintSuppressions(World inWorld) {
inWorld.getLint().clearSuppressions();
}
}
|
117,614
|
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z
| 2005-11-23T01:40:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* 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.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.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 instruciton we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
sources[i].updateTarget(old, fresh);
}
}
}
// 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) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == PreInitialization) { // pr74952
ShadowRange range = getRange();
range.insert(InstructionConstants.NOP,Range.InsideAfter);
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
// Create a store instruction to put the value from the top of the
// stack into a local variable slot. This is a trimmed version of
// what is in initializeArgVars() (since there is only one argument
// at a handler jp and only before advice is supported) (pr46298)
argVars = new BcelVar[1];
int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
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) {
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)
{
InstructionList body = 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 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);
thisJoinPointStaticPartVar =
new BcelFieldRef(
isEnclosingJp?
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$EnclosingStaticPart")):
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart")),
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();
BcelObjectType aspectType = BcelWorld.getBcelObjectType(munger.getConcreteAspect());
String aspectname = munger.getConcreteAspect().getName();
String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect());
entrySuccessInstructions.append(new PUSH(fact.getConstantPool(),t.getName()));
entrySuccessInstructions.append(fact.createInvoke(aspectname,"ajc$createAspectInstance",new ObjectType(aspectname),
new Type[]{new ObjectType("java.lang.String")},Constants.INVOKESTATIC));
entrySuccessInstructions.append(fact.createPutStatic(t.getName(),ptwField,
new ObjectType(aspectname)));
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(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();
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().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 == ResolvedType.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()),
"",IMessage.ERROR,getSourceLocation(),null,
new ISourceLocation[]{ munger.getSourceLocation()});
world.getMessageHandler().handleMessage(msg);
}
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType((declaringType.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())?
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()));
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();
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];
ResolvedType stateTypeX = 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();
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 == ResolvedType.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()),
"",IMessage.ERROR,getSourceLocation(),null,
new ISourceLocation[]{ munger.getSourceLocation()});
world.getMessageHandler().handleMessage(msg);
}
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
stateRTX);
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
// ATAJ for @AJ aspect we need to link the closure with the joinpoint instance
if (munger.getConcreteAspect()!=null && munger.getConcreteAspect().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;
}
}
|
117,614
|
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z
| 2005-11-23T01:40:00Z
|
weaver/src/org/aspectj/weaver/patterns/ArgsAnnotationPointcut.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.ast.Var;
/**
* @author colyer
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class ArgsAnnotationPointcut extends NameBindingPointcut {
private AnnotationPatternList arguments;
private String declarationText;
/**
*
*/
public ArgsAnnotationPointcut(AnnotationPatternList arguments) {
super();
this.arguments = arguments;
this.pointcutKind = ATARGS;
buildDeclarationText();
}
public AnnotationPatternList getArguments() {
return arguments;
}
public Set couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS; // empty args() matches jps with no args
}
public Pointcut parameterizeWith(Map typeVariableMap) {
ArgsAnnotationPointcut ret = new ArgsAnnotationPointcut(arguments.parameterizeWith(typeVariableMap));
ret.copyLocationFrom(this);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo)
*/
public FuzzyBoolean fastMatch(FastMatchInfo info) {
return FuzzyBoolean.MAYBE;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow)
*/
protected FuzzyBoolean matchInternal(Shadow shadow) {
arguments.resolve(shadow.getIWorld());
FuzzyBoolean ret =
arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes()));
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings)
*/
protected void resolveBindings(IScope scope, Bindings bindings) {
if (!scope.getWorld().isInJava5Mode()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ATARGS_ONLY_SUPPORTED_AT_JAVA5_LEVEL),
getSourceLocation()));
return;
}
arguments.resolveBindings(scope, bindings, true);
if (arguments.ellipsisCount > 1) {
scope.message(IMessage.ERROR, this,
"uses more than one .. in args (compiler limitation)");
}
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap)
*/
protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) {
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE),
bindings.getEnclosingAdvice().getSourceLocation(), null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
AnnotationPatternList list = arguments.resolveReferences(bindings);
Pointcut ret = new ArgsAnnotationPointcut(list);
ret.copyLocationFrom(this);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState)
*/
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
int len = shadow.getArgCount();
// do some quick length tests first
int numArgsMatchedByEllipsis = (len + arguments.ellipsisCount) - arguments.size();
if (numArgsMatchedByEllipsis < 0) return Literal.FALSE; // should never happen
if ((numArgsMatchedByEllipsis > 0) && (arguments.ellipsisCount == 0)) {
return Literal.FALSE; // should never happen
}
// now work through the args and the patterns, skipping at ellipsis
Test ret = Literal.TRUE;
int argsIndex = 0;
for (int i = 0; i < arguments.size(); i++) {
if (arguments.get(i) == AnnotationTypePattern.ELLIPSIS) {
// match ellipsisMatchCount args
argsIndex += numArgsMatchedByEllipsis;
} else if (arguments.get(i) == AnnotationTypePattern.ANY) {
argsIndex++;
} else {
// match the argument type at argsIndex with the ExactAnnotationTypePattern
// we know it is exact because nothing else is allowed in args
ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern)arguments.get(i);
UnresolvedType argType = shadow.getArgType(argsIndex);
ResolvedType rArgType = argType.resolve(shadow.getIWorld());
if (rArgType == ResolvedType.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()),
"",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()});
}
ResolvedType rAnnType = ap.getAnnotationType().resolve(shadow.getIWorld());
if (ap instanceof BindingAnnotationTypePattern) {
BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)ap;
Var annvar = shadow.getArgAnnotationVar(argsIndex,rAnnType);
state.set(btp.getFormalIndex(),annvar);
}
if (!ap.matches(rArgType).alwaysTrue()) {
// we need a test...
ret = Test.makeAnd(ret,
Test.makeHasAnnotation(
shadow.getArgVar(argsIndex),
rAnnType));
}
argsIndex++;
}
}
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns()
*/
public List getBindingAnnotationTypePatterns() {
List l = new ArrayList();
AnnotationTypePattern[] pats = arguments.getAnnotationPatterns();
for (int i = 0; i < pats.length; i++) {
if (pats[i] instanceof BindingAnnotationTypePattern) {
l.add(pats[i]);
}
}
return l;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns()
*/
public List getBindingTypePatterns() {
return Collections.EMPTY_LIST;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.ATARGS);
arguments.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
AnnotationPatternList annotationPatternList = AnnotationPatternList.read(s,context);
ArgsAnnotationPointcut ret = new ArgsAnnotationPointcut(annotationPatternList);
ret.readLocation(context, s);
return ret;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (!(obj instanceof ArgsAnnotationPointcut)) return false;
ArgsAnnotationPointcut other = (ArgsAnnotationPointcut) obj;
return other.arguments.equals(arguments);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return 17 + 37*arguments.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
private void buildDeclarationText() {
StringBuffer buf = new StringBuffer("@args");
buf.append(arguments.toString());
this.declarationText = buf.toString();
}
public String toString() { return this.declarationText; }
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
117,614
|
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z
| 2005-11-23T01:40:00Z
|
weaver/src/org/aspectj/weaver/patterns/ArgsPointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.BetaException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
/**
* args(arguments)
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class ArgsPointcut extends NameBindingPointcut {
private static final String ASPECTJ_JP_SIGNATURE_PREFIX = "Lorg/aspectj/lang/JoinPoint";
private static final String ASPECTJ_SYNTHETIC_SIGNATURE_PREFIX = "Lorg/aspectj/runtime/internal/";
private TypePatternList arguments;
private String stringRepresentation;
public ArgsPointcut(TypePatternList arguments) {
this.arguments = arguments;
this.pointcutKind = ARGS;
this.stringRepresentation = "args" + arguments.toString() + "";
}
public TypePatternList getArguments() {
return arguments;
}
public Pointcut parameterizeWith(Map typeVariableMap) {
ArgsPointcut ret = new ArgsPointcut(this.arguments.parameterizeWith(typeVariableMap));
ret.copyLocationFrom(this);
return ret;
}
public Set couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS; // empty args() matches jps with no args
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
ResolvedType[] argumentsToMatchAgainst = getArgumentsToMatchAgainst(shadow);
FuzzyBoolean ret =
arguments.matches(argumentsToMatchAgainst, TypePattern.DYNAMIC);
return ret;
}
private ResolvedType[] getArgumentsToMatchAgainst(Shadow shadow) {
ResolvedType[] argumentsToMatchAgainst = shadow.getIWorld().resolve(shadow.getGenericArgTypes());
// special treatment for adviceexecution which may have synthetic arguments we
// want to ignore.
if (shadow.getKind() == Shadow.AdviceExecution) {
int numExtraArgs = 0;
for (int i = 0; i < argumentsToMatchAgainst.length; i++) {
String argumentSignature = argumentsToMatchAgainst[i].getSignature();
if (argumentSignature.startsWith(ASPECTJ_JP_SIGNATURE_PREFIX) || argumentSignature.startsWith(ASPECTJ_SYNTHETIC_SIGNATURE_PREFIX)) {
numExtraArgs++;
} else {
// normal arg after AJ type means earlier arg was NOT synthetic
numExtraArgs = 0;
}
}
if (numExtraArgs > 0) {
int newArgLength = argumentsToMatchAgainst.length - numExtraArgs;
ResolvedType[] argsSubset = new ResolvedType[newArgLength];
System.arraycopy(argumentsToMatchAgainst, 0, argsSubset, 0, newArgLength);
argumentsToMatchAgainst = argsSubset;
}
} else if (shadow.getKind() == Shadow.ConstructorExecution) {
if (shadow.getMatchingSignature().getParameterTypes().length < argumentsToMatchAgainst.length) {
// there are one or more synthetic args on the end, caused by non-public itd constructor
int newArgLength = shadow.getMatchingSignature().getParameterTypes().length;
ResolvedType[] argsSubset = new ResolvedType[newArgLength];
System.arraycopy(argumentsToMatchAgainst, 0, argsSubset, 0, newArgLength);
argumentsToMatchAgainst = argsSubset;
}
}
return argumentsToMatchAgainst;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns()
*/
public List getBindingAnnotationTypePatterns() {
return Collections.EMPTY_LIST;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns()
*/
public List getBindingTypePatterns() {
List l = new ArrayList();
TypePattern[] pats = arguments.getTypePatterns();
for (int i = 0; i < pats.length; i++) {
if (pats[i] instanceof BindingTypePattern) {
l.add(pats[i]);
}
}
return l;
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.ARGS);
arguments.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
ArgsPointcut ret = new ArgsPointcut(TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public boolean equals(Object other) {
if (!(other instanceof ArgsPointcut)) return false;
ArgsPointcut o = (ArgsPointcut)other;
return o.arguments.equals(this.arguments);
}
public int hashCode() {
return arguments.hashCode();
}
public void resolveBindings(IScope scope, Bindings bindings) {
arguments.resolveBindings(scope, bindings, true, true);
if (arguments.ellipsisCount > 1) {
scope.message(IMessage.ERROR, this,
"uses more than one .. in args (compiler limitation)");
}
}
public void postRead(ResolvedType enclosingType) {
arguments.postRead(enclosingType);
}
public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) {
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ARGS_IN_DECLARE),
bindings.getEnclosingAdvice().getSourceLocation(), null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
TypePatternList args = arguments.resolveReferences(bindings);
if (inAspect.crosscuttingMembers != null) {
inAspect.crosscuttingMembers.exposeTypes(args.getExactTypes());
}
Pointcut ret = new ArgsPointcut(args);
ret.copyLocationFrom(this);
return ret;
}
private Test findResidueNoEllipsis(Shadow shadow, ExposedState state, TypePattern[] patterns) {
ResolvedType[] argumentsToMatchAgainst = getArgumentsToMatchAgainst(shadow);
int len = argumentsToMatchAgainst.length;
//System.err.println("boudn to : " + len + ", " + patterns.length);
if (patterns.length != len) {
return Literal.FALSE;
}
Test ret = Literal.TRUE;
for (int i=0; i < len; i++) {
UnresolvedType argType = shadow.getGenericArgTypes()[i];
TypePattern type = patterns[i];
ResolvedType argRTX = shadow.getIWorld().resolve(argType,true);
if (!(type instanceof BindingTypePattern)) {
if (argRTX == ResolvedType.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()),
"",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()});
shadow.getIWorld().getMessageHandler().handleMessage(msg);
}
if (type.matchesInstanceof(argRTX).alwaysTrue()) {
continue;
}
}
World world = shadow.getIWorld();
ResolvedType typeToExpose = type.getExactType().resolve(world);
if (typeToExpose.isParameterizedType()) {
boolean inDoubt = (type.matchesInstanceof(argRTX) == FuzzyBoolean.MAYBE);
if (inDoubt && world.getLint().uncheckedArgument.isEnabled()) {
String uncheckedMatchWith = typeToExpose.getSimpleBaseName();
if (argRTX.isParameterizedType() && (argRTX.getRawType() == typeToExpose.getRawType())) {
uncheckedMatchWith = argRTX.getSimpleName();
}
if (!isUncheckedArgumentWarningSuppressed()) {
world.getLint().uncheckedArgument.signal(
new String[] {
typeToExpose.getSimpleName(),
uncheckedMatchWith,
typeToExpose.getSimpleBaseName(),
shadow.toResolvedString(world)},
getSourceLocation(),
new ISourceLocation[] {shadow.getSourceLocation()});
}
}
}
ret = Test.makeAnd(ret,
exposeStateForVar(shadow.getArgVar(i), type, state,shadow.getIWorld()));
}
return ret;
}
/**
* We need to find out if someone has put the @SuppressAjWarnings{"uncheckedArgument"}
* annotation somewhere. That somewhere is going to be an a piece of advice that uses this
* pointcut. But how do we find it???
* @return
*/
private boolean isUncheckedArgumentWarningSuppressed() {
return false;
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
ResolvedType[] argsToMatch = getArgumentsToMatchAgainst(shadow);
if (arguments.matches(argsToMatch, TypePattern.DYNAMIC).alwaysFalse()) {
return Literal.FALSE;
}
int ellipsisCount = arguments.ellipsisCount;
if (ellipsisCount == 0) {
return findResidueNoEllipsis(shadow, state, arguments.getTypePatterns());
} else if (ellipsisCount == 1) {
TypePattern[] patternsWithEllipsis = arguments.getTypePatterns();
TypePattern[] patternsWithoutEllipsis = new TypePattern[argsToMatch.length];
int lenWithEllipsis = patternsWithEllipsis.length;
int lenWithoutEllipsis = patternsWithoutEllipsis.length;
// l1+1 >= l0
int indexWithEllipsis = 0;
int indexWithoutEllipsis = 0;
while (indexWithoutEllipsis < lenWithoutEllipsis) {
TypePattern p = patternsWithEllipsis[indexWithEllipsis++];
if (p == TypePattern.ELLIPSIS) {
int newLenWithoutEllipsis =
lenWithoutEllipsis - (lenWithEllipsis-indexWithEllipsis);
while (indexWithoutEllipsis < newLenWithoutEllipsis) {
patternsWithoutEllipsis[indexWithoutEllipsis++] = TypePattern.ANY;
}
} else {
patternsWithoutEllipsis[indexWithoutEllipsis++] = p;
}
}
return findResidueNoEllipsis(shadow, state, patternsWithoutEllipsis);
} else {
throw new BetaException("unimplemented");
}
}
public String toString() {
return this.stringRepresentation;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
117,614
|
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z
| 2005-11-23T01:40:00Z
|
weaver/src/org/aspectj/weaver/patterns/KindedPointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.Checker;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
public class KindedPointcut extends Pointcut {
Shadow.Kind kind;
private SignaturePattern signature;
private Set matchKinds;
private ShadowMunger munger = null; // only set after concretization
public KindedPointcut(
Shadow.Kind kind,
SignaturePattern signature) {
this.kind = kind;
this.signature = signature;
this.pointcutKind = KINDED;
this.matchKinds = new HashSet();
matchKinds.add(kind);
}
public KindedPointcut(
Shadow.Kind kind,
SignaturePattern signature,
ShadowMunger munger) {
this(kind, signature);
this.munger = munger;
}
public SignaturePattern getSignature() {
return signature;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#couldMatchKinds()
*/
public Set couldMatchKinds() {
return matchKinds;
}
public boolean couldEverMatchSameJoinPointsAs(KindedPointcut other) {
if (this.kind != other.kind) return false;
String myName = signature.getName().maybeGetSimpleName();
String yourName = other.signature.getName().maybeGetSimpleName();
if (myName != null && yourName != null) {
if ( !myName.equals(yourName)) {
return false;
}
}
if (signature.getParameterTypes().ellipsisCount == 0) {
if (other.signature.getParameterTypes().ellipsisCount == 0) {
if (signature.getParameterTypes().getTypePatterns().length !=
other.signature.getParameterTypes().getTypePatterns().length) {
return false;
}
}
}
return true;
}
public FuzzyBoolean fastMatch(FastMatchInfo info) {
if (info.getKind() != null) {
if (info.getKind() != kind) return FuzzyBoolean.NO;
}
return FuzzyBoolean.MAYBE;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
if (shadow.getKind() != kind) return FuzzyBoolean.NO;
if (!signature.matches(shadow.getMatchingSignature(), shadow.getIWorld(),this.kind == Shadow.MethodCall)){
if(kind == Shadow.MethodCall) {
warnOnConfusingSig(shadow);
//warnOnBridgeMethod(shadow);
}
return FuzzyBoolean.NO;
}
return FuzzyBoolean.YES;
}
// private void warnOnBridgeMethod(Shadow shadow) {
// if (shadow.getIWorld().getLint().noJoinpointsForBridgeMethods.isEnabled()) {
// ResolvedMember rm = shadow.getSignature().resolve(shadow.getIWorld());
// if (rm!=null) {
// int shadowModifiers = rm.getModifiers(); //shadow.getSignature().getModifiers(shadow.getIWorld());
// if (ResolvedType.hasBridgeModifier(shadowModifiers)) {
// shadow.getIWorld().getLint().noJoinpointsForBridgeMethods.signal(new String[]{},getSourceLocation(),
// new ISourceLocation[]{shadow.getSourceLocation()});
// }
// }
// }
// }
private void warnOnConfusingSig(Shadow shadow) {
// Don't do all this processing if we don't need to !
if (!shadow.getIWorld().getLint().unmatchedSuperTypeInCall.isEnabled()) return;
// no warnings for declare error/warning
if (munger instanceof Checker) return;
World world = shadow.getIWorld();
// warning never needed if the declaring type is any
UnresolvedType exactDeclaringType = signature.getDeclaringType().getExactType();
ResolvedType shadowDeclaringType =
shadow.getSignature().getDeclaringType().resolve(world);
if (signature.getDeclaringType().isStar()
|| exactDeclaringType == ResolvedType.MISSING
|| exactDeclaringType.resolve(world).isMissing())
return;
// warning not needed if match type couldn't ever be the declaring type
if (!shadowDeclaringType.isAssignableFrom(exactDeclaringType.resolve(world))) {
return;
}
// if the method in the declaring type is *not* visible to the
// exact declaring type then warning not needed.
int shadowModifiers = shadow.getSignature().resolve(world).getModifiers();
if (!ResolvedType
.isVisible(
shadowModifiers,
shadowDeclaringType,
exactDeclaringType.resolve(world))) {
return;
}
if (!signature.getReturnType().matchesStatically(shadow.getSignature().getReturnType().resolve(world))) {
// Covariance issue...
// The reason we didn't match is that the type pattern for the pointcut (Car) doesn't match the
// return type for the specific declaration at the shadow. (FastCar Sub.getCar())
// XXX Put out another XLINT in this case?
return;
}
// PR60015 - Don't report the warning if the declaring type is object and 'this' is an interface
if (exactDeclaringType.resolve(world).isInterface() && shadowDeclaringType.equals(world.resolve("java.lang.Object"))) {
return;
}
SignaturePattern nonConfusingPattern =
new SignaturePattern(
signature.getKind(),
signature.getModifiers(),
signature.getReturnType(),
TypePattern.ANY,
signature.getName(),
signature.getParameterTypes(),
signature.getThrowsPattern(),
signature.getAnnotationPattern());
if (nonConfusingPattern
.matches(shadow.getSignature(), shadow.getIWorld(),true)) {
shadow.getIWorld().getLint().unmatchedSuperTypeInCall.signal(
new String[] {
shadow.getSignature().getDeclaringType().toString(),
signature.getDeclaringType().toString()
},
this.getSourceLocation(),
new ISourceLocation[] {shadow.getSourceLocation()} );
}
}
public boolean equals(Object other) {
if (!(other instanceof KindedPointcut)) return false;
KindedPointcut o = (KindedPointcut)other;
return o.kind == this.kind && o.signature.equals(this.signature);
}
public int hashCode() {
int result = 17;
result = 37*result + kind.hashCode();
result = 37*result + signature.hashCode();
return result;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(kind.getSimpleName());
buf.append("(");
buf.append(signature.toString());
buf.append(")");
return buf.toString();
}
public void postRead(ResolvedType enclosingType) {
signature.postRead(enclosingType);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.KINDED);
kind.write(s);
signature.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
Shadow.Kind kind = Shadow.Kind.read(s);
SignaturePattern sig = SignaturePattern.read(s, context);
KindedPointcut ret = new KindedPointcut(kind, sig);
ret.readLocation(context, s);
return ret;
}
// XXX note: there is no namebinding in any kinded pointcut.
// still might want to do something for better error messages
// We want to do something here to make sure we don't sidestep the parameter
// list in capturing type identifiers.
public void resolveBindings(IScope scope, Bindings bindings) {
if (kind == Shadow.Initialization) {
// scope.getMessageHandler().handleMessage(
// MessageUtil.error(
// "initialization unimplemented in 1.1beta1",
// this.getSourceLocation()));
}
signature = signature.resolveBindings(scope, bindings);
if (kind == Shadow.ConstructorExecution) { // Bug fix 60936
if (signature.getDeclaringType() != null) {
World world = scope.getWorld();
UnresolvedType exactType = signature.getDeclaringType().getExactType();
if (signature.getKind() == Member.CONSTRUCTOR &&
!exactType.equals(ResolvedType.MISSING) &&
exactType.resolve(world).isInterface() &&
!signature.getDeclaringType().isIncludeSubtypes()) {
world.getLint().noInterfaceCtorJoinpoint.signal(exactType.toString(), getSourceLocation());
}
}
}
// no parameterized types
if (kind == Shadow.StaticInitialization) {
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getDeclaringType().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_STATIC_INIT_JPS_FOR_PARAMETERIZED_TYPES),
getSourceLocation()));
}
}
// no parameterized types in declaring type position
if ((kind == Shadow.FieldGet) || (kind == Shadow.FieldSet)) {
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getDeclaringType().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.GET_AND_SET_DONT_SUPPORT_DEC_TYPE_PARAMETERS),
getSourceLocation()));
}
// fields can't have a void type!
UnresolvedType returnType = signature.getReturnType().getExactType();
if (returnType == ResolvedType.VOID) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.FIELDS_CANT_HAVE_VOID_TYPE),
getSourceLocation()));
}
}
// no join points for initialization and preinitialization of parameterized types
// no throwable parameterized types
if ((kind == Shadow.Initialization) || (kind == Shadow.PreInitialization)) {
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getDeclaringType().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_INIT_JPS_FOR_PARAMETERIZED_TYPES),
getSourceLocation()));
}
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getThrowsPattern().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES),
getSourceLocation()));
}
}
// no parameterized types in declaring type position
// no throwable parameterized types
if ((kind == Shadow.MethodExecution) || (kind == Shadow.ConstructorExecution)) {
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getDeclaringType().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.EXECUTION_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES),
getSourceLocation()));
}
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getThrowsPattern().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES),
getSourceLocation()));
}
}
// no parameterized types in declaring type position
// no throwable parameterized types
if ((kind == Shadow.MethodCall) || (kind == Shadow.ConstructorCall)) {
HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getDeclaringType().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CALL_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES),
getSourceLocation()));
}
visitor = new HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor();
signature.getThrowsPattern().traverse(visitor, null);
if (visitor.wellHasItThen/*?*/()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.NO_GENERIC_THROWABLES),
getSourceLocation()));
}
}
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
return match(shadow).alwaysTrue() ? Literal.TRUE : Literal.FALSE;
}
public Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) {
Pointcut ret = new KindedPointcut(kind, signature, bindings.getEnclosingAdvice());
ret.copyLocationFrom(this);
return ret;
}
public Pointcut parameterizeWith(Map typeVariableMap) {
Pointcut ret = new KindedPointcut(kind, signature.parameterizeWith(typeVariableMap), munger );
ret.copyLocationFrom(this);
return ret;
}
public Shadow.Kind getKind() {
return kind;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
117,614
|
Bug 117614 ajc crashes on common-logging-1.0.4.jar
|
--- Dump Properties --- Dump file: ajcore.20051122.152749.326.txt Dump reason: org.aspectj.weaver.BCException Dump on exception: true Dump at exit condition: abort ---- Exception Information --- org.aspectj.weaver.BCException: bad resolve of void org.apache.log4j.Category.log(java.lang.String, org.apache.log4j.Level, java.lang.Object, java.lang.Throwable) at org.aspectj.weaver.World.getModifiers(World.java:216) at org.aspectj.weaver.Member.getModifiers(Member.java:406) at org.aspectj.weaver.patterns.KindedPointcut.warnOnConfusingSig(KindedPointcut.java:109) at org.aspectj.weaver.patterns.KindedPointcut.match(KindedPointcut.java:69) at org.aspectj.weaver.patterns.OrPointcut.match(OrPointcut.java:44) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.patterns.AndPointcut.match(AndPointcut.java:43) at org.aspectj.weaver.ShadowMunger.match(ShadowMunger.java:62) at org.aspectj.weaver.Advice.match(Advice.java:91) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:1126) at org.aspectj.weaver.bcel.BcelClassWeaver.matchInvokeInstruction(BcelClassWeaver.java:1115) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:987) at org.aspectj.weaver.bcel.BcelClassWeaver.match(BcelClassWeaver.java:827) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:348) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:83) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:742) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:707) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:634) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:577) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:243) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:383) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:680) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:109) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:60) at org.aspectj.tools.ajc.Main.run(Main.java:291)
|
resolved fixed
|
6eb77c5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-11-24T14:28:27Z
| 2005-11-23T01:40:00Z
|
weaver/src/org/aspectj/weaver/patterns/WithinAnnotationPointcut.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.ast.Var;
/**
* @author colyer
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class WithinAnnotationPointcut extends NameBindingPointcut {
private AnnotationTypePattern annotationTypePattern;
private ShadowMunger munger;
private String declarationText;
/**
*
*/
public WithinAnnotationPointcut(AnnotationTypePattern type) {
super();
this.annotationTypePattern = type;
this.pointcutKind = ATWITHIN;
buildDeclarationText();
}
public WithinAnnotationPointcut(AnnotationTypePattern type, ShadowMunger munger) {
this(type);
this.munger = munger;
this.pointcutKind = ATWITHIN;
}
public AnnotationTypePattern getAnnotationTypePattern() {
return annotationTypePattern;
}
public Set couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS;
}
public Pointcut parameterizeWith(Map typeVariableMap) {
WithinAnnotationPointcut ret = new WithinAnnotationPointcut(this.annotationTypePattern.parameterizeWith(typeVariableMap));
ret.copyLocationFrom(this);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo)
*/
public FuzzyBoolean fastMatch(FastMatchInfo info) {
return annotationTypePattern.fastMatches(info.getType());
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow)
*/
protected FuzzyBoolean matchInternal(Shadow shadow) {
ResolvedType enclosingType = shadow.getIWorld().resolve(shadow.getEnclosingType(),true);
if (enclosingType == ResolvedType.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_WITHINPCD,
shadow.getEnclosingType().getName()),
shadow.getSourceLocation(),true,new ISourceLocation[]{getSourceLocation()});
shadow.getIWorld().getMessageHandler().handleMessage(msg);
}
annotationTypePattern.resolve(shadow.getIWorld());
return annotationTypePattern.matches(enclosingType);
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings)
*/
protected void resolveBindings(IScope scope, Bindings bindings) {
if (!scope.getWorld().isInJava5Mode()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ATWITHIN_ONLY_SUPPORTED_AT_JAVA5_LEVEL),
getSourceLocation()));
return;
}
annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true);
// must be either a Var, or an annotation type pattern
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap)
*/
protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) {
ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings);
Pointcut ret = new WithinAnnotationPointcut(newType, bindings.getEnclosingAdvice());
ret.copyLocationFrom(this);
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState)
*/
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
if (annotationTypePattern instanceof BindingAnnotationTypePattern) {
BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern;
UnresolvedType annotationType = btp.annotationType;
Var var = shadow.getWithinAnnotationVar(annotationType);
// This should not happen, we shouldn't have gotten this far
// if we weren't going to find the annotation
if (var == null)
throw new BCException("Impossible! annotation=["+annotationType+
"] shadow=["+shadow+" at "+shadow.getSourceLocation()+
"] pointcut is at ["+getSourceLocation()+"]");
state.set(btp.getFormalIndex(),var);
}
return Literal.TRUE;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns()
*/
public List getBindingAnnotationTypePatterns() {
if (annotationTypePattern instanceof BindingAnnotationTypePattern) {
List l = new ArrayList();
l.add(annotationTypePattern);
return l;
} else return Collections.EMPTY_LIST;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns()
*/
public List getBindingTypePatterns() {
return Collections.EMPTY_LIST;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.ATWITHIN);
annotationTypePattern.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
AnnotationTypePattern type = AnnotationTypePattern.read(s, context);
WithinAnnotationPointcut ret = new WithinAnnotationPointcut((ExactAnnotationTypePattern)type);
ret.readLocation(context, s);
return ret;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (!(obj instanceof WithinAnnotationPointcut)) return false;
WithinAnnotationPointcut other = (WithinAnnotationPointcut) obj;
return other.annotationTypePattern.equals(this.annotationTypePattern);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return 17 + 19*annotationTypePattern.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
private void buildDeclarationText() {
StringBuffer buf = new StringBuffer();
buf.append("@within(");
String annPatt = annotationTypePattern.toString();
buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt);
buf.append(")");
this.declarationText = buf.toString();
}
public String toString() {
return this.declarationText;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.