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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
88,862 |
Bug 88862 Declare annotation on ITDs
|
I'll use this bug to capture info on the implementation...
|
resolved fixed
|
0d14ccf
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-03-23T21:31:49Z | 2005-03-23T15:00:00Z |
weaver/src/org/aspectj/weaver/patterns/SignaturePattern.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.AdviceSignature;
import org.aspectj.lang.reflect.ConstructorSignature;
import org.aspectj.lang.reflect.FieldSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.Constants;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.World;
public class SignaturePattern extends PatternNode {
private Member.Kind kind;
private ModifiersPattern modifiers;
private TypePattern returnType;
private TypePattern declaringType;
private NamePattern name;
private TypePatternList parameterTypes;
private ThrowsPattern throwsPattern;
private AnnotationTypePattern annotationPattern;
public SignaturePattern(Member.Kind kind, ModifiersPattern modifiers,
TypePattern returnType, TypePattern declaringType,
NamePattern name, TypePatternList parameterTypes,
ThrowsPattern throwsPattern,
AnnotationTypePattern annotationPattern) {
this.kind = kind;
this.modifiers = modifiers;
this.returnType = returnType;
this.name = name;
this.declaringType = declaringType;
this.parameterTypes = parameterTypes;
this.throwsPattern = throwsPattern;
this.annotationPattern = annotationPattern;
}
public SignaturePattern resolveBindings(IScope scope, Bindings bindings) {
if (returnType != null) {
returnType = returnType.resolveBindings(scope, bindings, false, false);
}
if (declaringType != null) {
declaringType = declaringType.resolveBindings(scope, bindings, false, false);
}
if (parameterTypes != null) {
parameterTypes = parameterTypes.resolveBindings(scope, bindings, false, false);
}
if (throwsPattern != null) {
throwsPattern = throwsPattern.resolveBindings(scope, bindings);
}
if (annotationPattern != null) {
annotationPattern = annotationPattern.resolveBindings(scope,bindings,false);
}
return this;
}
public SignaturePattern resolveBindingsFromRTTI() {
if (returnType != null) {
returnType = returnType.resolveBindingsFromRTTI(false, false);
}
if (declaringType != null) {
declaringType = declaringType.resolveBindingsFromRTTI(false, false);
}
if (parameterTypes != null) {
parameterTypes = parameterTypes.resolveBindingsFromRTTI(false, false);
}
if (throwsPattern != null) {
throwsPattern = throwsPattern.resolveBindingsFromRTTI();
}
return this;
}
public void postRead(ResolvedTypeX enclosingType) {
if (returnType != null) {
returnType.postRead(enclosingType);
}
if (declaringType != null) {
declaringType.postRead(enclosingType);
}
if (parameterTypes != null) {
parameterTypes.postRead(enclosingType);
}
}
public boolean matches(Member member, World world) {
return (matchesIgnoringAnnotations(member,world) &&
matchesAnnotations(member,world));
}
public boolean matchesAnnotations(Member member,World world) {
ResolvedMember rMember = member.resolve(world);
if (rMember == null) {
if (member.getName().startsWith(NameMangler.PREFIX)) {
return false;
}
world.getLint().unresolvableMember.signal(member.toString(), getSourceLocation());
return false;
}
annotationPattern.resolve(world);
return annotationPattern.matches(rMember).alwaysTrue();
}
public boolean matchesIgnoringAnnotations(Member member, World world) {
//XXX performance gains would come from matching on name before resolving
// to fail fast. ASC 30th Nov 04 => Not necessarily, it didn't make it faster for me.
// Here is the code I used:
// String n1 = member.getName();
// String n2 = this.getName().maybeGetSimpleName();
// if (n2!=null && !n1.equals(n2)) return false;
// FIXME ASC :
if (member == null) return false;
ResolvedMember sig = member.resolve(world);
if (sig == null) {
//XXX
if (member.getName().startsWith(NameMangler.PREFIX)) {
return false;
}
world.getLint().unresolvableMember.signal(member.toString(), getSourceLocation());
return false;
}
// Java5 introduces bridge methods, we don't want to match on them at all...
if (sig.isBridgeMethod()) {
return false;
}
// This check should only matter when used from WithincodePointcut as KindedPointcut
// has already effectively checked this with the shadows kind.
if (kind != member.getKind()) {
return false;
}
if (kind == Member.ADVICE) return true;
if (!modifiers.matches(sig.getModifiers())) return false;
if (kind == Member.STATIC_INITIALIZATION) {
//System.err.println("match static init: " + sig.getDeclaringType() + " with " + this);
return declaringType.matchesStatically(sig.getDeclaringType().resolve(world));
} else if (kind == Member.FIELD) {
if (!returnType.matchesStatically(sig.getReturnType().resolve(world))) return false;
if (!name.matches(sig.getName())) return false;
boolean ret = declaringTypeMatch(member.getDeclaringType(), member, world);
//System.out.println(" ret: " + ret);
return ret;
} else if (kind == Member.METHOD) {
// Change all this in the face of covariance...
// Check the name
if (!name.matches(sig.getName())) return false;
// Check the parameters
if (!parameterTypes.matches(world.resolve(sig.getParameterTypes()), TypePattern.STATIC).alwaysTrue()) {
return false;
}
// If we have matched on parameters, let's just check it isn't because the last parameter in the pattern
// is an array type and the method is declared with varargs
// XXX - Ideally the shadow would be included in the msg but we don't know it...
if (isNotMatchBecauseOfVarargsIssue(parameterTypes,sig.getModifiers())) {
world.getLint().cantMatchArrayTypeOnVarargs.signal(sig.toString(),getSourceLocation());
return false;
}
if (parameterTypes.size()>0 && (sig.isVarargsMethod()^parameterTypes.get(parameterTypes.size()-1).isVarArgs))
return false;
// Check the throws pattern
if (!throwsPattern.matches(sig.getExceptions(), world)) return false;
return declaringTypeMatchAllowingForCovariance(member,world,returnType,sig.getReturnType().resolve(world));
} else if (kind == Member.CONSTRUCTOR) {
if (!parameterTypes.matches(world.resolve(sig.getParameterTypes()), TypePattern.STATIC).alwaysTrue()) {
return false;
}
// If we have matched on parameters, let's just check it isn't because the last parameter in the pattern
// is an array type and the method is declared with varargs
// XXX - Ideally the shadow would be included in the msg but we don't know it...
if (isNotMatchBecauseOfVarargsIssue(parameterTypes,sig.getModifiers())) {
world.getLint().cantMatchArrayTypeOnVarargs.signal(sig.toString(),getSourceLocation());
return false;
}
if (!throwsPattern.matches(sig.getExceptions(), world)) return false;
return declaringType.matchesStatically(member.getDeclaringType().resolve(world));
//return declaringTypeMatch(member.getDeclaringType(), member, world);
}
return false;
}
public boolean declaringTypeMatchAllowingForCovariance(Member member,World world,TypePattern returnTypePattern,ResolvedTypeX sigReturn) {
TypeX onTypeUnresolved = member.getDeclaringType();
ResolvedTypeX onType = onTypeUnresolved.resolve(world);
// fastmatch
if (declaringType.matchesStatically(onType) && returnTypePattern.matchesStatically(sigReturn))
return true;
Collection declaringTypes = member.getDeclaringTypes(world);
boolean checkReturnType = true;
// XXX Possible enhancement? Doesn't seem to speed things up
// if (returnTypePattern.isStar()) {
// if (returnTypePattern instanceof WildTypePattern) {
// if (((WildTypePattern)returnTypePattern).getDimensions()==0) checkReturnType = false;
// }
// }
// Sometimes that list includes types that don't explicitly declare the member we are after -
// they are on the list because their supertype is on the list, that's why we use
// lookupMethod rather than lookupMemberNoSupers()
for (Iterator i = declaringTypes.iterator(); i.hasNext(); ) {
ResolvedTypeX type = (ResolvedTypeX)i.next();
if (declaringType.matchesStatically(type)) {
if (!checkReturnType) return true;
ResolvedMember rm = type.lookupMethod(member);
if (rm==null) rm = type.lookupMethodInITDs(member); // It must be in here, or we have *real* problems
TypeX returnTypeX = rm.getReturnType();
ResolvedTypeX returnType = returnTypeX.resolve(world);
if (returnTypePattern.matchesStatically(returnType)) return true;
}
}
return false;
}
// for dynamic join point matching
public boolean matches(JoinPoint.StaticPart jpsp) {
Signature sig = jpsp.getSignature();
if (kind == Member.ADVICE && !(sig instanceof AdviceSignature)) return false;
if (kind == Member.CONSTRUCTOR && !(sig instanceof ConstructorSignature)) return false;
if (kind == Member.FIELD && !(sig instanceof FieldSignature)) return false;
if (kind == Member.METHOD && !(sig instanceof MethodSignature)) return false;
if (kind == Member.STATIC_INITIALIZATION && !(jpsp.getKind().equals(JoinPoint.STATICINITIALIZATION))) return false;
if (kind == Member.POINTCUT) return false;
if (kind == Member.ADVICE) return true;
if (!modifiers.matches(sig.getModifiers())) return false;
if (kind == Member.STATIC_INITIALIZATION) {
//System.err.println("match static init: " + sig.getDeclaringType() + " with " + this);
return declaringType.matchesStatically(sig.getDeclaringType());
} else if (kind == Member.FIELD) {
Class returnTypeClass = ((FieldSignature)sig).getFieldType();
if (!returnType.matchesStatically(returnTypeClass)) return false;
if (!name.matches(sig.getName())) return false;
boolean ret = declaringTypeMatch(sig);
//System.out.println(" ret: " + ret);
return ret;
} else if (kind == Member.METHOD) {
MethodSignature msig = ((MethodSignature)sig);
Class returnTypeClass = msig.getReturnType();
Class[] params = msig.getParameterTypes();
Class[] exceptionTypes = msig.getExceptionTypes();
if (!returnType.matchesStatically(returnTypeClass)) return false;
if (!name.matches(sig.getName())) return false;
if (!parameterTypes.matches(params, TypePattern.STATIC).alwaysTrue()) {
return false;
}
if (isNotMatchBecauseOfVarargsIssue(parameterTypes,msig.getModifiers())) { return false; }
if (!throwsPattern.matches(exceptionTypes)) return false;
return declaringTypeMatch(sig); // XXXAJ5 - Need to make this a covariant aware version for dynamic JP matching to work
} else if (kind == Member.CONSTRUCTOR) {
ConstructorSignature csig = (ConstructorSignature)sig;
Class[] params = csig.getParameterTypes();
Class[] exceptionTypes = csig.getExceptionTypes();
if (!parameterTypes.matches(params, TypePattern.STATIC).alwaysTrue()) {
return false;
}
if (isNotMatchBecauseOfVarargsIssue(parameterTypes,csig.getModifiers())) { return false; }
if (!throwsPattern.matches(exceptionTypes)) return false;
return declaringType.matchesStatically(sig.getDeclaringType());
//return declaringTypeMatch(member.getDeclaringType(), member, world);
}
return false;
}
public boolean matches(Class declaringClass, java.lang.reflect.Member member) {
if (kind == Member.ADVICE) return true;
if (kind == Member.POINTCUT) return false;
if ((member != null) && !(modifiers.matches(member.getModifiers()))) return false;
if (kind == Member.STATIC_INITIALIZATION) {
return declaringType.matchesStatically(declaringClass);
}
if (kind == Member.FIELD) {
if (!(member instanceof Field)) return false;
Class fieldTypeClass = ((Field)member).getType();
if (!returnType.matchesStatically(fieldTypeClass)) return false;
if (!name.matches(member.getName())) return false;
return declaringTypeMatch(member.getDeclaringClass());
}
if (kind == Member.METHOD) {
if (! (member instanceof Method)) return false;
Class returnTypeClass = ((Method)member).getReturnType();
Class[] params = ((Method)member).getParameterTypes();
Class[] exceptionTypes = ((Method)member).getExceptionTypes();
if (!returnType.matchesStatically(returnTypeClass)) return false;
if (!name.matches(member.getName())) return false;
if (!parameterTypes.matches(params, TypePattern.STATIC).alwaysTrue()) {
return false;
}
if (isNotMatchBecauseOfVarargsIssue(parameterTypes,member.getModifiers())) { return false; }
if (!throwsPattern.matches(exceptionTypes)) return false;
return declaringTypeMatch(member.getDeclaringClass()); // XXXAJ5 - Need to make this a covariant aware version for dynamic JP matching to work
}
if (kind == Member.CONSTRUCTOR) {
if (! (member instanceof Constructor)) return false;
Class[] params = ((Constructor)member).getParameterTypes();
Class[] exceptionTypes = ((Constructor)member).getExceptionTypes();
if (!parameterTypes.matches(params, TypePattern.STATIC).alwaysTrue()) {
return false;
}
if (isNotMatchBecauseOfVarargsIssue(parameterTypes,member.getModifiers())) { return false; }
if (!throwsPattern.matches(exceptionTypes)) return false;
return declaringType.matchesStatically(declaringClass);
}
return false;
}
// For methods, the above covariant aware version (declaringTypeMatchAllowingForCovariance) is used - this version is still here for fields
private boolean declaringTypeMatch(TypeX onTypeUnresolved, Member member, World world) {
ResolvedTypeX onType = onTypeUnresolved.resolve(world);
// fastmatch
if (declaringType.matchesStatically(onType)) return true;
Collection declaringTypes = member.getDeclaringTypes(world);
for (Iterator i = declaringTypes.iterator(); i.hasNext(); ) {
ResolvedTypeX type = (ResolvedTypeX)i.next();
if (declaringType.matchesStatically(type)) return true;
}
return false;
}
private boolean declaringTypeMatch(Signature sig) {
Class onType = sig.getDeclaringType();
if (declaringType.matchesStatically(onType)) return true;
Collection declaringTypes = getDeclaringTypes(sig);
for (Iterator it = declaringTypes.iterator(); it.hasNext(); ) {
Class pClass = (Class) it.next();
if (declaringType.matchesStatically(pClass)) return true;
}
return false;
}
private boolean declaringTypeMatch(Class clazz) {
if (clazz == null) return false;
if (declaringType.matchesStatically(clazz)) return true;
Class[] ifs = clazz.getInterfaces();
for (int i = 0; i<ifs.length; i++) {
if (declaringType.matchesStatically(ifs[i])) return true;
}
return declaringTypeMatch(clazz.getSuperclass());
}
private Collection getDeclaringTypes(Signature sig) {
List l = new ArrayList();
Class onType = sig.getDeclaringType();
String memberName = sig.getName();
if (sig instanceof FieldSignature) {
Class fieldType = ((FieldSignature)sig).getFieldType();
Class superType = onType;
while(superType != null) {
try {
Field f = (superType.getDeclaredField(memberName));
if (f.getType() == fieldType) {
l.add(superType);
}
} catch (NoSuchFieldException nsf) {}
superType = superType.getSuperclass();
}
} else if (sig instanceof MethodSignature) {
Class[] paramTypes = ((MethodSignature)sig).getParameterTypes();
Class superType = onType;
while(superType != null) {
try {
Method m = (superType.getDeclaredMethod(memberName,paramTypes));
l.add(superType);
} catch (NoSuchMethodException nsm) {}
superType = superType.getSuperclass();
}
}
return l;
}
public NamePattern getName() { return name; }
public TypePattern getDeclaringType() { return declaringType; }
public Member.Kind getKind() {
return kind;
}
public String toString() {
StringBuffer buf = new StringBuffer();
if (annotationPattern != AnnotationTypePattern.ANY) {
buf.append(annotationPattern.toString());
buf.append(' ');
}
if (modifiers != ModifiersPattern.ANY) {
buf.append(modifiers.toString());
buf.append(' ');
}
if (kind == Member.STATIC_INITIALIZATION) {
buf.append(declaringType.toString());
buf.append(".<clinit>()");
} else if (kind == Member.HANDLER) {
buf.append("handler(");
buf.append(parameterTypes.get(0));
buf.append(")");
} else {
if (!(kind == Member.CONSTRUCTOR)) {
buf.append(returnType.toString());
buf.append(' ');
}
if (declaringType != TypePattern.ANY) {
buf.append(declaringType.toString());
buf.append('.');
}
if (kind == Member.CONSTRUCTOR) {
buf.append("new");
} else {
buf.append(name.toString());
}
if (kind == Member.METHOD || kind == Member.CONSTRUCTOR) {
buf.append(parameterTypes.toString());
}
}
return buf.toString();
}
public boolean equals(Object other) {
if (!(other instanceof SignaturePattern)) return false;
SignaturePattern o = (SignaturePattern)other;
return o.kind.equals(this.kind)
&& o.modifiers.equals(this.modifiers)
&& o.returnType.equals(this.returnType)
&& o.declaringType.equals(this.declaringType)
&& o.name.equals(this.name)
&& o.parameterTypes.equals(this.parameterTypes)
&& o.throwsPattern.equals(this.throwsPattern)
&& o.annotationPattern.equals(this.annotationPattern);
}
public int hashCode() {
int result = 17;
result = 37*result + kind.hashCode();
result = 37*result + modifiers.hashCode();
result = 37*result + returnType.hashCode();
result = 37*result + declaringType.hashCode();
result = 37*result + name.hashCode();
result = 37*result + parameterTypes.hashCode();
result = 37*result + throwsPattern.hashCode();
result = 37*result + annotationPattern.hashCode();
return result;
}
public void write(DataOutputStream s) throws IOException {
kind.write(s);
modifiers.write(s);
returnType.write(s);
declaringType.write(s);
name.write(s);
parameterTypes.write(s);
throwsPattern.write(s);
annotationPattern.write(s);
writeLocation(s);
}
public static SignaturePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException {
Member.Kind kind = Member.Kind.read(s);
ModifiersPattern modifiers = ModifiersPattern.read(s);
TypePattern returnType = TypePattern.read(s, context);
TypePattern declaringType = TypePattern.read(s, context);
NamePattern name = NamePattern.read(s);
TypePatternList parameterTypes = TypePatternList.read(s, context);
ThrowsPattern throwsPattern = ThrowsPattern.read(s, context);
AnnotationTypePattern annotationPattern = AnnotationTypePattern.ANY;
if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) {
annotationPattern = AnnotationTypePattern.read(s,context);
}
SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType,
name, parameterTypes, throwsPattern,annotationPattern);
ret.readLocation(context, s);
return ret;
}
/**
* @return
*/
public ModifiersPattern getModifiers() {
return modifiers;
}
/**
* @return
*/
public TypePatternList getParameterTypes() {
return parameterTypes;
}
/**
* @return
*/
public TypePattern getReturnType() {
return returnType;
}
/**
* @return
*/
public ThrowsPattern getThrowsPattern() {
return throwsPattern;
}
/**
* return true if last argument in params is an Object[] but the modifiers say this method
* was declared with varargs (Object...). We shouldn't be matching if this is the case.
*/
private boolean isNotMatchBecauseOfVarargsIssue(TypePatternList params,int modifiers) {
if (params.size()>0 && (modifiers & Constants.ACC_VARARGS)!=0) {
// we have at least one parameter in the pattern list, and the method has a varargs signature
TypePattern lastPattern = params.get(params.size()-1);
if (lastPattern.isArray() && !lastPattern.isVarArgs) return true;
}
return false;
}
public AnnotationTypePattern getAnnotationPattern() {
return annotationPattern;
}
public boolean isStarAnnotation() {
return annotationPattern == AnnotationTypePattern.ANY;
}
}
|
85,297 |
Bug 85297 Improvements to incremental compilation
| null |
resolved fixed
|
e460b1e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-05T14:50:06Z | 2005-02-15T17:53:20Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.aspectj.org.eclipse.jdt.internal.core.builder.ReferenceCollection;
import org.aspectj.org.eclipse.jdt.internal.core.builder.StringSet;
/**
* Holds state needed for incremental compilation
*/
public class AjState {
AjBuildManager buildManager;
long lastSuccessfulBuildTime = -1;
long currentBuildTime = -1;
AjBuildConfig buildConfig;
AjBuildConfig newBuildConfig;
// Map/*<File, List<UnwovenClassFile>*/ classesFromFile = new HashMap();
Map/*<File, CompilationResult*/ resultsFromFile = new HashMap();
Map/*<File, ReferenceCollection>*/ references = new HashMap();
Map/*File, List<UnwovenClassFile>*/ binarySourceFiles = new HashMap();
Map/*<String, UnwovenClassFile>*/ classesFromName = new HashMap();
List/*File*/ compiledSourceFiles = new ArrayList();
List/*String*/ resources = new ArrayList();
ArrayList/*<String>*/ qualifiedStrings;
ArrayList/*<String>*/ simpleStrings;
Set addedFiles;
Set deletedFiles;
Set /*BinarySourceFile*/addedBinaryFiles;
Set /*BinarySourceFile*/deletedBinaryFiles;
List addedClassFiles;
public AjState(AjBuildManager buildManager) {
this.buildManager = buildManager;
}
void successfulCompile(AjBuildConfig config) {
buildConfig = config;
lastSuccessfulBuildTime = currentBuildTime;
}
/**
* Returns false if a batch build is needed.
*/
boolean prepareForNextBuild(AjBuildConfig newBuildConfig) {
currentBuildTime = System.currentTimeMillis();
addedClassFiles = new ArrayList();
if (lastSuccessfulBuildTime == -1 || buildConfig == null) {
return false;
}
// we don't support incremental with an outjar yet
if (newBuildConfig.getOutputJar() != null) return false;
// we can't do an incremental build if one of our paths
// has changed, or a jar on a path has been modified
if (pathChange(buildConfig,newBuildConfig)) {
// last time we built, .class files and resource files from jars on the
// inpath will have been copied to the output directory.
// these all need to be deleted in preparation for the clean build that is
// coming - otherwise a file that has been deleted from an inpath jar
// since the last build will not be deleted from the output directory.
removeAllResultsOfLastBuild();
return false;
}
simpleStrings = new ArrayList();
qualifiedStrings = new ArrayList();
Set oldFiles = new HashSet(buildConfig.getFiles());
Set newFiles = new HashSet(newBuildConfig.getFiles());
addedFiles = new HashSet(newFiles);
addedFiles.removeAll(oldFiles);
deletedFiles = new HashSet(oldFiles);
deletedFiles.removeAll(newFiles);
Set oldBinaryFiles = new HashSet(buildConfig.getBinaryFiles());
Set newBinaryFiles = new HashSet(newBuildConfig.getBinaryFiles());
addedBinaryFiles = new HashSet(newBinaryFiles);
addedBinaryFiles.removeAll(oldBinaryFiles);
deletedBinaryFiles = new HashSet(oldBinaryFiles);
deletedBinaryFiles.removeAll(newBinaryFiles);
this.newBuildConfig = newBuildConfig;
return true;
}
private Collection getModifiedFiles() {
return getModifiedFiles(lastSuccessfulBuildTime);
}
Collection getModifiedFiles(long lastBuildTime) {
List ret = new ArrayList();
//not our job to account for new and deleted files
for (Iterator i = buildConfig.getFiles().iterator(); i.hasNext(); ) {
File file = (File)i.next();
if (!file.exists()) continue;
long modTime = file.lastModified();
//System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime);
// need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms
if (modTime + 1000 >= lastBuildTime) {
ret.add(file);
}
}
return ret;
}
private Collection getModifiedBinaryFiles() {
return getModifiedBinaryFiles(lastSuccessfulBuildTime);
}
Collection getModifiedBinaryFiles(long lastBuildTime) {
List ret = new ArrayList();
//not our job to account for new and deleted files
for (Iterator i = buildConfig.getBinaryFiles().iterator(); i.hasNext(); ) {
AjBuildConfig.BinarySourceFile bsfile = (AjBuildConfig.BinarySourceFile)i.next();
File file = bsfile.binSrc;
if (!file.exists()) continue;
long modTime = file.lastModified();
//System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime);
// need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms
if (modTime + 1000 >= lastBuildTime) {
ret.add(bsfile);
}
}
return ret;
}
private boolean classFileChangedInDirSinceLastBuild(File dir) {
File[] classFiles = FileUtil.listFiles(dir, new FileFilter(){
public boolean accept(File pathname) {
return pathname.getName().endsWith(".class");
}
});
for (int i = 0; i < classFiles.length; i++) {
long modTime = classFiles[i].lastModified();
if (modTime + 1000 >= lastSuccessfulBuildTime) return true;
}
return false;
}
private boolean pathChange(AjBuildConfig oldConfig, AjBuildConfig newConfig) {
boolean changed = false;
List oldClasspath = oldConfig.getClasspath();
List newClasspath = newConfig.getClasspath();
if (changed(oldClasspath,newClasspath,true)) return true;
List oldAspectpath = oldConfig.getAspectpath();
List newAspectpath = newConfig.getAspectpath();
if (changed(oldAspectpath,newAspectpath,true)) return true;
List oldInJars = oldConfig.getInJars();
List newInJars = newConfig.getInJars();
if (changed(oldInJars,newInJars,false)) return true;
List oldInPath = oldConfig.getInpath();
List newInPath = newConfig.getInpath();
if (changed(oldInPath, newInPath,false)) return true;
return changed;
}
private boolean changed(List oldPath, List newPath, boolean checkClassFiles) {
if (oldPath == null) oldPath = new ArrayList();
if (newPath == null) newPath = new ArrayList();
if (oldPath.size() != newPath.size()) {
return true;
}
for (int i = 0; i < oldPath.size(); i++) {
if (!oldPath.get(i).equals(newPath.get(i))) {
return true;
}
Object o = oldPath.get(i); // String on classpath, File on other paths
File f = null;
if (o instanceof String) {
f = new File((String)o);
} else {
f = (File) o;
}
if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) {
return true;
}
if (f.exists() && f.isDirectory() && checkClassFiles) {
return classFileChangedInDirSinceLastBuild(f);
}
}
return false;
}
public List getFilesToCompile(boolean firstPass) {
List thisTime = new ArrayList();
if (firstPass) {
compiledSourceFiles = new ArrayList();
Collection modifiedFiles = getModifiedFiles();
//System.out.println("modified: " + modifiedFiles);
thisTime.addAll(modifiedFiles);
//??? eclipse IncrementalImageBuilder appears to do this
// for (Iterator i = modifiedFiles.iterator(); i.hasNext();) {
// File file = (File) i.next();
// addDependentsOf(file);
// }
thisTime.addAll(addedFiles);
deleteClassFiles();
deleteResources();
addAffectedSourceFiles(thisTime,thisTime);
} else {
addAffectedSourceFiles(thisTime,compiledSourceFiles);
}
compiledSourceFiles = thisTime;
return thisTime;
}
public Map /* String -> List<ucf> */ getBinaryFilesToCompile(boolean firstTime) {
if (lastSuccessfulBuildTime == -1 || buildConfig == null) {
return binarySourceFiles;
}
// else incremental...
Map toWeave = new HashMap();
if (firstTime) {
List addedOrModified = new ArrayList();
addedOrModified.addAll(addedBinaryFiles);
addedOrModified.addAll(getModifiedBinaryFiles());
for (Iterator iter = addedOrModified.iterator(); iter.hasNext();) {
AjBuildConfig.BinarySourceFile bsf = (AjBuildConfig.BinarySourceFile) iter.next();
UnwovenClassFile ucf = createUnwovenClassFile(bsf);
if (ucf == null) continue;
List ucfs = new ArrayList();
ucfs.add(ucf);
addDependentsOf(ucf.getClassName());
binarySourceFiles.put(bsf.binSrc.getPath(),ucfs);
toWeave.put(bsf.binSrc.getPath(),ucfs);
}
deleteBinaryClassFiles();
} else {
// return empty set... we've already done our bit.
}
return toWeave;
}
/**
* Called when a path change is about to trigger a full build, but
* we haven't cleaned up from the last incremental build...
*/
private void removeAllResultsOfLastBuild() {
// remove all binarySourceFiles, and all classesFromName...
for (Iterator iter = binarySourceFiles.values().iterator(); iter.hasNext();) {
List ucfs = (List) iter.next();
for (Iterator iterator = ucfs.iterator(); iterator.hasNext();) {
UnwovenClassFile ucf = (UnwovenClassFile) iterator.next();
try {
ucf.deleteRealFile();
} catch (IOException ex) { /* we did our best here */ }
}
}
for (Iterator iterator = classesFromName.values().iterator(); iterator.hasNext();) {
UnwovenClassFile ucf = (UnwovenClassFile) iterator.next();
try {
ucf.deleteRealFile();
} catch (IOException ex) { /* we did our best here */ }
}
for (Iterator iter = resources.iterator(); iter.hasNext();) {
String resource = (String) iter.next();
new File(buildConfig.getOutputDir(),resource).delete();
}
}
private void deleteClassFiles() {
for (Iterator i = deletedFiles.iterator(); i.hasNext(); ) {
File deletedFile = (File)i.next();
//System.out.println("deleting: " + deletedFile);
addDependentsOf(deletedFile);
InterimCompilationResult intRes = (InterimCompilationResult) resultsFromFile.get(deletedFile);
resultsFromFile.remove(deletedFile);
//System.out.println("deleting: " + unwovenClassFiles);
if (intRes == null) continue;
for (int j=0; j<intRes.unwovenClassFiles().length; j++ ) {
deleteClassFile(intRes.unwovenClassFiles()[j]);
}
}
}
private void deleteBinaryClassFiles() {
// range of bsf is ucfs, domain is files (.class and jars) in inpath/jars
for (Iterator iter = deletedBinaryFiles.iterator(); iter.hasNext();) {
AjBuildConfig.BinarySourceFile deletedFile = (AjBuildConfig.BinarySourceFile) iter.next();
List ucfs = (List) binarySourceFiles.get(deletedFile.binSrc.getPath());
binarySourceFiles.remove(deletedFile.binSrc.getPath());
deleteClassFile((UnwovenClassFile)ucfs.get(0));
}
}
private void deleteResources() {
List oldResources = new ArrayList();
oldResources.addAll(resources);
// note - this deliberately ignores resources in jars as we don't yet handle jar changes
// with incremental compilation
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory() && AjBuildManager.COPY_INPATH_DIR_RESOURCES) {
deleteResourcesFromDirectory(inPathElement,oldResources);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
maybeDeleteResource(resource, oldResources);
}
}
// oldResources need to be deleted...
for (Iterator iter = oldResources.iterator(); iter.hasNext();) {
String victim = (String) iter.next();
File f = new File(buildConfig.getOutputDir(),victim);
if (f.exists()) {
f.delete();
}
resources.remove(victim);
}
}
private void maybeDeleteResource(String resName, List oldResources) {
if (resources.contains(resName)) {
oldResources.remove(resName);
File source = new File(buildConfig.getOutputDir(),resName);
if ((source != null) && (source.exists()) &&
(source.lastModified() >= lastSuccessfulBuildTime)) {
resources.remove(resName); // will ensure it is re-copied
}
}
}
private void deleteResourcesFromDirectory(File dir, List oldResources) {
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
maybeDeleteResource(filename, oldResources);
}
}
private void deleteClassFile(UnwovenClassFile classFile) {
classesFromName.remove(classFile.getClassName());
buildManager.bcelWeaver.deleteClassFile(classFile.getClassName());
try {
classFile.deleteRealFile();
} catch (IOException e) {
//!!! might be okay to ignore
}
}
private UnwovenClassFile createUnwovenClassFile(AjBuildConfig.BinarySourceFile bsf) {
UnwovenClassFile ucf = null;
try {
ucf = buildManager.bcelWeaver.addClassFile(bsf.binSrc, bsf.fromInPathDirectory, buildConfig.getOutputDir());
} catch(IOException ex) {
IMessage msg = new Message("can't read class file " + bsf.binSrc.getPath(),
new SourceLocation(bsf.binSrc,0),false);
buildManager.handler.handleMessage(msg);
}
return ucf;
}
public void noteResult(InterimCompilationResult result) {
File sourceFile = new File(result.fileName());
CompilationResult cr = result.result();
if (result != null) {
references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences));
}
InterimCompilationResult previous = (InterimCompilationResult) resultsFromFile.get(sourceFile);
UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles();
for (int i = 0; i < unwovenClassFiles.length; i++) {
UnwovenClassFile lastTimeRound = removeFromPreviousIfPresent(unwovenClassFiles[i],previous);
recordClassFile(unwovenClassFiles[i],lastTimeRound);
classesFromName.put(unwovenClassFiles[i].getClassName(),unwovenClassFiles[i]);
}
if (previous != null) {
for (int i = 0; i < previous.unwovenClassFiles().length; i++) {
if (previous.unwovenClassFiles()[i] != null) {
deleteClassFile(previous.unwovenClassFiles()[i]);
}
}
}
resultsFromFile.put(sourceFile, result);
}
private UnwovenClassFile removeFromPreviousIfPresent(UnwovenClassFile cf, InterimCompilationResult previous) {
if (previous == null) return null;
UnwovenClassFile[] unwovenClassFiles = previous.unwovenClassFiles();
for (int i = 0; i < unwovenClassFiles.length; i++) {
UnwovenClassFile candidate = unwovenClassFiles[i];
if ((candidate != null) && candidate.getFilename().equals(cf.getFilename())) {
unwovenClassFiles[i] = null;
return candidate;
}
}
return null;
}
private void recordClassFile(UnwovenClassFile thisTime, UnwovenClassFile lastTime) {
if (simpleStrings == null) return; // batch build
if (lastTime == null) {
addDependentsOf(thisTime.getClassName());
return;
}
byte[] newBytes = thisTime.getBytes();
byte[] oldBytes = lastTime.getBytes();
boolean bytesEqual = (newBytes.length == oldBytes.length);
for (int i = 0; (i < oldBytes.length) && bytesEqual; i++) {
if (newBytes[i] != oldBytes[i]) bytesEqual = false;
}
if (!bytesEqual) {
try {
ClassFileReader reader = new ClassFileReader(oldBytes, lastTime.getFilename().toCharArray());
// ignore local types since they're only visible inside a single method
if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) {
addDependentsOf(lastTime.getClassName());
}
} catch (ClassFormatException e) {
addDependentsOf(lastTime.getClassName());
}
}
}
// public void noteClassesFromFile(CompilationResult result, String sourceFileName, List unwovenClassFiles) {
// File sourceFile = new File(sourceFileName);
//
// if (result != null) {
// references.put(sourceFile, new ReferenceCollection(result.qualifiedReferences, result.simpleNameReferences));
// }
//
// List previous = (List)classesFromFile.get(sourceFile);
// List newClassFiles = new ArrayList();
// for (Iterator i = unwovenClassFiles.iterator(); i.hasNext();) {
// UnwovenClassFile cf = (UnwovenClassFile) i.next();
// cf = writeClassFile(cf, findAndRemoveClassFile(cf.getClassName(), previous));
// newClassFiles.add(cf);
// classesFromName.put(cf.getClassName(), cf);
// }
//
// if (previous != null && !previous.isEmpty()) {
// for (Iterator i = previous.iterator(); i.hasNext();) {
// UnwovenClassFile cf = (UnwovenClassFile) i.next();
// deleteClassFile(cf);
// }
// }
//
// classesFromFile.put(sourceFile, newClassFiles);
// resultsFromFile.put(sourceFile, result);
// }
//
// private UnwovenClassFile findAndRemoveClassFile(String name, List previous) {
// if (previous == null) return null;
// for (Iterator i = previous.iterator(); i.hasNext();) {
// UnwovenClassFile cf = (UnwovenClassFile) i.next();
// if (cf.getClassName().equals(name)) {
// i.remove();
// return cf;
// }
// }
// return null;
// }
//
// private UnwovenClassFile writeClassFile(UnwovenClassFile cf, UnwovenClassFile previous) {
// if (simpleStrings == null) { // batch build
// addedClassFiles.add(cf);
// return cf;
// }
//
// try {
// if (previous == null) {
// addedClassFiles.add(cf);
// addDependentsOf(cf.getClassName());
// return cf;
// }
//
// byte[] oldBytes = previous.getBytes();
// byte[] newBytes = cf.getBytes();
// //if (this.compileLoop > 1) { // only optimize files which were recompiled during the dependent pass, see 33990
// notEqual : if (newBytes.length == oldBytes.length) {
// for (int i = newBytes.length; --i >= 0;) {
// if (newBytes[i] != oldBytes[i]) break notEqual;
// }
// //addedClassFiles.add(previous); //!!! performance wasting
// buildManager.bcelWorld.addSourceObjectType(previous.getJavaClass());
// return previous; // bytes are identical so skip them
// }
// //}
// ClassFileReader reader = new ClassFileReader(oldBytes, previous.getFilename().toCharArray());
// // ignore local types since they're only visible inside a single method
// if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) {
// addDependentsOf(cf.getClassName());
// }
// } catch (ClassFormatException e) {
// addDependentsOf(cf.getClassName());
// }
// addedClassFiles.add(cf);
// return cf;
// }
private static StringSet makeStringSet(List strings) {
StringSet ret = new StringSet(strings.size());
for (Iterator iter = strings.iterator(); iter.hasNext();) {
String element = (String) iter.next();
ret.add(element);
}
return ret;
}
protected void addAffectedSourceFiles(List addTo, List lastTimeSources) {
if (qualifiedStrings.isEmpty() && simpleStrings.isEmpty()) return;
// the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X'
char[][][] qualifiedNames = ReferenceCollection.internQualifiedNames(makeStringSet(qualifiedStrings));
// if a well known qualified name was found then we can skip over these
if (qualifiedNames.length < qualifiedStrings.size())
qualifiedNames = null;
char[][] simpleNames = ReferenceCollection.internSimpleNames(makeStringSet(simpleStrings));
// if a well known name was found then we can skip over these
if (simpleNames.length < simpleStrings.size())
simpleNames = null;
//System.err.println("simple: " + simpleStrings);
//System.err.println("qualif: " + qualifiedStrings);
for (Iterator i = references.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
ReferenceCollection refs = (ReferenceCollection)entry.getValue();
if (refs != null && refs.includes(qualifiedNames, simpleNames)) {
File file = (File)entry.getKey();
if (file.exists()) {
if (!lastTimeSources.contains(file)) { //??? O(n**2)
addTo.add(file);
}
}
}
}
qualifiedStrings.clear();
simpleStrings.clear();
}
protected void addDependentsOf(String qualifiedTypeName) {
int lastDot = qualifiedTypeName.lastIndexOf('.');
String typeName;
if (lastDot != -1) {
String packageName = qualifiedTypeName.substring(0,lastDot).replace('.', '/');
if (!qualifiedStrings.contains(packageName)) { //??? O(n**2)
qualifiedStrings.add(packageName);
}
typeName = qualifiedTypeName.substring(lastDot+1);
} else {
qualifiedStrings.add("");
typeName = qualifiedTypeName;
}
int memberIndex = typeName.indexOf('$');
if (memberIndex > 0)
typeName = typeName.substring(0, memberIndex);
if (!simpleStrings.contains(typeName)) { //??? O(n**2)
simpleStrings.add(typeName);
}
//System.err.println("adding: " + qualifiedTypeName);
}
protected void addDependentsOf(File sourceFile) {
InterimCompilationResult intRes = (InterimCompilationResult)resultsFromFile.get(sourceFile);
if (intRes == null) return;
for (int i = 0; i < intRes.unwovenClassFiles().length; i++) {
addDependentsOf(intRes.unwovenClassFiles()[i].getClassName());
}
}
}
|
85,297 |
Bug 85297 Improvements to incremental compilation
| null |
resolved fixed
|
e460b1e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-05T14:50:06Z | 2005-02-15T17:53:20Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/IStateListener.java
| |
85,297 |
Bug 85297 Improvements to incremental compilation
| null |
resolved fixed
|
e460b1e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-05T14:50:06Z | 2005-02-15T17:53:20Z |
tests/src/org/aspectj/systemtest/incremental/IncrementalTests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.incremental;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class IncrementalTests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(IncrementalTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/incremental/incremental.xml");
}
public void test001() throws Exception {
runTest("expect class added in initial incremental tests");
nextIncrement(false);
copyFileAndDoIncrementalBuild("src.20/main/Main.java","src/main/Main.java");
assertAdded("main/Target.class");
run("main.Main");
}
public void test002() throws Exception {
runTest("expect class removed in initial incremental tests");
nextIncrement(false);
assertAdded("main/Target.class");
copyFileAndDoIncrementalBuild("src.20/main/Main.java","src/main/Main.java");
assertDeleted("main/Target.class");
run("main.Main");
}
public void test003() throws Exception {
runTest("expect class updated in initial incremental tests");
long lastTime = nextIncrement(true);
copyFileAndDoIncrementalBuild("src.20/main/Main.java","src/main/Main.java");
assertUpdated("main/Main.class",lastTime);
run("main.Main");
}
public void test004() throws Exception {
runTest("add file with class");
nextIncrement(false);
copyFileAndDoIncrementalBuild("src.20/main/Target.java","src/main/Target.java");
assertAdded("main/Target.class");
long lastTime = nextIncrement(true);
copyFileAndDoIncrementalBuild("src.30/main/Main.java","src/main/Main.java");
assertUpdated("main/Main.class",lastTime);
run("main.Main");
}
public void test005()throws Exception {
runTest("delete source file before incremental compile");
nextIncrement(false);
MessageSpec messageSpec = new MessageSpec(null,newMessageList(new Message(6,"delete/Target.java",null,null)));
deleteFileAndDoIncrementalBuild("src/delete/DeleteMe.java",messageSpec);
nextIncrement(false);
copyFileAndDoIncrementalBuild("src.30/delete/Target.java","src/delete/Target.java");
run("delete.Main");
}
public void test006() throws Exception {
runTest("do everything in default package (sourceroots)");
nextIncrement(false);
copyFileAndDoIncrementalBuild("changes/Target.20.java","src/Target.java");
run("Target");
long lastTime = nextIncrement(true);
copyFileAndDoIncrementalBuild("changes/Main.30.java","src/Main.java");
assertUpdated("Main.class",lastTime);
nextIncrement(false);
MessageSpec messageSpec = new MessageSpec(null,newMessageList(new Message(6,"Main.java",null,null)));
deleteFileAndDoIncrementalBuild("src/Target.java",messageSpec);
nextIncrement(false);
copyFileAndDoIncrementalBuild("changes/Main.50.java","src/Main.java");
run("Main");
}
public void test007() throws Exception {
runTest("change sources in default package");
nextIncrement(false);
copyFileAndDoIncrementalBuild("changes/Main.20.java","src/Main.java");
run("Main");
}
public void test008() throws Exception {
runTest("change source");
nextIncrement(false);
copyFileAndDoIncrementalBuild("changes/Main.20.java","src/app/Main.java");
run("app.Main");
}
public void test009() throws Exception {
runTest("incrementally change only string literal, still expect advice");
long lastTime = nextIncrement(true);
copyFileAndDoIncrementalBuild("changes/Main.20.java","src/packageOne/Main.java");
assertUpdated("packageOne/Main.class",lastTime);
run("packageOne.Main",new String[] {"in longer packageOne.Main.main(..)",
"before main packageOne.Main"},
null);
}
public void test010() throws Exception {
runTest("add aspect source file and check world is rewoven");
nextIncrement(false);
copyFileAndDoIncrementalBuild("changes/Detour.20.java","src/Detour.java");
assertAdded("Detour.class");
run("Main");
}
public void test011() throws Exception {
runTest("make sure additional classes generated during weave are deleted with src class file");
nextIncrement(false);
assertTrue("AdviceOnIntroduced$AjcClosure1.class exists",
new File(ajc.getSandboxDirectory(),"AdviceOnIntroduced$AjcClosure1.class").exists());
deleteFileAndDoIncrementalBuild("src/AdviceOnIntroduced.java");
assertDeleted("AdviceOnIntroduced$AjcClosure1.class");
}
public void test012() throws Exception {
runTest("incremental with aspect-driven full rebuild");
nextIncrement(false);
MessageSpec messageSpec = new MessageSpec(newMessageList(new Message(3,"Main.java",null,null)),null);
copyFileAndDoIncrementalBuild("changes/Aspect.20.java","src/Aspect.java",messageSpec);
run("Main");
}
public void testIncrementalResourceAdditionToInPath() throws Exception {
runTest("incremental with addition of resource to inpath directory");
RunResult result = run("Hello");
assertTrue("Should have been advised",result.getStdOut().indexOf("World") != -1);
nextIncrement(false);
assertFalse("Resource file should not exist yet",new File(ajc.getSandboxDirectory(),"AResourceFile.txt").exists());
copyFileAndDoIncrementalBuild("changes/AResourceFile.txt", "indir/AResourceFile.txt");
// resources are *NOT* copied from inpath directories
assertFalse("Resource file should not exist yet",new File(ajc.getSandboxDirectory(),"AResourceFile.txt").exists());
}
public void testAdditionOfResourceToInJar() throws Exception {
runTest("incremental with addition of resource to inpath jar");
nextIncrement(true);
assertFalse("Resource file should not exist yet",new File(ajc.getSandboxDirectory(),"AResourceFile.txt").exists());
copyFileAndDoIncrementalBuild("changes/MyJar.20.jar", "MyJar.jar");
// resources *are* copied from inpath jars
assertAdded("AResourceFile.txt");
}
public void testRemovalOfResourceFromInJar() throws Exception {
runTest("incremental with removal of resource from inpath jar");
nextIncrement(true);
assertAdded("AResourceFile.txt");
copyFileAndDoIncrementalBuild("changes/MyJar.20.jar", "MyJar.jar");
// resources *are* copied from inpath jars
assertDeleted("AResourceFile.txt");
}
public void testAdditionOfClassToInPathJar() throws Exception {
runTest("incremental with addition of class to inpath jar");
nextIncrement(true);
assertFalse("Hello2.class should not exist yet",new File(ajc.getSandboxDirectory(),"Hello2.class").exists());
copyFileAndDoIncrementalBuild("changes/MyJar.20.jar", "MyJar.jar");
assertAdded("Hello2.class");
}
public void testRemovalOfClassFromInPathJar() throws Exception {
runTest("incremental with removal of class from inpath jar");
nextIncrement(true);
assertAdded("Hello2.class");
copyFileAndDoIncrementalBuild("changes/MyJar.20.jar", "MyJar.jar");
assertDeleted("Hello2.class");
}
public void testAdditionOfClassToInJarJar() throws Exception {
runTest("incremental with addition of class to injar jar");
nextIncrement(true);
assertFalse("Hello2.class should not exist yet",new File(ajc.getSandboxDirectory(),"Hello2.class").exists());
copyFileAndDoIncrementalBuild("changes/MyJar.20.jar", "MyJar.jar");
assertAdded("Hello2.class");
}
public void testRemovalOfClassFromInJarJar() throws Exception {
runTest("incremental with removal of class from injar jar");
nextIncrement(true);
assertAdded("Hello2.class");
copyFileAndDoIncrementalBuild("changes/MyJar.20.jar", "MyJar.jar");
assertDeleted("Hello2.class");
}
public void testAdditionOfClassToInPathDir() throws Exception {
runTest("incremental with addition of class to inpath dir");
nextIncrement(true);
assertFalse("Hello2.class should not exist yet",new File(ajc.getSandboxDirectory(),"Hello2.class").exists());
copyFileAndDoIncrementalBuild("changes/Hello2.20.class", "indir/Hello2.class");
assertAdded("Hello2.class");
}
public void testRemovalOfClassFromInPathDir() throws Exception {
runTest("incremental with removal of class from inpath dir");
nextIncrement(true);
assertAdded("Hello2.class");
deleteFileAndDoIncrementalBuild("indir/Hello2.class");
assertDeleted("Hello2.class");
}
public void testUpdateOfClassInInPathDir() throws Exception {
runTest("incremental with update of class in inpath dir");
nextIncrement(true);
RunResult before = run("Hello");
assertTrue("Should say hello",before.getStdOut().startsWith("hello"));
copyFileAndDoIncrementalBuild("changes/Hello.20.class", "indir/Hello.class");
RunResult after = run("Hello");
assertTrue("Should say updated hello",after.getStdOut().startsWith("updated hello"));
}
}
|
90,588 |
Bug 90588 compiler verifyerror and an NPE
| null |
resolved fixed
|
d697649
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-13T13:26:54Z | 2005-04-07T10:33:20Z |
tests/bugs150/pr90588/AbstractClass.java
| |
90,588 |
Bug 90588 compiler verifyerror and an NPE
| null |
resolved fixed
|
d697649
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-13T13:26:54Z | 2005-04-07T10:33:20Z |
tests/bugs150/pr90588/ConcreteClass.java
| |
90,588 |
Bug 90588 compiler verifyerror and an NPE
| null |
resolved fixed
|
d697649
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-13T13:26:54Z | 2005-04-07T10:33:20Z |
tests/src/org/aspectj/systemtest/knownfailures/KnownfailuresTests.java
| |
82,171 |
Bug 82171 enable ASM interoperability with JavaCore via uniform element handles
| null |
resolved fixed
|
df7fff4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-14T16:44:01Z | 2005-01-04T20:20:00Z |
asm/src/org/aspectj/asm/AsmManager.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* Andy Clement incremental support and switch on/off state
* ******************************************************************/
package org.aspectj.asm;
import java.io.*;
import java.util.*;
import org.aspectj.asm.internal.*;
import org.aspectj.bridge.ISourceLocation;
/**
* The Abstract Structure Model (ASM) represents the containment hierarchy and crossccutting
* structure map for AspectJ programs. It is used by IDE views such as the document outline,
* and by other tools such as ajdoc to show both AspectJ declarations and crosscutting links,
* such as which advice affects which join point shadows.
*
* @author Mik Kersten
*/
public class AsmManager {
/**
* @deprecated use getDefault() method instead
*/
private static AsmManager INSTANCE = new AsmManager();
private boolean shouldSaveModel = true;
protected IHierarchy hierarchy;
private List structureListeners = new ArrayList();
private IRelationshipMap mapper;
private static boolean creatingModel = false;
public static boolean dumpModelPostBuild = false; // Dumping the model is expensive
public static boolean attemptIncrementalModelRepairs = false;
// for debugging ...
// For offline debugging, you can now ask for the AsmManager to
// dump the model - see the method setReporting()
private static boolean dumpModel = false;
private static boolean dumpRelationships = false;
private static boolean dumpDeltaProcessing = false;
private static String dumpFilename = "";
private static boolean reporting = false;
// static {
// setReporting("c:/model.nfo",true,true,true,true);
// }
protected AsmManager() {
hierarchy = new AspectJElementHierarchy();
// List relationships = new ArrayList();
mapper = new RelationshipMap(hierarchy);
}
public IHierarchy getHierarchy() {
return hierarchy;
}
public static AsmManager getDefault() {
return INSTANCE;
}
public IRelationshipMap getRelationshipMap() {
return mapper;
}
public void fireModelUpdated() {
notifyListeners();
if (dumpModelPostBuild && hierarchy.getConfigFile() != null) {
writeStructureModel(hierarchy.getConfigFile());
}
}
/**
* Constructs map each time it's called.
*/
public HashMap getInlineAnnotations(
String sourceFile,
boolean showSubMember,
boolean showMemberAndType) {
if (!hierarchy.isValid()) return null;
HashMap annotations = new HashMap();
IProgramElement node = hierarchy.findElementForSourceFile(sourceFile);
if (node == IHierarchy.NO_STRUCTURE) {
return null;
} else {
IProgramElement fileNode = (IProgramElement)node;
ArrayList peNodes = new ArrayList();
getAllStructureChildren(fileNode, peNodes, showSubMember, showMemberAndType);
for (Iterator it = peNodes.iterator(); it.hasNext(); ) {
IProgramElement peNode = (IProgramElement)it.next();
List entries = new ArrayList();
entries.add(peNode);
ISourceLocation sourceLoc = peNode.getSourceLocation();
if (null != sourceLoc) {
Integer hash = new Integer(sourceLoc.getLine());
List existingEntry = (List)annotations.get(hash);
if (existingEntry != null) {
entries.addAll(existingEntry);
}
annotations.put(hash, entries);
}
}
return annotations;
}
}
private void getAllStructureChildren(IProgramElement node, List result, boolean showSubMember, boolean showMemberAndType) {
List children = node.getChildren();
if (node.getChildren() == null) return;
for (Iterator it = children.iterator(); it.hasNext(); ) {
IProgramElement next = (IProgramElement)it.next();
List rels = AsmManager.getDefault().getRelationshipMap().get(next);
if (next != null
&& ((next.getKind() == IProgramElement.Kind.CODE && showSubMember)
|| (next.getKind() != IProgramElement.Kind.CODE && showMemberAndType))
&& rels != null
&& rels.size() > 0) {
result.add(next);
}
getAllStructureChildren((IProgramElement)next, result, showSubMember, showMemberAndType);
}
}
public void addListener(IHierarchyListener listener) {
structureListeners.add(listener);
}
public void removeStructureListener(IHierarchyListener listener) {
structureListeners.remove(listener);
}
// this shouldn't be needed - but none of the people that add listeners
// in the test suite ever remove them. AMC added this to be called in
// setup() so that the test cases would cease leaking listeners and go
// back to executing at a reasonable speed.
public void removeAllListeners() {
structureListeners.clear();
}
private void notifyListeners() {
for (Iterator it = structureListeners.iterator(); it.hasNext(); ) {
((IHierarchyListener)it.next()).elementsUpdated(hierarchy);
}
}
/**
* Fails silently.
*/
public void writeStructureModel(String configFilePath) {
try {
String filePath = genExternFilePath(configFilePath);
FileOutputStream fos = new FileOutputStream(filePath);
ObjectOutputStream s = new ObjectOutputStream(fos);
s.writeObject(hierarchy); // Store the program element tree
s.writeObject(mapper); // Store the relationships
s.flush();
fos.flush();
fos.close();
s.close();
} catch (Exception e) {
// System.err.println("AsmManager: Unable to write structure model: "+configFilePath+" because of:");
// e.printStackTrace();
}
}
/**
* @todo add proper handling of bad paths/suffixes/etc
* @param configFilePath path to an ".lst" file
*/
public void readStructureModel(String configFilePath) {
boolean hierarchyReadOK = false;
try {
if (configFilePath == null) {
hierarchy.setRoot(IHierarchy.NO_STRUCTURE);
} else {
String filePath = genExternFilePath(configFilePath);
FileInputStream in = new FileInputStream(filePath);
ObjectInputStream s = new ObjectInputStream(in);
hierarchy = (AspectJElementHierarchy)s.readObject();
hierarchyReadOK = true;
mapper = (RelationshipMap)s.readObject();
((RelationshipMap)mapper).setHierarchy(hierarchy);
}
} catch (FileNotFoundException fnfe) {
// That is OK
hierarchy.setRoot(IHierarchy.NO_STRUCTURE);
} catch (EOFException eofe) {
// Might be an old format sym file that is missing its relationships
if (!hierarchyReadOK) {
System.err.println("AsmManager: Unable to read structure model: "+configFilePath+" because of:");
eofe.printStackTrace();
hierarchy.setRoot(IHierarchy.NO_STRUCTURE);
}
} catch (Exception e) {
// System.err.println("AsmManager: Unable to read structure model: "+configFilePath+" because of:");
// e.printStackTrace();
hierarchy.setRoot(IHierarchy.NO_STRUCTURE);
} finally {
notifyListeners();
}
}
private String genExternFilePath(String configFilePath) {
return configFilePath.substring(0, configFilePath.lastIndexOf(".lst")) + ".ajsym";
}
public void setShouldSaveModel(boolean shouldSaveModel) {
this.shouldSaveModel = shouldSaveModel;
}
// ==== implementation of canonical file path map and accessors ==============
// a more sophisticated optimisation is left here commented out as the
// performance gains don't justify the disturbance this close to a release...
// can't call prepareForWeave until preparedForCompilation has completed...
// public synchronized void prepareForCompilation(List files) {
// canonicalFilePathMap.prepopulate(files);
// }
//
// public synchronized void prepareForWeave() {
// canonicalFilePathMap.handover();
// }
public String getCanonicalFilePath(File f) {
return canonicalFilePathMap.get(f);
}
private CanonicalFilePathMap canonicalFilePathMap = new CanonicalFilePathMap();
private static class CanonicalFilePathMap {
private static final int MAX_SIZE = 4000;
private Map pathMap = new HashMap(MAX_SIZE);
// // guards to ensure correctness and liveness
// private boolean cacheInUse = false;
// private boolean stopRequested = false;
//
// private synchronized boolean isCacheInUse() {
// return cacheInUse;
// }
//
// private synchronized void setCacheInUse(boolean val) {
// cacheInUse = val;
// if (val) {
// notifyAll();
// }
// }
//
// private synchronized boolean isStopRequested() {
// return stopRequested;
// }
//
// private synchronized void requestStop() {
// stopRequested = true;
// }
//
// /**
// * Begin prepopulating the map by adding an entry from
// * file.getPath -> file.getCanonicalPath for each file in
// * the list. Do this on a background thread.
// * @param files
// */
// public void prepopulate(final List files) {
// stopRequested = false;
// setCacheInUse(false);
// if (pathMap.size() > MAX_SIZE) {
// pathMap.clear();
// }
// new Thread() {
// public void run() {
// System.out.println("Starting cache population: " + System.currentTimeMillis());
// Iterator it = files.iterator();
// while (!isStopRequested() && it.hasNext()) {
// File f = (File)it.next();
// if (pathMap.get(f.getPath()) == null) {
// // may reuse cache across compiles from ides...
// try {
// pathMap.put(f.getPath(),f.getCanonicalPath());
// } catch (IOException ex) {
// pathMap.put(f.getPath(),f.getPath());
// }
// }
// }
// System.out.println("Cached " + files.size());
// setCacheInUse(true);
// System.out.println("Cache populated: " + System.currentTimeMillis());
// }
// }.start();
// }
//
// /**
// * Stop pre-populating the cache - our customers are ready to use it.
// * If there are any cache misses from this point on, we'll populate the
// * cache as we go.
// * The handover is done this way to ensure that only one thread is ever
// * accessing the cache, and that we minimize synchronization.
// */
// public synchronized void handover() {
// if (!isCacheInUse()) {
// requestStop();
// try {
// while (!isCacheInUse()) wait();
// } catch (InterruptedException intEx) { } // just continue
// }
// }
public String get(File f) {
// if (!cacheInUse) { // unsynchronized test - should never be parallel
// // threads at this point
// throw new IllegalStateException(
// "Must take ownership of cache before using by calling " +
// "handover()");
// }
String ret = (String) pathMap.get(f.getPath());
if (ret == null) {
try {
ret = f.getCanonicalPath();
} catch (IOException ioEx) {
ret = f.getPath();
}
pathMap.put(f.getPath(),ret);
if (pathMap.size() > MAX_SIZE) pathMap.clear();
}
return ret;
}
}
public static void setReporting(String filename,boolean dModel,boolean dRels,boolean dDeltaProcessing,boolean deletefile) {
reporting = true;
dumpModel = dModel;
dumpRelationships = dRels;
dumpDeltaProcessing = dDeltaProcessing;
if (deletefile) new File(filename).delete();
dumpFilename = filename;
}
public static boolean isReporting() {
return reporting;
}
public void reportModelInfo(String reasonForReport) {
if (!dumpModel && !dumpRelationships) return;
try {
FileWriter fw = new FileWriter(dumpFilename,true);
BufferedWriter bw = new BufferedWriter(fw);
if (dumpModel) {
bw.write("=== MODEL STATUS REPORT ========= "+reasonForReport+"\n");
dumptree(bw,AsmManager.getDefault().getHierarchy().getRoot(),0);
bw.write("=== END OF MODEL REPORT =========\n");
}
if (dumpRelationships) {
bw.write("=== RELATIONSHIPS REPORT ========= "+reasonForReport+"\n");
dumprels(bw);
bw.write("=== END OF RELATIONSHIPS REPORT ==\n");
}
Properties p = ModelInfo.summarizeModel().getProperties();
Enumeration pkeyenum = p.keys();
bw.write("=== Properties of the model and relationships map =====\n");
while (pkeyenum.hasMoreElements()) {
String pkey = (String)pkeyenum.nextElement();
bw.write(pkey+"="+p.getProperty(pkey)+"\n");
}
bw.flush();
fw.close();
} catch (IOException e) {
System.err.println("InternalError: Unable to report model information:");
e.printStackTrace();
}
}
public static void dumptree(Writer w,IProgramElement node,int indent) throws IOException {
for (int i =0 ;i<indent;i++) w.write(" ");
String loc = "";
if (node!=null) {
if (node.getSourceLocation()!=null)
loc = node.getSourceLocation().toString();
}
w.write(node+" ["+(node==null?"null":node.getKind().toString())+"] "+loc+"\n");
if (node!=null)
for (Iterator i = node.getChildren().iterator();i.hasNext();) {
dumptree(w,(IProgramElement)i.next(),indent+2);
}
}
private void dumprels(Writer w) throws IOException {
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();
w.write("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid+"\n");
}
}
}
}
//===================== DELTA PROCESSING CODE ============== start ==========//
// XXX shouldn't be aware of the delimiter
private String getFilename(String hid) {
return hid.substring(0,hid.indexOf("|"));
}
// This code is *SLOW* but it isnt worth fixing until we address the
// bugs in binary weaving.
public void fixupStructureModel(Writer fw,List filesToBeCompiled,Set files_added,Set files_deleted) throws IOException {
// Three kinds of things to worry about:
// 1. New files have been added since the last compile
// 2. Files have been deleted since the last compile
// 3. Files have 'changed' since the last compile (really just those in config.getFiles())
// List files = config.getFiles();
IHierarchy model = AsmManager.getDefault().getHierarchy();
boolean modelModified = false;
// Files to delete are: those to be compiled + those that have been deleted
Set filesToRemoveFromStructureModel = new HashSet(filesToBeCompiled);
filesToRemoveFromStructureModel.addAll(files_deleted);
Set deletedNodes = new HashSet();
for (Iterator iter = filesToRemoveFromStructureModel.iterator(); iter.hasNext();) {
File fileForCompilation = (File) iter.next();
String correctedPath = AsmManager.getDefault().getCanonicalFilePath(fileForCompilation);
IProgramElement progElem = (IProgramElement)model.findInFileMap(correctedPath);
if (progElem!=null) {
// Found it, let's remove it
if (dumpDeltaProcessing) {
fw.write("Deleting "+progElem+" node for file "+fileForCompilation+"\n");
}
removeNode(progElem);
deletedNodes.add(getFilename(progElem.getHandleIdentifier()));
if (!model.removeFromFileMap(correctedPath.toString()))
throw new RuntimeException("Whilst repairing model, couldn't remove entry for file: "+correctedPath.toString()+" from the filemap");
modelModified = true;
}
}
if (modelModified) {
model.flushTypeMap();
model.updateHandleMap(deletedNodes);
}
}
public void processDelta(List filesToBeCompiled,Set files_added,Set files_deleted) {
try {
Writer fw = null;
// Are we recording this ?
if (dumpDeltaProcessing) {
FileWriter filew = new FileWriter(dumpFilename,true);
fw = new BufferedWriter(filew);
fw.write("=== Processing delta changes for the model ===\n");
fw.write("Files for compilation:#"+filesToBeCompiled.size()+":"+filesToBeCompiled+"\n");
fw.write("Files added :#"+files_added.size()+":"+files_added+"\n");
fw.write("Files deleted :#"+files_deleted.size()+":"+files_deleted+"\n");
}
long stime = System.currentTimeMillis();
fixupStructureModel(fw,filesToBeCompiled,files_added,files_deleted);
long etime1 = System.currentTimeMillis(); // etime1-stime = time to fix up the model
IHierarchy model = AsmManager.getDefault().getHierarchy();
// Some of this code relies on the fact that relationships are always in pairs, so you know
// if you are the target of a relationship because you are also the source of a relationship
// This seems a valid assumption for now...
//TODO Speed this code up by making this assumption:
// the only piece of the handle that is interesting is the file name. We are working at file granularity, if the
// file does not exist (i.e. its not in the filemap) then any handle inside that file cannot exist.
if (dumpDeltaProcessing) fw.write("Repairing relationships map:\n");
// Now sort out the relationships map
IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
Set sourcesToRemove = new HashSet();
Set nonExistingHandles = new HashSet(); // Cache of handles that we *know* are invalid
int srchandlecounter = 0;
int tgthandlecounter = 0;
// Iterate over the source handles in the relationships map
Set keyset = irm.getEntries(); // These are source handles
for (Iterator keyiter = keyset.iterator(); keyiter.hasNext();) {
String hid = (String) keyiter.next();
srchandlecounter++;
// Do we already know this handle points to nowhere?
if (nonExistingHandles.contains(hid)) {
sourcesToRemove.add(hid);
} else {
// We better check if it actually exists
IProgramElement existingElement = model.getElement(hid);
if (dumpDeltaProcessing) fw.write("Looking for handle ["+hid+"] in model, found: "+existingElement+"\n");
// Did we find it?
if (existingElement == null) {
// No, so delete this relationship
sourcesToRemove.add(hid);
nonExistingHandles.add(hid); // Speed up a bit you swine
} else {
// Ok, so the source is valid, what about the targets?
List relationships = irm.get(hid);
List relationshipsToRemove = new ArrayList();
// Iterate through the relationships against this source handle
for (Iterator reliter = relationships.iterator();reliter.hasNext();) {
IRelationship rel = (IRelationship) reliter.next();
List targets = rel.getTargets();
List targetsToRemove = new ArrayList();
// Iterate through the targets for this relationship
for (Iterator targetIter = targets.iterator();targetIter.hasNext();) {
String targethid = (String) targetIter.next();
tgthandlecounter++;
// Do we already know it doesn't exist?
if (nonExistingHandles.contains(targethid)) {
if (dumpDeltaProcessing) fw.write("Target handle ["+targethid+"] for srchid["+hid+"]rel["+rel.getName()+"] does not exist\n");
targetsToRemove.add(targethid);
} else {
// We better check
IProgramElement existingTarget = model.getElement(targethid);
if (existingTarget == null) {
if (dumpDeltaProcessing) fw.write("Target handle ["+targethid+"] for srchid["+hid+"]rel["+rel.getName()+"] does not exist\n");
targetsToRemove.add(targethid);
nonExistingHandles.add(targethid);
}
}
}
// Do we have some targets that need removing?
if (targetsToRemove.size()!=0) {
// Are we removing *all* of the targets for this relationship (i.e. removing the relationship)
if (targetsToRemove.size()==targets.size()) {
if (dumpDeltaProcessing) fw.write("No targets remain for srchid["+hid+"] rel["+rel.getName()+"]: removing it\n");
relationshipsToRemove.add(rel);
} else {
// Remove all the targets that are no longer valid
for (Iterator targsIter = targetsToRemove.iterator();targsIter.hasNext();) {
String togo = (String) targsIter.next();
targets.remove(togo);
}
// Should have already been caught above, but lets double check ...
if (targets.size()==0) {
if (dumpDeltaProcessing) fw.write("No targets remain for srchid["+hid+"] rel["+rel.getName()+"]: removing it\n");
relationshipsToRemove.add(rel); // TODO Should only remove this relationship for the srchid?
}
}
}
}
// Now, were any relationships emptied during that processing and so need removing for this source handle
if (relationshipsToRemove.size()>0) {
// Are we removing *all* of the relationships for this source handle?
if (relationshipsToRemove.size() == relationships.size()) {
// We know they are all going to go, so just delete the source handle.
sourcesToRemove.add(hid);
} else {
for (int i = 0 ;i<relationshipsToRemove.size();i++) {
IRelationship irel = (IRelationship)relationshipsToRemove.get(i);
verifyAssumption(irm.remove(hid,irel),"Failed to remove relationship "+irel.getName()+" for shid "+hid);
}
List rels = irm.get(hid);
if (rels==null || rels.size()==0) sourcesToRemove.add(hid);
}
}
}
}
}
// Remove sources that have no valid relationships any more
for (Iterator srciter = sourcesToRemove.iterator(); srciter.hasNext();) {
String hid = (String) srciter.next();
irm.removeAll(hid);
IProgramElement ipe = model.getElement(hid);
if (ipe!=null) {
// If the relationship was hanging off a 'code' node, delete it.
if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
removeSingleNode(ipe);
}
}
}
long etime2 = System.currentTimeMillis(); // etime2-stime = time to repair the relationship map
if (dumpDeltaProcessing) {
fw.write("===== Delta Processing timing ==========\n");
fw.write("Hierarchy="+(etime1-stime)+"ms Relationshipmap="+(etime2-etime1)+"ms\n");
fw.write("===== Traversal ========================\n");
fw.write("Source handles processed="+srchandlecounter+"\n");
fw.write("Target handles processed="+tgthandlecounter+"\n");
fw.write("========================================\n");
fw.flush();fw.close();
}
reportModelInfo("After delta processing");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Removes a specified program element from the structure model.
* We go to the parent of the program element, ask for all its children
* and remove the node we want to delete from the list of children.
*/
private void removeSingleNode(IProgramElement progElem) {
verifyAssumption(progElem!=null);
boolean deleteOK = false;
IProgramElement parent = progElem.getParent();
List kids = parent.getChildren();
for (int i =0 ;i<kids.size();i++) {
if (kids.get(i).equals(progElem)) {
kids.remove(i);
deleteOK=true;
break;
}
}
verifyAssumption(deleteOK);
}
/**
* Removes a specified program element from the structure model.
* Two processing stages:
* <p>First: We go to the parent of the program element, ask for all its children
* and remove the node we want to delete from the list of children.
* <p>Second:We check if that parent has any other children. If it has no other
* children and it is either a CODE node or a PACKAGE node, we delete it too.
*/
private void removeNode(IProgramElement progElem) {
// StringBuffer flightrecorder = new StringBuffer();
try {
// flightrecorder.append("In removeNode, about to chuck away: "+progElem+"\n");
verifyAssumption(progElem!=null);
boolean deleteOK = false;
IProgramElement parent = progElem.getParent();
// flightrecorder.append("Parent of it is "+parent+"\n");
List kids = parent.getChildren();
// flightrecorder.append("Which has "+kids.size()+" kids\n");
for (int i =0 ;i<kids.size();i++) {
// flightrecorder.append("Comparing with "+kids.get(i)+"\n");
if (kids.get(i).equals(progElem)) {
kids.remove(i);
// flightrecorder.append("Removing it\n");
deleteOK=true;
break;
}
}
// verifyAssumption(deleteOK,flightrecorder.toString());
// Are there any kids left for this node?
if (parent.getChildren().size()==0 && parent.getParent()!=null &&
(parent.getKind().equals(IProgramElement.Kind.CODE) ||
parent.getKind().equals(IProgramElement.Kind.PACKAGE))) {
// This node is on its own, we should trim it too *as long as its not a structural node* which we currently check by making sure its a code node
// We should trim if it
// System.err.println("Deleting parent:"+parent);
removeNode(parent);
}
} catch (NullPointerException npe ){
// Occurred when commenting out other 2 ras classes in wsif?? reproducable?
// System.err.println(flightrecorder.toString());
npe.printStackTrace();
}
}
public static void verifyAssumption(boolean b,String info) {
if (!b) {
System.err.println("=========== ASSERTION IS NOT TRUE =========v");
System.err.println(info);
Thread.dumpStack();
System.err.println("=========== ASSERTION IS NOT TRUE =========^");
throw new RuntimeException("Assertion is false");
}
}
public static void verifyAssumption(boolean b) {
if (!b) {
Thread.dumpStack();
throw new RuntimeException("Assertion is false");
}
}
//===================== DELTA PROCESSING CODE ============== end ==========//
/**
* A ModelInfo object captures basic information about the structure model.
* It is used for testing and producing debug info.
*/
public static class ModelInfo {
private Hashtable nodeTypeCount = new Hashtable();
private Properties extraProperties = new Properties();
private ModelInfo(IHierarchy hierarchy,IRelationshipMap relationshipMap) {
IProgramElement ipe = hierarchy.getRoot();
walkModel(ipe);
recordStat("FileMapSize",
new Integer(hierarchy.getFileMapEntrySet().size()).toString());
recordStat("RelationshipMapSize",
new Integer(relationshipMap.getEntries().size()).toString());
}
private void walkModel(IProgramElement ipe) {
countNode(ipe);
List kids = ipe.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement nextElement = (IProgramElement) iter.next();
walkModel(nextElement);
}
}
private void countNode(IProgramElement ipe) {
String node = ipe.getKind().toString();
Integer ctr = (Integer)nodeTypeCount.get(node);
if (ctr==null) {
nodeTypeCount.put(node,new Integer(1));
} else {
ctr = new Integer(ctr.intValue()+1);
nodeTypeCount.put(node,ctr);
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Model node summary:\n");
Enumeration nodeKeys = nodeTypeCount.keys();
while (nodeKeys.hasMoreElements()) {
String key = (String)nodeKeys.nextElement();
Integer ct = (Integer)nodeTypeCount.get(key);
sb.append(key+"="+ct+"\n");
}
sb.append("Model stats:\n");
Enumeration ks = extraProperties.keys();
while (ks.hasMoreElements()) {
String k = (String)ks.nextElement();
String v = extraProperties.getProperty(k);
sb.append(k+"="+v+"\n");
}
return sb.toString();
}
public Properties getProperties() {
Properties p = new Properties();
Enumeration nodeKeys = nodeTypeCount.keys();
while (nodeKeys.hasMoreElements()) {
String key = (String)nodeKeys.nextElement();
Integer ct = (Integer)nodeTypeCount.get(key);
p.setProperty(key,ct.toString());
}
p.putAll(extraProperties);
return p;
}
public void recordStat(String string, String string2) {
extraProperties.setProperty(string,string2);
}
public static ModelInfo summarizeModel() {
return new ModelInfo(AsmManager.getDefault().getHierarchy(),
AsmManager.getDefault().getRelationshipMap());
}
}
/**
* Set to indicate whether we are currently building a structure model, should
* be set up front.
*/
public static void setCreatingModel(boolean b) {
creatingModel = b;
}
/**
* returns true if we are currently generating a structure model, enables
* guarding of expensive operations on an empty/null model.
*/
public static boolean isCreatingModel() { return creatingModel;}
}
|
82,171 |
Bug 82171 enable ASM interoperability with JavaCore via uniform element handles
| null |
resolved fixed
|
df7fff4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-14T16:44:01Z | 2005-01-04T20:20:00Z |
asm/src/org/aspectj/asm/IElementHandleProvider.java
| |
82,171 |
Bug 82171 enable ASM interoperability with JavaCore via uniform element handles
| null |
resolved fixed
|
df7fff4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-14T16:44:01Z | 2005-01-04T20:20:00Z |
asm/src/org/aspectj/asm/internal/AspectJElementHierarchy.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* Andy Clement Extensions for better IDE representation
* ******************************************************************/
package org.aspectj.asm.internal;
import java.io.*;
import java.util.*;
import org.aspectj.asm.*;
import org.aspectj.bridge.*;
/**
* @author Mik Kersten
*/
public class AspectJElementHierarchy implements IHierarchy {
protected IProgramElement root = null;
protected String configFile = null;
private Map fileMap = null;
private Map handleMap = null;
private Map typeMap = null;
public IProgramElement getElement(String handle) {
IProgramElement cachedEntry = (IProgramElement)handleMap.get(handle);
if (cachedEntry!=null) return cachedEntry;
StringTokenizer st = new StringTokenizer(handle, ProgramElement.ID_DELIM);
String file = st.nextToken();
int line = new Integer(st.nextToken()).intValue();
// int col = new Integer(st.nextToken()).intValue(); TODO: use column number when available
String canonicalSFP = AsmManager.getDefault().getCanonicalFilePath(new File(file));
IProgramElement ret = findNodeForSourceLineHelper(root,canonicalSFP, line);
if (ret!=null) {
handleMap.put(handle,ret);
}
return ret;
}
public IProgramElement getRoot() {
return root;
}
public void setRoot(IProgramElement root) {
this.root = root;
handleMap = new HashMap();
typeMap = new HashMap();
}
public void addToFileMap( Object key, Object value ){
fileMap.put( key, value );
}
public boolean removeFromFileMap(Object key) {
return (fileMap.remove(key)!=null);
}
public void setFileMap(HashMap fileMap) {
this.fileMap = fileMap;
}
public Object findInFileMap( Object key ) {
return fileMap.get(key);
}
public Set getFileMapEntrySet() {
return fileMap.entrySet();
}
public boolean isValid() {
return root != null && fileMap != null;
}
/**
* Returns the first match
*
* @param parent
* @param kind not null
* @return null if not found
*/
public IProgramElement findElementForSignature(IProgramElement parent, IProgramElement.Kind kind, String signature) {
for (Iterator it = parent.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (node.getKind() == kind && signature.equals(node.toSignatureString())) {
return node;
} else {
IProgramElement childSearch = findElementForSignature(node, kind, signature);
if (childSearch != null) return childSearch;
}
}
return null;
}
public IProgramElement findElementForLabel(
IProgramElement parent,
IProgramElement.Kind kind,
String label) {
for (Iterator it = parent.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (node.getKind() == kind && label.equals(node.toLabelString())) {
return node;
} else {
IProgramElement childSearch = findElementForLabel(node, kind, label);
if (childSearch != null) return childSearch;
}
}
return null;
}
/**
* @param packageName if null default package is searched
* @param className can't be null
*/
public IProgramElement findElementForType(String packageName, String typeName) {
StringBuffer keyb = (packageName == null) ? new StringBuffer() :
new StringBuffer(packageName);
keyb.append(".");
keyb.append(typeName);
String key = keyb.toString();
IProgramElement ret = (IProgramElement) typeMap.get(key);
if (ret == null) {
IProgramElement packageNode = null;
if (packageName == null) {
packageNode = root;
} else {
if (root == null) return null;
List kids = root.getChildren();
if (kids == null) return null;
for (Iterator it = kids.iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (packageName.equals(node.getName())) {
packageNode = node;
}
}
if (packageNode == null) return null;
}
// this searches each file for a class
for (Iterator it = packageNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement fileNode = (IProgramElement)it.next();
IProgramElement cNode = findClassInNodes(fileNode.getChildren(), typeName);
if (cNode != null) {
ret = cNode;
typeMap.put(key,ret);
}
}
}
return ret;
}
private IProgramElement findClassInNodes(Collection nodes, String name) {
String baseName;
String innerName;
int dollar = name.indexOf('$');
if (dollar == -1) {
baseName = name;
innerName = null;
} else {
baseName = name.substring(0, dollar);
innerName = name.substring(dollar+1);
}
for (Iterator j = nodes.iterator(); j.hasNext(); ) {
IProgramElement classNode = (IProgramElement)j.next();
if (baseName.equals(classNode.getName())) {
if (innerName == null) return classNode;
else return findClassInNodes(classNode.getChildren(), innerName);
} else if (name.equals(classNode.getName())) {
return classNode;
}
}
return null;
}
/**
* @param sourceFilePath modified to '/' delimited path for consistency
* @return a new structure node for the file if it was not found in the model
*/
public IProgramElement findElementForSourceFile(String sourceFile) {
try {
if (!isValid() || sourceFile == null) {
return IHierarchy.NO_STRUCTURE;
} else {
String correctedPath =
AsmManager.getDefault().getCanonicalFilePath(new File(sourceFile));
//StructureNode node = (StructureNode)getFileMap().get(correctedPath);//findFileNode(filePath, model);
IProgramElement node = (IProgramElement)findInFileMap(correctedPath);//findFileNode(filePath, model);
if (node != null) {
return node;
} else {
return createFileStructureNode(correctedPath);
}
}
} catch (Exception e) {
return IHierarchy.NO_STRUCTURE;
}
}
/**
* TODO: discriminate columns
*/
public IProgramElement findElementForSourceLine(ISourceLocation location) {
try {
return findElementForSourceLine(
AsmManager.getDefault().getCanonicalFilePath(
location.getSourceFile()),
location.getLine());
} catch (Exception e) {
return null;
}
}
/**
* Never returns null
*
* @param sourceFilePath canonicalized path for consistency
* @param lineNumber if 0 or 1 the corresponding file node will be returned
* @return a new structure node for the file if it was not found in the model
*/
public IProgramElement findElementForSourceLine(String sourceFilePath, int lineNumber) {
String canonicalSFP = AsmManager.getDefault().getCanonicalFilePath(
new File(sourceFilePath));
IProgramElement node = findNodeForSourceLineHelper(root, canonicalSFP, lineNumber);
if (node != null) {
return node;
} else {
return createFileStructureNode(sourceFilePath);
}
}
private IProgramElement createFileStructureNode(String sourceFilePath) {
// SourceFilePath might have originated on windows on linux...
int lastSlash = sourceFilePath.lastIndexOf('\\');
if (lastSlash == -1) {
lastSlash = sourceFilePath.lastIndexOf('/');
}
String fileName = sourceFilePath.substring(lastSlash+1);
IProgramElement fileNode = new ProgramElement(fileName, IProgramElement.Kind.FILE_JAVA, null);
fileNode.setSourceLocation(new SourceLocation(new File(sourceFilePath), 1, 1));
fileNode.addChild(NO_STRUCTURE);
return fileNode;
}
private IProgramElement findNodeForSourceLineHelper(IProgramElement node, String sourceFilePath, int lineNumber) {
if (matches(node, sourceFilePath, lineNumber)
&& !hasMoreSpecificChild(node, sourceFilePath, lineNumber)) {
return node;
}
if (node != null && node.getChildren() != null) {
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
IProgramElement foundNode = findNodeForSourceLineHelper(
(IProgramElement)it.next(),
sourceFilePath,
lineNumber);
if (foundNode != null) return foundNode;
}
}
return null;
}
private boolean matches(IProgramElement node, String sourceFilePath, int lineNumber) {
// try {
// if (node != null && node.getSourceLocation() != null)
// System.err.println("====\n1: " +
// sourceFilePath + "\n2: " +
// node.getSourceLocation().getSourceFile().getCanonicalPath().equals(sourceFilePath)
// );
return node != null
&& node.getSourceLocation() != null
&& node.getSourceLocation().getSourceFile().getAbsolutePath().equals(sourceFilePath)
&& ((node.getSourceLocation().getLine() <= lineNumber
&& node.getSourceLocation().getEndLine() >= lineNumber)
||
(lineNumber <= 1
&& node.getKind().isSourceFile())
);
// } catch (IOException ioe) {
// return false;
// }
}
private boolean hasMoreSpecificChild(IProgramElement node, String sourceFilePath, int lineNumber) {
for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
IProgramElement child = (IProgramElement)it.next();
if (matches(child, sourceFilePath, lineNumber)) return true;
}
return false;
}
public String getConfigFile() {
return configFile;
}
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
// TODO: optimize this lookup
public IProgramElement findElementForHandle(String handle) {
// try the cache first...
IProgramElement ret = (IProgramElement) handleMap.get(handle);
if (ret != null) return ret;
StringTokenizer st = new StringTokenizer(handle, ProgramElement.ID_DELIM);
String file = st.nextToken();
int line = new Integer(st.nextToken()).intValue();
// int col = new Integer(st.nextToken()).intValue();
// TODO: use column number when available
ret = findElementForSourceLine(file, line);
if (ret != null) {
cache(handle,(ProgramElement)ret);
}
return ret;
// IProgramElement parent = findElementForType(packageName, typeName);
// if (parent == null) return null;
// if (kind == IProgramElement.Kind.CLASS ||
// kind == IProgramElement.Kind.ASPECT) {
// return parent;
// } else {
// return findElementForSignature(parent, kind, name);
// }
}
//
// private IProgramElement findElementForBytecodeInfo(
// IProgramElement node,
// String parentName,
// String name,
// String signature) {
// for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
// IProgramElement curr = (IProgramElement)it.next();
// if (parentName.equals(curr.getParent().getBytecodeName())
// && name.equals(curr.getBytecodeName())
// && signature.equals(curr.getBytecodeSignature())) {
// return node;
// } else {
// IProgramElement childSearch = findElementForBytecodeInfo(curr, parentName, name, signature);
// if (childSearch != null) return childSearch;
// }
// }
// return null;
// }
protected void cache(String handle, ProgramElement pe) {
handleMap.put(handle,pe);
}
public void flushTypeMap() {
typeMap.clear();
}
public void flushHandleMap() {
handleMap.clear();
}
public void updateHandleMap(Set deletedFiles) {
// Only delete the entries we need to from the handle map - for performance reasons
List forRemoval = new ArrayList();
Set k = handleMap.keySet();
for (Iterator iter = k.iterator(); iter.hasNext();) {
String handle = (String) iter.next();
if (deletedFiles.contains(getFilename(handle))) forRemoval.add(handle);
}
for (Iterator iter = forRemoval.iterator(); iter.hasNext();) {
String handle = (String) iter.next();
handleMap.remove(handle);
}
}
// XXX shouldn't be aware of the delimiter
private String getFilename(String hid) {
return hid.substring(0,hid.indexOf("|"));
}
}
|
82,171 |
Bug 82171 enable ASM interoperability with JavaCore via uniform element handles
| null |
resolved fixed
|
df7fff4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-14T16:44:01Z | 2005-01-04T20:20:00Z |
asm/src/org/aspectj/asm/internal/FullPathHandleProvider.java
| |
82,171 |
Bug 82171 enable ASM interoperability with JavaCore via uniform element handles
| null |
resolved fixed
|
df7fff4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-14T16:44:01Z | 2005-01-04T20:20:00Z |
asm/src/org/aspectj/asm/internal/ProgramElement.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* Andy Clement Extensions for better IDE representation
* ******************************************************************/
package org.aspectj.asm.internal;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.HierarchyWalker;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
/**
* @author Mik Kersten
*/
public class ProgramElement implements IProgramElement {
static final String ID_DELIM = "|";
protected IProgramElement parent = null;
protected String name = "";
// children.listIterator() should support remove() operation
protected List children = new ArrayList();
protected IMessage message = null;
protected ISourceLocation sourceLocation = null;
private List modifiers = new ArrayList();
private List relations = new ArrayList();
private Kind kind;
private Accessibility accessibility;
private String declaringType = "";
private String formalComment = "";
private String packageName = null;
private boolean runnable = false;
private boolean implementor = false;
private boolean overrider = false;
private String bytecodeName;
private String bytecodeSignature;
// private String fullSignature;
private String returnType;
private List parameterNames = null;
private List parameterTypes = null;
private String details = null;
private ExtraInformation info;
/**
* Used during de-externalization.
*/
public ProgramElement() { }
/**
* Use to create program element nodes that do not correspond to source locations.
*/
public ProgramElement(
String name,
Kind kind,
List children) {
this.name = name;
this.kind = kind;
setChildren(children);
// System.err.println("> created: " + name + ", children: " + children);
}
public ProgramElement(
String name,
IProgramElement.Kind kind,
ISourceLocation sourceLocation,
int modifiers,
String formalComment,
List children)
{
this(name, kind, children);
this.sourceLocation = sourceLocation;
this.kind = kind;
this.formalComment = formalComment;
this.modifiers = genModifiers(modifiers);
this.accessibility = genAccessibility(modifiers);
cacheByHandle();
}
/**
* Use to create program element nodes that correspond to source locations.
*/
public ProgramElement(
String name,
Kind kind,
int modifiers,
Accessibility accessibility,
String declaringType,
String packageName,
String formalComment,
ISourceLocation sourceLocation,
List relations,
List children,
boolean member) {
this(name, kind, children);
this.sourceLocation = sourceLocation;
this.kind = kind;
this.modifiers = genModifiers(modifiers);
this.accessibility = accessibility;
this.declaringType = declaringType;
this.packageName = packageName;
this.formalComment = formalComment;
this.relations = relations;
cacheByHandle();
}
public List getModifiers() {
return modifiers;
}
public Accessibility getAccessibility() {
return accessibility;
}
public void setAccessibility(Accessibility a) {
accessibility=a;
}
public String getDeclaringType() {
return declaringType;
}
public String getPackageName() {
if (kind == Kind.PACKAGE) return getName();
if (getParent() == null || !(getParent() instanceof IProgramElement)) {
return "";
}
return ((IProgramElement)getParent()).getPackageName();
}
public Kind getKind() {
return kind;
}
public boolean isCode() {
return kind.equals(Kind.CODE);
}
public ISourceLocation getSourceLocation() {
return sourceLocation;
}
public void setSourceLocation(ISourceLocation sourceLocation) {
this.sourceLocation = sourceLocation;
}
public IMessage getMessage() {
return message;
}
public void setMessage(IMessage message) {
this.message = message;
}
public IProgramElement getParent() {
return parent;
}
public void setParent(IProgramElement parent) {
this.parent = parent;
}
public boolean isMemberKind() {
return kind.isMember();
}
public void setRunnable(boolean value) {
this.runnable = value;
}
public boolean isRunnable() {
return runnable;
}
public boolean isImplementor() {
return implementor;
}
public void setImplementor(boolean value) {
this.implementor = value;
}
public boolean isOverrider() {
return overrider;
}
public void setOverrider(boolean value) {
this.overrider = value;
}
public List getRelations() {
return relations;
}
public void setRelations(List relations) {
if (relations.size() > 0) {
this.relations = relations;
}
}
public String getFormalComment() {
return formalComment;
}
public String toString() {
return toLabelString();
}
private static List genModifiers(int modifiers) {
List modifiersList = new ArrayList();
if ((modifiers & AccStatic) != 0) modifiersList.add(IProgramElement.Modifiers.STATIC);
if ((modifiers & AccFinal) != 0) modifiersList.add(IProgramElement.Modifiers.FINAL);
if ((modifiers & AccSynchronized) != 0) modifiersList.add(IProgramElement.Modifiers.SYNCHRONIZED);
if ((modifiers & AccVolatile) != 0) modifiersList.add(IProgramElement.Modifiers.VOLATILE);
if ((modifiers & AccTransient) != 0) modifiersList.add(IProgramElement.Modifiers.TRANSIENT);
if ((modifiers & AccNative) != 0) modifiersList.add(IProgramElement.Modifiers.NATIVE);
if ((modifiers & AccAbstract) != 0) modifiersList.add(IProgramElement.Modifiers.ABSTRACT);
return modifiersList;
}
public static IProgramElement.Accessibility genAccessibility(int modifiers) {
if ((modifiers & AccPublic) != 0) return IProgramElement.Accessibility.PUBLIC;
if ((modifiers & AccPrivate) != 0) return IProgramElement.Accessibility.PRIVATE;
if ((modifiers & AccProtected) != 0) return IProgramElement.Accessibility.PROTECTED;
if ((modifiers & AccPrivileged) != 0) return IProgramElement.Accessibility.PRIVILEGED;
else return IProgramElement.Accessibility.PACKAGE;
}
// XXX these names and values are from org.eclipse.jdt.internal.compiler.env.IConstants
private static int AccPublic = 0x0001;
private static int AccPrivate = 0x0002;
private static int AccProtected = 0x0004;
private static int AccPrivileged = 0x0006; // XXX is this right?
private static int AccStatic = 0x0008;
private static int AccFinal = 0x0010;
private static int AccSynchronized = 0x0020;
private static int AccVolatile = 0x0040;
private static int AccTransient = 0x0080;
private static int AccNative = 0x0100;
// private static int AccInterface = 0x0200;
private static int AccAbstract = 0x0400;
// private static int AccStrictfp = 0x0800;
private String sourceSignature;
public String getBytecodeName() {
return bytecodeName;
}
public String getBytecodeSignature() {
return bytecodeSignature;
}
public void setBytecodeName(String bytecodeName) {
this.bytecodeName = bytecodeName;
}
public void setBytecodeSignature(String bytecodeSignature) {
this.bytecodeSignature = bytecodeSignature;
}
public String getSourceSignature() {
return sourceSignature;
}
public void setSourceSignature(String string) {
sourceSignature = string;
}
public void setKind(Kind kind) {
this.kind = kind;
}
public void setCorrespondingType(String returnType) {
this.returnType = returnType;
}
public String getCorrespondingType() {
return returnType;
}
public String getName() {
return name;
}
public List getChildren() {
return children;
}
public void setChildren(List children) {
this.children = children;
if (children == null) return;
for (Iterator it = children.iterator(); it.hasNext(); ) {
((IProgramElement)it.next()).setParent(this);
}
}
public void addChild(IProgramElement child) {
if (children == null) {
children = new ArrayList();
}
children.add(child);
child.setParent(this);
}
public void addChild(int position, IProgramElement child) {
if (children == null) {
children = new ArrayList();
}
children.add(position, child);
child.setParent(this);
}
public boolean removeChild(IProgramElement child) {
child.setParent(null);
return children.remove(child);
}
public void setName(String string) {
name = string;
}
// private void setParents() {
//// System.err.println(">> setting parents on: " + name);
// if (children == null) return;
// for (Iterator it = children.iterator(); it.hasNext(); ) {
// ((IProgramElement)it.next()).setParent(this);
// }
// }
public IProgramElement walk(HierarchyWalker walker) {
if (children!=null) {
for (Iterator it = children.iterator(); it.hasNext(); ) {
IProgramElement child = (IProgramElement)it.next();
walker.process(child);
}
}
return this;
}
public String toLongString() {
final StringBuffer buffer = new StringBuffer();
HierarchyWalker walker = new HierarchyWalker() {
private int depth = 0;
public void preProcess(IProgramElement node) {
for (int i = 0; i < depth; i++) buffer.append(' ');
buffer.append(node.toString());
buffer.append('\n');
depth += 2;
}
public void postProcess(IProgramElement node) {
depth -= 2;
}
};
walker.process(this);
return buffer.toString();
}
public void setModifiers(int i) {
this.modifiers = genModifiers(i);
}
public String toSignatureString() {
StringBuffer sb = new StringBuffer();
sb.append(name);
if (parameterTypes != null ) {
sb.append('(');
for (Iterator it = parameterTypes.iterator(); it.hasNext(); ) {
sb.append((String)it.next());
if (it.hasNext()) sb.append(", ");
}
sb.append(')');
}
return sb.toString();
}
public static boolean shortITDNames = true;
/**
* TODO: move the "parent != null"==>injar heuristic to more explicit
*/
public String toLinkLabelString() {
String label;
if (kind == Kind.CODE || kind == Kind.INITIALIZER) {
label = parent.getParent().getName() + ": ";
} else if (kind.isInterTypeMember()) {
if (shortITDNames) {
// if (name.indexOf('.')!=-1) return toLabelString().substring(name.indexOf('.')+1);
label="";
} else {
int dotIndex = name.indexOf('.');
if (dotIndex != -1) {
return parent.getName() + ": " + toLabelString().substring(dotIndex+1);
} else {
label = parent.getName() + '.';
}
}
} else if (kind == Kind.CLASS || kind == Kind.ASPECT || kind == Kind.INTERFACE) {
label = "";
} else if (kind.equals(Kind.DECLARE_PARENTS)) {
label = "";
} else {
if (parent != null) {
label = parent.getName() + '.';
} else {
label = "injar aspect: ";
}
}
label += toLabelString();
return label;
}
public String toLabelString() {
String label = toSignatureString();
if (details != null) {
label += ": " + details;
}
return label;
}
public static String createHandleIdentifier(File sourceFile, int line,int column,int offset) {
StringBuffer sb = new StringBuffer();
sb.append(AsmManager.getDefault().getCanonicalFilePath(sourceFile));
sb.append(ID_DELIM);
sb.append(line);
sb.append(ID_DELIM);
sb.append(column);
sb.append(ID_DELIM);
sb.append(offset);
return sb.toString();
}
private String handle = null;
public String getHandleIdentifier() {
if (null == handle) {
if (sourceLocation != null) {
return genHandleIdentifier(sourceLocation);
}
}
return handle;
}
public static String genHandleIdentifier(ISourceLocation sourceLocation) {
StringBuffer sb = new StringBuffer();
sb.append(AsmManager.getDefault()
.getCanonicalFilePath(sourceLocation.getSourceFile()));
sb.append(ID_DELIM);
sb.append(sourceLocation.getLine());
sb.append(ID_DELIM);
sb.append(sourceLocation.getColumn());
sb.append(ID_DELIM);
sb.append(sourceLocation.getOffset());
return sb.toString();
}
public List getParameterNames() {
return parameterNames;
}
public List getParameterTypes() {
return parameterTypes;
}
public void setParameterNames(List list) {
parameterNames = list;
}
public void setParameterTypes(List list) {
parameterTypes = list;
}
public String getDetails() {
return details;
}
public void setDetails(String string) {
details = string;
}
public void setFormalComment(String formalComment) {
this.formalComment = formalComment;
}
/** AMC added to speed up findByHandle lookups in AspectJElementHierarchy */
private void cacheByHandle() {
String handle = getHandleIdentifier();
if (handle != null) {
AspectJElementHierarchy hierarchy = (AspectJElementHierarchy)
AsmManager.getDefault().getHierarchy();
hierarchy.cache(handle,this);
}
}
public void setExtraInfo(ExtraInformation info) {
this.info = info;
}
public ExtraInformation getExtraInfo() {
return info;
}
}
|
82,171 |
Bug 82171 enable ASM interoperability with JavaCore via uniform element handles
| null |
resolved fixed
|
df7fff4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-14T16:44:01Z | 2005-01-04T20:20:00Z |
docs/sandbox/api-clients/org/aspectj/samples/AsmRelationshipMapExtensionTest.java
|
package org.aspectj.samples;
import java.util.Iterator;
import java.util.List;
import org.aspectj.ajde.AjdeTestCase;
import org.aspectj.asm.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.ResolvedTypeX;
/**
* @author Mik Kersten
*/
public class AsmRelationshipMapExtensionTest extends AjdeTestCase {
public void testDeclares() {
System.out.println("----------------------------------");
System.out.println("Parents declared by declare parents statements: ");
HierarchyWalker walker = new HierarchyWalker() {
public void preProcess(IProgramElement node) {
if (node.getKind().equals(IProgramElement.Kind.DECLARE_PARENTS)) {
System.out.println(node);
List relations = AsmManager.getDefault().getRelationshipMap().get(node);
if (relations != null) {
for (Iterator it = relations.iterator(); it.hasNext();) {
IRelationship relationship = (IRelationship) it.next();
List targets = relationship.getTargets();
for (Iterator iter = targets.iterator(); iter.hasNext();) {
IProgramElement currElt = AsmManager
.getDefault().getHierarchy()
.getElement((String) iter.next());
System.out.println("--> " + relationship.getName() + ": " + currElt);
}
}
}
}
}
};
AsmManager.getDefault().getHierarchy().getRoot().walk(walker);
}
protected void setUp() throws Exception {
AsmRelationshipProvider.setDefault(new DeclareInfoProvider());
super.setUp("examples");
assertTrue("build success",
doSynchronousBuild("../examples/coverage/coverage.lst"));
}
}
class DeclareInfoProvider extends AsmRelationshipProvider {
public void addDeclareParentsRelationship(ISourceLocation decp,
ResolvedTypeX targetType, List newParents) {
super.addDeclareParentsRelationship(decp, targetType, newParents);
for (Iterator it = newParents.iterator(); it.hasNext();) {
ResolvedTypeX superType = (ResolvedTypeX) it.next();
String sourceHandle = ProgramElement.createHandleIdentifier(
decp.getSourceFile(),decp.getLine(),decp.getColumn(), decp.getOffset());
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForHandle(sourceHandle);
String superHandle = ProgramElement.createHandleIdentifier(
superType.getSourceLocation().getSourceFile(),
superType.getSourceLocation().getLine(),
superType.getSourceLocation().getColumn(),
superType.getSourceLocation().getOffset()
);
if (sourceHandle != null && superHandle != null) {
IRelationship foreward = AsmManager.getDefault().getRelationshipMap().get(
sourceHandle,
IRelationship.Kind.DECLARE,
"super types declared",
false,
true);
foreward.addTarget(superHandle);
IRelationship back = AsmManager.getDefault().getRelationshipMap().get(
superHandle, IRelationship.Kind.DECLARE,
"declared as super type by",
false,
true);
back.addTarget(sourceHandle);
}
}
}
}
|
82,171 |
Bug 82171 enable ASM interoperability with JavaCore via uniform element handles
| null |
resolved fixed
|
df7fff4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-14T16:44:01Z | 2005-01-04T20:20:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AsmInterTypeRelationshipProvider.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
//import java.io.IOException;
import org.aspectj.asm.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.weaver.*;
/**
* !!! is this class still being used?
*
* @author Mik Kersten
*/
public class AsmInterTypeRelationshipProvider {
protected static AsmInterTypeRelationshipProvider INSTANCE = new AsmInterTypeRelationshipProvider();
public static final String INTER_TYPE_DECLARES = "declared on";
public static final String INTER_TYPE_DECLARED_BY = "aspect declarations";
public void addRelationship(
ResolvedTypeX onType,
EclipseTypeMunger munger) {
// IProgramElement.Kind kind = IProgramElement.Kind.ERROR;
// if (munger.getMunger().getKind() == ResolvedTypeMunger.Field) {
// kind = IProgramElement.Kind.INTER_TYPE_FIELD;
// } else if (munger.getMunger().getKind() == ResolvedTypeMunger.Constructor) {
// kind = IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR;
// } else if (munger.getMunger().getKind() == ResolvedTypeMunger.Method) {
// kind = IProgramElement.Kind.INTER_TYPE_METHOD;
// } else if (munger.getMunger().getKind() == ResolvedTypeMunger.Parent) {
// kind = IProgramElement.Kind.INTER_TYPE_PARENT;
// }
if (munger.getSourceLocation() != null
&& munger.getSourceLocation() != null) {
String sourceHandle = ProgramElement.createHandleIdentifier(
munger.getSourceLocation().getSourceFile(),
munger.getSourceLocation().getLine(),
munger.getSourceLocation().getColumn(),
munger.getSourceLocation().getOffset());
String targetHandle = ProgramElement.createHandleIdentifier(
onType.getSourceLocation().getSourceFile(),
onType.getSourceLocation().getLine(),
onType.getSourceLocation().getColumn(),
onType.getSourceLocation().getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY,false,true);
back.addTarget(sourceHandle);
}
}
}
public static AsmInterTypeRelationshipProvider getDefault() {
return INSTANCE;
}
/**
* Reset the instance of this class, intended for extensibility.
* This enables a subclass to become used as the default instance.
*/
public static void setDefault(AsmInterTypeRelationshipProvider instance) {
INSTANCE = instance;
}
}
|
82,171 |
Bug 82171 enable ASM interoperability with JavaCore via uniform element handles
| null |
resolved fixed
|
df7fff4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-14T16:44:01Z | 2005-01-04T20:20:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten revisions, added additional relationships
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.IOException;
import java.util.*;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.asm.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemHandler;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
/**
* At each iteration of <CODE>processCompilationUnit</CODE> the declarations for a
* particular compilation unit are added to the hierarchy passed as a a parameter.
* <p>
* Clients who extend this class need to ensure that they do not override any of the existing
* behavior. If they do, the structure model will not be built properly and tools such as IDE
* structure views and ajdoc will fail.
* <p>
* <b>Note:</b> this class is not considered public API and the overridable
* methods are subject to change.
*
* @author Mik Kersten
*/
public class AsmHierarchyBuilder extends ASTVisitor {
protected AsmElementFormatter formatter = new AsmElementFormatter();
/**
* Reset for every compilation unit.
*/
protected AjBuildConfig buildConfig;
/**
* Reset for every compilation unit.
*/
protected Stack stack;
/**
* Reset for every compilation unit.
*/
private CompilationResult currCompilationResult;
/**
*
* @param cuDeclaration
* @param buildConfig
* @param structureModel hiearchy to add this unit's declarations to
*/
public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) {
currCompilationResult = cuDeclaration.compilationResult();
LangUtil.throwIaxIfNull(currCompilationResult, "result");
stack = new Stack();
this.buildConfig = buildConfig;
internalBuild(cuDeclaration, structureModel);
// throw new RuntimeException("not implemented");
}
private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) {
LangUtil.throwIaxIfNull(structureModel, "structureModel");
if (!currCompilationResult.equals(unit.compilationResult())) {
throw new IllegalArgumentException("invalid unit: " + unit);
}
// ---- summary
// add unit to package (or root if no package),
// first removing any duplicate (XXX? removes children if 3 classes in same file?)
// push the node on the stack
// and traverse
// -- create node to add
final File file = new File(new String(unit.getFileName()));
final IProgramElement cuNode;
{
// AMC - use the source start and end from the compilation unit decl
int startLine = getStartLine(unit);
int endLine = getEndLine(unit);
SourceLocation sourceLocation
= new SourceLocation(file, startLine, endLine);
sourceLocation.setOffset(unit.sourceStart);
cuNode = new ProgramElement(
new String(file.getName()),
IProgramElement.Kind.FILE_JAVA,
sourceLocation,
0,
"",
new ArrayList());
}
cuNode.addChild(new ProgramElement(
"import declarations",
IProgramElement.Kind.IMPORT_REFERENCE,
null,
0,
"",
new ArrayList()));
final IProgramElement addToNode = genAddToNode(unit, structureModel);
// -- remove duplicates before adding (XXX use them instead?)
if (addToNode!=null && addToNode.getChildren()!=null) {
for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) {
IProgramElement child = (IProgramElement)itt.next();
ISourceLocation childLoc = child.getSourceLocation();
if (null == childLoc) {
// XXX ok, packages have null source locations
// signal others?
} else if (childLoc.getSourceFile().equals(file)) {
itt.remove();
}
}
}
// -- add and traverse
addToNode.addChild(cuNode);
stack.push(cuNode);
unit.traverse(this, unit.scope);
// -- update file map (XXX do this before traversal?)
try {
structureModel.addToFileMap(file.getCanonicalPath(), cuNode);
} catch (IOException e) {
System.err.println("IOException " + e.getMessage()
+ " creating path for " + file );
// XXX signal IOException when canonicalizing file path
}
}
/**
* Get/create the node (package or root) to add to.
*/
private IProgramElement genAddToNode(
CompilationUnitDeclaration unit,
IHierarchy structureModel) {
final IProgramElement addToNode;
{
ImportReference currentPackage = unit.currentPackage;
if (null == currentPackage) {
addToNode = structureModel.getRoot();
} else {
String pkgName;
{
StringBuffer nameBuffer = new StringBuffer();
final char[][] importName = currentPackage.getImportName();
final int last = importName.length-1;
for (int i = 0; i < importName.length; i++) {
nameBuffer.append(new String(importName[i]));
if (i < last) {
nameBuffer.append('.');
}
}
pkgName = nameBuffer.toString();
}
IProgramElement pkgNode = null;
if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) {
for (Iterator it = structureModel.getRoot().getChildren().iterator();
it.hasNext(); ) {
IProgramElement currNode = (IProgramElement)it.next();
if (pkgName.equals(currNode.getName())) {
pkgNode = currNode;
break;
}
}
}
if (pkgNode == null) {
// note packages themselves have no source location
pkgNode = new ProgramElement(
pkgName,
IProgramElement.Kind.PACKAGE,
new ArrayList()
);
structureModel.getRoot().addChild(pkgNode);
}
addToNode = pkgNode;
}
}
return addToNode;
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
String name = new String(typeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (typeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (typeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (typeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(typeDeclaration),
typeDeclaration.modifiers,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(typeDeclaration));
peNode.setFormalComment(generateJavadocComment(typeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
stack.pop();
}
// ??? share impl with visit(TypeDeclaration, ..) ?
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
String name = new String(memberTypeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
String fullName = "<undefined>";
if (memberTypeDeclaration.allocation != null
&& memberTypeDeclaration.allocation.type != null) {
// Create a name something like 'new Runnable() {..}'
fullName = "new "+memberTypeDeclaration.allocation.type.toString()+"() {..}";
} else if (memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
// If we couldn't find a nice name like 'new Runnable() {..}' then use the number after the $
fullName = new String(memberTypeDeclaration.binding.constantPoolName());
int dollar = fullName.indexOf('$');
fullName = fullName.substring(dollar+1);
}
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
IProgramElement peNode = new ProgramElement(
fullName,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
stack.pop();
}
private String genSourceSignature(TypeDeclaration typeDeclaration) {
StringBuffer output = new StringBuffer();
typeDeclaration.printHeader(0, output);
return output.toString();
}
private IProgramElement findEnclosingClass(Stack stack) {
for (int i = stack.size()-1; i >= 0; i--) {
IProgramElement pe = (IProgramElement)stack.get(i);
if (pe.getKind() == IProgramElement.Kind.CLASS) {
return pe;
}
}
return (IProgramElement)stack.peek();
}
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
IProgramElement peNode = null;
// For intertype decls, use the modifiers from the original signature, not the generated method
if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration;
ResolvedMember sig = itd.getSignature();
peNode = new ProgramElement(
"",
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
(sig!=null?sig.getModifiers():0),
"",
new ArrayList());
} else {
peNode = new ProgramElement(
"",
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
methodDeclaration.modifiers,
"",
new ArrayList());
}
formatter.genLabelAndKind(methodDeclaration, peNode);
genBytecodeInfo(methodDeclaration, peNode);
List namedPointcuts = genNamedPointcuts(methodDeclaration);
addUsesPointcutRelationsForNode(peNode, namedPointcuts, methodDeclaration);
if (methodDeclaration.returnType!=null) {
peNode.setCorrespondingType(methodDeclaration.returnType.toString());
} else {
peNode.setCorrespondingType(null);
}
peNode.setSourceSignature(genSourceSignature(methodDeclaration));
peNode.setFormalComment(generateJavadocComment(methodDeclaration));
// TODO: add return type test
if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) {
if (peNode.toLabelString().equals("main(String[])")
&& peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC)
&& peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) {
((IProgramElement)stack.peek()).setRunnable(true);
}
}
stack.push(peNode);
return true;
}
private void addUsesPointcutRelationsForNode(IProgramElement peNode, List namedPointcuts, MethodDeclaration declaration) {
for (Iterator it = namedPointcuts.iterator(); it.hasNext();) {
ReferencePointcut rp = (ReferencePointcut) it.next();
ResolvedMember member = getPointcutDeclaration(rp, declaration);
if (member != null) {
IRelationship foreward = AsmManager.getDefault().getRelationshipMap().get(peNode.getHandleIdentifier(), IRelationship.Kind.USES_POINTCUT, "uses pointcut", false, true);
foreward.addTarget(ProgramElement.genHandleIdentifier(member.getSourceLocation()));
IRelationship back = AsmManager.getDefault().getRelationshipMap().get(ProgramElement.genHandleIdentifier(member.getSourceLocation()), IRelationship.Kind.USES_POINTCUT, "pointcut used by", false, true);
back.addTarget(peNode.getHandleIdentifier());
}
}
}
private ResolvedMember getPointcutDeclaration(ReferencePointcut rp, MethodDeclaration declaration) {
World world = ((AjLookupEnvironment)declaration.scope.environment()).factory.getWorld();
TypeX onType = rp.onType;
if (onType == null) {
if (declaration.binding != null) {
Member member = EclipseFactory.makeResolvedMember(declaration.binding);
onType = member.getDeclaringType();
} else {
return null;
}
}
ResolvedMember[] members = onType.getDeclaredPointcuts(world);
if (members != null) {
for (int i = 0; i < members.length; i++) {
if (members[i].getName().equals(rp.name)) {
return members[i];
}
}
}
return null;
}
/**
* @param methodDeclaration
* @return all of the named pointcuts referenced by the PCD of this declaration
*/
private List genNamedPointcuts(MethodDeclaration methodDeclaration) {
List pointcuts = new ArrayList();
if (methodDeclaration instanceof AdviceDeclaration) {
if (((AdviceDeclaration)methodDeclaration).pointcutDesignator != null)
addAllNamed(((AdviceDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts);
} else if (methodDeclaration instanceof PointcutDeclaration) {
if (((PointcutDeclaration)methodDeclaration).pointcutDesignator != null)
addAllNamed(((PointcutDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts);
}
return pointcuts;
}
/**
* @param left
* @param pointcuts accumulator for named pointcuts
*/
private void addAllNamed(Pointcut pointcut, List pointcuts) {
if (pointcut == null) return;
if (pointcut instanceof ReferencePointcut) {
ReferencePointcut rp = (ReferencePointcut)pointcut;
pointcuts.add(rp);
} else if (pointcut instanceof AndPointcut) {
AndPointcut ap = (AndPointcut)pointcut;
addAllNamed(ap.getLeft(), pointcuts);
addAllNamed(ap.getRight(), pointcuts);
} else if (pointcut instanceof OrPointcut) {
OrPointcut op = (OrPointcut)pointcut;
addAllNamed(op.getLeft(), pointcuts);
addAllNamed(op.getRight(), pointcuts);
}
}
private String genSourceSignature(MethodDeclaration methodDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(methodDeclaration.modifiers, output);
methodDeclaration.printReturnType(0, output).append(methodDeclaration.selector).append('(');
if (methodDeclaration.arguments != null) {
for (int i = 0; i < methodDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (methodDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < methodDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) {
if (methodDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
Member member = EclipseFactory.makeResolvedMember(methodDeclaration.binding);
memberName = member.getName();
memberBytecodeSignature = member.getSignature();
} catch (BCException bce) { // bad type name
memberName = "<undefined>";
} catch (NullPointerException npe) {
memberName = "<undefined>";
}
peNode.setBytecodeName(memberName);
peNode.setBytecodeSignature(memberBytecodeSignature);
}
((IProgramElement)stack.peek()).addChild(peNode);
}
public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
IProgramElement peNode = new ProgramElement(
new String(importRef.toString()),
IProgramElement.Kind.IMPORT_REFERENCE,
makeLocation(importRef),
0,
"",
new ArrayList());
ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0);
imports.addChild(0, peNode);
stack.push(peNode);
}
return true;
}
public void endVisit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
stack.pop();
}
}
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
IProgramElement peNode = null;
if (fieldDeclaration.type == null) { // The field represents an enum value
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.ENUM_VALUE,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
"", new ArrayList());
peNode.setCorrespondingType(fieldDeclaration.binding.type.debugName());
} else {
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.FIELD,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
"", new ArrayList());
peNode.setCorrespondingType(fieldDeclaration.type.toString());
}
peNode.setSourceSignature(genSourceSignature(fieldDeclaration));
peNode.setFormalComment(generateJavadocComment(fieldDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
stack.pop();
}
/**
* Checks if comments should be added to the model before generating.
*/
protected String generateJavadocComment(ASTNode astNode) {
if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null;
StringBuffer sb = new StringBuffer(); // !!! specify length?
boolean completed = false;
int startIndex = -1;
if (astNode instanceof MethodDeclaration) {
startIndex = ((MethodDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof FieldDeclaration) {
startIndex = ((FieldDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof TypeDeclaration) {
startIndex = ((TypeDeclaration)astNode).declarationSourceStart;
}
if (startIndex == -1) {
return null;
} else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /**
&& currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*'
&& currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') {
for (int i = startIndex; i < astNode.sourceStart && !completed; i++) {
char curr = currCompilationResult.compilationUnit.getContents()[i];
if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */
sb.append(currCompilationResult.compilationUnit.getContents()[i]);
}
return sb.toString();
} else {
return null;
}
}
/**
* Doesn't print qualified allocation expressions.
*/
protected String genSourceSignature(FieldDeclaration fieldDeclaration) {
StringBuffer output = new StringBuffer();
FieldDeclaration.printModifiers(fieldDeclaration.modifiers, output);
if (fieldDeclaration.type == null) { // This is an enum value
output.append(fieldDeclaration.binding.type.debugName()).append(" ").append(fieldDeclaration.name);
} else {
fieldDeclaration.type.print(0, output).append(' ').append(fieldDeclaration.name);
}
if (fieldDeclaration.initialization != null
&& !(fieldDeclaration.initialization instanceof QualifiedAllocationExpression)) {
output.append(" = "); //$NON-NLS-1$
if (fieldDeclaration.initialization instanceof ExtendedStringLiteral) {
output.append("\"<extended string literal>\"");
} else {
fieldDeclaration.initialization.printExpression(0, output);
}
}
output.append(';');
return output.toString();
}
// public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// new String(importRef.toString()),
// ProgramElementNode.Kind.,
// makeLocation(importRef),
// 0,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(0, peNode);
// stack.push(peNode);
// return true;
// }
// public void endVisit(ImportReference importRef,CompilationUnitScope scope) {
// stack.pop();
// }
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
if (constructorDeclaration.isDefaultConstructor) {
stack.push(null); // a little wierd but does the job
return true;
}
StringBuffer argumentsSignature = new StringBuffer();
argumentsSignature.append("(");
if (constructorDeclaration.arguments!=null) {
for (int i = 0;i<constructorDeclaration.arguments.length;i++) {
argumentsSignature.append(constructorDeclaration.arguments[i].type);
if (i+1<constructorDeclaration.arguments.length) argumentsSignature.append(",");
}
}
argumentsSignature.append(")");
IProgramElement peNode = new ProgramElement(
new String(constructorDeclaration.selector)+argumentsSignature,
IProgramElement.Kind.CONSTRUCTOR,
makeLocation(constructorDeclaration),
constructorDeclaration.modifiers,
"",
new ArrayList());
peNode.setModifiers(constructorDeclaration.modifiers);
peNode.setSourceSignature(genSourceSignature(constructorDeclaration));
// Fix to enable us to anchor things from ctor nodes
if (constructorDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
Member member = EclipseFactory.makeResolvedMember(constructorDeclaration.binding);
memberName = member.getName();
memberBytecodeSignature = member.getSignature();
} catch (BCException bce) { // bad type name
memberName = "<undefined>";
} catch (NullPointerException npe) {
memberName = "<undefined>";
}
peNode.setBytecodeName(memberName);
peNode.setBytecodeSignature(memberBytecodeSignature);
}
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
stack.pop();
}
private String genSourceSignature(ConstructorDeclaration constructorDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(constructorDeclaration.modifiers, output);
output.append(constructorDeclaration.selector).append('(');
if (constructorDeclaration.arguments != null) {
for (int i = 0; i < constructorDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (constructorDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < constructorDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
// public boolean visit(Clinit clinit, ClassScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// "<clinit>",
// ProgramElementNode.Kind.INITIALIZER,
// makeLocation(clinit),
// clinit.modifiers,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(peNode);
// stack.push(peNode);
// return false;
// }
// public void endVisit(Clinit clinit, ClassScope scope) {
// stack.pop();
// }
/** This method works-around an odd traverse implementation on Initializer
*/
private Initializer inInitializer = null;
public boolean visit(Initializer initializer, MethodScope scope) {
if (initializer == inInitializer) return false;
inInitializer = initializer;
IProgramElement peNode = new ProgramElement(
"...",
IProgramElement.Kind.INITIALIZER,
makeLocation(initializer),
initializer.modifiers,
"",
new ArrayList());
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
initializer.block.traverse(this, scope);
stack.pop();
return false;
}
// ??? handle non-existant files
protected ISourceLocation makeLocation(ASTNode node) {
String fileName = "";
if (currCompilationResult.getFileName() != null) {
fileName = new String(currCompilationResult.getFileName());
}
// AMC - different strategies based on node kind
int startLine = getStartLine(node);
int endLine = getEndLine(node);
SourceLocation loc = null;
if ( startLine <= endLine ) {
// found a valid end line for this node...
loc = new SourceLocation(new File(fileName), startLine, endLine);
loc.setOffset(node.sourceStart);
} else {
loc = new SourceLocation(new File(fileName), startLine);
loc.setOffset(node.sourceStart);
}
return loc;
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getStartLine( ASTNode n){
// if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n);
// if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n);
// if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
n.sourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getEndLine( ASTNode n){
if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n);
if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n);
if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
n.sourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractVariableDeclaration avd ) {
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// avd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractVariableDeclaration avd ){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
avd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractMethodDeclaration amd ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// amd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractMethodDeclaration amd) {
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
amd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( TypeDeclaration td ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// td.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( TypeDeclaration td){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
td.declarationSourceEnd);
}
}
|
82,171 |
Bug 82171 enable ASM interoperability with JavaCore via uniform element handles
| null |
resolved fixed
|
df7fff4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-14T16:44:01Z | 2005-01-04T20:20:00Z |
weaver/src/org/aspectj/weaver/AsmRelationshipProvider.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.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Utility;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.weaver.bcel.BcelAdvice;
public class AsmRelationshipProvider {
protected static AsmRelationshipProvider INSTANCE = new AsmRelationshipProvider();
public static final String ADVISES = "advises";
public static final String ADVISED_BY = "advised by";
public static final String DECLARES_ON = "declares on";
public static final String DECLAREDY_BY = "declared by";
public static final String MATCHED_BY = "matched by";
public static final String MATCHES_DECLARE = "matches declare";
public static final String INTER_TYPE_DECLARES = "declared on";
public static final String INTER_TYPE_DECLARED_BY = "aspect declarations";
public static final String ANNOTATES = "annotates";
public static final String ANNOTATED_BY = "annotated by";
public void checkerMunger(IHierarchy model, Shadow shadow, Checker checker) {
if (!AsmManager.isCreatingModel()) return;
if (shadow.getSourceLocation() == null || checker.getSourceLocation() == null) return;
// Ensure a node for the target exists
IProgramElement targetNode = getNode(AsmManager.getDefault().getHierarchy(), shadow);
String sourceHandle = ProgramElement.createHandleIdentifier(
checker.getSourceLocation().getSourceFile(),
checker.getSourceLocation().getLine(),
checker.getSourceLocation().getColumn(),
checker.getSourceLocation().getOffset());
String targetHandle = ProgramElement.createHandleIdentifier(
shadow.getSourceLocation().getSourceFile(),
shadow.getSourceLocation().getLine(),
shadow.getSourceLocation().getColumn(),
shadow.getSourceLocation().getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE, MATCHED_BY,false,true);
foreward.addTarget(targetHandle);
// foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE, MATCHES_DECLARE,false,true);
if (back != null && back.getTargets() != null) {
back.addTarget(sourceHandle);
//back.getTargets().add(sourceHandle);
}
}
}
// For ITDs
public void addRelationship(
ResolvedTypeX onType,
ResolvedTypeMunger munger,
ResolvedTypeX originatingAspect) {
if (!AsmManager.isCreatingModel()) return;
String sourceHandle = "";
if (munger.getSourceLocation()!=null) {
sourceHandle = ProgramElement.createHandleIdentifier(
munger.getSourceLocation().getSourceFile(),
munger.getSourceLocation().getLine(),
munger.getSourceLocation().getColumn(),
munger.getSourceLocation().getOffset());
} else {
sourceHandle = ProgramElement.createHandleIdentifier(
originatingAspect.getSourceLocation().getSourceFile(),
originatingAspect.getSourceLocation().getLine(),
originatingAspect.getSourceLocation().getColumn(),
originatingAspect.getSourceLocation().getOffset());
}
if (originatingAspect.getSourceLocation() != null) {
String targetHandle = ProgramElement.createHandleIdentifier(
onType.getSourceLocation().getSourceFile(),
onType.getSourceLocation().getLine(),
onType.getSourceLocation().getColumn(),
onType.getSourceLocation().getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES,false,true);
foreward.addTarget(targetHandle);
// foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY,false,true);
back.addTarget(sourceHandle);
// back.getTargets().add(sourceHandle);
}
}
}
public void addDeclareParentsRelationship(ISourceLocation decp,ResolvedTypeX targetType, List newParents) {
if (!AsmManager.isCreatingModel()) return;
String sourceHandle = ProgramElement.createHandleIdentifier(decp.getSourceFile(),decp.getLine(),decp.getColumn(),decp.getOffset());
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForHandle(sourceHandle);
String targetHandle = ProgramElement.createHandleIdentifier(
targetType.getSourceLocation().getSourceFile(),
targetType.getSourceLocation().getLine(),
targetType.getSourceLocation().getColumn(),
targetType.getSourceLocation().getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY,false,true);
back.addTarget(sourceHandle);
}
}
/**
* Adds a declare annotation relationship, sometimes entities don't have source locs (methods/fields) so use other
* variants of this method if that is the case as they will look the entities up in the structure model.
*/
public void addDeclareAnnotationRelationship(ISourceLocation declareAnnotationLocation,ISourceLocation annotatedLocation) {
if (!AsmManager.isCreatingModel()) return;
String sourceHandle = ProgramElement.createHandleIdentifier(declareAnnotationLocation.getSourceFile(),declareAnnotationLocation.getLine(),
declareAnnotationLocation.getColumn(),declareAnnotationLocation.getOffset());
IProgramElement declareAnnotationPE = AsmManager.getDefault().getHierarchy().findElementForHandle(sourceHandle);
String targetHandle = ProgramElement.createHandleIdentifier(
annotatedLocation.getSourceFile(),
annotatedLocation.getLine(),
annotatedLocation.getColumn(),
annotatedLocation.getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY,false,true);
back.addTarget(sourceHandle);
}
}
public void adviceMunger(IHierarchy model, Shadow shadow, ShadowMunger munger) {
if (!AsmManager.isCreatingModel()) return;
if (munger instanceof Advice) {
Advice advice = (Advice)munger;
if (advice.getKind().isPerEntry() || advice.getKind().isCflow()) {
// TODO: might want to show these in the future
return;
}
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
IProgramElement targetNode = getNode(AsmManager.getDefault().getHierarchy(), shadow);
boolean runtimeTest = ((BcelAdvice)munger).hasDynamicTests();
// Work out extra info to inform interested UIs !
IProgramElement.ExtraInformation ai = new IProgramElement.ExtraInformation();
String adviceHandle = advice.getHandle();
// What kind of advice is it?
// TODO: Prob a better way to do this but I just want to
// get it into CVS !!!
AdviceKind ak = ((Advice)munger).getKind();
ai.setExtraAdviceInformation(ak.getName());
IProgramElement adviceElement = AsmManager.getDefault().getHierarchy().findElementForHandle(adviceHandle);
adviceElement.setExtraInfo(ai);
if (adviceHandle != null && targetNode != null) {
if (targetNode != null) {
String targetHandle = targetNode.getHandleIdentifier();
IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.ADVICE, ADVISES,runtimeTest,true);
if (foreward != null) foreward.addTarget(targetHandle);//foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.ADVICE, ADVISED_BY,runtimeTest,true);
if (back != null) back.addTarget(adviceHandle);//back.getTargets().add(adviceHandle);
}
}
}
}
protected IProgramElement getNode(IHierarchy model, Shadow shadow) {
Member enclosingMember = shadow.getEnclosingCodeSignature();
IProgramElement enclosingNode = lookupMember(model, enclosingMember);
if (enclosingNode == null) {
Lint.Kind err = shadow.getIWorld().getLint().shadowNotInStructure;
if (err.isEnabled()) {
err.signal(shadow.toString(), shadow.getSourceLocation());
}
return null;
}
Member shadowSig = shadow.getSignature();
if (!shadowSig.equals(enclosingMember)) {
IProgramElement bodyNode = findOrCreateCodeNode(enclosingNode, shadowSig, shadow);
return bodyNode;
} else {
return enclosingNode;
}
}
private boolean sourceLinesMatch(ISourceLocation loc1,ISourceLocation loc2) {
if (loc1.getLine()!=loc2.getLine()) return false;
return true;
}
private IProgramElement findOrCreateCodeNode(IProgramElement enclosingNode, Member shadowSig, Shadow shadow)
{
for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (shadowSig.getName().equals(node.getBytecodeName()) &&
shadowSig.getSignature().equals(node.getBytecodeSignature()) &&
sourceLinesMatch(node.getSourceLocation(),shadow.getSourceLocation()))
{
return node;
}
}
ISourceLocation sl = shadow.getSourceLocation();
// XXX why not use shadow file? new SourceLocation(sl.getSourceFile(), sl.getLine()),
SourceLocation peLoc = new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(),sl.getLine());
peLoc.setOffset(sl.getOffset());
IProgramElement peNode = new ProgramElement(
shadow.toString(),
IProgramElement.Kind.CODE,
peLoc,
0,
"",
new ArrayList());
peNode.setBytecodeName(shadowSig.getName());
peNode.setBytecodeSignature(shadowSig.getSignature());
enclosingNode.addChild(peNode);
return peNode;
}
protected IProgramElement lookupMember(IHierarchy model, Member member) {
TypeX declaringType = member.getDeclaringType();
IProgramElement classNode =
model.findElementForType(declaringType.getPackageName(), declaringType.getClassName());
return findMemberInClass(classNode, member);
}
protected IProgramElement findMemberInClass(
IProgramElement classNode,
Member member)
{
if (classNode == null) return null; // XXX remove this check
for (Iterator it = classNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (member.getName().equals(node.getBytecodeName()) &&
member.getSignature().equals(node.getBytecodeSignature()))
{
return node;
}
}
// if we can't find the member, we'll just put it in the class
return classNode;
}
// private static IProgramElement.Kind genShadowKind(Shadow shadow) {
// IProgramElement.Kind shadowKind;
// if (shadow.getKind() == Shadow.MethodCall
// || shadow.getKind() == Shadow.ConstructorCall
// || shadow.getKind() == Shadow.FieldGet
// || shadow.getKind() == Shadow.FieldSet
// || shadow.getKind() == Shadow.ExceptionHandler) {
// return IProgramElement.Kind.CODE;
//
// } else if (shadow.getKind() == Shadow.MethodExecution) {
// return IProgramElement.Kind.METHOD;
//
// } else if (shadow.getKind() == Shadow.ConstructorExecution) {
// return IProgramElement.Kind.CONSTRUCTOR;
//
// } else if (shadow.getKind() == Shadow.PreInitialization
// || shadow.getKind() == Shadow.Initialization) {
// return IProgramElement.Kind.CLASS;
//
// } else if (shadow.getKind() == Shadow.AdviceExecution) {
// return IProgramElement.Kind.ADVICE;
//
// } else {
// return IProgramElement.Kind.ERROR;
// }
// }
public static AsmRelationshipProvider getDefault() {
return INSTANCE;
}
/**
* Reset the instance of this class, intended for extensibility.
* This enables a subclass to become used as the default instance.
*/
public static void setDefault(AsmRelationshipProvider instance) {
INSTANCE = instance;
}
/**
* Add a relationship to the known set for a declare @method/@constructor construct.
* Locating the method is a messy (for messy read 'fragile') bit of code that could break at any moment
* but it's working for my simple testcase. Currently just fails silently if any of the lookup code
* doesn't find anything...
*/
public void addDeclareAnnotationRelationship(ISourceLocation sourceLocation, String typename,Method method) {
if (!AsmManager.isCreatingModel()) return;
String pkg = null;
String type = typename;
int packageSeparator = typename.lastIndexOf(".");
if (packageSeparator!=-1) {
pkg = typename.substring(0,packageSeparator);
type = typename.substring(packageSeparator+1);
}
IProgramElement typeElem = AsmManager.getDefault().getHierarchy().findElementForType(pkg,type);
if (typeElem == null) return;
StringBuffer parmString = new StringBuffer("(");
Type[] args = method.getArgumentTypes();
for (int i = 0; i < args.length; i++) {
Type type2 = args[i];
String s = Utility.signatureToString(type2.getSignature());
if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1);
parmString.append(s);
if ((i+1)<args.length) parmString.append(",");
}
parmString.append(")");
IProgramElement methodElem = null;
if (method.getName().startsWith("<init>")) {
// its a ctor
methodElem = AsmManager.getDefault().getHierarchy().findElementForSignature(typeElem,IProgramElement.Kind.CONSTRUCTOR,type+parmString);
} else {
// its a method
methodElem = AsmManager.getDefault().getHierarchy().findElementForSignature(typeElem,IProgramElement.Kind.METHOD,method.getName()+parmString);
}
if (methodElem == null) return;
try {
String sourceHandle =
ProgramElement.createHandleIdentifier(sourceLocation.getSourceFile(),sourceLocation.getLine(),
sourceLocation.getColumn(),sourceLocation.getOffset());
String targetHandle = methodElem.getHandleIdentifier();
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY,false,true);
back.addTarget(sourceHandle);
}
} catch (Throwable t) { // I'm worried about that code above, this will make sure we don't explode if it plays up
t.printStackTrace(); // I know I know .. but I don't want to lose it!
}
}
/**
* Add a relationship to the known set for a declare @field construct. Locating the field is trickier than
* it might seem since we have no line number info for it, we have to dig through the structure model under
* the fields' type in order to locate it. Currently just fails silently if any of the lookup code
* doesn't find anything...
*/
public void addDeclareAnnotationRelationship(ISourceLocation sourceLocation, String typename,Field field) {
if (!AsmManager.isCreatingModel()) return;
String pkg = null;
String type = typename;
int packageSeparator = typename.lastIndexOf(".");
if (packageSeparator!=-1) {
pkg = typename.substring(0,packageSeparator);
type = typename.substring(packageSeparator+1);
}
IProgramElement typeElem = AsmManager.getDefault().getHierarchy().findElementForType(pkg,type);
if (typeElem == null) return;
IProgramElement fieldElem = AsmManager.getDefault().getHierarchy().findElementForSignature(typeElem,IProgramElement.Kind.FIELD,field.getName());
if (fieldElem== null) return;
String sourceHandle =
ProgramElement.createHandleIdentifier(sourceLocation.getSourceFile(),sourceLocation.getLine(),
sourceLocation.getColumn(),sourceLocation.getOffset());
String targetHandle = fieldElem.getHandleIdentifier();
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY,false,true);
back.addTarget(sourceHandle);
}
}
}
|
82,171 |
Bug 82171 enable ASM interoperability with JavaCore via uniform element handles
| null |
resolved fixed
|
df7fff4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-14T16:44:01Z | 2005-01-04T20:20:00Z |
weaver/src/org/aspectj/weaver/ShadowMunger.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.Collection;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* For every shadow munger, nothing can be done with it until it is concretized. Then...
*
* (Then we call fast match.)
*
* For every shadow munger, for every shadow,
* first match is called,
* then (if match returned true) the shadow munger is specialized for the shadow,
* which may modify state.
* Then implement is called.
*/
public abstract class ShadowMunger implements PartialOrder.PartialComparable, IHasPosition {
protected Pointcut pointcut;
// these three fields hold the source location of this munger
protected int start, end;
protected ISourceContext sourceContext;
private ISourceLocation sourceLocation;
private String handle = null;
public ShadowMunger(Pointcut pointcut, int start, int end, ISourceContext sourceContext) {
this.pointcut = pointcut;
this.start = start;
this.end = end;
this.sourceContext = sourceContext;
}
public abstract ShadowMunger concretize(ResolvedTypeX fromType, World world, PerClause clause);
public abstract void specializeOn(Shadow shadow);
public abstract void implementOn(Shadow shadow);
/**
* All overriding methods should call super
*/
public boolean match(Shadow shadow, World world) {
return pointcut.match(shadow).maybeTrue();
}
public int fallbackCompareTo(Object other) {
return toString().compareTo(toString());
}
public int getEnd() {
return end;
}
public int getStart() {
return start;
}
public ISourceLocation getSourceLocation() {
if (sourceLocation == null) {
if (sourceContext != null) {
sourceLocation = sourceContext.makeSourceLocation(this);
}
}
return sourceLocation;
}
public String getHandle() {
if (null == handle) {
ISourceLocation sl = getSourceLocation();
if (sl != null) {
handle = ProgramElement.createHandleIdentifier(
sl.getSourceFile(),
sl.getLine(),
sl.getColumn(),
sl.getOffset());
}
}
return handle;
}
// ---- fields
public static final ShadowMunger[] NONE = new ShadowMunger[0];
public Pointcut getPointcut() {
return pointcut;
}
// pointcut may be updated during rewriting...
public void setPointcut(Pointcut pointcut) {
this.pointcut = pointcut;
}
/**
* @return a Collection of ResolvedTypeX for all checked exceptions that
* might be thrown by this munger
*/
public abstract Collection getThrownExceptions();
}
|
91,858 |
Bug 91858 NullPointerException when declare @type is spelt with capital letter
|
I have the following code in an AspectJ project: declare @Type: MainClass : @MyAnnotation; I believe the correct syntax should be: declare @type: MainClass : @MyAnnotation; However when I saved my aspect with the first version I got the following NullPointerException: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.DeclareAnnotationDeclaration.postParse (DeclareAnnotationDeclaration.java:83) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope.postParse (ClassScope.java:175) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope.buildFieldsAndM ethods(ClassScope.java:154) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope.build FieldsAndMethods(CompilationUnitScope.java:63) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindi ngs(AjLookupEnvironment.java:104) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile (Compiler.java:331) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:348) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:683) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:191) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild (AjBuildManager.java:109) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:165)
|
resolved fixed
|
78abc76
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-20T12:57:49Z | 2005-04-19T08:40:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/DeclareAnnotationDeclaration.java
|
/* *******************************************************************
* Copyright (c) 2005 IBM Corporation.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Adrian Colyer initial implementation
* Andy Clement wired up to back end
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.flow.FlowInfo;
import org.aspectj.org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits;
import org.aspectj.weaver.patterns.DeclareAnnotation;
public class DeclareAnnotationDeclaration extends DeclareDeclaration {
private Annotation annotation;
public DeclareAnnotationDeclaration(CompilationResult result, DeclareAnnotation symbolicDeclare, Annotation annotation) {
super(result,symbolicDeclare);
this.annotation = annotation;
addAnnotation(annotation);
if (symbolicDeclare==null) return; // there is an error that will already be getting reported (e.g. incorrect pattern on decaf/decac)
symbolicDeclare.setAnnotationString(annotation.toString());
}
public void analyseCode(ClassScope classScope,
InitializationFlowContext initializationContext, FlowInfo flowInfo) {
super.analyseCode(classScope, initializationContext, flowInfo);
long bits = annotation.resolvedType.getAnnotationTagBits();
if ((bits&TagBits.AnnotationTarget)!=0) {
// The annotation is stored against a method. For declare @type we need to
// confirm the annotation targets the right types. Earlier checking will
// have not found this problem because an annotation for target METHOD will
// not be reported on as we *do* store it against a method in this case
DeclareAnnotation.Kind k = ((DeclareAnnotation)declareDecl).getKind();
if (k.equals(DeclareAnnotation.AT_TYPE))
if ((bits&TagBits.AnnotationForMethod)!=0)
classScope.problemReporter().disallowedTargetForAnnotation(annotation);
if (k.equals(DeclareAnnotation.AT_FIELD))
if ((bits&TagBits.AnnotationForMethod)!=0)
classScope.problemReporter().disallowedTargetForAnnotation(annotation);
}
}
public Annotation getDeclaredAnnotation() {
return annotation;
}
protected boolean shouldDelegateCodeGeneration() {
return true; // declare annotation needs a method to be written out.
}
private void addAnnotation(Annotation ann) {
if (this.annotations == null) {
this.annotations = new Annotation[1];
} else {
Annotation[] old = this.annotations;
this.annotations = new Annotation[old.length + 1];
System.arraycopy(old,0,this.annotations,1,old.length);
}
this.annotations[0] = ann;
}
public void postParse(TypeDeclaration typeDec) {
super.postParse(typeDec);
((DeclareAnnotation)declareDecl).setAnnotationMethod(new String(selector));
}
}
|
91,858 |
Bug 91858 NullPointerException when declare @type is spelt with capital letter
|
I have the following code in an AspectJ project: declare @Type: MainClass : @MyAnnotation; I believe the correct syntax should be: declare @type: MainClass : @MyAnnotation; However when I saved my aspect with the first version I got the following NullPointerException: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.DeclareAnnotationDeclaration.postParse (DeclareAnnotationDeclaration.java:83) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope.postParse (ClassScope.java:175) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope.buildFieldsAndM ethods(ClassScope.java:154) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope.build FieldsAndMethods(CompilationUnitScope.java:63) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindi ngs(AjLookupEnvironment.java:104) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile (Compiler.java:331) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:348) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:683) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:191) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild (AjBuildManager.java:109) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:165)
|
resolved fixed
|
78abc76
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-20T12:57:49Z | 2005-04-19T08:40:00Z |
tests/src/org/aspectj/systemtest/ajc150/DeclareAnnotationTests.java
|
/*******************************************************************************
* Copyright (c) 2005 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement initial implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.File;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class DeclareAnnotationTests extends XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(DeclareAnnotationTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
// parsing the various forms of declare @
public void testDeclareAnnotationParsing() {
runTest("basic declare annotation parse test");
}
// declare @type
// declare @type for one simple annotation on one specific type
public void testAtType_OneAnnotationHittingOneType_Src() {
runTest("declare @type 1");
}
// declare @type for one simple annotation to multiple types
public void testAtType_OneAnnotationHittingMultipleTypes_Src() {
runTest("declare @type 2");
}
// declare @type for one simple annotation and a pointcut that matches on it
public void testAtType_PointcutMatchingOnDeclaredAnnotation() {
runTest("declare @type - with matching pointcut");
}
// binary weaving declare @type, one annotation on one type
public void testAtType_OneAnnotationHittingOneType_Bin() {
runTest("declare @type - binary weaving");
}
// an annotation with multiple values (all the primitives and string)
// is declared upon a single type
public void testAtType_ComplexAnnotation_BinWeaving() {
runTest("declare @type - complex annotation - binary weaving");
}
public void testAtType_ComplexAnnotation_SrcWeaving() {
runTest("declare @type - complex annotation - source weaving");
}
// two annotations are declared on a type
public void testAtType_TwoAnnotationsOnOneType_BinWeaving() {
runTest("declare @type - two annotations hit one type - binary weaving");
}
public void testAtType_TwoAnnotationsOnOneType_SrcWeaving() {
runTest("declare @type - two annotations hit one type - source weaving");
}
// decp and deca can interact, let's try some variants that should
// result in the same thing
public void testAtType_InteractingWithDeclareParents1_BinWeaving() {
runTest("declare @type - declare parents interactions (order 1) - binary weaving");
}
public void testAtType_InteractingWithDeclareParents1_SrcWeaving() {
runTest("declare @type - declare parents interactions (order 1) - source weaving");
}
public void testAtType_InteractingWithDeclareParents2_BinWeaving() {
runTest("declare @type - declare parents interactions (order 2) - binary weaving");
}
public void testAtType_InteractingWithDeclareParents2_SrcWeaving() {
runTest("declare @type - declare parents interactions (order 2) - source weaving");
}
public void testAtType_InteractingWithDeclareParents3_BinWeaving() {
runTest("declare @type - declare parents interactions (order 3) - binary weaving");
}
public void testAtType_InteractingWithDeclareParents3_SrcWeaving() {
runTest("declare @type - declare parents interactions (order 3) - source weaving");
}
public void testAtType_InteractingWithDeclareParents4_BinWeaving() {
runTest("declare @type - declare parents interactions (order 4) - binary weaving");
}
public void testAtType_InteractingWithDeclareParents4_SrcWeaving() {
runTest("declare @type - declare parents interactions (order 4) - source weaving");
}
public void testAtType_AnnotatingAlreadyAnnotatedType_BinWeaving() {
runTest("declare @type - annotating an already annotated type - binary weaving");
}
public void testAtType_AnnotatingAlreadyAnnotatedType_SrcWeaving() {
runTest("declare @type - annotating an already annotated type - source weaving");
}
// testing for error messages when exact type patterns used
// public void testAtType_UsingWrongAnnotationOnAType_BinWeaving()
// runTest("declare @type - annotations with different targets - binary weaving");
// }
public void testAtType_UsingWrongAnnotationOnAType_SrcWeaving() {
runTest("declare @type - annotations with different targets - source weaving");
}
// testing for the lint message when non exact patterns used
// public void testAtType_UsingWrongAnnotationOnAType_TypeSpecifiedByPattern_BinWeaving() {
// runTest("declare @type - annotations with different targets (using type patterns) - binary weaving");
// }
public void testAtType_UsingWrongAnnotationOnAType_TypeSpecifiedByPattern_SrcWeaving() {
runTest("declare @type - annotations with different targets (using type patterns) - source weaving");
}
// testing how multiple decAtType/decps interact when they rely on each other
public void testAtType_ComplexDecpDecAtTypeInteractions_BinWeaving() {
runTest("declare @type - complex decp decAtType interactions - binary weaving");
}
public void testAtType_ComplexDecpDecAtTypeInteractions_SrcWeaving() {
runTest("declare @type - complex decp decAtType interactions - source weaving");
}
public void testAtType_PuttingIncorrectAnnosOnTypes_SrcWeaving() {
runTest("declare @type - trying to put annotation targetting annos on normal types - source weaving");
}
public void testAtType_PuttingIncorrectAnnosOnTypes_BinWeaving() {
runTest("declare @type - trying to put annotation targetting annos on normal types - binary weaving");
}
public void testAtType_PuttingIncorrectAnnosOnTypesWithPatterns_SrcWeaving() {
runTest("declare @type - trying to put annotation targetting annos on normal types (uses pattern) - source weaving");
}
public void testAtType_PuttingIncorrectAnnosOnTypesWithPatterns_BinWeaving() {
runTest("declare @type - trying to put annotation targetting annos on normal types (uses pattern) - binary weaving");
}
// I think this fails because of a freaky JDT compiler bug ...
// public void testAtType_UsingClassOrEnumElementValuesInAnnotations_SrcWeaving() {
// runTest("declare @type - covering enum and class element values - source weaving");
// }
public void testAtType_UsingClassOrEnumElementValuesInAnnotations_BinWeaving() {
runTest("declare @type - covering enum and class element values - binary weaving");
}
/////////////////////////////////////////////////////////////////////////////////
// declare @field
public void testAtField_SimpleSource() {
runTest("declare @field - simple source weaving");
}
public void testAtField_SimpleBinary() {
runTest("declare @field - simple binary weaving");
}
// lint warning
public void testAtField_TwoTheSameOnOneSource() {
runTest("declare @field - two the same on one - source weaving");
}
// lint warning
public void testAtField_TwoTheSameOnOneBinary() {
runTest("declare @field - two the same on one - binary weaving");
}
public void testAtField_TwoDifferentOnOneSource() {
runTest("declare @field - two different on one - source weaving");
}
public void testAtField_TwoDifferentOnOneBinary() {
runTest("declare @field - two different on one - binary weaving");
}
public void testAtField_WrongTargetSource() {
runTest("declare @field - wrong target - source weaving");
}
// Can't do a test like this - as verification of the declare @ is
// done when the aspect is first compiled.
// public void testAtField_WrongTargetBinary() {
// runTest("declare @field - wrong target - binary weaving");
// }
public void testAtField_RightTargetSource() {
runTest("declare @field - right target - source weaving");
}
public void testAtField_RightTargetBinary() {
runTest("declare @field - right target - binary weaving");
}
public void testAtField_RecursiveSource() {
runTest("declare @field - recursive application - source weaving");
}
public void testAtField_RecursiveBinary() {
runTest("declare @field - recursive application - binary weaving");
}
public void testAtField_RecursiveOtherOrderSource() {
runTest("declare @field - recursive application (other order) - source weaving");
}
public void testAtField_RecursiveOtherOrderBinary() {
runTest("declare @field - recursive application (other order) - binary weaving");
}
/////////////////////////////////////////////////////////////////////////////////
// declare @method
public void testAtMethod_SimpleSource() {
runTest("declare @method - simple source weaving");
}
public void testAtMethod_SimpleBinary() {
runTest("declare @method - simple binary weaving");
}
/////////////////////////////////////////////////////////////////////////////////
// declare @constructor
public void testAtCtor_SimpleSource() {
runTest("declare @constructor - simple source weaving");
}
public void testAtCtor_SimpleBinary() {
runTest("declare @constructor - simple binary weaving");
}
/////////////////////////////////////////////////////////////////////////////////
// declare @method @constructor
public void testAtMethodCtor_WrongTargetSource() {
runTest("declare @method @ctor - wrong target - source weaving");
}
public void testAtMethodCtor_RightTargetSource() {
runTest("declare @method @ctor - right target - source weaving");
}
public void testAtMethodCtor_RightTargetBinary() {
runTest("declare @method @ctor - right target - binary weaving");
}
// lint warning
public void testAtMethodCtor_TwoTheSameOnOneSource() {
runTest("declare @method @ctor - two the same on one - source weaving");
}
// lint warning
public void testAtMethodCtor_TwoTheSameOnOneBinary() {
runTest("declare @method @ctor - two the same on one - binary weaving");
}
public void testAtMethodCtor_TwoDifferentOnOneSource() {
runTest("declare @method @ctor - two different on one - source weaving");
}
public void testAtMethodCtor_TwoDifferentOnOneBinary() {
runTest("declare @method @ctor - two different on one - binary weaving");
}
// to debug this test, uncomment the first line which will give you a nice
// dump of the structure model in c:/debug.txt
public void testStructureModel() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare all annotations on one class - source weaving");
if (getCurrentTest().canRunOnThisVM()) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE,
"declare @type: p.q.DeathByAnnotations : @Colored(\"red\")");
assertTrue("Couldn't find 'declare @type' element in the tree",ipe!=null);
List l = AsmManager.getDefault().getRelationshipMap().get(ipe);
assertTrue("Should have a relationship but does not ",l.size()>0);
ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: * m*(..) : @Fruit(\"tomato\")");
assertTrue("Couldn't find 'declare @method element in the tree",ipe!=null);
l = AsmManager.getDefault().getRelationshipMap().get(ipe);
assertTrue("Should have a relationship but does not ",l.size()>0);
ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR,
"declare @constructor: p.q.DeathByAnnotations.new(..) : @Fruit(\"tomato\")");
assertTrue("Couldn't find 'declare @constructor element in the tree",ipe!=null);
l = AsmManager.getDefault().getRelationshipMap().get(ipe);
assertTrue("Should have a relationship but does not ",l.size()>0);
ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_FIELD,
"declare @field: * p.q.DeathByAnnotations.* : @Material(\"wood\")");
assertTrue("Couldn't find 'declare @field element in the tree",ipe!=null);
l = AsmManager.getDefault().getRelationshipMap().get(ipe);
assertTrue("Should have a relationship but does not ",l.size()>0);
}
}
}
|
91,858 |
Bug 91858 NullPointerException when declare @type is spelt with capital letter
|
I have the following code in an AspectJ project: declare @Type: MainClass : @MyAnnotation; I believe the correct syntax should be: declare @type: MainClass : @MyAnnotation; However when I saved my aspect with the first version I got the following NullPointerException: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.DeclareAnnotationDeclaration.postParse (DeclareAnnotationDeclaration.java:83) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope.postParse (ClassScope.java:175) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope.buildFieldsAndM ethods(ClassScope.java:154) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope.build FieldsAndMethods(CompilationUnitScope.java:63) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindi ngs(AjLookupEnvironment.java:104) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile (Compiler.java:331) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile (Compiler.java:348) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation (AjBuildManager.java:683) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:191) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild (AjBuildManager.java:109) at org.aspectj.ajde.internal.CompilerAdapter.compile (CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run (AspectJBuildManager.java:165)
|
resolved fixed
|
78abc76
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-20T12:57:49Z | 2005-04-19T08:40:00Z |
weaver/src/org/aspectj/weaver/patterns/PatternParser.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.util.ArrayList;
import java.util.List;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
//XXX doesn't handle errors for extra tokens very well (sometimes ignores)
public class PatternParser {
private ITokenSource tokenSource;
private ISourceContext sourceContext;
/**
* Constructor for PatternParser.
*/
public PatternParser(ITokenSource tokenSource) {
super();
this.tokenSource = tokenSource;
this.sourceContext = tokenSource.getSourceContext();
}
public PerClause maybeParsePerClause() {
IToken tok = tokenSource.peek();
if (tok == IToken.EOF) return null;
if (tok.isIdentifier()) {
String name = tok.getString();
if (name.equals("issingleton")) {
return parsePerSingleton();
} else if (name.equals("perthis")) {
return parsePerObject(true);
} else if (name.equals("pertarget")) {
return parsePerObject(false);
} else if (name.equals("percflow")) {
return parsePerCflow(false);
} else if (name.equals("percflowbelow")) {
return parsePerCflow(true);
} else if (name.equals("pertypewithin")) { // PTWIMPL Parse the pertypewithin clause
return parsePerTypeWithin();
} else {
return null;
}
}
return null;
}
private PerClause parsePerCflow(boolean isBelow) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new PerCflow(entry, isBelow);
}
private PerClause parsePerObject(boolean isThis) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new PerObject(entry, isThis);
}
private PerClause parsePerTypeWithin() {
parseIdentifier();
eat("(");
TypePattern withinTypePattern = parseTypePattern();
eat(")");
return new PerTypeWithin(withinTypePattern);
}
private PerClause parsePerSingleton() {
parseIdentifier();
eat("(");
eat(")");
return new PerSingleton();
}
public Declare parseDeclare() {
int startPos = tokenSource.peek().getStart();
eatIdentifier("declare");
String kind = parseIdentifier();
eat(":");
Declare ret;
if (kind.equals("error")) {
ret = parseErrorOrWarning(true);
} else if (kind.equals("warning")) {
ret = parseErrorOrWarning(false);
} else if (kind.equals("precedence")) {
ret = parseDominates();
} else if (kind.equals("dominates")) {
throw new ParserException("name changed to declare precedence", tokenSource.peek(-2));
} else if (kind.equals("parents")) {
ret = parseParents();
} else if (kind.equals("soft")) {
ret = parseSoft();
} else {
throw new ParserException("expected one of error, warning, parents, soft, dominates",
tokenSource.peek(-1));
}
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
public Declare parseDeclareAnnotation() {
int startPos = tokenSource.peek().getStart();
eatIdentifier("declare");
eat("@");
String kind = parseIdentifier();
eat(":");
Declare ret;
if (kind.equals("type")) {
ret = parseDeclareAtType();
} else if (kind.equals("method")) {
ret = parseDeclareAtMethod(true);
} else if (kind.equals("field")) {
ret = parseDeclareAtField();
} else if (kind.equals("constructor")) {
ret = parseDeclareAtMethod(false);
} else {
throw new ParserException("expected one of type, method, field, constructor",
tokenSource.peek(-1));
}
eat(";");
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
public DeclareAnnotation parseDeclareAtType() {
return new DeclareAnnotation(DeclareAnnotation.AT_TYPE,parseTypePattern());
}
public DeclareAnnotation parseDeclareAtMethod(boolean isMethod) {
SignaturePattern sp = parseMethodOrConstructorSignaturePattern();
boolean isConstructorPattern = (sp.getKind() == Member.CONSTRUCTOR);
if (isMethod && isConstructorPattern) {
throw new ParserException("method signature pattern",tokenSource.peek(-1));
}
if (!isMethod && !isConstructorPattern) {
throw new ParserException("constructor signature pattern",tokenSource.peek(-1));
}
if (isConstructorPattern) return new DeclareAnnotation(DeclareAnnotation.AT_CONSTRUCTOR,sp);
else return new DeclareAnnotation(DeclareAnnotation.AT_METHOD,sp);
}
public DeclareAnnotation parseDeclareAtField() {
return new DeclareAnnotation(DeclareAnnotation.AT_FIELD,parseFieldSignaturePattern());
}
public DeclarePrecedence parseDominates() {
List l = new ArrayList();
do {
l.add(parseTypePattern());
} while (maybeEat(","));
return new DeclarePrecedence(l);
}
private Declare parseParents() {
TypePattern p = parseTypePattern();
IToken t = tokenSource.next();
if (!(t.getString().equals("extends") || t.getString().equals("implements"))) {
throw new ParserException("extends or implements", t);
}
List l = new ArrayList();
do {
l.add(parseTypePattern());
} while (maybeEat(","));
//XXX somewhere in the chain we need to enforce that we have only ExactTypePatterns
return new DeclareParents(p, l);
}
private Declare parseSoft() {
TypePattern p = parseTypePattern();
eat(":");
Pointcut pointcut = parsePointcut();
return new DeclareSoft(p, pointcut);
}
private Declare parseErrorOrWarning(boolean isError) {
Pointcut pointcut = parsePointcut();
eat(":");
String message = parsePossibleStringSequence(true);
return new DeclareErrorOrWarning(isError, pointcut, message);
}
public Pointcut parsePointcut() {
Pointcut p = parseAtomicPointcut();
if (maybeEat("&&")) {
p = new AndPointcut(p, parseNotOrPointcut());
}
if (maybeEat("||")) {
p = new OrPointcut(p, parsePointcut());
}
return p;
}
private Pointcut parseNotOrPointcut() {
Pointcut p = parseAtomicPointcut();
if (maybeEat("&&")) {
p = new AndPointcut(p, parsePointcut());
}
return p;
}
private Pointcut parseAtomicPointcut() {
if (maybeEat("!")) {
int startPos = tokenSource.peek(-1).getStart();
Pointcut p = new NotPointcut(parseAtomicPointcut(), startPos);
return p;
}
if (maybeEat("(")) {
Pointcut p = parsePointcut();
eat(")");
return p;
}
if (maybeEat("@")) {
int startPos = tokenSource.peek().getStart();
Pointcut p = parseAnnotationPointcut();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext, startPos, endPos);
return p;
}
int startPos = tokenSource.peek().getStart();
Pointcut p = parseSinglePointcut();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext, startPos, endPos);
return p;
}
public Pointcut parseSinglePointcut() {
int start = tokenSource.getIndex();
IToken t = tokenSource.peek();
Pointcut p = t.maybeGetParsedPointcut();
if (p != null) {
tokenSource.next();
return p;
}
String kind = parseIdentifier();
tokenSource.setIndex(start);
if (kind.equals("execution") || kind.equals("call") ||
kind.equals("get") || kind.equals("set")) {
return parseKindedPointcut();
} else if (kind.equals("args")) {
return parseArgsPointcut();
} else if (kind.equals("this") || kind.equals("target")) {
return parseThisOrTargetPointcut();
} else if (kind.equals("within")) {
return parseWithinPointcut();
} else if (kind.equals("withincode")) {
return parseWithinCodePointcut();
} else if (kind.equals("cflow")) {
return parseCflowPointcut(false);
} else if (kind.equals("cflowbelow")) {
return parseCflowPointcut(true);
} else if (kind.equals("adviceexecution")) {
parseIdentifier(); eat("(");
eat(")");
return new KindedPointcut(Shadow.AdviceExecution,
new SignaturePattern(Member.ADVICE, ModifiersPattern.ANY,
TypePattern.ANY, TypePattern.ANY, NamePattern.ANY,
TypePatternList.ANY,
ThrowsPattern.ANY,
AnnotationTypePattern.ANY));
} else if (kind.equals("handler")) {
parseIdentifier(); eat("(");
TypePattern typePat = parseTypePattern();
eat(")");
return new HandlerPointcut(typePat);
} else if (kind.equals("initialization")) {
parseIdentifier(); eat("(");
SignaturePattern sig = parseConstructorSignaturePattern();
eat(")");
return new KindedPointcut(Shadow.Initialization, sig);
} else if (kind.equals("staticinitialization")) {
parseIdentifier(); eat("(");
TypePattern typePat = parseTypePattern();
eat(")");
return new KindedPointcut(Shadow.StaticInitialization,
new SignaturePattern(Member.STATIC_INITIALIZATION, ModifiersPattern.ANY,
TypePattern.ANY, typePat, NamePattern.ANY, TypePatternList.EMPTY,
ThrowsPattern.ANY,AnnotationTypePattern.ANY));
} else if (kind.equals("preinitialization")) {
parseIdentifier(); eat("(");
SignaturePattern sig = parseConstructorSignaturePattern();
eat(")");
return new KindedPointcut(Shadow.PreInitialization, sig);
} else {
return parseReferencePointcut();
}
}
public Pointcut parseAnnotationPointcut() {
int start = tokenSource.getIndex();
IToken t = tokenSource.peek();
String kind = parseIdentifier();
tokenSource.setIndex(start);
if (kind.equals("annotation")) {
return parseAtAnnotationPointcut();
} else if (kind.equals("args")) {
return parseArgsAnnotationPointcut();
} else if (kind.equals("this") || kind.equals("target")) {
return parseThisOrTargetAnnotationPointcut();
} else if (kind.equals("within")) {
return parseWithinAnnotationPointcut();
} else if (kind.equals("withincode")) {
return parseWithinCodeAnnotationPointcut();
} throw new ParserException("@pointcut name expected, but found " + kind, t);
}
private Pointcut parseAtAnnotationPointcut() {
parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("@AnnotationName or parameter", tokenSource.peek());
}
ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new AnnotationPointcut(type);
}
private SignaturePattern parseConstructorSignaturePattern() {
SignaturePattern ret = parseMethodOrConstructorSignaturePattern();
if (ret.getKind() == Member.CONSTRUCTOR) return ret;
throw new ParserException("constructor pattern required, found method pattern",
ret);
}
private Pointcut parseWithinCodePointcut() {
parseIdentifier();
eat("(");
SignaturePattern sig = parseMethodOrConstructorSignaturePattern();
eat(")");
return new WithincodePointcut(sig);
}
private Pointcut parseCflowPointcut(boolean isBelow) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new CflowPointcut(entry, isBelow, null);
}
/**
* Method parseWithinPointcut.
* @return Pointcut
*/
private Pointcut parseWithinPointcut() {
parseIdentifier();
eat("(");
TypePattern type = parseTypePattern();
eat(")");
return new WithinPointcut(type);
}
/**
* Method parseThisOrTargetPointcut.
* @return Pointcut
*/
private Pointcut parseThisOrTargetPointcut() {
String kind = parseIdentifier();
eat("(");
TypePattern type = parseTypePattern();
eat(")");
return new ThisOrTargetPointcut(kind.equals("this"), type);
}
private Pointcut parseThisOrTargetAnnotationPointcut() {
String kind = parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek());
}
ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new ThisOrTargetAnnotationPointcut(kind.equals("this"),type);
}
private Pointcut parseWithinAnnotationPointcut() {
String kind = parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek());
}
AnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new WithinAnnotationPointcut(type);
}
private Pointcut parseWithinCodeAnnotationPointcut() {
String kind = parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek());
}
ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new WithinCodeAnnotationPointcut(type);
}
/**
* Method parseArgsPointcut.
* @return Pointcut
*/
private Pointcut parseArgsPointcut() {
parseIdentifier();
TypePatternList arguments = parseArgumentsPattern();
return new ArgsPointcut(arguments);
}
private Pointcut parseArgsAnnotationPointcut() {
parseIdentifier();
AnnotationPatternList arguments = parseArgumentsAnnotationPattern();
return new ArgsAnnotationPointcut(arguments);
}
private Pointcut parseReferencePointcut() {
TypePattern onType = parseTypePattern();
NamePattern name = tryToExtractName(onType);
if (name == null) {
throw new ParserException("name pattern", tokenSource.peek());
}
if (onType.toString().equals("")) {
onType = null;
}
TypePatternList arguments = parseArgumentsPattern();
return new ReferencePointcut(onType, name.maybeGetSimpleName(), arguments);
}
public List parseDottedIdentifier() {
List ret = new ArrayList();
ret.add(parseIdentifier());
while (maybeEat(".")) {
ret.add(parseIdentifier());
}
return ret;
}
private KindedPointcut parseKindedPointcut() {
String kind = parseIdentifier();
eat("(");
SignaturePattern sig;
Shadow.Kind shadowKind = null;
if (kind.equals("execution")) {
sig = parseMethodOrConstructorSignaturePattern();
if (sig.getKind() == Member.METHOD) {
shadowKind = Shadow.MethodExecution;
} else if (sig.getKind() == Member.CONSTRUCTOR) {
shadowKind = Shadow.ConstructorExecution;
}
} else if (kind.equals("call")) {
sig = parseMethodOrConstructorSignaturePattern();
if (sig.getKind() == Member.METHOD) {
shadowKind = Shadow.MethodCall;
} else if (sig.getKind() == Member.CONSTRUCTOR) {
shadowKind = Shadow.ConstructorCall;
}
} else if (kind.equals("get")) {
sig = parseFieldSignaturePattern();
shadowKind = Shadow.FieldGet;
} else if (kind.equals("set")) {
sig = parseFieldSignaturePattern();
shadowKind = Shadow.FieldSet;
} else {
throw new ParserException("bad kind: " + kind, tokenSource.peek());
}
eat(")");
return new KindedPointcut(shadowKind, sig);
}
public TypePattern parseTypePattern() {
TypePattern p = parseAtomicTypePattern();
if (maybeEat("&&")) {
p = new AndTypePattern(p, parseNotOrTypePattern());
}
if (maybeEat("||")) {
p = new OrTypePattern(p, parseTypePattern());
}
return p;
}
private TypePattern parseNotOrTypePattern() {
TypePattern p = parseAtomicTypePattern();
if (maybeEat("&&")) {
p = new AndTypePattern(p, parseTypePattern());
}
return p;
}
private TypePattern parseAtomicTypePattern() {
AnnotationTypePattern ap = maybeParseAnnotationPattern();
if (maybeEat("!")) {
//int startPos = tokenSource.peek(-1).getStart();
//??? we lose source location for true start of !type
TypePattern p = new NotTypePattern(parseAtomicTypePattern());
p = setAnnotationPatternForTypePattern(p,ap);
return p;
}
if (maybeEat("(")) {
TypePattern p = parseTypePattern();
p = setAnnotationPatternForTypePattern(p,ap);
eat(")");
boolean isVarArgs = maybeEat("...");
p.setIsVarArgs(isVarArgs);
return p;
}
int startPos = tokenSource.peek().getStart();
TypePattern p = parseSingleTypePattern();
int endPos = tokenSource.peek(-1).getEnd();
p = setAnnotationPatternForTypePattern(p,ap);
p.setLocation(sourceContext, startPos, endPos);
return p;
}
private TypePattern setAnnotationPatternForTypePattern(TypePattern t, AnnotationTypePattern ap) {
TypePattern ret = t;
if (ap != AnnotationTypePattern.ANY) {
if (t == TypePattern.ANY) {
ret = new WildTypePattern(new NamePattern[] {NamePattern.ANY},false,0,false);
}
if (t.annotationPattern == AnnotationTypePattern.ANY) {
ret.setAnnotationTypePattern(ap);
} else {
ret.setAnnotationTypePattern(new AndAnnotationTypePattern(ap,t.annotationPattern)); //???
}
}
return ret;
}
public AnnotationTypePattern maybeParseAnnotationPattern() {
AnnotationTypePattern ret = AnnotationTypePattern.ANY;
AnnotationTypePattern nextPattern = null;
while ((nextPattern = maybeParseSingleAnnotationPattern()) != null) {
if (ret == AnnotationTypePattern.ANY) {
ret = nextPattern;
} else {
ret = new AndAnnotationTypePattern(ret,nextPattern);
}
}
return ret;
}
public AnnotationTypePattern maybeParseSingleAnnotationPattern() {
AnnotationTypePattern ret = null;
// LALR(2) - fix by making "!@" a single token
int startIndex = tokenSource.getIndex();
if (maybeEat("!")) {
if (maybeEat("@")) {
if (maybeEat("(")) {
TypePattern p = parseTypePattern();
ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p));
eat(")");
return ret;
} else {
TypePattern p = parseSingleTypePattern();
ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p));
return ret;
}
} else {
tokenSource.setIndex(startIndex); // not for us!
return ret;
}
}
if (maybeEat("@")) {
if (maybeEat("(")) {
TypePattern p = parseTypePattern();
ret = new WildAnnotationTypePattern(p);
eat(")");
return ret;
} else {
TypePattern p = parseSingleTypePattern();
ret = new WildAnnotationTypePattern(p);
return ret;
}
} else {
tokenSource.setIndex(startIndex); // not for us!
return ret;
}
}
public TypePattern parseSingleTypePattern() {
List names = parseDottedNamePattern();
// new ArrayList();
// NamePattern p1 = parseNamePattern();
// names.add(p1);
// while (maybeEat(".")) {
// if (maybeEat(".")) {
// names.add(NamePattern.ELLIPSIS);
// }
// NamePattern p2 = parseNamePattern();
// names.add(p2);
// }
int dim = 0;
while (maybeEat("[")) {
eat("]");
dim++;
}
boolean isVarArgs = maybeEat("...");
boolean includeSubtypes = maybeEat("+");
int endPos = tokenSource.peek(-1).getEnd();
//??? what about the source location of any's????
if (names.size() == 1 && ((NamePattern)names.get(0)).isAny() && dim == 0 && !isVarArgs) return TypePattern.ANY;
// Notice we increase the dimensions if varargs is set. this is to allow type matching to
// succeed later: The actual signature at runtime of a method declared varargs is an array type of
// the original declared type (so Integer... becomes Integer[] in the bytecode). So, here for the
// pattern 'Integer...' we create a WildTypePattern 'Integer[]' with varargs set. If this matches
// during shadow matching, we confirm that the varargs flags match up before calling it a successful
// match.
return new WildTypePattern(names, includeSubtypes, dim+(isVarArgs?1:0), endPos,isVarArgs);
}
// private AnnotationTypePattern completeAnnotationPattern(AnnotationTypePattern p) {
// if (maybeEat("&&")) {
// return new AndAnnotationTypePattern(p,parseNotOrAnnotationPattern());
// }
// if (maybeEat("||")) {
// return new OrAnnotationTypePattern(p,parseAnnotationTypePattern());
// }
// return p;
// }
//
// protected AnnotationTypePattern parseAnnotationTypePattern() {
// AnnotationTypePattern ap = parseAtomicAnnotationPattern();
// if (maybeEat("&&")) {
// ap = new AndAnnotationTypePattern(ap, parseNotOrAnnotationPattern());
// }
//
// if (maybeEat("||")) {
// ap = new OrAnnotationTypePattern(ap, parseAnnotationTypePattern());
// }
// return ap;
// }
//
// private AnnotationTypePattern parseNotOrAnnotationPattern() {
// AnnotationTypePattern p = parseAtomicAnnotationPattern();
// if (maybeEat("&&")) {
// p = new AndAnnotationTypePattern(p,parseAnnotationTypePattern());
// }
// return p;
// }
protected ExactAnnotationTypePattern parseAnnotationNameOrVarTypePattern() {
ExactAnnotationTypePattern p = null;
int startPos = tokenSource.peek().getStart();
if (maybeEat("@")) {
throw new ParserException("@Foo form was deprecated in AspectJ 5 M2: annotation name or var ",tokenSource.peek(-1));
}
p = parseSimpleAnnotationName();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext,startPos,endPos);
return p;
}
/**
* @return
*/
private ExactAnnotationTypePattern parseSimpleAnnotationName() {
// the @ has already been eaten...
ExactAnnotationTypePattern p;
StringBuffer annotationName = new StringBuffer();
annotationName.append(parseIdentifier());
while (maybeEat(".")) {
annotationName.append('.');
annotationName.append(parseIdentifier());
}
TypeX type = TypeX.forName(annotationName.toString());
p = new ExactAnnotationTypePattern(type);
return p;
}
// private AnnotationTypePattern parseAtomicAnnotationPattern() {
// if (maybeEat("!")) {
// //int startPos = tokenSource.peek(-1).getStart();
// //??? we lose source location for true start of !type
// AnnotationTypePattern p = new NotAnnotationTypePattern(parseAtomicAnnotationPattern());
// return p;
// }
// if (maybeEat("(")) {
// AnnotationTypePattern p = parseAnnotationTypePattern();
// eat(")");
// return p;
// }
// int startPos = tokenSource.peek().getStart();
// eat("@");
// StringBuffer annotationName = new StringBuffer();
// annotationName.append(parseIdentifier());
// while (maybeEat(".")) {
// annotationName.append('.');
// annotationName.append(parseIdentifier());
// }
// TypeX type = TypeX.forName(annotationName.toString());
// AnnotationTypePattern p = new ExactAnnotationTypePattern(type);
// int endPos = tokenSource.peek(-1).getEnd();
// p.setLocation(sourceContext, startPos, endPos);
// return p;
// }
private boolean isAnnotationPattern(PatternNode p) {
return (p instanceof AnnotationTypePattern);
}
public List parseDottedNamePattern() {
List names = new ArrayList();
StringBuffer buf = new StringBuffer();
IToken previous = null;
boolean justProcessedEllipsis = false; // Remember if we just dealt with an ellipsis (PR61536)
boolean justProcessedDot = false;
boolean onADot = false;
while (true) {
IToken tok = null;
int startPos = tokenSource.peek().getStart();
String afterDot = null;
while (true) {
if (previous !=null && previous.getString().equals(".")) justProcessedDot = true;
tok = tokenSource.peek();
onADot = (tok.getString().equals("."));
if (previous != null) {
if (!isAdjacent(previous, tok)) break;
}
if (tok.getString() == "*" || tok.isIdentifier()) {
buf.append(tok.getString());
} else if (tok.getLiteralKind() != null) {
//System.err.println("literal kind: " + tok.getString());
String s = tok.getString();
int dot = s.indexOf('.');
if (dot != -1) {
buf.append(s.substring(0, dot));
afterDot = s.substring(dot+1);
previous = tokenSource.next();
break;
}
buf.append(s); // ??? so-so
} else {
break;
}
previous = tokenSource.next();
//XXX need to handle floats and other fun stuff
}
int endPos = tokenSource.peek(-1).getEnd();
if (buf.length() == 0 && names.isEmpty()) {
throw new ParserException("name pattern", tok);
}
if (buf.length() == 0 && justProcessedEllipsis) {
throw new ParserException("name pattern cannot finish with ..", tok);
}
if (buf.length() == 0 && justProcessedDot && !onADot) {
throw new ParserException("name pattern cannot finish with .", tok);
}
if (buf.length() == 0) {
names.add(NamePattern.ELLIPSIS);
justProcessedEllipsis = true;
} else {
checkLegalName(buf.toString(), previous);
NamePattern ret = new NamePattern(buf.toString());
ret.setLocation(sourceContext, startPos, endPos);
names.add(ret);
justProcessedEllipsis = false;
}
if (afterDot == null) {
buf.setLength(0);
if (!maybeEat(".")) break;
else previous = tokenSource.peek(-1);
} else {
buf.setLength(0);
buf.append(afterDot);
afterDot = null;
}
}
//System.err.println("parsed: " + names);
return names;
}
public NamePattern parseNamePattern() {
StringBuffer buf = new StringBuffer();
IToken previous = null;
IToken tok;
int startPos = tokenSource.peek().getStart();
while (true) {
tok = tokenSource.peek();
if (previous != null) {
if (!isAdjacent(previous, tok)) break;
}
if (tok.getString() == "*" || tok.isIdentifier()) {
buf.append(tok.getString());
} else if (tok.getLiteralKind() != null) {
//System.err.println("literal kind: " + tok.getString());
String s = tok.getString();
if (s.indexOf('.') != -1) break;
buf.append(s); // ??? so-so
} else {
break;
}
previous = tokenSource.next();
//XXX need to handle floats and other fun stuff
}
int endPos = tokenSource.peek(-1).getEnd();
if (buf.length() == 0) {
throw new ParserException("name pattern", tok);
}
checkLegalName(buf.toString(), previous);
NamePattern ret = new NamePattern(buf.toString());
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private void checkLegalName(String s, IToken tok) {
char ch = s.charAt(0);
if (!(ch == '*' || Character.isJavaIdentifierStart(ch))) {
throw new ParserException("illegal identifier start (" + ch + ")", tok);
}
for (int i=1, len=s.length(); i < len; i++) {
ch = s.charAt(i);
if (!(ch == '*' || Character.isJavaIdentifierPart(ch))) {
throw new ParserException("illegal identifier character (" + ch + ")", tok);
}
}
}
private boolean isAdjacent(IToken first, IToken second) {
return first.getEnd() == second.getStart()-1;
}
public ModifiersPattern parseModifiersPattern() {
int requiredFlags = 0;
int forbiddenFlags = 0;
int start;
while (true) {
start = tokenSource.getIndex();
boolean isForbidden = false;
isForbidden = maybeEat("!");
IToken t = tokenSource.next();
int flag = ModifiersPattern.getModifierFlag(t.getString());
if (flag == -1) break;
if (isForbidden) forbiddenFlags |= flag;
else requiredFlags |= flag;
}
tokenSource.setIndex(start);
if (requiredFlags == 0 && forbiddenFlags == 0) {
return ModifiersPattern.ANY;
} else {
return new ModifiersPattern(requiredFlags, forbiddenFlags);
}
}
public TypePatternList parseArgumentsPattern() {
List patterns = new ArrayList();
eat("(");
if (maybeEat(")")) {
return new TypePatternList();
}
do {
if (maybeEat(".")) {
eat(".");
patterns.add(TypePattern.ELLIPSIS);
} else {
patterns.add(parseTypePattern());
}
} while (maybeEat(","));
eat(")");
return new TypePatternList(patterns);
}
public AnnotationPatternList parseArgumentsAnnotationPattern() {
List patterns = new ArrayList();
eat("(");
if (maybeEat(")")) {
return new AnnotationPatternList();
}
do {
if (maybeEat(".")) {
eat(".");
patterns.add(AnnotationTypePattern.ELLIPSIS);
} else if (maybeEat("*")) {
patterns.add(AnnotationTypePattern.ANY);
} else {
patterns.add(parseAnnotationNameOrVarTypePattern());
}
} while (maybeEat(","));
eat(")");
return new AnnotationPatternList(patterns);
}
public ThrowsPattern parseOptionalThrowsPattern() {
IToken t = tokenSource.peek();
if (t.isIdentifier() && t.getString().equals("throws")) {
tokenSource.next();
List required = new ArrayList();
List forbidden = new ArrayList();
do {
boolean isForbidden = maybeEat("!");
//???might want an error for a second ! without a paren
TypePattern p = parseTypePattern();
if (isForbidden) forbidden.add(p);
else required.add(p);
} while (maybeEat(","));
return new ThrowsPattern(new TypePatternList(required), new TypePatternList(forbidden));
}
return ThrowsPattern.ANY;
}
public SignaturePattern parseMethodOrConstructorSignaturePattern() {
int startPos = tokenSource.peek().getStart();
AnnotationTypePattern annotationPattern = maybeParseAnnotationPattern();
ModifiersPattern modifiers = parseModifiersPattern();
TypePattern returnType = parseTypePattern();
TypePattern declaringType;
NamePattern name = null;
Member.Kind kind;
// here we can check for 'new'
if (maybeEatNew(returnType)) {
kind = Member.CONSTRUCTOR;
if (returnType.toString().length() == 0) {
declaringType = TypePattern.ANY;
} else {
declaringType = returnType;
}
returnType = TypePattern.ANY;
name = NamePattern.ANY;
} else {
kind = Member.METHOD;
IToken nameToken = tokenSource.peek();
declaringType = parseTypePattern();
if (maybeEat(".")) {
nameToken = tokenSource.peek();
name = parseNamePattern();
} else {
name = tryToExtractName(declaringType);
if (declaringType.toString().equals("")) {
declaringType = TypePattern.ANY;
}
}
if (name == null) {
throw new ParserException("name pattern", tokenSource.peek());
}
String simpleName = name.maybeGetSimpleName();
//XXX should add check for any Java keywords
if (simpleName != null && simpleName.equals("new")) {
throw new ParserException("method name (not constructor)",
nameToken);
}
}
TypePatternList parameterTypes = parseArgumentsPattern();
ThrowsPattern throwsPattern = parseOptionalThrowsPattern();
SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType, name, parameterTypes, throwsPattern, annotationPattern);
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private boolean maybeEatNew(TypePattern returnType) {
if (returnType instanceof WildTypePattern) {
WildTypePattern p = (WildTypePattern)returnType;
if (p.maybeExtractName("new")) return true;
}
int start = tokenSource.getIndex();
if (maybeEat(".")) {
String id = maybeEatIdentifier();
if (id != null && id.equals("new")) return true;
tokenSource.setIndex(start);
}
return false;
}
public SignaturePattern parseFieldSignaturePattern() {
int startPos = tokenSource.peek().getStart();
AnnotationTypePattern annotationPattern = maybeParseAnnotationPattern();
ModifiersPattern modifiers = parseModifiersPattern();
TypePattern returnType = parseTypePattern();
TypePattern declaringType = parseTypePattern();
NamePattern name;
//System.err.println("parsed field: " + declaringType.toString());
if (maybeEat(".")) {
name = parseNamePattern();
} else {
name = tryToExtractName(declaringType);
if (declaringType.toString().equals("")) {
declaringType = TypePattern.ANY;
}
}
SignaturePattern ret = new SignaturePattern(Member.FIELD, modifiers, returnType,
declaringType, name, TypePatternList.ANY, ThrowsPattern.ANY,annotationPattern);
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private NamePattern tryToExtractName(TypePattern nextType) {
if (nextType == TypePattern.ANY) {
return NamePattern.ANY;
} else if (nextType instanceof WildTypePattern) {
WildTypePattern p = (WildTypePattern)nextType;
return p.extractName();
} else {
return null;
}
}
public String parsePossibleStringSequence(boolean shouldEnd) {
StringBuffer result = new StringBuffer();
IToken token = tokenSource.next();
if (token.getLiteralKind()==null) {
throw new ParserException("string",token);
}
while (token.getLiteralKind().equals("string")) {
result.append(token.getString());
boolean plus = maybeEat("+");
if (!plus) break;
token = tokenSource.next();
if (token.getLiteralKind()==null) {
throw new ParserException("string",token);
}
}
eatIdentifier(";");
IToken t = tokenSource.next();
if (shouldEnd && t!=IToken.EOF) {
throw new ParserException("<string>;",token);
}
return result.toString();
}
public String parseStringLiteral() {
IToken token = tokenSource.next();
String literalKind = token.getLiteralKind();
if (literalKind == "string") {
return token.getString();
}
throw new ParserException("string", token);
}
public String parseIdentifier() {
IToken token = tokenSource.next();
if (token.isIdentifier()) return token.getString();
throw new ParserException("identifier", token);
}
public void eatIdentifier(String expectedValue) {
IToken next = tokenSource.next();
if (!next.getString().equals(expectedValue)) {
throw new ParserException(expectedValue, next);
}
}
public boolean maybeEatIdentifier(String expectedValue) {
IToken next = tokenSource.peek();
if (next.getString().equals(expectedValue)) {
tokenSource.next();
return true;
} else {
return false;
}
}
public void eat(String expectedValue) {
IToken next = tokenSource.next();
if (next.getString() != expectedValue) {
throw new ParserException(expectedValue, next);
}
}
public boolean maybeEat(String token) {
IToken next = tokenSource.peek();
if (next.getString() == token) {
tokenSource.next();
return true;
} else {
return false;
}
}
public String maybeEatIdentifier() {
IToken next = tokenSource.peek();
if (next.isIdentifier()) {
tokenSource.next();
return next.getString();
} else {
return null;
}
}
public boolean peek(String token) {
IToken next = tokenSource.peek();
return next.getString() == token;
}
public PatternParser(String data) {
this(BasicTokenSource.makeTokenSource(data));
}
}
|
92,053 |
Bug 92053 @args causes a VerifyError: Unable to pop operand off an empty stack
|
I'm getting a VerifyError exception when I try to use @args in following code: ------------------ Test3.java ------------------------- import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Ann {} @Ann class AClass{} public class Test3 { void abc(AClass y) {} public static void main(String[] args) { new Test3().abc(new AClass()); } } aspect Annotations { before(Ann ann) : call(* Test3.*(..)) && @args(ann) { System.out.println("Before: " + thisJoinPoint); } } ---- On JRockIt5 jre and AspectJ 1.5.0M2 I get following result: ----------- java.lang.VerifyError: (class: Test3, method: main signature: ([Ljava/lang/String;)V) Unable to pop operand off an empty stack ----------- I'm getting similar error with sun jre and with older versions of AspectJ5 (20050324155000 and from 10th feb).
|
resolved fixed
|
3f942a4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-20T14:32:40Z | 2005-04-20T12:26:40Z |
tests/java5/annotations/binding/bugs/Test3.java
| |
92,053 |
Bug 92053 @args causes a VerifyError: Unable to pop operand off an empty stack
|
I'm getting a VerifyError exception when I try to use @args in following code: ------------------ Test3.java ------------------------- import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Ann {} @Ann class AClass{} public class Test3 { void abc(AClass y) {} public static void main(String[] args) { new Test3().abc(new AClass()); } } aspect Annotations { before(Ann ann) : call(* Test3.*(..)) && @args(ann) { System.out.println("Before: " + thisJoinPoint); } } ---- On JRockIt5 jre and AspectJ 1.5.0M2 I get following result: ----------- java.lang.VerifyError: (class: Test3, method: main signature: ([Ljava/lang/String;)V) Unable to pop operand off an empty stack ----------- I'm getting similar error with sun jre and with older versions of AspectJ5 (20050324155000 and from 10th feb).
|
resolved fixed
|
3f942a4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-20T14:32:40Z | 2005-04-20T12:26:40Z |
tests/src/org/aspectj/systemtest/ajc150/AnnotationBinding.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.File;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class AnnotationBinding extends XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(AnnotationBinding.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
///////////////////////////////////// @ANNOTATION and CALL
// Very simple annotation binding for 'call() && @annotation()'
public void testCallAnnotationBinding1() {
runTest("call annotation binding 1");
}
// 'call() && @annotation()' when the called method has multiple arguments
public void testCallAnnotationBinding2() {
runTest("call annotation binding 2");
}
// 'call() && @annotation()' when the called method takes primitive arguments (YUCK!)
public void testCallAnnotationBinding3() {
runTest("call annotation binding 3");
}
// 'call() && @annotation()' when runtime type will exhibit different annotation (due to interface implementing)
public void testCallAnnotationBinding4() {
runTest("call annotation binding 4");
}
// 'call() && @annotation()' when target doesnt have an annotation !
public void testCallAnnotationBinding5() {
runTest("call annotation binding 5");
}
// 'call() && @annotation()' when runtime type will exhibit different annotation (due to subclassing)
public void testCallAnnotationBinding6() {
runTest("call annotation binding 6");
}
// 'call() && @annotation()' using named pointcut
public void testCallAnnotationBinding7() {
runTest("call annotation binding 7");
}
///////////////////////////////////// @TARGET
// 'call() && @target()'
public void testAtTargetAnnotationBinding1() {
runTest("@target annotation binding 1");
}
// 'call() && @target() && @target'
public void testAtTargetAnnotationBinding2() {
runTest("@target annotation binding 2");
}
// 'call() && @target()' - using a type hierarchy where some levels are missing annotations
public void testAtTargetAnnotationBinding3() {
runTest("@target annotation binding 3");
}
// 'call() && @target()' - using a type hierarchy where some levels are missing annotations
// but the annotation is inherited
public void testAtTargetAnnotationBinding4() {
runTest("@target annotation binding 4");
}
// @target() with an annotation in a package
public void testAtTargetAnnotationBinding5() {
runTest("@target annotation binding 5");
}
///////////////////////////////////// @THIS
// 'call() && @this()'
public void testAtThisAnnotationBinding1() {
runTest("@this annotation binding 1");
}
// 'call() && @this() && @this'
public void testAtThisAnnotationBinding2() {
runTest("@this annotation binding 2");
}
// 'call() && @this()' - using a type hierarchy where some levels are missing annotations
public void testAtThisAnnotationBinding3() {
runTest("@this annotation binding 3");
}
// 'call() && @this()' - using a type hierarchy where some levels are missing annotations
// but the annotation is inherited
public void testAtThisAnnotationBinding4() {
runTest("@this annotation binding 4");
}
// '@this() and @target()' used together
public void testAtThisAtTargetAnnotationBinding() {
runTest("@this annotation binding 5");
}
///////////////////////////////////// @ARGS
// complex case when there are 3 parameters
public void testAtArgs1() {
runTest("@args annotation binding 1");
}
// simple case when there is only one parameter
public void testAtArgs2() {
runTest("@args annotation binding 2");
}
// simple case when there is only one parameter and no binding
public void testAtArgs3() {
runTest("@args annotation binding 3");
}
// complex case binding different annotation kinds
public void testAtArgs4() {
runTest("@args annotation binding 4");
}
// check @args and execution()
public void testAtArgs5() {
runTest("@args annotation binding 5");
}
///////////////////////////////////// @ANNOTATION and EXECUTION
// 'execution() && @annotation()'
public void testExecutionAnnotationBinding1() {
runTest("execution and @annotation");
}
///////////////////////////////////// @ANNOTATION and SET
// 'set() && @annotation()'
public void testFieldAnnotationBinding1() {
runTest("set and @annotation");
}
// 'get() && @annotation()'
public void testFieldAnnotationBinding2() {
runTest("get and @annotation");
}
// 'get() && @annotation()' when using array fields
public void testFieldAnnotationBinding3() {
runTest("get and @annotation with arrays");
}
///////////////////////////////////// @ANNOTATION and CTOR-CALL
// 'ctor-call(new) && @annotation()'
public void testCtorCallAnnotationBinding1() {
runTest("cons call and @annotation");
}
///////////////////////////////////// @ANNOTATION and CTOR-CALL
// 'ctor-execution() && @annotation()'
public void testCtorExecAnnotationBinding1() {
runTest("cons exe and @annotation");
}
///////////////////////////////////// @ANNOTATION and STATICINITIALIZATION
// 'staticinitialization() && @annotation()'
public void testStaticInitAnnotationBinding1() {
runTest("staticinit and @annotation");
}
///////////////////////////////////// @ANNOTATION and PREINITIALIZATION
// 'preinitialization() && @annotation()'
public void testPreInitAnnotationBinding1() {
runTest("preinit and @annotation");
}
///////////////////////////////////// @ANNOTATION and INITIALIZATION
// 'initialization() && @annotation()'
public void testInitAnnotationBinding1() {
runTest("init and @annotation");
}
///////////////////////////////////// @ANNOTATION and ADVICEEXECUTION
// 'adviceexecution() && @annotation()'
public void testAdviceExecAnnotationBinding1() {
runTest("adviceexecution and @annotation");
}
///////////////////////////////////// @ANNOTATION and HANDLER
// 'handler() && @annotation()'
public void testHandlerAnnotationBinding1() {
runTest("handler and @annotation");
}
///////////////////////////////////// @WITHIN
// '@within()'
public void testWithinBinding1() {
runTest("@within");
}
//'@within()' but multiple types around (some annotated)
public void testWithinBinding2() {
runTest("@within - multiple types");
}
///////////////////////////////////// @WITHINCODE
// '@withincode() && call(* println(..))'
public void testWithinCodeBinding1() {
runTest("@withincode() and call(* println(..))");
}
///////////////////////////////////// @ANNOTATION complex tests
// Using package names for the types (including the annotation) - NO BINDING
public void testPackageNamedTypesNoBinding() {
runTest("packages and no binding");
}
// Using package names for the types (including the annotation) - INCLUDES BINDING
public void testPackageNamedTypesWithBinding() {
runTest("packages and binding");
}
// declare parents: @Color * implements Serializable
public void testDeclareParentsWithAnnotatedAnyPattern() {
runTest("annotated any pattern");
}
// Should error (in a nice way!) on usage of an annotation that isnt imported
public void testAnnotationUsedButNotImported() {
runTest("annotation not imported");
}
// Binding with calls/executions of static methods
public void testCallsAndExecutionsOfStaticMethods() {
runTest("binding with static methods");
}
/////////////////////////////////////////////////////////////////////////////////
// annotation binding with ITDs
public void testAnnotationBindingAndITDs1() {
runTest("simple binding annotation values where itd method is annotated");
}
public void testAnnotationBindingAndITDs2() {
runTest("simple binding annotation values where itd field is annotated");
}
public void testAnnotationBindingAndITDs3() {
runTest("simple binding annotation values where itd ctor is annotated");
}
public void testAnnotationBindingAndITDs4() {
runTest("simple binding annotation values where itd method is annotated via declare");
}
public void testAnnotationBindingAndITDs5() {
runTest("simple binding annotation values where itd field is annotated via declare");
}
public void testAnnotationBindingAndITDs6() {
runTest("simple binding annotation values where itd field is annotated multiple times via declare");
}
public void testAnnotationBindingAndITDs7() {
runTest("simple binding annotation values where itd ctor is annotated via declare");
}
public void testAnnotationBindingAndITDs4_asmtest() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("simple binding annotation values where itd method is annotated via declare");
if (getCurrentTest().canRunOnThisVM()) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: int A.m() : @Fruit(\"orange\")");
assertTrue("Couldn't find 'declare @method' element in the tree",ipe!=null);
List l = AsmManager.getDefault().getRelationshipMap().get(ipe);
assertTrue("Should have a relationship but does not ",l.size()>0);
ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,
"declare @method: int A.n() : @Fruit(\"banana\")");
assertTrue("Couldn't find 'declare @method element in the tree",ipe!=null);
l = AsmManager.getDefault().getRelationshipMap().get(ipe);
assertTrue("Should have a relationship but does not ",l.size()>0);
Relationship rel = (Relationship)l.get(0);
assertTrue("Should have 1 target but has "+rel.getTargets().size(),rel.getTargets().size()==1);
String tgt = (String)rel.getTargets().get(0);
assertTrue("Should point to line 10 but doesnt: "+tgt,tgt.indexOf("|10|")!=-1);
}
}
public void testAnnotationBindingAndITDs5_asmtest() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("simple binding annotation values where itd field is annotated via declare");
if (getCurrentTest().canRunOnThisVM()) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_FIELD,
"declare @field: int A.i : @Fruit(\"orange\")");
assertTrue("Couldn't find 'declare @type' element in the tree",ipe!=null);
List l = AsmManager.getDefault().getRelationshipMap().get(ipe);
assertTrue("Should have a relationship but does not ",l.size()>0);
ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_FIELD,
"declare @field: java.lang.String A.j : @Fruit(\"banana\")");
assertTrue("Couldn't find 'declare @field element in the tree",ipe!=null);
l = AsmManager.getDefault().getRelationshipMap().get(ipe);
assertTrue("Should have a relationship but does not ",l.size()>0);
Relationship rel = (Relationship)l.get(0);
assertTrue("Should have 1 target but has "+rel.getTargets().size(),rel.getTargets().size()==1);
String tgt = (String)rel.getTargets().get(0);
assertTrue("Should point to line 10 but doesnt: "+tgt,tgt.indexOf("|10|")!=-1);
}
}
public void testAnnotationBindingAndITDs7_asmtest() {
// AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("simple binding annotation values where itd ctor is annotated via declare");
if (getCurrentTest().canRunOnThisVM()) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR,
"declare @constructor: A.new(java.lang.String) : @Fruit(\"pear\")");
assertTrue("Couldn't find 'declare @constructor' element in the tree",ipe!=null);
List l = AsmManager.getDefault().getRelationshipMap().get(ipe);
assertTrue("Should have a relationship but does not ",l.size()>0);
ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR,
"declare @constructor: A.new(int) : @Fruit(\"orange\")");
assertTrue("Couldn't find 'declare @constructor element in the tree",ipe!=null);
l = AsmManager.getDefault().getRelationshipMap().get(ipe);
assertTrue("Should have a relationship but does not ",l.size()>0);
Relationship rel = (Relationship)l.get(0);
assertTrue("Should have 1 target but has "+rel.getTargets().size(),rel.getTargets().size()==1);
String tgt = (String)rel.getTargets().get(0);
assertTrue("Should point to line 10 but doesnt: "+tgt,tgt.indexOf("|10|")!=-1);
}
}
}
|
92,053 |
Bug 92053 @args causes a VerifyError: Unable to pop operand off an empty stack
|
I'm getting a VerifyError exception when I try to use @args in following code: ------------------ Test3.java ------------------------- import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Ann {} @Ann class AClass{} public class Test3 { void abc(AClass y) {} public static void main(String[] args) { new Test3().abc(new AClass()); } } aspect Annotations { before(Ann ann) : call(* Test3.*(..)) && @args(ann) { System.out.println("Before: " + thisJoinPoint); } } ---- On JRockIt5 jre and AspectJ 1.5.0M2 I get following result: ----------- java.lang.VerifyError: (class: Test3, method: main signature: ([Ljava/lang/String;)V) Unable to pop operand off an empty stack ----------- I'm getting similar error with sun jre and with older versions of AspectJ5 (20050324155000 and from 10th feb).
|
resolved fixed
|
3f942a4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-20T14:32:40Z | 2005-04-20T12:26:40Z |
weaver/src/org/aspectj/weaver/patterns/ArgsAnnotationPointcut.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.ast.Var;
/**
* @author colyer
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class ArgsAnnotationPointcut extends NameBindingPointcut {
private AnnotationPatternList arguments;
/**
*
*/
public ArgsAnnotationPointcut(AnnotationPatternList arguments) {
super();
this.arguments = arguments;
}
public Set couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS; // empty args() matches jps with no args
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo)
*/
public FuzzyBoolean fastMatch(FastMatchInfo info) {
return FuzzyBoolean.MAYBE;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow)
*/
protected FuzzyBoolean matchInternal(Shadow shadow) {
arguments.resolve(shadow.getIWorld());
FuzzyBoolean ret =
arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes()));
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings)
*/
protected void resolveBindings(IScope scope, Bindings bindings) {
arguments.resolveBindings(scope, bindings, true);
if (arguments.ellipsisCount > 1) {
scope.message(IMessage.ERROR, this,
"uses more than one .. in args (compiler limitation)");
}
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#resolveBindingsFromRTTI()
*/
protected void resolveBindingsFromRTTI() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedTypeX, org.aspectj.weaver.IntMap)
*/
protected Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
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);
TypeX argType = shadow.getArgType(argsIndex);
ResolvedTypeX rArgType = argType.resolve(shadow.getIWorld());
if (rArgType == ResolvedTypeX.MISSING) {
IMessage msg = new Message(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_ARG_TYPE,argType.getName()),
"",IMessage.ERROR,shadow.getSourceLocation(),null,new ISourceLocation[]{getSourceLocation()});
}
if (ap.matches(rArgType).alwaysTrue()) { // !!! ASC Can we ever take this branch?
// !!! AMC - Yes, if annotation is @Inherited
argsIndex++;
continue;
} else {
// we need a test...
ResolvedTypeX rAnnType = ap.annotationType.resolve(shadow.getIWorld());
if (ap instanceof BindingAnnotationTypePattern) {
BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)ap;
Var annvar = shadow.getArgAnnotationVar(argsIndex,rAnnType);
state.set(btp.getFormalIndex(),annvar);
ret = Test.makeAnd(ret,Test.makeHasAnnotation(shadow.getArgVar(argsIndex),rAnnType));
argsIndex++;
} else {
ret = Test.makeAnd(ret,Test.makeHasAnnotation(shadow.getArgVar(argsIndex),rAnnType));
argsIndex++;
}
}
}
}
return ret;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns()
*/
public List getBindingAnnotationTypePatterns() {
List l = new ArrayList();
AnnotationTypePattern[] pats = arguments.getAnnotationPatterns();
for (int i = 0; i < pats.length; i++) {
if (pats[i] instanceof BindingAnnotationTypePattern) {
l.add(pats[i]);
}
}
return l;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns()
*/
public List getBindingTypePatterns() {
return Collections.EMPTY_LIST;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.ATARGS);
arguments.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
AnnotationPatternList annotationPatternList = AnnotationPatternList.read(s,context);
ArgsAnnotationPointcut ret = new ArgsAnnotationPointcut(annotationPatternList);
ret.readLocation(context, s);
return ret;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (!(obj instanceof ArgsAnnotationPointcut)) return false;
ArgsAnnotationPointcut other = (ArgsAnnotationPointcut) obj;
return other.arguments.equals(arguments);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return 17 + 37*arguments.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer buf = new StringBuffer("@args");
buf.append(arguments.toString());
return buf.toString();
}
}
|
91,912 |
Bug 91912 Request for a new type of relationship in the structure model
|
Declare soft relationships are currently 'advises' and 'advised by' relationships. Would it be possible to add 'softens' and 'softened by' (or 'softens exception at' and 'exception softened by') relationships to the structure model?
|
resolved fixed
|
7a61380
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-21T17:00:18Z | 2005-04-19T14:13:20Z |
asm/src/org/aspectj/asm/IRelationship.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* ******************************************************************/
package org.aspectj.asm;
import java.io.*;
import java.util.List;
/**
* @author Mik Kersten
*/
public interface IRelationship extends Serializable {
public String getName();
public List/*String*/ getTargets();
public String getSourceHandle();
public boolean addTarget(String handle);
public Kind getKind();
public boolean hasRuntimeTest();
/**
* Uses "typesafe enum" pattern.
*/
public static class Kind implements Serializable {
public static final Kind DECLARE_WARNING = new Kind("declare warning");
public static final Kind DECLARE_ERROR = new Kind("declare error");
public static final Kind ADVICE_AROUND = new Kind("around advice");
public static final Kind ADVICE_AFTERRETURNING = new Kind("after returning advice");
public static final Kind ADVICE_AFTERTHROWING = new Kind("after throwing advice");
public static final Kind ADVICE_AFTER = new Kind("after advice");
public static final Kind ADVICE_BEFORE = new Kind("before advice");
public static final Kind ADVICE = new Kind("advice");
public static final Kind DECLARE = new Kind("declare");
public static final Kind DECLARE_INTER_TYPE = new Kind("inter-type declaration");
public static final Kind USES_POINTCUT = new Kind("uses pointcut");
public static final Kind[] ALL = {
DECLARE_WARNING, DECLARE_ERROR,
ADVICE_AROUND,ADVICE_AFTERRETURNING,ADVICE_AFTERTHROWING,ADVICE_AFTER,ADVICE_BEFORE,
ADVICE, DECLARE, DECLARE_INTER_TYPE, USES_POINTCUT };
private final String name;
private Kind(String name) {
this.name = name;
}
public String toString() {
return name;
}
// The 4 declarations below are necessary for serialization
private static int nextOrdinal = 0;
private final int ordinal = nextOrdinal++;
private Object readResolve() throws ObjectStreamException {
return ALL[ordinal];
}
}
}
|
91,912 |
Bug 91912 Request for a new type of relationship in the structure model
|
Declare soft relationships are currently 'advises' and 'advised by' relationships. Would it be possible to add 'softens' and 'softened by' (or 'softens exception at' and 'exception softened by') relationships to the structure model?
|
resolved fixed
|
7a61380
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-21T17:00:18Z | 2005-04-19T14:13:20Z |
weaver/src/org/aspectj/weaver/AsmRelationshipProvider.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.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Utility;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.weaver.bcel.BcelAdvice;
public class AsmRelationshipProvider {
protected static AsmRelationshipProvider INSTANCE = new AsmRelationshipProvider();
public static final String ADVISES = "advises";
public static final String ADVISED_BY = "advised by";
public static final String DECLARES_ON = "declares on";
public static final String DECLAREDY_BY = "declared by";
public static final String MATCHED_BY = "matched by";
public static final String MATCHES_DECLARE = "matches declare";
public static final String INTER_TYPE_DECLARES = "declared on";
public static final String INTER_TYPE_DECLARED_BY = "aspect declarations";
public static final String ANNOTATES = "annotates";
public static final String ANNOTATED_BY = "annotated by";
public void checkerMunger(IHierarchy model, Shadow shadow, Checker checker) {
if (!AsmManager.isCreatingModel()) return;
if (shadow.getSourceLocation() == null || checker.getSourceLocation() == null) return;
// Ensure a node for the target exists
IProgramElement targetNode = getNode(AsmManager.getDefault().getHierarchy(), shadow);
String sourceHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
checker.getSourceLocation().getSourceFile(),
checker.getSourceLocation().getLine(),
checker.getSourceLocation().getColumn(),
checker.getSourceLocation().getOffset());
String targetHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
shadow.getSourceLocation().getSourceFile(),
shadow.getSourceLocation().getLine(),
shadow.getSourceLocation().getColumn(),
shadow.getSourceLocation().getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE, MATCHED_BY,false,true);
foreward.addTarget(targetHandle);
// foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE, MATCHES_DECLARE,false,true);
if (back != null && back.getTargets() != null) {
back.addTarget(sourceHandle);
//back.getTargets().add(sourceHandle);
}
}
}
// For ITDs
public void addRelationship(
ResolvedTypeX onType,
ResolvedTypeMunger munger,
ResolvedTypeX originatingAspect) {
if (!AsmManager.isCreatingModel()) return;
String sourceHandle = "";
if (munger.getSourceLocation()!=null) {
sourceHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
munger.getSourceLocation().getSourceFile(),
munger.getSourceLocation().getLine(),
munger.getSourceLocation().getColumn(),
munger.getSourceLocation().getOffset());
} else {
sourceHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
originatingAspect.getSourceLocation().getSourceFile(),
originatingAspect.getSourceLocation().getLine(),
originatingAspect.getSourceLocation().getColumn(),
originatingAspect.getSourceLocation().getOffset());
}
if (originatingAspect.getSourceLocation() != null) {
String targetHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
onType.getSourceLocation().getSourceFile(),
onType.getSourceLocation().getLine(),
onType.getSourceLocation().getColumn(),
onType.getSourceLocation().getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES,false,true);
foreward.addTarget(targetHandle);
// foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY,false,true);
back.addTarget(sourceHandle);
// back.getTargets().add(sourceHandle);
}
}
}
public void addDeclareParentsRelationship(ISourceLocation decp,ResolvedTypeX targetType, List newParents) {
if (!AsmManager.isCreatingModel()) return;
String sourceHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(decp.getSourceFile(),decp.getLine(),decp.getColumn(),decp.getOffset());
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForHandle(sourceHandle);
String targetHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
targetType.getSourceLocation().getSourceFile(),
targetType.getSourceLocation().getLine(),
targetType.getSourceLocation().getColumn(),
targetType.getSourceLocation().getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, INTER_TYPE_DECLARED_BY,false,true);
back.addTarget(sourceHandle);
}
}
/**
* Adds a declare annotation relationship, sometimes entities don't have source locs (methods/fields) so use other
* variants of this method if that is the case as they will look the entities up in the structure model.
*/
public void addDeclareAnnotationRelationship(ISourceLocation declareAnnotationLocation,ISourceLocation annotatedLocation) {
if (!AsmManager.isCreatingModel()) return;
String sourceHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(declareAnnotationLocation.getSourceFile(),declareAnnotationLocation.getLine(),
declareAnnotationLocation.getColumn(),declareAnnotationLocation.getOffset());
IProgramElement declareAnnotationPE = AsmManager.getDefault().getHierarchy().findElementForHandle(sourceHandle);
String targetHandle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(
annotatedLocation.getSourceFile(),
annotatedLocation.getLine(),
annotatedLocation.getColumn(),
annotatedLocation.getOffset());
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY,false,true);
back.addTarget(sourceHandle);
}
}
public void adviceMunger(IHierarchy model, Shadow shadow, ShadowMunger munger) {
if (!AsmManager.isCreatingModel()) return;
if (munger instanceof Advice) {
Advice advice = (Advice)munger;
if (advice.getKind().isPerEntry() || advice.getKind().isCflow()) {
// TODO: might want to show these in the future
return;
}
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
IProgramElement targetNode = getNode(AsmManager.getDefault().getHierarchy(), shadow);
boolean runtimeTest = ((BcelAdvice)munger).hasDynamicTests();
// Work out extra info to inform interested UIs !
IProgramElement.ExtraInformation ai = new IProgramElement.ExtraInformation();
String adviceHandle = advice.getHandle();
// What kind of advice is it?
// TODO: Prob a better way to do this but I just want to
// get it into CVS !!!
AdviceKind ak = ((Advice)munger).getKind();
ai.setExtraAdviceInformation(ak.getName());
IProgramElement adviceElement = AsmManager.getDefault().getHierarchy().findElementForHandle(adviceHandle);
adviceElement.setExtraInfo(ai);
if (adviceHandle != null && targetNode != null) {
if (targetNode != null) {
String targetHandle = targetNode.getHandleIdentifier();
IRelationship foreward = mapper.get(adviceHandle, IRelationship.Kind.ADVICE, ADVISES,runtimeTest,true);
if (foreward != null) foreward.addTarget(targetHandle);//foreward.getTargets().add(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.ADVICE, ADVISED_BY,runtimeTest,true);
if (back != null) back.addTarget(adviceHandle);//back.getTargets().add(adviceHandle);
}
}
}
}
protected IProgramElement getNode(IHierarchy model, Shadow shadow) {
Member enclosingMember = shadow.getEnclosingCodeSignature();
IProgramElement enclosingNode = lookupMember(model, enclosingMember);
if (enclosingNode == null) {
Lint.Kind err = shadow.getIWorld().getLint().shadowNotInStructure;
if (err.isEnabled()) {
err.signal(shadow.toString(), shadow.getSourceLocation());
}
return null;
}
Member shadowSig = shadow.getSignature();
if (!shadowSig.equals(enclosingMember)) {
IProgramElement bodyNode = findOrCreateCodeNode(enclosingNode, shadowSig, shadow);
return bodyNode;
} else {
return enclosingNode;
}
}
private boolean sourceLinesMatch(ISourceLocation loc1,ISourceLocation loc2) {
if (loc1.getLine()!=loc2.getLine()) return false;
return true;
}
private IProgramElement findOrCreateCodeNode(IProgramElement enclosingNode, Member shadowSig, Shadow shadow)
{
for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (shadowSig.getName().equals(node.getBytecodeName()) &&
shadowSig.getSignature().equals(node.getBytecodeSignature()) &&
sourceLinesMatch(node.getSourceLocation(),shadow.getSourceLocation()))
{
return node;
}
}
ISourceLocation sl = shadow.getSourceLocation();
// XXX why not use shadow file? new SourceLocation(sl.getSourceFile(), sl.getLine()),
SourceLocation peLoc = new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(),sl.getLine());
peLoc.setOffset(sl.getOffset());
IProgramElement peNode = new ProgramElement(
shadow.toString(),
IProgramElement.Kind.CODE,
peLoc,
0,
"",
new ArrayList());
peNode.setBytecodeName(shadowSig.getName());
peNode.setBytecodeSignature(shadowSig.getSignature());
enclosingNode.addChild(peNode);
return peNode;
}
protected IProgramElement lookupMember(IHierarchy model, Member member) {
TypeX declaringType = member.getDeclaringType();
IProgramElement classNode =
model.findElementForType(declaringType.getPackageName(), declaringType.getClassName());
return findMemberInClass(classNode, member);
}
protected IProgramElement findMemberInClass(
IProgramElement classNode,
Member member)
{
if (classNode == null) return null; // XXX remove this check
for (Iterator it = classNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (member.getName().equals(node.getBytecodeName()) &&
member.getSignature().equals(node.getBytecodeSignature()))
{
return node;
}
}
// if we can't find the member, we'll just put it in the class
return classNode;
}
// private static IProgramElement.Kind genShadowKind(Shadow shadow) {
// IProgramElement.Kind shadowKind;
// if (shadow.getKind() == Shadow.MethodCall
// || shadow.getKind() == Shadow.ConstructorCall
// || shadow.getKind() == Shadow.FieldGet
// || shadow.getKind() == Shadow.FieldSet
// || shadow.getKind() == Shadow.ExceptionHandler) {
// return IProgramElement.Kind.CODE;
//
// } else if (shadow.getKind() == Shadow.MethodExecution) {
// return IProgramElement.Kind.METHOD;
//
// } else if (shadow.getKind() == Shadow.ConstructorExecution) {
// return IProgramElement.Kind.CONSTRUCTOR;
//
// } else if (shadow.getKind() == Shadow.PreInitialization
// || shadow.getKind() == Shadow.Initialization) {
// return IProgramElement.Kind.CLASS;
//
// } else if (shadow.getKind() == Shadow.AdviceExecution) {
// return IProgramElement.Kind.ADVICE;
//
// } else {
// return IProgramElement.Kind.ERROR;
// }
// }
public static AsmRelationshipProvider getDefault() {
return INSTANCE;
}
/**
* Reset the instance of this class, intended for extensibility.
* This enables a subclass to become used as the default instance.
*/
public static void setDefault(AsmRelationshipProvider instance) {
INSTANCE = instance;
}
/**
* Add a relationship to the known set for a declare @method/@constructor construct.
* Locating the method is a messy (for messy read 'fragile') bit of code that could break at any moment
* but it's working for my simple testcase. Currently just fails silently if any of the lookup code
* doesn't find anything...
*/
public void addDeclareAnnotationRelationship(ISourceLocation sourceLocation, String typename,Method method) {
if (!AsmManager.isCreatingModel()) return;
String pkg = null;
String type = typename;
int packageSeparator = typename.lastIndexOf(".");
if (packageSeparator!=-1) {
pkg = typename.substring(0,packageSeparator);
type = typename.substring(packageSeparator+1);
}
IProgramElement typeElem = AsmManager.getDefault().getHierarchy().findElementForType(pkg,type);
if (typeElem == null) return;
StringBuffer parmString = new StringBuffer("(");
Type[] args = method.getArgumentTypes();
for (int i = 0; i < args.length; i++) {
Type type2 = args[i];
String s = Utility.signatureToString(type2.getSignature());
if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1);
parmString.append(s);
if ((i+1)<args.length) parmString.append(",");
}
parmString.append(")");
IProgramElement methodElem = null;
if (method.getName().startsWith("<init>")) {
// its a ctor
methodElem = AsmManager.getDefault().getHierarchy().findElementForSignature(typeElem,IProgramElement.Kind.CONSTRUCTOR,type+parmString);
} else {
// its a method
methodElem = AsmManager.getDefault().getHierarchy().findElementForSignature(typeElem,IProgramElement.Kind.METHOD,method.getName()+parmString);
}
if (methodElem == null) return;
try {
String sourceHandle =
AsmManager.getDefault().getHandleProvider().createHandleIdentifier(sourceLocation.getSourceFile(),sourceLocation.getLine(),
sourceLocation.getColumn(),sourceLocation.getOffset());
String targetHandle = methodElem.getHandleIdentifier();
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY,false,true);
back.addTarget(sourceHandle);
}
} catch (Throwable t) { // I'm worried about that code above, this will make sure we don't explode if it plays up
t.printStackTrace(); // I know I know .. but I don't want to lose it!
}
}
/**
* Add a relationship to the known set for a declare @field construct. Locating the field is trickier than
* it might seem since we have no line number info for it, we have to dig through the structure model under
* the fields' type in order to locate it. Currently just fails silently if any of the lookup code
* doesn't find anything...
*/
public void addDeclareAnnotationRelationship(ISourceLocation sourceLocation, String typename,Field field) {
if (!AsmManager.isCreatingModel()) return;
String pkg = null;
String type = typename;
int packageSeparator = typename.lastIndexOf(".");
if (packageSeparator!=-1) {
pkg = typename.substring(0,packageSeparator);
type = typename.substring(packageSeparator+1);
}
IProgramElement typeElem = AsmManager.getDefault().getHierarchy().findElementForType(pkg,type);
if (typeElem == null) return;
IProgramElement fieldElem = AsmManager.getDefault().getHierarchy().findElementForSignature(typeElem,IProgramElement.Kind.FIELD,field.getName());
if (fieldElem== null) return;
String sourceHandle =
AsmManager.getDefault().getHandleProvider().createHandleIdentifier(sourceLocation.getSourceFile(),sourceLocation.getLine(),
sourceLocation.getColumn(),sourceLocation.getOffset());
String targetHandle = fieldElem.getHandleIdentifier();
IRelationshipMap mapper = AsmManager.getDefault().getRelationshipMap();
if (sourceHandle != null && targetHandle != null) {
IRelationship foreward = mapper.get(sourceHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATES,false,true);
foreward.addTarget(targetHandle);
IRelationship back = mapper.get(targetHandle, IRelationship.Kind.DECLARE_INTER_TYPE, ANNOTATED_BY,false,true);
back.addTarget(sourceHandle);
}
}
}
|
92,630 |
Bug 92630 Null Pointer Exception thrown by ajc compiler
| null |
resolved fixed
|
02f75ba
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-04-26T16:14:06Z | 2005-04-25T20:13:20Z |
weaver/src/org/aspectj/weaver/bcel/UnwovenClassFile.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.util.FileUtil;
public class UnwovenClassFile {
protected String filename;
protected byte[] bytes;
// protected JavaClass javaClass = null;
//protected byte[] writtenBytes = null;
protected List /* ChildClass */ writtenChildClasses = new ArrayList(0);
protected String className = null;
public UnwovenClassFile(String filename, byte[] bytes) {
this.filename = filename;
this.bytes = bytes;
}
public String getFilename() {
return filename;
}
public String makeInnerFileName(String innerName) {
String prefix = filename.substring(0, filename.length()-6); // strip the .class
return prefix + "$" + innerName + ".class";
}
public byte[] getBytes() {
// if (bytes == null) bytes = javaClass.getBytes();
return bytes;
}
public JavaClass getJavaClass() {
//XXX need to know when to make a new class and when not to
//XXX this is an important optimization
if (getBytes() == null) {
System.out.println("no bytes for: " + getFilename());
//Thread.currentThread().dumpStack();
Thread.dumpStack();
}
return Utility.makeJavaClass(filename, getBytes());
// if (javaClass == null) javaClass = Utility.makeJavaClass(filename, getBytes());
// return javaClass;
}
public boolean exists() {
return getBytes() != null;
}
public void writeUnchangedBytes() throws IOException {
writeWovenBytes(getBytes(), Collections.EMPTY_LIST);
}
public void writeWovenBytes(byte[] bytes, List childClasses) throws IOException {
writeChildClasses(childClasses);
//System.err.println("should write: " + getClassName());
//System.err.println("about to write: " + this + ", " + writtenBytes + ", ");
// + writtenBytes != null + " && " + unchanged(bytes, writtenBytes) );
//if (writtenBytes != null && unchanged(bytes, writtenBytes)) return;
//System.err.println(" actually wrote it");
BufferedOutputStream os = FileUtil.makeOutputStream(new File(filename));
os.write(bytes);
os.close();
//writtenBytes = bytes;
}
private void writeChildClasses(List childClasses) throws IOException {
//??? we only really need to delete writtenChildClasses whose
//??? names aren't in childClasses; however, it's unclear
//??? how much that will affect performance
deleteAllChildClasses();
childClasses.removeAll(writtenChildClasses); //XXX is this right
for (Iterator iter = childClasses.iterator(); iter.hasNext();) {
ChildClass childClass = (ChildClass) iter.next();
writeChildClassFile(childClass.name, childClass.bytes);
}
writtenChildClasses = childClasses;
}
private void writeChildClassFile(String innerName, byte[] bytes) throws IOException {
BufferedOutputStream os =
FileUtil.makeOutputStream(new File(makeInnerFileName(innerName)));
os.write(bytes);
os.close();
}
protected void deleteAllChildClasses() {
for (Iterator iter = writtenChildClasses.iterator(); iter.hasNext();) {
ChildClass childClass = (ChildClass) iter.next();
deleteChildClassFile(childClass.name);
}
}
protected void deleteChildClassFile(String innerName) {
File childClassFile = new File(makeInnerFileName(innerName));
childClassFile.delete();
}
/* private */ static boolean unchanged(byte[] b1, byte[] b2) {
int len = b1.length;
if (b2.length != len) return false;
for (int i=0; i < len; i++) {
if (b1[i] != b2[i]) return false;
}
return true;
}
public String getClassName() {
if (className == null) className = getJavaClass().getClassName();
return className;
}
public String toString() {
return "UnwovenClassFile(" + filename + ", " + getClassName() + ")";
}
/**
* delete not just this file, but any files in the same directory that
* were generated as a result of weaving it (e.g. for an around closure).
*/
public void deleteRealFile() throws IOException {
File victim = new File(filename);
String namePrefix = victim.getName();
namePrefix = namePrefix.substring(0,namePrefix.lastIndexOf('.'));
final String targetPrefix = namePrefix + "$Ajc";
File dir = victim.getParentFile();
if (dir != null) {
File[] weaverGenerated = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(targetPrefix);
}});
for (int i = 0; i < weaverGenerated.length; i++) {
weaverGenerated[i].delete();
}
}
victim.delete();
}
// record
public static class ChildClass {
public final String name;
public final byte[] bytes;
ChildClass(String name, byte[] bytes) {
this.name = name;
this.bytes = bytes;
}
public boolean equals(Object other) {
if (! (other instanceof ChildClass)) return false;
ChildClass o = (ChildClass) other;
return o.name.equals(name) && unchanged(o.bytes, bytes);
}
public int hashCode() {
return name.hashCode();
}
public String toString() {
return "(ChildClass " + name + ")";
}
}
}
|
92,906 |
Bug 92906 showWeaveInfo for declare annotations
|
declaring annotations (declare @type, @constructor, @method and @field) currently doesn't show a message when the -showWeaveInfo option is set in ajc. Appropriate messages should be displayed.
|
resolved fixed
|
abc9a58
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-04T09:22:43Z | 2005-04-27T13:53:20Z |
ajde/testsrc/org/aspectj/ajde/ShowWeaveMessagesTestCase.java
|
/* *******************************************************************
* Copyright (c) 2004 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement Initial version
* ******************************************************************/
package org.aspectj.ajde;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.ajde.internal.CompilerAdapter;
import org.aspectj.bridge.IMessage;
import org.aspectj.util.FileUtil;
/**
* Weaving messages are complicated things. There are multiple places where weaving
* takes place and the places vary depending on whether we are doing a binary weave or
* going from source. All places that output weaving messages are tagged:
* // TAG: WeavingMessage
* so you can easily find them!
*
* Advice is the simplest to deal with as that is advice weaving is always done in the weaver.
*
* Next is intertype declarations. These are also always done in the weaver but in the case
* of a binary weave we don't know the originating source line for the ITD.
*
* Finally, declares.
* Declare Parents: extends Can only be done when going from source, if attempted by a
* binary weave then an error message (compiler limitation) is
* produced.
* Declare Parents: implements Is (currently!) done at both compile time and weave time.
* If going from source then the message is produced by the
* code in the compiler. if going from binary then the message
* is produced by the weaver.
* Declare Soft: Comes out with 'advice' as a special kind of advice: softener advice
*
*
* Q: Where are the messages turned on/off?
* A: It is a bit messy. See BuildArgParser.genBuildConfig(). Basically that method is the first time
* we parse the option set. Whether weaving messages are on or off is stored in the build config.
* As soon as we have parser the options and determined that weave messages are on, we grab the
* top level message handler and tell it not to ignore WeaveInfo messages.
*
*
* TODO - Other forms of declare? Do they need messages? e.g. declare precedence *
*/
public class ShowWeaveMessagesTestCase extends AjdeTestCase {
private static boolean regenerate;
private static boolean debugTests = false;
static {
// Switch this to true for a single iteration if you want to reconstruct the
// 'expected weaving messages' files.
regenerate = false;
}
private CompilerAdapter compilerAdapter;
public static final String PROJECT_DIR = "WeaveInfoMessagesTest";
public static final String binDir = "bin";
public static final String expectedResultsDir = "expected";
public ShowWeaveMessagesTestCase(String arg0) {
super(arg0);
}
/*
* Ensure the output directory in clean
*/
protected void setUp() throws Exception {
super.setUp(PROJECT_DIR);
FileUtil.deleteContents(openFile(binDir));
}
protected void tearDown() throws Exception {
super.tearDown();
FileUtil.deleteContents(openFile(binDir));
File rogueSymFile = new File(currTestDataPath + File.separatorChar + "Empty.ajsym");
if (rogueSymFile.exists()) rogueSymFile.delete();
}
/**
* Weave all the possible kinds of advice and verify the messages that come out.
*/
public void testWeaveMessagesAdvice() {
if (debugTests) System.out.println("testWeaveMessagesAdvice: Building with One.lst");
compilerAdapter = new CompilerAdapter();
compilerAdapter.showInfoMessages(true);
compilerAdapter.compile((String) openFile("One.lst").getAbsolutePath(),new BPM(),false);
verifyWeavingMessages("advice",true);
}
/**
* Weave field and method ITDs and check the weave messages that come out.
*/
public void testWeaveMessagesITD() {
if (debugTests) System.out.println("\ntestWeaveMessagesITD: Building with Two.lst");
compilerAdapter = new CompilerAdapter();
compilerAdapter.showInfoMessages(true);
compilerAdapter.compile((String) openFile("Two.lst").getAbsolutePath(),new BPM(),false);
verifyWeavingMessages("itd",true);
}
/**
* Weave "declare parents: implements" and check the weave messages that come out.
*/
public void testWeaveMessagesDeclare() {
if (debugTests) System.out.println("\ntestWeaveMessagesDeclare: Building with Three.lst");
compilerAdapter = new CompilerAdapter();
compilerAdapter.showInfoMessages(true);
compilerAdapter.compile((String) openFile("Three.lst").getAbsolutePath(),new BPM(),false);
verifyWeavingMessages("declare1",true);
}
/**
* Weave "declare parents: extends" and check the weave messages that come out.
* Can't do equivalent binary test - as can't do extends in binary.
*/
public void testWeaveMessagesDeclareExtends() {
if (debugTests) System.out.println("\ntestWeaveMessagesDeclareExtends: Building with Four.lst");
compilerAdapter = new CompilerAdapter();
compilerAdapter.showInfoMessages(true);
compilerAdapter.compile((String) openFile("Four.lst").getAbsolutePath(),new BPM(),false);
verifyWeavingMessages("declare.extends",true);
}
/**
* Weave "declare soft: type: pointcut" and check the weave messages that come out.
*/
public void testWeaveMessagesDeclareSoft() {
if (debugTests) System.out.println("\ntestWeaveMessagesDeclareSoft: Building with Five.lst");
compilerAdapter = new CompilerAdapter();
compilerAdapter.showInfoMessages(true);
compilerAdapter.compile((String) openFile("Five.lst").getAbsolutePath(),new BPM(),false);
verifyWeavingMessages("declare.soft",true);
}
// BINARY WEAVING TESTS
/**
* Binary weave variant of the advice weaving test above - to check messages are ok for
* binary weave. Unlike the source level weave, in this test we are using an aspect on
* the aspectpath - which means it has already had its necessary parts woven - so the list
* of weaving messages we expect is less.
*/
public void testWeaveMessagesBinaryAdvice() {
if (debugTests) System.out.println("\ntestWeaveMessagesBinaryAdvice: Simple.jar + AspectAdvice.jar");
Set inpath = new HashSet();
inpath.add(openFile("Simple.jar"));
ideManager.getProjectProperties().setInpath(inpath);
Set aspectpath = new HashSet();
aspectpath.add(openFile("AspectAdvice.jar"));
ideManager.getProjectProperties().setAspectPath(aspectpath);
assertTrue("Build failed", doSynchronousBuild("Empty.lst"));
List l = ideManager.getCompilationSourceLineTasks();
verifyWeavingMessages("advice.binary",true);
}
public void testWeaveMessagesBinaryITD() {
if (debugTests) System.out.println("\ntestWeaveMessagesBinaryITD: Simple.jar + AspectITD.jar");
Set inpath = new HashSet();
inpath.add(openFile("Simple.jar"));
ideManager.getProjectProperties().setInpath(inpath);
Set aspectpath = new HashSet();
aspectpath.add(openFile("AspectITD.jar"));
ideManager.getProjectProperties().setAspectPath(aspectpath);
assertTrue("Build failed", doSynchronousBuild("Empty.lst"));
List l = ideManager.getCompilationSourceLineTasks();
verifyWeavingMessages("itd",false);
}
public void testWeaveMessagesBinaryDeclare() {
if (debugTests) System.out.println("\ntestWeaveMessagesBinaryDeclare: Simple.jar + AspectDeclare.jar");
Set inpath = new HashSet();
inpath.add(openFile("Simple.jar"));
ideManager.getProjectProperties().setInpath(inpath);
Set aspectpath = new HashSet();
aspectpath.add(openFile("AspectDeclare.jar"));
ideManager.getProjectProperties().setAspectPath(aspectpath);
assertTrue("Build failed", doSynchronousBuild("Empty.lst"));
verifyWeavingMessages("declare1",false);
}
/**
* Weave "declare soft: type: pointcut" and check the weave messages that come out.
*/
public void testWeaveMessagesBinaryDeclareSoft() {
if (debugTests) System.out.println("\ntestWeaveMessagesBinaryDeclareSoft: Simple.jar + AspectDeclareSoft.jar");
Set inpath = new HashSet();
inpath.add(openFile("Simple.jar"));
ideManager.getProjectProperties().setInpath(inpath);
Set aspectpath = new HashSet();
aspectpath.add(openFile("AspectDeclareSoft.jar"));
ideManager.getProjectProperties().setAspectPath(aspectpath);
assertTrue("Build failed", doSynchronousBuild("Empty.lst"));
verifyWeavingMessages("declare.soft",false);
}
// BINARY WEAVING WHEN WE'VE LOST THE SOURCE POINTERS
public void testWeaveMessagesBinaryAdviceNoDebugInfo() {
if (debugTests) System.out.println("\ntestWeaveMessagesBinaryAdvice: Simple.jar + AspectAdvice.jar");
Set inpath = new HashSet();
inpath.add(openFile("Simple_nodebug.jar"));
ideManager.getProjectProperties().setInpath(inpath);
Set aspectpath = new HashSet();
aspectpath.add(openFile("AspectAdvice_nodebug.jar"));
ideManager.getProjectProperties().setAspectPath(aspectpath);
assertTrue("Build failed", doSynchronousBuild("Empty.lst"));
List l = ideManager.getCompilationSourceLineTasks();
verifyWeavingMessages("advice.binary.nodebug",true);
}
public void testWeaveMessagesBinaryITDNoDebugInfo() {
if (debugTests) System.out.println("\ntestWeaveMessagesBinaryITD: Simple.jar + AspectITD.jar");
Set inpath = new HashSet();
inpath.add(openFile("Simple_nodebug.jar"));
ideManager.getProjectProperties().setInpath(inpath);
Set aspectpath = new HashSet();
aspectpath.add(openFile("AspectITD_nodebug.jar"));
ideManager.getProjectProperties().setAspectPath(aspectpath);
assertTrue("Build failed", doSynchronousBuild("Empty.lst"));
List l = ideManager.getCompilationSourceLineTasks();
verifyWeavingMessages("itd.nodebug",true);
}
public void testWeaveMessagesBinaryDeclareNoDebugInfo() {
if (debugTests) System.out.println("\ntestWeaveMessagesBinaryDeclareNoDebugInfo: Simple.jar + AspectDeclare.jar");
Set inpath = new HashSet();
inpath.add(openFile("Simple_nodebug.jar"));
ideManager.getProjectProperties().setInpath(inpath);
Set aspectpath = new HashSet();
aspectpath.add(openFile("AspectDeclare_nodebug.jar"));
ideManager.getProjectProperties().setAspectPath(aspectpath);
assertTrue("Build failed", doSynchronousBuild("Empty.lst"));
verifyWeavingMessages("declare1.nodebug",true);
}
/**
* Weave "declare soft: type: pointcut" and check the weave messages that come out.
*/
public void testWeaveMessagesBinaryDeclareSoftNoDebugInfo() {
if (debugTests) System.out.println("\ntestWeaveMessagesBinaryDeclareSoftNoDebugInfo: Simple.jar + AspectDeclareSoft.jar");
Set inpath = new HashSet();
inpath.add(openFile("Simple_nodebug.jar"));
ideManager.getProjectProperties().setInpath(inpath);
Set aspectpath = new HashSet();
aspectpath.add(openFile("AspectDeclareSoft_nodebug.jar"));
ideManager.getProjectProperties().setAspectPath(aspectpath);
assertTrue("Build failed", doSynchronousBuild("Empty.lst"));
verifyWeavingMessages("declare.soft.nodebug",true);
}
private class BPM implements BuildProgressMonitor {
public void start(String configFile) {}
public void setProgressText(String text) {}
public void setProgressBarVal(int newVal) { }
public void incrementProgressBarVal() {}
public void setProgressBarMax(int maxVal) { }
public int getProgressBarMax() {
return 0;
}
public void finish() {}
}
public void verifyWeavingMessages(String testid,boolean source) {
File expectedF = openFile(expectedResultsDir+File.separator+testid+".txt");
if (regenerate && source) {
// Create the file
saveWeaveMessages(expectedF);
} else {
// Verify the file matches what we have
compareWeaveMessages(expectedF);
}
}
/**
* Compare weaving messages with what is in the file
*/
private void compareWeaveMessages(File f) {
List fileContents = new ArrayList();
BufferedReader fr;
try {
// Load the file in
fr = new BufferedReader(new FileReader(f));
String line = null;
while ((line=fr.readLine())!=null) fileContents.add(line);
// See if the messages match
int msgCount = 0;
List l = ideManager.getCompilationSourceLineTasks();
for (Iterator iter = l.iterator(); iter.hasNext();) {
IMessage msg = ((NullIdeTaskListManager.SourceLineTask) iter.next()).message;
if (msg.getKind().equals(IMessage.WEAVEINFO)) {
if (!fileContents.contains(msg.getMessage())) {
fail("Could not find message '"+msg.getMessage()+"' in the expected results\n"+
stringify(fileContents));
} else {
fileContents.remove(msg.getMessage());
}
msgCount++;
}
}
assertTrue("Didn't get these expected messages: "+fileContents,fileContents.size()==0);
if (debugTests) System.out.println("Successfully verified "+msgCount+" weaving messages");
} catch (Exception e) {
fail("Unexpected exception saving weaving messages:"+e);
}
}
private String stringify(List l) {
StringBuffer result = new StringBuffer();
for (Iterator iter = l.iterator(); iter.hasNext();) {
String str = (String) iter.next();
result.append(str);result.append("\n");
}
return result.toString();
}
/**
* Store the weaving messages in the specified file.
*/
private void saveWeaveMessages(File f) {
System.out.println("Saving weave messages into "+f.getName());
FileWriter fw;
try {
fw = new FileWriter(f);
List l = ideManager.getCompilationSourceLineTasks();
for (Iterator iter = l.iterator(); iter.hasNext();) {
IMessage msg = ((NullIdeTaskListManager.SourceLineTask) iter.next()).message;
if (msg.getKind().equals(IMessage.WEAVEINFO)) {
fw.write(msg.getMessage()+"\n");
}
}
fw.close();
} catch (Exception e) {
fail("Unexpected exception saving weaving messages:"+e);
}
}
}
|
92,906 |
Bug 92906 showWeaveInfo for declare annotations
|
declaring annotations (declare @type, @constructor, @method and @field) currently doesn't show a message when the -showWeaveInfo option is set in ajc. Appropriate messages should be displayed.
|
resolved fixed
|
abc9a58
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-04T09:22:43Z | 2005-04-27T13:53:20Z |
bridge/src/org/aspectj/bridge/WeaveMessage.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:
* Andy Clement IBM initial implementation 30-May-2004
* ******************************************************************/
package org.aspectj.bridge;
public class WeaveMessage extends Message {
// Kinds of weaving message we can produce
public static WeaveMessageKind WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS =
new WeaveMessageKind(1,"Extending interface set for type '%1' (%2) to include '%3' (%4)");
public static WeaveMessageKind WEAVEMESSAGE_ITD =
new WeaveMessageKind(2,"Type '%1' (%2) has intertyped %3 from '%4' (%5)");
// %6 is information like "[with runtime test]"
public static WeaveMessageKind WEAVEMESSAGE_ADVISES =
new WeaveMessageKind(3,"Type '%1' (%2) advised by %3 advice from '%4' (%5)%6");
public static WeaveMessageKind WEAVEMESSAGE_DECLAREPARENTSEXTENDS =
new WeaveMessageKind(4,"Setting superclass of type '%1' (%2) to '%3' (%4)");
public static WeaveMessageKind WEAVEMESSAGE_SOFTENS =
new WeaveMessageKind(5,"Softening exceptions in type '%1' (%2) as defined by aspect '%3' (%4)");
public static WeaveMessageKind WEAVEMESSAGE_ANNOTATES =
new WeaveMessageKind(6,"'%1' (%2) is annoted with %3 from '%4' (%5)");
private String affectedtypename;
private String aspectname;
// private ctor - use the static factory method
private WeaveMessage(String message, String affectedtypename, String aspectname) {
super(message, IMessage.WEAVEINFO, null, null);
this.affectedtypename = affectedtypename;
this.aspectname = aspectname;
}
/**
* Static helper method for constructing weaving messages.
* @param kind what kind of message (e.g. declare parents)
* @param inserts inserts for the message (inserts are marked %n in the message)
* @return new weaving message
*/
public static WeaveMessage constructWeavingMessage(
WeaveMessageKind kind,
String[] inserts) {
StringBuffer str = new StringBuffer(kind.getMessage());
int pos = -1;
while ((pos=new String(str).indexOf("%"))!=-1) {
int n = Character.getNumericValue(str.charAt(pos+1));
str.replace(pos,pos+2,inserts[n-1]);
}
return new WeaveMessage(str.toString(), null, null);
}
/**
* Static helper method for constructing weaving messages.
* @param kind what kind of message (e.g. declare parents)
* @param inserts inserts for the message (inserts are marked %n in the message)
* @param affectedtypename the type which is being advised/declaredUpon
* @param aspectname the aspect that defined the advice or declares
* @return new weaving message
*/
public static WeaveMessage constructWeavingMessage(
WeaveMessageKind kind,
String[] inserts,
String affectedtypename,
String aspectname) {
StringBuffer str = new StringBuffer(kind.getMessage());
int pos = -1;
while ((pos=new String(str).indexOf("%"))!=-1) {
int n = Character.getNumericValue(str.charAt(pos+1));
str.replace(pos,pos+2,inserts[n-1]);
}
return new WeaveMessage(str.toString(), affectedtypename, aspectname);
}
/**
* @return Returns the aspectname.
*/
public String getAspectname() {
return aspectname;
}
/**
* @return Returns the affectedtypename.
*/
public String getAffectedtypename() {
return affectedtypename;
}
public static class WeaveMessageKind {
private int id;
private String message;
public WeaveMessageKind(int id,String message) {
this.id = id;
this.message = message;
}
public String getMessage() { return message; }
}
}
|
92,906 |
Bug 92906 showWeaveInfo for declare annotations
|
declaring annotations (declare @type, @constructor, @method and @field) currently doesn't show a message when the -showWeaveInfo option is set in ajc. Appropriate messages should be displayed.
|
resolved fixed
|
abc9a58
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-04T09:22:43Z | 2005-04-27T13:53:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.CPInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.IndexedInstruction;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LocalVariableInstruction;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUTFIELD;
import org.aspectj.apache.bcel.generic.PUTSTATIC;
import org.aspectj.apache.bcel.generic.RET;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.Select;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IClassWeaver;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverMetrics;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.Shadow.Kind;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.FastMatchInfo;
class BcelClassWeaver implements IClassWeaver {
/**
* This is called from {@link BcelWeaver} to perform the per-class weaving process.
*/
public static boolean weave(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers)
{
boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers).weave();
//System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState());
//clazz.print();
return b;
}
// --------------------------------------------
private final LazyClassGen clazz;
private final List shadowMungers;
private final List typeMungers;
private final BcelObjectType ty; // alias of clazz.getType()
private final BcelWorld world; // alias of ty.getWorld()
private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen()
private final InstructionFactory fact; // alias of clazz.getFactory();
private final List addedLazyMethodGens = new ArrayList();
private final Set addedDispatchTargets = new HashSet();
// Static setting across BcelClassWeavers
private static boolean inReweavableMode = false;
private static boolean compressReweavableAttributes = false;
private List addedSuperInitializersAsList = null; // List<IfaceInitList>
private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList
private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger>
private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger>
private 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)
{
super();
// assert world == clazz.getType().getWorld()
this.world = world;
this.clazz = clazz;
this.shadowMungers = shadowMungers;
this.typeMungers = typeMungers;
this.ty = clazz.getBcelObjectType();
this.cpg = clazz.getConstantPoolGen();
this.fact = clazz.getFactory();
fastMatchShadowMungers(shadowMungers);
initializeSuperInitializerMap(ty.getResolvedTypeX());
}
private List[] perKindShadowMungers;
private boolean canMatchBodyShadows = false;
private boolean canMatchInitialization = false;
private void fastMatchShadowMungers(List shadowMungers) {
// beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) !
perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1];
for (int i = 0; i < perKindShadowMungers.length; i++) {
ArrayList mungers = new ArrayList(0);
perKindShadowMungers[i] = new ArrayList(0);
}
for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
Set couldMatchKinds = munger.getPointcut().couldMatchKinds();
for (Iterator kindIterator = couldMatchKinds.iterator();
kindIterator.hasNext();) {
Shadow.Kind aKind = (Shadow.Kind) kindIterator.next();
perKindShadowMungers[aKind.getKey()].add(munger);
}
}
if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty())
canMatchInitialization = true;
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
Shadow.Kind kind = Shadow.SHADOW_KINDS[i];
if (!kind.isEnclosingKind() && !perKindShadowMungers[i+1].isEmpty()) {
canMatchBodyShadows = true;
}
if (perKindShadowMungers[i+1].isEmpty()) {
perKindShadowMungers[i+1] = null;
}
}
}
private boolean canMatch(Shadow.Kind kind) {
return perKindShadowMungers[kind.getKey()] != null;
}
private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) {
FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind);
for (Iterator i = shadowMungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
FuzzyBoolean fb = munger.getPointcut().fastMatch(info);
WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString()
if (fb.maybeTrue()) mungers.add(munger);
}
}
private void initializeSuperInitializerMap(ResolvedTypeX child) {
ResolvedTypeX[] superInterfaces = child.getDeclaredInterfaces();
for (int i=0, len=superInterfaces.length; i < len; i++) {
if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) {
if (addSuperInitializer(superInterfaces[i])) {
initializeSuperInitializerMap(superInterfaces[i]);
}
}
}
}
private boolean addSuperInitializer(ResolvedTypeX onType) {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
if (l != null) return false;
l = new IfaceInitList(onType);
addedSuperInitializers.put(onType, l);
return true;
}
public void addInitializer(ConcreteTypeMunger cm) {
NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger();
ResolvedTypeX onType = m.getSignature().getDeclaringType().resolve(world);
if (m.getSignature().isStatic()) {
addedClassInitializers.add(cm);
} else {
if (onType == ty.getResolvedTypeX()) {
addedThisInitializers.add(cm);
} else {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
l.list.add(cm);
}
}
}
private static class IfaceInitList implements PartialOrder.PartialComparable {
final ResolvedTypeX onType;
List list = new ArrayList();
IfaceInitList(ResolvedTypeX onType) {
this.onType = onType;
}
public int compareTo(Object other) {
IfaceInitList o = (IfaceInitList)other;
if (onType.isAssignableFrom(o.onType)) return +1;
else if (o.onType.isAssignableFrom(onType)) return -1;
else return 0;
}
public int fallbackCompareTo(Object other) {
return 0;
}
}
// XXX this is being called, but the result doesn't seem to be being used
public boolean addDispatchTarget(ResolvedMember m) {
return addedDispatchTargets.add(m);
}
public void addLazyMethodGen(LazyMethodGen gen) {
addedLazyMethodGens.add(gen);
}
public void addOrReplaceLazyMethodGen(LazyMethodGen mg) {
if (alreadyDefined(clazz, mg)) return;
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (existing.definingType == null) {
// this means existing was introduced on the class itself
return;
} else if (mg.definingType.isAssignableFrom(existing.definingType)) {
// existing is mg's subtype and dominates mg
return;
} else if (existing.definingType.isAssignableFrom(mg.definingType)) {
// mg is existing's subtype and dominates existing
i.remove();
addedLazyMethodGens.add(mg);
return;
} else {
throw new BCException("conflict between: " + mg + " and " + existing);
}
}
}
addedLazyMethodGens.add(mg);
}
private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) {
for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (!mg.isAbstract() && existing.isAbstract()) {
i.remove();
return false;
}
return true;
}
}
return false;
}
private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) {
return mg.getName().equals(existing.getName()) &&
mg.getSignature().equals(existing.getSignature());
}
// ----
public boolean weave() {
if (clazz.isWoven() && !clazz.isReweavable()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()),
ty.getSourceLocation(), null);
return false;
}
Set aspectsAffectingType = null;
if (inReweavableMode) aspectsAffectingType = new HashSet();
boolean isChanged = false;
// we want to "touch" all aspects
if (clazz.getType().isAspect()) isChanged = true;
// start by munging all typeMungers
for (Iterator i = typeMungers.iterator(); i.hasNext(); ) {
Object o = i.next();
if ( !(o instanceof BcelTypeMunger) ) {
//???System.err.println("surprising: " + o);
continue;
}
BcelTypeMunger munger = (BcelTypeMunger)o;
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
isChanged = true;
if (inReweavableMode) aspectsAffectingType.add(munger.getAspectType().getName());
}
}
// Weave special half type/half shadow mungers...
isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged;
isChanged = weaveDeclareAtField(clazz) || isChanged;
// XXX do major sort of stuff
// sort according to: Major: type hierarchy
// within each list: dominates
// don't forget to sort addedThisInitialiers according to dominates
addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values());
addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList);
if (addedSuperInitializersAsList == null) {
throw new BCException("circularity in inter-types");
}
// this will create a static initializer if there isn't one
// this is in just as bad taste as NOPs
LazyMethodGen staticInit = clazz.getStaticInitializer();
staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true));
// now go through each method, and match against each method. This
// sets up each method's {@link LazyMethodGen#matchedShadows} field,
// and it also possibly adds to {@link #initializationShadows}.
List methodGens = new ArrayList(clazz.getMethodGens());
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
//mg.getBody();
if (! mg.hasBody()) continue;
boolean shadowMungerMatched = match(mg);
if (shadowMungerMatched) {
// For matching mungers, add their declaring aspects to the list that affected this type
if (inReweavableMode) aspectsAffectingType.addAll(findAspectsForMungers(mg));
isChanged = true;
}
}
if (! isChanged) return false;
// now we weave all but the initialization shadows
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
implement(mg);
}
// if we matched any initialization shadows, we inline and weave
if (! initializationShadows.isEmpty()) {
// Repeat next step until nothing left to inline...cant go on
// infinetly as compiler will have detected and reported
// "Recursive constructor invocation"
while (inlineSelfConstructors(methodGens));
positionAndImplement(initializationShadows);
}
// finally, if we changed, we add in the introduced methods.
if (isChanged) {
clazz.getOrCreateWeaverStateInfo();
weaveInAddedMethods(); // FIXME asc are these potentially affected by declare annotation?
}
if (inReweavableMode) {
WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo();
wsi.addAspectsAffectingType(aspectsAffectingType);
wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes());
wsi.setReweavable(true,compressReweavableAttributes);
} else {
clazz.getOrCreateWeaverStateInfo().setReweavable(false,false);
}
return isChanged;
}
/**
* Weave any declare @method/@ctor statements into the members of the supplied class
*/
private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) {
List reportedProblems = new ArrayList();
List allDecams = world.getDeclareAnnotationOnMethods();
if (allDecams.isEmpty()) return false; // nothing to do
boolean isChanged = false;
// deal with ITDs
List itdMethodsCtors = getITDSubset(clazz,ResolvedTypeMunger.Method);
itdMethodsCtors.addAll(getITDSubset(clazz,ResolvedTypeMunger.Constructor));
if (!itdMethodsCtors.isEmpty()) {
// Can't use the subset called 'decaMs' as it won't be right for ITDs...
isChanged = weaveAtMethodOnITDSRepeatedly(allDecams,itdMethodsCtors,reportedProblems);
}
// deal with all the other methods...
List members = clazz.getMethodGens();
List decaMs = getMatchingSubset(allDecams,clazz.getType());
if (decaMs.isEmpty()) return false; // nothing to do
if (!members.isEmpty()) {
for (int memberCounter = 0;memberCounter<members.size();memberCounter++) {
LazyMethodGen mg = (LazyMethodGen)members.get(memberCounter);
if (!mg.getName().startsWith(NameMangler.PREFIX)) {
// Single first pass
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
for (Iterator iter = decaMs.iterator(); iter.hasNext();) {
DeclareAnnotation decaM = (DeclareAnnotation) iter.next();
if (decaM.matches(mg.getMemberView(),world)) {
if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) continue; // skip this one...
mg.addAnnotation(decaM.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod());
isChanged = true;
modificationOccured = true;
} else {
if (!decaM.isStarredAnnotationPattern())
worthRetrying.add(decaM); // an annotation is specified that might be put on by a subsequent decaf
}
}
// Multiple secondary passes
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
// lets have another go
List forRemoval = new ArrayList();
for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaM = (DeclareAnnotation) iter.next();
if (decaM.matches(mg.getMemberView(),world)) {
if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) continue; // skip this one...
mg.addAnnotation(decaM.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaM);
}
}
worthRetrying.removeAll(forRemoval);
}
}
}
}
return isChanged;
}
/**
* Looks through a list of declare annotation statements and only returns
* those that could possibly match on a field/method/ctor in type.
*/
private List getMatchingSubset(List declareAnnotations, ResolvedTypeX type) {
List subset = new ArrayList();
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.interMethodBody(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 itdIsActually = methodctorMunger.getSignature();
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
for (Iterator iter2 = decaMCs.iterator(); iter2.hasNext();) {
DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next();
if (decaMC.matches(itdIsActually,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz,methodctorMunger);
if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaMC,reportedErrors)) continue; // skip this one...
annotationHolder.addAnnotation(decaMC.getAnnotationX());
itdIsActually.addAnnotation(decaMC.getAnnotationX());
isChanged=true;
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),itdIsActually.getSourceLocation());
modificationOccured = true;
} else {
if (!decaMC.isStarredAnnotationPattern())
worthRetrying.add(decaMC); // an annotation is specified that might be put on by a subsequent decaf
}
}
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
List forRemoval = new ArrayList();
for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next();
if (decaMC.matches(itdIsActually,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,methodctorMunger);
if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaMC,reportedErrors)) continue; // skip this one...
annotationHolder.addAnnotation(decaMC.getAnnotationX());
itdIsActually.addAnnotation(decaMC.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),itdIsActually.getSourceLocation());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaMC);
}
worthRetrying.removeAll(forRemoval);
}
}
}
return isChanged;
}
/**
* Weave any declare @field statements into the fields of the supplied class
*
* Interesting case relating to public ITDd fields. The annotations are really stored against
* the interfieldinit method in the aspect, but the public field is placed in the target
* type and then is processed in the 2nd pass over fields that occurs. I think it would be
* more expensive to avoid putting the annotation on that inserted public field than just to
* have it put there as well as on the interfieldinit method.
*/
private boolean weaveDeclareAtField(LazyClassGen clazz) {
// BUGWARNING not getting enough warnings out on declare @field ?
// There is a potential problem here with warnings not coming out - this
// will occur if they are created on the second iteration round this loop.
// We currently deactivate error reporting for the second time round.
// A possible solution is to record what annotations were added by what
// decafs and check that to see if an error needs to be reported - this
// would be expensive so lets skip it for now
List reportedProblems = new ArrayList();
List allDecafs = world.getDeclareAnnotationOnFields();
if (allDecafs.isEmpty()) return false; // nothing to do
boolean isChanged = false;
List itdFields = getITDSubset(clazz,ResolvedTypeMunger.Field);
if (itdFields!=null) {
isChanged = weaveAtFieldRepeatedly(allDecafs,itdFields,reportedProblems);
}
List decaFs = getMatchingSubset(allDecafs,clazz.getType());
if (decaFs.isEmpty()) return false; // nothing more to do
Field[] fields = clazz.getFieldGens();
if (fields!=null) {
for (int fieldCounter = 0;fieldCounter<fields.length;fieldCounter++) {
BcelField aBcelField = new BcelField(clazz.getBcelObjectType(),fields[fieldCounter]);
if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) {
// Single first pass
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
// go through all the declare @field statements
for (Iterator iter = decaFs.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter.next();
if (decaF.matches(aBcelField,world)) {
if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) continue; // skip this one...
aBcelField.addAnnotation(decaF.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]);
isChanged = true;
modificationOccured = true;
} else {
if (!decaF.isStarredAnnotationPattern())
worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf
}
}
// Multiple secondary passes
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
// lets have another go
List forRemoval = new ArrayList();
for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter.next();
if (decaF.matches(aBcelField,world)) {
if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) continue; // skip this one...
aBcelField.addAnnotation(decaF.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]);
isChanged = true;
modificationOccured = true;
forRemoval.add(decaF);
}
}
worthRetrying.removeAll(forRemoval);
}
}
}
}
return isChanged;
}
/**
* 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.hasAnnotation(deca.getAnnotationTypeX())) {
if (world.getLint().elementAlreadyAnnotated.isEnabled()) {
Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode());
if (!reportedProblems.contains(uniqueID)) {
reportedProblems.add(uniqueID);
reportedProblems.add(new Integer(itdfieldsig.hashCode()*deca.hashCode()));
world.getLint().elementAlreadyAnnotated.signal(
new String[]{rm.toString(),deca.getAnnotationTypeX().toString()},
rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()});
}
}
return true;
}
return false;
}
private Set findAspectsForMungers(LazyMethodGen mg) {
Set aspectsAffectingType = new HashSet();
for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) {
BcelShadow aShadow = (BcelShadow) iter.next();
// Mungers in effect on that shadow
for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) {
ShadowMunger aMunger = (ShadowMunger) iter2.next();
if (aMunger instanceof BcelAdvice) {
BcelAdvice bAdvice = (BcelAdvice)aMunger;
aspectsAffectingType.add(bAdvice.getConcreteAspect().getName());
} else {
// It is a 'Checker' - we don't need to remember aspects that only contributed Checkers...
}
}
}
return aspectsAffectingType;
}
private boolean inlineSelfConstructors(List methodGens) {
boolean inlinedSomething = false;
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen) i.next();
if (! mg.getName().equals("<init>")) continue;
InstructionHandle ih = findSuperOrThisCall(mg);
if (ih != null && isThisCall(ih)) {
LazyMethodGen donor = getCalledMethod(ih);
inlineMethod(donor, mg, ih);
inlinedSomething = true;
}
}
return inlinedSomething;
}
private void positionAndImplement(List initializationShadows) {
for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) {
BcelShadow s = (BcelShadow) i.next();
positionInitializationShadow(s);
//s.getEnclosingMethod().print();
s.implement();
}
}
private void positionInitializationShadow(BcelShadow s) {
LazyMethodGen mg = s.getEnclosingMethod();
InstructionHandle call = findSuperOrThisCall(mg);
InstructionList body = mg.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow((BcelShadow) s);
if (s.getKind() == Shadow.PreInitialization) {
// XXX assert first instruction is an ALOAD_0.
// a pre shadow goes from AFTER the first instruction (which we believe to
// be an ALOAD_0) to just before the call to super
r.associateWithTargets(
Range.genStart(body, body.getStart().getNext()),
Range.genEnd(body, call.getPrev()));
} else {
// assert s.getKind() == Shadow.Initialization
r.associateWithTargets(
Range.genStart(body, call.getNext()),
Range.genEnd(body));
}
}
private boolean isThisCall(InstructionHandle ih) {
INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction();
return inst.getClassName(cpg).equals(clazz.getName());
}
/** inline a particular call in bytecode.
*
* @param donor the method we want to inline
* @param recipient the method containing the call we want to inline
* @param call the instructionHandle in recipient's body holding the call we want to
* inline.
*/
public static void inlineMethod(
LazyMethodGen donor,
LazyMethodGen recipient,
InstructionHandle call)
{
// assert recipient.contains(call)
/* Implementation notes:
*
* We allocate two slots for every tempvar so we don't screw up
* longs and doubles which may share space. This could be conservatively avoided
* (no reference to a long/double instruction, don't do it) or packed later.
* Right now we don't bother to pack.
*
* Allocate a new var for each formal param of the inlined. Fill with stack
* contents. Then copy the inlined instructions in with the appropriate remap
* table. Any framelocs used by locals in inlined are reallocated to top of
* frame,
*/
final InstructionFactory fact = recipient.getEnclosingClass().getFactory();
IntMap frameEnv = new IntMap();
// this also sets up the initial environment
InstructionList argumentStores =
genArgumentStores(donor, recipient, frameEnv, fact);
InstructionList inlineInstructions =
genInlineInstructions(donor, recipient, frameEnv, fact, false);
inlineInstructions.insert(argumentStores);
recipient.getBody().append(call, inlineInstructions);
Utility.deleteInstruction(call, recipient);
}
/** generate the instructions to be inlined.
*
* @param donor the method from which we will copy (and adjust frame and jumps)
* instructions.
* @param recipient the method the instructions will go into. Used to get the frame
* size so we can allocate new frame locations for locals in donor.
* @param frameEnv an environment to map from donor frame to recipient frame,
* initially populated with argument locations.
* @param fact an instruction factory for recipient
*/
static InstructionList genInlineInstructions(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact,
boolean keepReturns)
{
InstructionList footer = new InstructionList();
InstructionHandle end = footer.append(InstructionConstants.NOP);
InstructionList ret = new InstructionList();
InstructionList sourceList = donor.getBody();
Map srcToDest = new HashMap();
ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen();
ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen();
boolean isAcrossClass = donorCpg != recipientCpg;
// first pass: copy the instructions directly, populate the srcToDest map,
// fix frame instructions
for (InstructionHandle src = sourceList.getStart();
src != null;
src = src.getNext())
{
Instruction fresh = Utility.copyInstruction(src.getInstruction());
InstructionHandle dest;
if (fresh instanceof CPInstruction) {
// need to reset index to go to new constant pool. This is totally
// a computation leak... we're testing this LOTS of times. Sigh.
if (isAcrossClass) {
CPInstruction cpi = (CPInstruction) fresh;
cpi.setIndex(
recipientCpg.addConstant(
donorCpg.getConstant(cpi.getIndex()),
donorCpg));
}
}
if (src.getInstruction() == Range.RANGEINSTRUCTION) {
dest = ret.append(Range.RANGEINSTRUCTION);
} else if (fresh instanceof ReturnInstruction) {
if (keepReturns) {
dest = ret.append(fresh);
} else {
dest =
ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end));
}
} else if (fresh instanceof BranchInstruction) {
dest = ret.append((BranchInstruction) fresh);
} else if (
fresh instanceof LocalVariableInstruction || fresh instanceof RET) {
IndexedInstruction indexed = (IndexedInstruction) fresh;
int oldIndex = indexed.getIndex();
int freshIndex;
if (!frameEnv.hasKey(oldIndex)) {
freshIndex = recipient.allocateLocal(2);
frameEnv.put(oldIndex, freshIndex);
} else {
freshIndex = frameEnv.get(oldIndex);
}
indexed.setIndex(freshIndex);
dest = ret.append(fresh);
} else {
dest = ret.append(fresh);
}
srcToDest.put(src, dest);
}
// second pass: retarget branch instructions, copy ranges and tags
Map tagMap = new HashMap();
Map shadowMap = new HashMap();
for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart();
dest != null;
dest = dest.getNext(), src = src.getNext()) {
Instruction inst = dest.getInstruction();
// retarget branches
if (inst instanceof BranchInstruction) {
BranchInstruction branch = (BranchInstruction) inst;
InstructionHandle oldTarget = branch.getTarget();
InstructionHandle newTarget =
(InstructionHandle) srcToDest.get(oldTarget);
if (newTarget == null) {
// assert this is a GOTO
// this was a return instruction we previously replaced
} else {
branch.setTarget(newTarget);
if (branch instanceof Select) {
Select select = (Select) branch;
InstructionHandle[] oldTargets = select.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
select.setTarget(
k,
(InstructionHandle) srcToDest.get(oldTargets[k]));
}
}
}
}
//copy over tags and range attributes
InstructionTargeter[] srcTargeters = src.getTargeters();
if (srcTargeters != null) {
for (int j = srcTargeters.length - 1; j >= 0; j--) {
InstructionTargeter old = srcTargeters[j];
if (old instanceof Tag) {
Tag oldTag = (Tag) old;
Tag fresh = (Tag) tagMap.get(oldTag);
if (fresh == null) {
fresh = oldTag.copy();
tagMap.put(oldTag, fresh);
}
dest.addTargeter(fresh);
} else if (old instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) old;
if (er.getStart() == src) {
ExceptionRange freshEr =
new ExceptionRange(
recipient.getBody(),
er.getCatchType(),
er.getPriority());
freshEr.associateWithTargets(
dest,
(InstructionHandle)srcToDest.get(er.getEnd()),
(InstructionHandle)srcToDest.get(er.getHandler()));
}
} else if (old instanceof ShadowRange) {
ShadowRange oldRange = (ShadowRange) old;
if (oldRange.getStart() == src) {
BcelShadow oldShadow = oldRange.getShadow();
BcelShadow freshEnclosing =
oldShadow.getEnclosingShadow() == null
? null
: (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow());
BcelShadow freshShadow =
oldShadow.copyInto(recipient, freshEnclosing);
ShadowRange freshRange = new ShadowRange(recipient.getBody());
freshRange.associateWithShadow(freshShadow);
freshRange.associateWithTargets(
dest,
(InstructionHandle) srcToDest.get(oldRange.getEnd()));
shadowMap.put(oldRange, freshRange);
//recipient.matchedShadows.add(freshShadow);
// XXX should go through the NEW copied shadow and update
// the thisVar, targetVar, and argsVar
// ??? Might want to also go through at this time and add
// "extra" vars to the shadow.
}
}
}
}
}
if (!keepReturns) ret.append(footer);
return ret;
}
/** generate the argument stores in preparation for inlining.
*
* @param donor the method we will inline from. Used to get the signature.
* @param recipient the method we will inline into. Used to get the frame size
* so we can allocate fresh locations.
* @param frameEnv an empty environment we populate with a map from donor frame to
* recipient frame.
* @param fact an instruction factory for recipient
*/
private static InstructionList genArgumentStores(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact)
{
InstructionList ret = new InstructionList();
int donorFramePos = 0;
// writing ret back to front because we're popping.
if (! donor.isStatic()) {
int targetSlot = recipient.allocateLocal(Type.OBJECT);
ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot));
frameEnv.put(donorFramePos, targetSlot);
donorFramePos += 1;
}
Type[] argTypes = donor.getArgumentTypes();
for (int i = 0, len = argTypes.length; i < len; i++) {
Type argType = argTypes[i];
int argSlot = recipient.allocateLocal(argType);
ret.insert(InstructionFactory.createStore(argType, argSlot));
frameEnv.put(donorFramePos, argSlot);
donorFramePos += argType.getSize();
}
return ret;
}
/** get a called method: Assumes the called method is in this class,
* and the reference to it is exact (a la INVOKESPECIAL).
*
* @param ih The InvokeInstruction instructionHandle pointing to the called method.
*/
private LazyMethodGen getCalledMethod(
InstructionHandle ih)
{
InvokeInstruction inst = (InvokeInstruction) ih.getInstruction();
String methodName = inst.getName(cpg);
String signature = inst.getSignature(cpg);
return clazz.getLazyMethodGen(methodName, signature);
}
private void weaveInAddedMethods() {
Collections.sort(addedLazyMethodGens,
new Comparator() {
public int compare(Object a, Object b) {
LazyMethodGen aa = (LazyMethodGen) a;
LazyMethodGen bb = (LazyMethodGen) b;
int i = aa.getName().compareTo(bb.getName());
if (i != 0) return i;
return aa.getSignature().compareTo(bb.getSignature());
}
}
);
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
clazz.addMethodGen((LazyMethodGen)i.next());
}
}
void addPerSingletonField(Member field) {
ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType());
String aspectName = field.getReturnType().getName();
LazyMethodGen clinit = clazz.getStaticInitializer();
InstructionList setup = new InstructionList();
InstructionFactory fact = clazz.getFactory();
setup.append(fact.createNew(aspectType));
setup.append(InstructionFactory.createDup(1));
setup.append(fact.createInvoke(
aspectName,
"<init>",
Type.VOID,
new Type[0],
Constants.INVOKESPECIAL));
setup.append(
fact.createFieldAccess(
aspectName,
field.getName(),
aspectType,
Constants.PUTSTATIC));
clinit.getBody().insert(setup);
}
/**
* Returns null if this is not a Java constructor, and then we won't
* weave into it at all
*/
private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) {
int depth = 1;
InstructionHandle start = mg.getBody().getStart();
while (true) {
if (start == null) return null;
Instruction inst = start.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth--;
if (depth == 0) return start;
} else if (inst instanceof NEW) {
depth++;
}
start = start.getNext();
}
}
// ----
private boolean match(LazyMethodGen mg) {
BcelShadow enclosingShadow;
List shadowAccumulator = new ArrayList();
// we want to match ajsynthetic constructors...
if (mg.getName().equals("<init>")) {
return matchInit(mg, shadowAccumulator);
} else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) {
return false;
} else {
if (mg.getName().equals("<clinit>")) {
clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg);
//System.err.println(enclosingShadow);
} else if (mg.isAdviceMethod()) {
enclosingShadow = BcelShadow.makeAdviceExecution(world, mg);
} else {
AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature();
if (effective == null) {
enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows);
} else if (effective.isWeaveBody()) {
ResolvedMember rm = effective.getEffectiveSignature();
// Annotations for things with effective signatures are never stored in the effective
// signature itself - we have to hunt for them. Storing them in the effective signature
// would mean keeping two sets up to date (no way!!)
fixAnnotationsForResolvedMember(rm,mg.getMemberView());
enclosingShadow =
BcelShadow.makeShadowForMethod(world,mg,effective.getShadowKind(),rm);
} else {
return false;
}
}
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
match(mg, h, enclosingShadow, shadowAccumulator);
}
}
// FIXME asc change from string match if we can, rather brittle. this check actually prevents field-exec jps
if (canMatch(enclosingShadow.getKind()) && !mg.getName().startsWith("ajc$interFieldInit")) {
if (match(enclosingShadow, shadowAccumulator)) {
enclosingShadow.init();
}
}
mg.matchedShadows = shadowAccumulator;
return !shadowAccumulator.isEmpty();
}
}
private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) {
BcelShadow enclosingShadow;
// XXX the enclosing join point is wrong for things before ignoreMe.
InstructionHandle superOrThisCall = findSuperOrThisCall(mg);
// we don't walk bodies of things where it's a wrong constructor thingie
if (superOrThisCall == null) return false;
enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall);
// walk the body
boolean beforeSuperOrThisCall = true;
if (shouldWeaveBody(mg)) {
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
if (h == superOrThisCall) {
beforeSuperOrThisCall = false;
continue;
}
match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator);
}
}
if (canMatch(Shadow.ConstructorExecution))
match(enclosingShadow, shadowAccumulator);
}
// XXX we don't do pre-inits of interfaces
// now add interface inits
if (superOrThisCall != null && ! isThisCall(superOrThisCall)) {
InstructionHandle curr = enclosingShadow.getRange().getStart();
for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) {
IfaceInitList l = (IfaceInitList) i.next();
Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType);
BcelShadow initShadow =
BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig);
// insert code in place
InstructionList inits = genInitInstructions(l.list, false);
if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) {
initShadow.initIfaceInitializer(curr);
initShadow.getRange().insert(inits, Range.OutsideBefore);
}
}
// now we add our initialization code
InstructionList inits = genInitInstructions(addedThisInitializers, false);
enclosingShadow.getRange().insert(inits, Range.OutsideBefore);
}
// actually, you only need to inline the self constructors that are
// in a particular group (partition the constructors into groups where members
// call or are called only by those in the group). Then only inline
// constructors
// in groups where at least one initialization jp matched. Future work.
boolean addedInitialization =
match(
BcelShadow.makeUnfinishedInitialization(world, mg),
initializationShadows);
addedInitialization |=
match(
BcelShadow.makeUnfinishedPreinitialization(world, mg),
initializationShadows);
mg.matchedShadows = shadowAccumulator;
return addedInitialization || !shadowAccumulator.isEmpty();
}
private boolean shouldWeaveBody(LazyMethodGen mg) {
if (mg.isBridgeMethod()) return false;
if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>");
AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature();
if (a != null) return a.isWeaveBody();
return true;
}
/**
* first sorts the mungers, then gens the initializers in the right order
*/
private InstructionList genInitInstructions(List list, boolean isStatic) {
list = PartialOrder.sort(list);
if (list == null) {
throw new BCException("circularity in inter-types");
}
InstructionList ret = new InstructionList();
for (Iterator i = list.iterator(); i.hasNext();) {
ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next();
NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger();
ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType());
if (!isStatic) ret.append(InstructionConstants.ALOAD_0);
ret.append(Utility.createInvoke(fact, world, initMethod));
}
return ret;
}
private void match(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
Instruction i = ih.getInstruction();
if ((i instanceof FieldInstruction) &&
(canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet))
) {
FieldInstruction fi = (FieldInstruction) i;
if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) {
// check for sets of constant fields. We first check the previous
// instruction. If the previous instruction is a LD_WHATEVER (push
// constant on the stack) then we must resolve the field to determine
// if it's final. If it is final, then we don't generate a shadow.
InstructionHandle prevHandle = ih.getPrev();
Instruction prevI = prevHandle.getInstruction();
if (Utility.isConstantPushInstruction(prevI)) {
Member field = BcelWorld.makeFieldSignature(clazz, (FieldInstruction) i);
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
} else if (Modifier.isFinal(resolvedField.getModifiers())) {
// it's final, so it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
} else {
if (canMatch(Shadow.FieldSet))
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
if (canMatch(Shadow.FieldSet))
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
if (canMatch(Shadow.FieldGet))
matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else if (i instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction) i;
if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) {
if (canMatch(Shadow.ConstructorCall))
match(
BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
} else if (ii instanceof INVOKESPECIAL) {
String onTypeName = ii.getClassName(cpg);
if (onTypeName.equals(mg.getEnclosingClass().getName())) {
// we are private
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
} else {
// we are a super call, and this is not a join point in AspectJ-1.{0,1}
}
} else {
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
}
}
// performance optimization... we only actually care about ASTORE instructions,
// since that's what every javac type thing ever uses to start a handler, but for
// now we'll do this for everybody.
if (!canMatch(Shadow.ExceptionHandler)) return;
if (Range.isRangeHandle(ih)) return;
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int j = 0; j < targeters.length; j++) {
InstructionTargeter t = targeters[j];
if (t instanceof ExceptionRange) {
// assert t.getHandler() == ih
ExceptionRange er = (ExceptionRange) t;
if (er.getCatchType() == null) continue;
if (isInitFailureHandler(ih)) return;
match(
BcelShadow.makeExceptionHandler(
world,
er,
mg, ih, enclosingShadow),
shadowAccumulator);
}
}
}
}
private boolean isInitFailureHandler(InstructionHandle ih) {
// Skip the astore_0 and aload_0 at the start of the handler and
// then check if the instruction following these is
// 'putstatic ajc$initFailureCause'. If it is then we are
// in the handler we created in AspectClinit.generatePostSyntheticCode()
InstructionHandle twoInstructionsAway = ih.getNext().getNext();
if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) {
String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg);
if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true;
}
return false;
}
private void matchSetInstruction(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (
Modifier.isFinal(resolvedField.getModifiers())
&& Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) {
// it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(
BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(BcelShadow.makeFieldGet(world, mg, ih, enclosingShadow), shadowAccumulator);
}
}
/**
* 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 {
TypeX memberHostType = declaredSig.getDeclaringType();
ResolvedTypeX[] annotations = (ResolvedTypeX[])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.interMethodBody(rm,memberHostType);
ResolvedMember resolvedDooberry = world.resolve(realthing);
annotations = resolvedDooberry.getAnnotationTypes();
}
} else if (rm.getKind()==Member.CONSTRUCTOR) {
ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(),rm.getParameterTypes());
ResolvedMember resolvedDooberry = world.resolve(realThing);
annotations = resolvedDooberry.getAnnotationTypes();
}
if (annotations == null)
annotations = new ResolvedTypeX[0];
mapToAnnotations.put(rm,annotations);
}
rm.setAnnotationTypes(annotations);
} catch (Throwable t) {
//FIXME asc remove this catch after more testing has confirmed the above stuff is OK
throw new BCException("Unexpectedly went bang when searching for annotations on "+rm,t);
}
}
private void matchInvokeInstruction(LazyMethodGen mg,
InstructionHandle ih,
InvokeInstruction invoke,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
String methodName = invoke.getName(cpg);
if (methodName.startsWith(NameMangler.PREFIX)) {
Member method =
BcelWorld.makeMethodSignature(clazz, invoke);
ResolvedMember declaredSig = method.resolve(world);
//System.err.println(method + ", declaredSig: " +declaredSig);
if (declaredSig == null) return;
if (declaredSig.getKind() == Member.FIELD) {
Shadow.Kind kind;
if (method.getReturnType().equals(ResolvedTypeX.VOID)) {
kind = Shadow.FieldSet;
} else {
kind = Shadow.FieldGet;
}
if (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet))
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
kind, declaredSig),
shadowAccumulator);
} else {
AjAttribute.EffectiveSignatureAttribute effectiveSig =
declaredSig.getEffectiveSignature();
if (effectiveSig == null) return;
//System.err.println("call to inter-type member: " + effectiveSig);
if (effectiveSig.isWeaveBody()) return;
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);
boolean isMatched = false;
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger munger = (ShadowMunger)i.next();
if (munger.match(shadow, world)) {
WeaverMetrics.recordMatchResult(true);// Could pass: munger
shadow.addMunger(munger);
isMatched = true;
if (shadow.getKind() == Shadow.StaticInitialization) {
clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation());
}
} else {
WeaverMetrics.recordMatchResult(false); // Could pass: munger
}
}
if (isMatched) shadowAccumulator.add(shadow);
return isMatched;
}
// ----
private void implement(LazyMethodGen mg) {
List shadows = mg.matchedShadows;
if (shadows == null) return;
// We depend on a partial order such that inner shadows are earlier on the list
// than outer shadows. That's fine. This order is preserved if:
// A preceeds B iff B.getStart() is LATER THAN A.getStart().
for (Iterator i = shadows.iterator(); i.hasNext(); ) {
BcelShadow shadow = (BcelShadow)i.next();
shadow.implement();
}
mg.matchedShadows = null;
}
// ----
public LazyClassGen getLazyClassGen() {
return clazz;
}
public List getShadowMungers() {
return shadowMungers;
}
public BcelWorld getWorld() {
return world;
}
// Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info
public static void setReweavableMode(boolean mode,boolean compress) {
inReweavableMode = mode;
compressReweavableAttributes = compress;
}
}
|
92,906 |
Bug 92906 showWeaveInfo for declare annotations
|
declaring annotations (declare @type, @constructor, @method and @field) currently doesn't show a message when the -showWeaveInfo option is set in ajc. Appropriate messages should be displayed.
|
resolved fixed
|
abc9a58
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-04T09:22:43Z | 2005-04-27T13:53:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.jar.Attributes.Name;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.FileUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AnnotationOnTypeMunger;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.CrosscuttingMembersSet;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.IWeaver;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverMetrics;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.BindingAnnotationTypePattern;
import org.aspectj.weaver.patterns.BindingTypePattern;
import org.aspectj.weaver.patterns.CflowPointcut;
import org.aspectj.weaver.patterns.ConcreteCflowPointcut;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.FastMatchInfo;
import org.aspectj.weaver.patterns.IfPointcut;
import org.aspectj.weaver.patterns.KindedPointcut;
import org.aspectj.weaver.patterns.NameBindingPointcut;
import org.aspectj.weaver.patterns.NotPointcut;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.PointcutRewriter;
import org.aspectj.weaver.patterns.WithinPointcut;
public class BcelWeaver implements IWeaver {
private BcelWorld world;
private CrosscuttingMembersSet xcutSet;
private IProgressListener progressListener = null;
private double progressMade;
private double progressPerClassFile;
private boolean inReweavableMode = false;
public BcelWeaver(BcelWorld world) {
super();
WeaverMetrics.reset();
this.world = world;
this.xcutSet = world.getCrosscuttingMembersSet();
}
public BcelWeaver() {
this(new BcelWorld());
}
// ---- fields
// private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */
private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */
private List deletedTypenames = new ArrayList(); /* List<String> */
// private Map resources = new HashMap(); /* String -> UnwovenClassFile */
private Manifest manifest = null;
private boolean needToReweaveWorld = false;
private List shadowMungerList = null; // setup by prepareForWeave
private List typeMungerList = null; // setup by prepareForWeave
private List declareParentsList = null; // setup by prepareForWeave
private ZipOutputStream zipOutputStream;
// ----
// only called for testing
public void setShadowMungers(List l) {
shadowMungerList = l;
}
/**
* Add the given aspect to the weaver.
* The type is resolved to support DOT for static inner classes as well as DOLLAR
*
* @param aspectName
*/
public void addLibraryAspect(String aspectName) {
// 1 - resolve as is
ResolvedTypeX type = world.resolve(TypeX.forName(aspectName), true);
if (type.equals(ResolvedTypeX.MISSING)) {
// fallback on inner class lookup mechanism
String fixedName = aspectName;
int hasDot = fixedName.lastIndexOf('.');
while (hasDot > 0) {
//System.out.println("BcelWeaver.addLibraryAspect " + fixedName);
char[] fixedNameChars = fixedName.toCharArray();
fixedNameChars[hasDot] = '$';
fixedName = new String(fixedNameChars);
hasDot = fixedName.lastIndexOf('.');
type = world.resolve(TypeX.forName(fixedName), true);
if (!type.equals(ResolvedTypeX.MISSING)) {
break;
}
}
}
//System.out.println("type: " + type + " for " + aspectName);
if (type.isAspect()) {
xcutSet.addOrReplaceAspect(type);
} else {
// FIXME : Alex: better warning upon no such aspect from aop.xml
throw new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName);
}
}
public void addLibraryJarFile(File inFile) throws IOException {
List addedAspects = null;
if (inFile.isDirectory()) {
addedAspects = addAspectsFromDirectory(inFile);
} else {
addedAspects = addAspectsFromJarFile(inFile);
}
for (Iterator i = addedAspects.iterator(); i.hasNext();) {
ResolvedTypeX aspectX = (ResolvedTypeX) i.next();
xcutSet.addOrReplaceAspect(aspectX);
}
}
private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException {
ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered
List addedAspects = new ArrayList();
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
continue;
}
// FIXME ASC performance? of this alternative soln.
ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName());
JavaClass jc = parser.parse();
inStream.closeEntry();
ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX();
if (type.isAspect()) {
addedAspects.add(type);
}
}
inStream.close();
return addedAspects;
}
private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{
List addedAspects = new ArrayList();
File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){
public boolean accept(File pathname) {
return pathname.getName().endsWith(".class");
}
});
for (int i = 0; i < classFiles.length; i++) {
FileInputStream fis = new FileInputStream(classFiles[i]);
byte[] bytes = FileUtil.readAsByteArray(fis);
addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects);
}
return addedAspects;
}
private void addIfAspect(byte[] bytes, String name, List toList) throws IOException {
ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name);
JavaClass jc = parser.parse();
ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX();
if (type.isAspect()) {
toList.add(type);
}
}
// // The ANT copy task should be used to copy resources across.
// private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false;
private Set alreadyConfirmedReweavableState;
/**
* Add any .class files in the directory to the outdir. Anything other than .class files in
* the directory (or its subdirectories) are considered resources and are also copied.
*
*/
public List addDirectoryContents(File inFile,File outDir) throws IOException {
List addedClassFiles = new ArrayList();
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(inFile,new FileFilter() {
public boolean accept(File f) {
boolean accept = !f.isDirectory();
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
addedClassFiles.add(addClassFile(files[i],inFile,outDir));
}
return addedClassFiles;
}
/** Adds all class files in the jar
*/
public List addJarFile(File inFile, File outDir, boolean canBeDirectory){
// System.err.println("? addJarFile(" + inFile + ", " + outDir + ")");
List addedClassFiles = new ArrayList();
needToReweaveWorld = true;
JarFile inJar = null;
try {
// Is this a directory we are looking at?
if (inFile.isDirectory() && canBeDirectory) {
addedClassFiles.addAll(addDirectoryContents(inFile,outDir));
} else {
inJar = new JarFile(inFile);
addManifest(inJar.getManifest());
Enumeration entries = inJar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = (JarEntry)entries.nextElement();
InputStream inStream = inJar.getInputStream(entry);
byte[] bytes = FileUtil.readAsByteArray(inStream);
String filename = entry.getName();
// System.out.println("? addJarFile() filename='" + filename + "'");
UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes);
if (filename.endsWith(".class")) {
this.addClassFile(classFile);
addedClassFiles.add(classFile);
}
// else if (!entry.isDirectory()) {
//
// /* bug-44190 Copy meta-data */
// addResource(filename,classFile);
// }
inStream.close();
}
inJar.close();
}
} catch (FileNotFoundException ex) {
IMessage message = new Message(
"Could not find input jar file " + inFile.getPath() + ", ignoring",
new SourceLocation(inFile,0),
false);
world.getMessageHandler().handleMessage(message);
} catch (IOException ex) {
IMessage message = new Message(
"Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
new SourceLocation(inFile,0),
true);
world.getMessageHandler().handleMessage(message);
} finally {
if (inJar != null) {
try {inJar.close();}
catch (IOException ex) {
IMessage message = new Message(
"Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
new SourceLocation(inFile,0),
true);
world.getMessageHandler().handleMessage(message);
}
}
}
return addedClassFiles;
}
// public void addResource(String name, File inPath, File outDir) throws IOException {
//
// /* Eliminate CVS files. Relative paths use "/" */
// if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
//// System.err.println("? addResource('" + name + "')");
//// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath));
//// byte[] bytes = new byte[(int)inPath.length()];
//// inStream.read(bytes);
//// inStream.close();
// byte[] bytes = FileUtil.readAsByteArray(inPath);
// UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes);
// addResource(name,resourceFile);
// }
// }
public boolean needToReweaveWorld() {
return needToReweaveWorld;
}
/** Should be addOrReplace
*/
public void addClassFile(UnwovenClassFile classFile) {
addedClasses.add(classFile);
// if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) {
//// throw new RuntimeException(classFile.getClassName());
// }
world.addSourceObjectType(classFile.getJavaClass());
}
public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException {
FileInputStream fis = new FileInputStream(classFile);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = classFile.getAbsolutePath().substring(
inPathDir.getAbsolutePath().length()+1);
UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes);
if (filename.endsWith(".class")) {
// System.err.println("BCELWeaver: processing class from input directory "+classFile);
this.addClassFile(ucf);
}
fis.close();
return ucf;
}
public void deleteClassFile(String typename) {
deletedTypenames.add(typename);
// sourceJavaClasses.remove(typename);
world.deleteSourceObjectType(TypeX.forName(typename));
}
// public void addResource (String name, UnwovenClassFile resourceFile) {
// /* bug-44190 Change error to warning and copy first resource */
// if (!resources.containsKey(name)) {
// resources.put(name, resourceFile);
// }
// else {
// world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'",
// null, null);
// }
// }
// ---- weave preparation
public void prepareForWeave() {
needToReweaveWorld = false;
CflowPointcut.clearCaches();
// update mungers
for (Iterator i = addedClasses.iterator(); i.hasNext(); ) {
UnwovenClassFile jc = (UnwovenClassFile)i.next();
String name = jc.getClassName();
ResolvedTypeX type = world.resolve(name);
//System.err.println("added: " + type + " aspect? " + type.isAspect());
if (type.isAspect()) {
needToReweaveWorld |= xcutSet.addOrReplaceAspect(type);
}
}
for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) {
String name = (String)i.next();
if (xcutSet.deleteAspect(TypeX.forName(name))) needToReweaveWorld = true;
}
shadowMungerList = xcutSet.getShadowMungers();
rewritePointcuts(shadowMungerList);
typeMungerList = xcutSet.getTypeMungers();
declareParentsList = xcutSet.getDeclareParents();
// The ordering here used to be based on a string compare on toString() for the two mungers -
// that breaks for the @AJ style where advice names aren't programmatically generated. So we
// have changed the sorting to be based on source location in the file - this is reliable, in
// the case of source locations missing, we assume they are 'sorted' - i.e. the order in
// which they were added to the collection is correct, this enables the @AJ stuff to work properly.
// When @AJ processing starts filling in source locations for mungers, this code may need
// a bit of alteration...
Collections.sort(
shadowMungerList,
new Comparator() {
public int compare(Object o1, Object o2) {
ShadowMunger sm1 = (ShadowMunger)o1;
ShadowMunger sm2 = (ShadowMunger)o2;
if (sm1.getSourceLocation()==null) return (sm2.getSourceLocation()==null?0:1);
if (sm2.getSourceLocation()==null) return -1;
return (sm2.getSourceLocation().getOffset()-sm1.getSourceLocation().getOffset());
}
});
}
/*
* Rewrite all of the pointcuts in the world into their most efficient
* form for subsequent matching. Also ensure that if pc1.equals(pc2)
* then pc1 == pc2 (for non-binding pcds) by making references all
* point to the same instance.
* Since pointcuts remember their match decision on the last shadow,
* this makes matching faster when many pointcuts share common elements,
* or even when one single pointcut has one common element (which can
* be a side-effect of DNF rewriting).
*/
private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) {
PointcutRewriter rewriter = new PointcutRewriter();
for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
Pointcut p = munger.getPointcut();
Pointcut newP = rewriter.rewrite(p);
// validateBindings now whilst we still have around the pointcut
// that resembles what the user actually wrote in their program
// text.
if (munger instanceof Advice) {
Advice advice = (Advice) munger;
if (advice.getSignature() != null) {
final int numFormals;
final String names[];
//ATAJ for @AJ aspect, the formal have to be checked according to the argument number
// since xxxJoinPoint presence or not have side effects
if (advice.getConcreteAspect().isAnnotationStyleAspect()) {
numFormals = advice.getBaseParameterCount();
int numArgs = advice.getSignature().getParameterTypes().length;
if (numFormals > 0) {
names = advice.getSignature().getParameterNames(world);
validateBindings(newP,p,numArgs,names);
}
} else {
numFormals = advice.getBaseParameterCount();
if (numFormals > 0) {
names = advice.getBaseParameterNames(world);
validateBindings(newP,p,numFormals,names);
}
}
}
}
munger.setPointcut(newP);
}
// now that we have optimized individual pointcuts, optimize
// across the set of pointcuts....
// Use a map from key based on pc equality, to value based on
// pc identity.
Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap();
for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
Pointcut p = munger.getPointcut();
munger.setPointcut(shareEntriesFromMap(p,pcMap));
}
}
private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) {
// some things cant be shared...
if (p instanceof NameBindingPointcut) return p;
if (p instanceof IfPointcut) return p;
if (p instanceof ConcreteCflowPointcut) return p;
if (p instanceof AndPointcut) {
AndPointcut apc = (AndPointcut) p;
Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap);
Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap);
return new AndPointcut(left,right);
} else if (p instanceof OrPointcut) {
OrPointcut opc = (OrPointcut) p;
Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap);
Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap);
return new OrPointcut(left,right);
} else if (p instanceof NotPointcut) {
NotPointcut npc = (NotPointcut) p;
Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap);
return new NotPointcut(not);
} else {
// primitive pcd
if (pcMap.containsKey(p)) { // based on equality
return (Pointcut) pcMap.get(p); // same instance (identity)
} else {
pcMap.put(p,p);
return p;
}
}
}
// userPointcut is the pointcut that the user wrote in the program text.
// dnfPointcut is the same pointcut rewritten in DNF
// numFormals is the number of formal parameters in the pointcut
// if numFormals > 0 then every branch of a disjunction must bind each formal once and only once.
// in addition, the left and right branches of a disjunction must hold on join point kinds in
// common.
private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) {
if (numFormals == 0) return; // nothing to check
if (dnfPointcut.couldMatchKinds().isEmpty()) return; // cant have problems if you dont match!
if (dnfPointcut instanceof OrPointcut) {
OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut;
Pointcut[] leftBindings = new Pointcut[numFormals];
Pointcut[] rightBindings = new Pointcut[numFormals];
validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings);
} else {
Pointcut[] bindings = new Pointcut[numFormals];
validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings);
}
}
private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals,
String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) {
Pointcut left = pc.getLeft();
Pointcut right = pc.getRight();
if (left instanceof OrPointcut) {
Pointcut[] newRightBindings = new Pointcut[numFormals];
validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings);
} else {
if (left.couldMatchKinds().size() > 0)
validateSingleBranch(left, userPointcut, numFormals, names, leftBindings);
}
if (right instanceof OrPointcut) {
Pointcut[] newLeftBindings = new Pointcut[numFormals];
validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings);
} else {
if (right.couldMatchKinds().size() > 0)
validateSingleBranch(right, userPointcut, numFormals, names, rightBindings);
}
Set kindsInCommon = left.couldMatchKinds();
kindsInCommon.retainAll(right.couldMatchKinds());
if (!kindsInCommon.isEmpty() && couldEverMatchSameJoinPoints(left,right)) {
// we know that every branch binds every formal, so there is no ambiguity
// if each branch binds it in exactly the same way...
List ambiguousNames = new ArrayList();
for (int i = 0; i < numFormals; i++) {
if (!leftBindings[i].equals(rightBindings[i])) {
ambiguousNames.add(names[i]);
}
}
if (!ambiguousNames.isEmpty())
raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames);
}
}
// pc is a pointcut that does not contain any disjunctions
// check that every formal is bound (negation doesn't count).
// we know that numFormals > 0 or else we would not be called
private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) {
boolean[] foundFormals = new boolean[numFormals];
for (int i = 0; i < foundFormals.length; i++) {
foundFormals[i] = false;
}
validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings);
for (int i = 0; i < foundFormals.length; i++) {
if (!foundFormals[i]) {
boolean ignore = false;
// ATAJ soften the unbound error for implicit bindings like JoinPoint in @AJ style
for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) {
if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) {
ignore = true;
break;
}
}
if (!ignore) {
raiseUnboundFormalError(names[i],userPointcut);
}
}
}
}
// each formal must appear exactly once
private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) {
if (pc instanceof NotPointcut) {
// nots can only appear at leaves in DNF
NotPointcut not = (NotPointcut) pc;
if (not.getNegatedPointcut() instanceof NameBindingPointcut) {
NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut();
if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty())
raiseNegationBindingError(userPointcut);
}
} else if (pc instanceof AndPointcut) {
AndPointcut and = (AndPointcut) pc;
validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings);
validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings);
} else if (pc instanceof NameBindingPointcut) {
List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns();
for (Iterator iter = btps.iterator(); iter.hasNext();) {
BindingTypePattern btp = (BindingTypePattern) iter.next();
int index = btp.getFormalIndex();
bindings[index] = pc;
if (foundFormals[index]) {
raiseAmbiguousBindingError(names[index],userPointcut);
} else {
foundFormals[index] = true;
}
}
List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns();
for (Iterator iter = baps.iterator(); iter.hasNext();) {
BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next();
int index = bap.getFormalIndex();
bindings[index] = pc;
if (foundFormals[index]) {
raiseAmbiguousBindingError(names[index],userPointcut);
} else {
foundFormals[index] = true;
}
}
} else if (pc instanceof ConcreteCflowPointcut) {
ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc;
int[] slots = cfp.getUsedFormalSlots();
for (int i = 0; i < slots.length; i++) {
bindings[slots[i]] = cfp;
if (foundFormals[slots[i]]) {
raiseAmbiguousBindingError(names[slots[i]],userPointcut);
} else {
foundFormals[slots[i]] = true;
}
}
}
}
// By returning false from this method, we are allowing binding of the same
// variable on either side of an or.
// Be conservative :- have to consider overriding, varargs, autoboxing,
// the effects of itds (on within for example), interfaces, the fact that
// join points can have multiple signatures and so on.
private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) {
if ((left instanceof OrPointcut) || (right instanceof OrPointcut)) return true;
// look for withins
WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class);
WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class);
if ((leftWithin != null) && (rightWithin != null)) {
if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false;
}
// look for kinded
KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class);
KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class);
if ((leftKind != null) && (rightKind != null)) {
if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false;
}
return true;
}
private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) {
if (toSearch instanceof NotPointcut) return null;
if (toLookFor.isInstance(toSearch)) return toSearch;
if (toSearch instanceof AndPointcut) {
AndPointcut apc = (AndPointcut) toSearch;
Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor);
if (left != null) return left;
return findFirstPointcutIn(apc.getRight(),toLookFor);
}
return null;
}
/**
* @param userPointcut
*/
private void raiseNegationBindingError(Pointcut userPointcut) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING),
userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
}
/**
* @param name
* @param userPointcut
*/
private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING,
name),
userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
}
/**
* @param userPointcut
*/
private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) {
StringBuffer formalNames = new StringBuffer(names.get(0).toString());
for (int i = 1; i < names.size(); i++) {
formalNames.append(", ");
formalNames.append(names.get(i));
}
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames),
userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
}
/**
* @param name
* @param userPointcut
*/
private void raiseUnboundFormalError(String name, Pointcut userPointcut) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL,
name),
userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
}
// public void dumpUnwoven(File file) throws IOException {
// BufferedOutputStream os = FileUtil.makeOutputStream(file);
// this.zipOutputStream = new ZipOutputStream(os);
// dumpUnwoven();
// /* BUG 40943*/
// dumpResourcesToOutJar();
// zipOutputStream.close(); //this flushes and closes the acutal file
// }
//
//
// public void dumpUnwoven() throws IOException {
// Collection filesToDump = new HashSet(sourceJavaClasses.values());
// for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// dumpUnchanged(classFile);
// }
// }
// public void dumpResourcesToOutPath() throws IOException {
//// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet());
// Iterator i = resources.keySet().iterator();
// while (i.hasNext()) {
// UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next());
// dumpUnchanged(res);
// }
// //resources = new HashMap();
// }
//
/* BUG #40943 */
// public void dumpResourcesToOutJar() throws IOException {
//// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet());
// Iterator i = resources.keySet().iterator();
// while (i.hasNext()) {
// String name = (String)i.next();
// UnwovenClassFile res = (UnwovenClassFile)resources.get(name);
// writeZipEntry(name,res.getBytes());
// }
// resources = new HashMap();
// }
//
// // halfway house for when the jar is managed outside of the weaver, but the resources
// // to be copied are known in the weaver.
// public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException {
// this.zipOutputStream = zos;
// dumpResourcesToOutJar();
// }
public void addManifest (Manifest newManifest) {
// System.out.println("? addManifest() newManifest=" + newManifest);
if (manifest == null) {
manifest = newManifest;
}
}
public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
private static final String WEAVER_MANIFEST_VERSION = "1.0";
private static final Attributes.Name CREATED_BY = new Name("Created-By");
private static final String WEAVER_CREATED_BY = "AspectJ Compiler";
public Manifest getManifest (boolean shouldCreate) {
if (manifest == null && shouldCreate) {
manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION);
attributes.put(CREATED_BY,WEAVER_CREATED_BY);
}
return manifest;
}
// ---- weaving
// Used by some test cases only...
public Collection weave(File file) throws IOException {
OutputStream os = FileUtil.makeOutputStream(file);
this.zipOutputStream = new ZipOutputStream(os);
prepareForWeave();
Collection c = weave( new IClassFileProvider() {
public Iterator getClassFileIterator() {
return addedClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(UnwovenClassFile result) {
try {
writeZipEntry(result.filename, result.bytes);
} catch(IOException ex) {}
}
public void processingReweavableState() {}
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {}
};
}
});
// /* BUG 40943*/
// dumpResourcesToOutJar();
zipOutputStream.close(); //this flushes and closes the acutal file
return c;
}
// public Collection weave() throws IOException {
// prepareForWeave();
// Collection filesToWeave;
//
// if (needToReweaveWorld) {
// filesToWeave = sourceJavaClasses.values();
// } else {
// filesToWeave = addedClasses;
// }
//
// Collection wovenClassNames = new ArrayList();
// world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave +
// "(world=" + needToReweaveWorld + ")", null, null);
//
//
// //System.err.println("typeMungers: " + typeMungerList);
//
// prepareToProcessReweavableState();
// // clear all state from files we'll be reweaving
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = getClassType(className);
// processReweavableStateIfPresent(className, classType);
// }
//
//
//
// //XXX this isn't quite the right place for this...
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// addTypeMungers(className);
// }
//
// // first weave into aspects
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
// if (classType.isAspect()) {
// weave(classFile, classType);
// wovenClassNames.add(className);
// }
// }
//
// // then weave into non-aspects
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
// if (! classType.isAspect()) {
// weave(classFile, classType);
// wovenClassNames.add(className);
// }
// }
//
// if (zipOutputStream != null && !needToReweaveWorld) {
// Collection filesToDump = new HashSet(sourceJavaClasses.values());
// filesToDump.removeAll(filesToWeave);
// for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// dumpUnchanged(classFile);
// }
// }
//
// addedClasses = new ArrayList();
// deletedTypenames = new ArrayList();
//
// return wovenClassNames;
// }
// variation of "weave" that sources class files from an external source.
public Collection weave(IClassFileProvider input) throws IOException {
Collection wovenClassNames = new ArrayList();
IWeaveRequestor requestor = input.getRequestor();
requestor.processingReweavableState();
prepareToProcessReweavableState();
// clear all state from files we'll be reweaving
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = getClassType(className);
processReweavableStateIfPresent(className, classType);
}
requestor.addingTypeMungers();
// We process type mungers in two groups, first mungers that change the type
// hierarchy, then 'normal' ITD type mungers.
// Process the types in a predictable order (rather than the order encountered).
// For class A, the order is superclasses of A then superinterfaces of A
// (and this mechanism is applied recursively)
List typesToProcess = new ArrayList();
for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) {
UnwovenClassFile clf = (UnwovenClassFile) iter.next();
typesToProcess.add(clf.getClassName());
}
while (typesToProcess.size()>0) {
weaveParentsFor(typesToProcess,(String)typesToProcess.get(0));
}
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
addNormalTypeMungers(className);
}
requestor.weavingAspects();
// first weave into aspects
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
if (classType.isAspect()) {
weaveAndNotify(classFile, classType,requestor);
wovenClassNames.add(className);
}
}
requestor.weavingClasses();
// then weave into non-aspects
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
if (! classType.isAspect()) {
weaveAndNotify(classFile, classType, requestor);
wovenClassNames.add(className);
}
}
addedClasses = new ArrayList();
deletedTypenames = new ArrayList();
// if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning
if (world.behaveInJava5Way &&
world.getLint().adviceDidNotMatch.isEnabled()) {
List l = world.getCrosscuttingMembersSet().getShadowMungers();
for (Iterator iter = l.iterator(); iter.hasNext();) {
ShadowMunger element = (ShadowMunger) iter.next();
if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers
BcelAdvice ba = (BcelAdvice)element;
if (!ba.hasMatchedSomething()) {
BcelMethod meth = (BcelMethod)ba.getSignature();
if (meth!=null) {
AnnotationX[] anns = (AnnotationX[])meth.getAnnotations();
// Check if they want to suppress the warning on this piece of advice
if (!Utility.isSuppressing(anns,"adviceDidNotMatch")) {
world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(),element.getSourceLocation());
}
}
}
}
}
}
requestor.weaveCompleted();
return wovenClassNames;
}
/**
* 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process
* supertypes (classes/interfaces) of 'typeToWeave' that are in the
* 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from
* the 'typesForWeaving' list.
*
* Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may
* break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it
* may choose to weave them in either order - but you'll probably have other problems if
* you are supplying partial hierarchies like that !
*/
private void weaveParentsFor(List typesForWeaving,String typeToWeave) {
// Look at the supertype first
ResolvedTypeX rtx = world.resolve(typeToWeave);
ResolvedTypeX superType = rtx.getSuperclass();
if (superType!=null && typesForWeaving.contains(superType.getClassName())) {
weaveParentsFor(typesForWeaving,superType.getClassName());
}
// Then look at the superinterface list
ResolvedTypeX[] interfaceTypes = rtx.getDeclaredInterfaces();
for (int i = 0; i < interfaceTypes.length; i++) {
ResolvedTypeX rtxI = interfaceTypes[i];
if (typesForWeaving.contains(rtxI.getClassName())) {
weaveParentsFor(typesForWeaving,rtxI.getClassName());
}
}
weaveParentTypeMungers(rtx); // Now do this type
typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process
}
public void prepareToProcessReweavableState() {
if (inReweavableMode)
world.showMessage(IMessage.INFO,
WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE),
null, null);
alreadyConfirmedReweavableState = new HashSet();
}
public void processReweavableStateIfPresent(String className, BcelObjectType classType) {
// If the class is marked reweavable, check any aspects around when it was built are in this world
WeaverStateInfo wsi = classType.getWeaverState();
if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around!
world.showMessage(IMessage.INFO,
WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()),
null,null);
Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType();
if (aspectsPreviouslyInWorld!=null) {
for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) {
String requiredTypeName = (String) iter.next();
if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) {
ResolvedTypeX rtx = world.resolve(TypeX.forName(requiredTypeName),true);
boolean exists = rtx!=ResolvedTypeX.MISSING;
if (!exists) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className),
classType.getSourceLocation(), null);
} else {
if (!world.getMessageHandler().isIgnoring(IMessage.INFO))
world.showMessage(IMessage.INFO,
WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()),
null,null);
alreadyConfirmedReweavableState.add(requiredTypeName);
}
}
}
}
classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData()));
} else {
classType.resetState();
}
}
private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType,
IWeaveRequestor requestor) throws IOException {
LazyClassGen clazz = weaveWithoutDump(classFile,classType);
classType.finishedWith();
//clazz is null if the classfile was unchanged by weaving...
if (clazz != null) {
UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
for (int i = 0; i < newClasses.length; i++) {
requestor.acceptResult(newClasses[i]);
}
} else {
requestor.acceptResult(classFile);
}
}
// helper method
public BcelObjectType getClassType(String forClass) {
return BcelWorld.getBcelObjectType(world.resolve(forClass));
}
public void addParentTypeMungers(String typeName) {
weaveParentTypeMungers(world.resolve(typeName));
}
public void addNormalTypeMungers(String typeName) {
weaveNormalTypeMungers(world.resolve(typeName));
}
public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) {
List childClasses = clazz.getChildClasses(world);
UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes());
int index = 1;
for (Iterator iter = childClasses.iterator(); iter.hasNext();) {
UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next();
UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
ret[index++] = childClass;
}
return ret;
}
/**
* Weaves new parents and annotations onto a type ("declare parents" and "declare @type")
*
* Algorithm:
* 1. First pass, do parents then do annotations. During this pass record:
* - any parent mungers that don't match but have a non-wild annotation type pattern
* - any annotation mungers that don't match
* 2. Multiple subsequent passes which go over the munger lists constructed in the first
* pass, repeatedly applying them until nothing changes.
* FIXME asc confirm that algorithm is optimal ??
*/
public void weaveParentTypeMungers(ResolvedTypeX onType) {
onType.clearInterTypeMungers();
List decpToRepeat = new ArrayList();
List decaToRepeat = new ArrayList();
boolean aParentChangeOccurred = false;
boolean anAnnotationChangeOccurred = false;
// First pass - apply all decp mungers
for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) {
DeclareParents decp = (DeclareParents)i.next();
boolean typeChanged = applyDeclareParents(decp,onType);
if (typeChanged) {
aParentChangeOccurred = true;
} else { // Perhaps it would have matched if a 'dec @type' had modified the type
if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp);
}
}
// Still first pass - apply all dec @type mungers
for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) {
DeclareAnnotation decA = (DeclareAnnotation)i.next();
boolean typeChanged = applyDeclareAtType(decA,onType,true);
if (typeChanged) {
anAnnotationChangeOccurred = true;
}
}
while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
anAnnotationChangeOccurred = aParentChangeOccurred = false;
List decpToRepeatNextTime = new ArrayList();
for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) {
DeclareParents decp = (DeclareParents) iter.next();
boolean typeChanged = applyDeclareParents(decp,onType);
if (typeChanged) {
aParentChangeOccurred = true;
} else {
decpToRepeatNextTime.add(decp);
}
}
for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) {
DeclareAnnotation decA = (DeclareAnnotation) iter.next();
boolean typeChanged = applyDeclareAtType(decA,onType,false);
if (typeChanged) {
anAnnotationChangeOccurred = true;
}
}
decpToRepeat = decpToRepeatNextTime;
}
}
/**
* Apply a declare @type - return true if we change the type
*/
private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedTypeX onType,boolean reportProblems) {
boolean didSomething = false;
if (decA.matches(onType)) {
//FIXME asc important this should be guarded by the 'already has annotation' check below but isn't since the compiler is producing classfiles with deca affected things in...
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation());
if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) {
// FIXME asc Could put out a lint here for an already annotated type - the problem is that it may have
// picked up the annotation during 'source weaving' in which case the message is misleading. Leaving it
// off for now...
// if (reportProblems) {
// world.getLint().elementAlreadyAnnotated.signal(
// new String[]{onType.toString(),decA.getAnnotationTypeX().toString()},
// onType.getSourceLocation(),new ISourceLocation[]{decA.getSourceLocation()});
// }
return false;
}
AnnotationX annoX = decA.getAnnotationX();
// check the annotation is suitable for the target
boolean problemReported = verifyTargetIsOK(decA, onType, annoX,reportProblems);
if (!problemReported) {
didSomething = true;
ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
newAnnotationTM.setSourceLocation(decA.getSourceLocation());
onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world)));
decA.copyAnnotationTo(onType);
}
}
return didSomething;
}
/**
* Checks for an @target() on the annotation and if found ensures it allows the annotation
* to be attached to the target type that matched.
*/
private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedTypeX onType, AnnotationX annoX,boolean outputProblems) {
boolean problemReported = false;
if (annoX.specifiesTarget()) {
if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) ||
(!annoX.allowedOnRegularType())) {
if (outputProblems) {
if (decA.isExactPattern()) {
world.getMessageHandler().handleMessage(MessageUtil.error(
WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,
onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation()));
} else {
if (world.getLint().invalidTargetForAnnotation.isEnabled()) {
world.getLint().invalidTargetForAnnotation.signal(
new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()});
}
}
}
problemReported = true;
}
}
return problemReported;
}
/**
* Apply a single declare parents - return true if we change the type
*/
private boolean applyDeclareParents(DeclareParents p, ResolvedTypeX onType) {
boolean didSomething = false;
List newParents = p.findMatchingNewParents(onType,true);
if (!newParents.isEmpty()) {
didSomething=true;
BcelObjectType classType = BcelWorld.getBcelObjectType(onType);
//System.err.println("need to do declare parents for: " + onType);
for (Iterator j = newParents.iterator(); j.hasNext(); ) {
ResolvedTypeX newParent = (ResolvedTypeX)j.next();
// We set it here so that the imminent matching for ITDs can succeed - we
// still haven't done the necessary changes to the class file itself
// (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent()
classType.addParent(newParent);
ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent);
newParentMunger.setSourceLocation(p.getSourceLocation());
onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)));
}
}
return didSomething;
}
public void weaveNormalTypeMungers(ResolvedTypeX onType) {
for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
if (m.matches(onType)) {
onType.addInterTypeMunger(m);
}
}
}
// exposed for ClassLoader dynamic weaving
public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
return weave(classFile, classType, false);
}
// non-private for testing
LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
LazyClassGen ret = weave(classFile, classType, true);
if (progressListener != null) {
progressMade += progressPerClassFile;
progressListener.setProgress(progressMade);
progressListener.setText("woven: " + classFile.getFilename());
}
return ret;
}
private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
if (classType.isSynthetic()) {
if (dump) dumpUnchanged(classFile);
return null;
}
// JavaClass javaClass = classType.getJavaClass();
List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX());
List typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
classType.getResolvedTypeX().checkInterTypeMungers();
LazyClassGen clazz = null;
if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() ||
world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0 ) {
clazz = classType.getLazyClassGen();
//System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState());
try {
boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers);
if (isChanged) {
if (dump) dump(classFile, clazz);
return clazz;
}
} catch (RuntimeException re) {
System.err.println("trouble in: ");
clazz.print(System.err);
re.printStackTrace();
throw re;
} catch (Error re) {
System.err.println("trouble in: ");
clazz.print(System.err);
throw re;
}
}
// this is very odd return behavior trying to keep everyone happy
if (dump) {
dumpUnchanged(classFile);
return clazz;
} else {
// ATAJ: the class was not weaved, but since it gets there early it may have new generated inner classes
// attached to it to support LTW perX aspectOf support (see BcelPerClauseAspectAdder)
// that aggressively defines the inner <aspect>$mayHaveAspect interface.
if (clazz != null && !clazz.getChildClasses(world).isEmpty()) {
return clazz;
}
return null;
}
}
// ---- writing
private void dumpUnchanged(UnwovenClassFile classFile) throws IOException {
if (zipOutputStream != null) {
writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes());
} else {
classFile.writeUnchangedBytes();
}
}
private String getEntryName(String className) {
//XXX what does bcel's getClassName do for inner names
return className.replace('.', '/') + ".class";
}
private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException {
if (zipOutputStream != null) {
String mainClassName = classFile.getJavaClass().getClassName();
writeZipEntry(getEntryName(mainClassName),
clazz.getJavaClass(world).getBytes());
if (!clazz.getChildClasses(world).isEmpty()) {
for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) {
UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next();
writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
}
}
} else {
classFile.writeWovenBytes(
clazz.getJavaClass(world).getBytes(),
clazz.getChildClasses(world)
);
}
}
private void writeZipEntry(String name, byte[] bytes) throws IOException {
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zipOutputStream.putNextEntry(newEntry);
zipOutputStream.write(bytes);
zipOutputStream.closeEntry();
}
private List fastMatch(List list, ResolvedTypeX type) {
if (list == null) return Collections.EMPTY_LIST;
// here we do the coarsest grained fast match with no kind constraints
// this will remove all obvious non-matches and see if we need to do any weaving
FastMatchInfo info = new FastMatchInfo(type, null);
List result = new ArrayList();
Iterator iter = list.iterator();
while (iter.hasNext()) {
ShadowMunger munger = (ShadowMunger)iter.next();
FuzzyBoolean fb = munger.getPointcut().fastMatch(info);
WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info
if (fb.maybeTrue()) {
result.add(munger);
}
}
return result;
}
public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) {
progressListener = listener;
this.progressMade = previousProgress;
this.progressPerClassFile = progressPerClassFile;
}
public void setReweavableMode(boolean mode,boolean compress) {
inReweavableMode = mode;
WeaverStateInfo.setReweavableModeDefaults(mode,compress);
BcelClassWeaver.setReweavableMode(mode,compress);
}
public boolean isReweavable() {
return inReweavableMode;
}
public World getWorld() {
return world;
}
}
|
92,906 |
Bug 92906 showWeaveInfo for declare annotations
|
declaring annotations (declare @type, @constructor, @method and @field) currently doesn't show a message when the -showWeaveInfo option is set in ajc. Appropriate messages should be displayed.
|
resolved fixed
|
abc9a58
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-04T09:22:43Z | 2005-04-27T13:53:20Z |
weaver/src/org/aspectj/weaver/bcel/Utility.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.Hashtable;
import java.util.List;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.annotation.ArrayElementValue;
import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePair;
import org.aspectj.apache.bcel.classfile.annotation.ElementValue;
import org.aspectj.apache.bcel.classfile.annotation.SimpleElementValue;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BIPUSH;
import org.aspectj.apache.bcel.generic.BasicType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPushInstruction;
import org.aspectj.apache.bcel.generic.INSTANCEOF;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.LDC;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.ReferenceType;
import org.aspectj.apache.bcel.generic.SIPUSH;
import org.aspectj.apache.bcel.generic.SWITCH;
import org.aspectj.apache.bcel.generic.Select;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
public class Utility {
private Utility() {
super();
}
public static Instruction createSuperInvoke(
InstructionFactory fact,
BcelWorld world,
Member signature) {
short kind;
if (signature.isInterface()) {
throw new RuntimeException("bad");
} else if (signature.isPrivate() || signature.getName().equals("<init>")) {
throw new RuntimeException("unimplemented, possibly bad");
} else if (signature.isStatic()) {
throw new RuntimeException("bad");
} else {
kind = Constants.INVOKESPECIAL;
}
return fact.createInvoke(
signature.getDeclaringType().getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
BcelWorld.makeBcelTypes(signature.getParameterTypes()),
kind);
}
// XXX don't need the world now
public static Instruction createInvoke(
InstructionFactory fact,
BcelWorld world,
Member signature) {
short kind;
if (signature.isInterface()) {
kind = Constants.INVOKEINTERFACE;
} else if (signature.isStatic()) {
kind = Constants.INVOKESTATIC;
} else if (signature.isPrivate() || signature.getName().equals("<init>")) {
kind = Constants.INVOKESPECIAL;
} else {
kind = Constants.INVOKEVIRTUAL;
}
return fact.createInvoke(
signature.getDeclaringType().getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
BcelWorld.makeBcelTypes(signature.getParameterTypes()),
kind);
}
public static Instruction createGet(InstructionFactory fact, Member signature) {
short kind;
if (signature.isStatic()) {
kind = Constants.GETSTATIC;
} else {
kind = Constants.GETFIELD;
}
return fact.createFieldAccess(
signature.getDeclaringType().getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
kind);
}
/**
* Creae a field GET instruction
*
* @param fact
* @param signature
* @param declaringType
* @return
*/
public static Instruction createGetOn(InstructionFactory fact, Member signature, TypeX declaringType) {
short kind;
if (signature.isStatic()) {
kind = Constants.GETSTATIC;
} else {
kind = Constants.GETFIELD;
}
return fact.createFieldAccess(
declaringType.getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
kind);
}
public static Instruction createSet(InstructionFactory fact, Member signature) {
short kind;
if (signature.isStatic()) {
kind = Constants.PUTSTATIC;
} else {
kind = Constants.PUTFIELD;
}
return fact.createFieldAccess(
signature.getDeclaringType().getName(),
signature.getName(),
BcelWorld.makeBcelType(signature.getReturnType()),
kind);
}
public static Instruction createInvoke(
InstructionFactory fact,
JavaClass declaringClass,
Method newMethod) {
short kind;
if (newMethod.isInterface()) {
kind = Constants.INVOKEINTERFACE;
} else if (newMethod.isStatic()) {
kind = Constants.INVOKESTATIC;
} else if (newMethod.isPrivate() || newMethod.getName().equals("<init>")) {
kind = Constants.INVOKESPECIAL;
} else {
kind = Constants.INVOKEVIRTUAL;
}
return fact.createInvoke(
declaringClass.getClassName(),
newMethod.getName(),
Type.getReturnType(newMethod.getSignature()),
Type.getArgumentTypes(newMethod.getSignature()),
kind);
}
public static byte[] stringToUTF(String s) {
try {
ByteArrayOutputStream out0 = new ByteArrayOutputStream();
DataOutputStream out1 = new DataOutputStream(out0);
out1.writeUTF(s);
return out0.toByteArray();
} catch (IOException e) {
throw new RuntimeException("sanity check");
}
}
public static Instruction createInstanceof(InstructionFactory fact, ReferenceType t) {
int cpoolEntry =
(t instanceof ArrayType)
? fact.getConstantPool().addArrayClass((ArrayType)t)
: fact.getConstantPool().addClass((ObjectType)t);
return new INSTANCEOF(cpoolEntry);
}
public static Instruction createInvoke(
InstructionFactory fact,
LazyMethodGen m) {
short kind;
if (m.getEnclosingClass().isInterface()) {
kind = Constants.INVOKEINTERFACE;
} else if (m.isStatic()) {
kind = Constants.INVOKESTATIC;
} else if (m.isPrivate() || m.getName().equals("<init>")) {
kind = Constants.INVOKESPECIAL;
} else {
kind = Constants.INVOKEVIRTUAL;
}
return fact.createInvoke(
m.getClassName(),
m.getName(),
m.getReturnType(),
m.getArgumentTypes(),
kind);
}
/**
* Create an invoke instruction
*
* @param fact
* @param kind INVOKEINTERFACE, INVOKEVIRTUAL..
* @param member
* @return
*/
public static Instruction createInvoke(
InstructionFactory fact,
short kind,
Member member) {
return fact.createInvoke(
member.getDeclaringType().getName(),
member.getName(),
BcelWorld.makeBcelType(member.getReturnType()),
BcelWorld.makeBcelTypes(member.getParameterTypes()),
kind);
}
// ??? these should perhaps be cached. Remember to profile this to see if it's a problem.
public static String[] makeArgNames(int n) {
String[] ret = new String[n];
for (int i=0; i<n; i++) {
ret[i] = "arg" + i;
}
return ret;
}
// Lookup table, for converting between pairs of types, it gives
// us the method name in the Conversions class
private static Hashtable validBoxing = new Hashtable();
static {
validBoxing.put("Ljava/lang/Byte;B","byteObject");
validBoxing.put("Ljava/lang/Character;C","charObject");
validBoxing.put("Ljava/lang/Double;D","doubleObject");
validBoxing.put("Ljava/lang/Float;F","floatObject");
validBoxing.put("Ljava/lang/Integer;I","intObject");
validBoxing.put("Ljava/lang/Long;J","longObject");
validBoxing.put("Ljava/lang/Short;S","shortObject");
validBoxing.put("Ljava/lang/Boolean;Z","booleanObject");
validBoxing.put("BLjava/lang/Byte;","byteValue");
validBoxing.put("CLjava/lang/Character;","charValue");
validBoxing.put("DLjava/lang/Double;","doubleValue");
validBoxing.put("FLjava/lang/Float;","floatValue");
validBoxing.put("ILjava/lang/Integer;","intValue");
validBoxing.put("JLjava/lang/Long;","longValue");
validBoxing.put("SLjava/lang/Short;","shortValue");
validBoxing.put("ZLjava/lang/Boolean;","booleanValue");
}
public static void appendConversion(
InstructionList il,
InstructionFactory fact,
ResolvedTypeX fromType,
ResolvedTypeX toType)
{
if (! toType.isConvertableFrom(fromType)) {
throw new BCException("can't convert from " + fromType + " to " + toType);
}
// XXX I'm sure this test can be simpler but my brain hurts and this works
if (!toType.getWorld().behaveInJava5Way) {
if (toType.needsNoConversionFrom(fromType)) return;
} else {
if (toType.needsNoConversionFrom(fromType) && !(toType.isPrimitive()^fromType.isPrimitive())) return;
}
if (toType.equals(ResolvedTypeX.VOID)) {
// assert fromType.equals(TypeX.OBJECT)
il.append(InstructionFactory.createPop(fromType.getSize()));
} else if (fromType.equals(ResolvedTypeX.VOID)) {
// assert toType.equals(TypeX.OBJECT)
il.append(InstructionFactory.createNull(Type.OBJECT));
return;
} else if (fromType.equals(TypeX.OBJECT)) {
Type to = BcelWorld.makeBcelType(toType);
if (toType.isPrimitive()) {
String name = toType.toString() + "Value";
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
to,
new Type[] { Type.OBJECT },
Constants.INVOKESTATIC));
} else {
il.append(fact.createCheckCast((ReferenceType)to));
}
} else if (toType.equals(TypeX.OBJECT)) {
// assert fromType.isPrimitive()
Type from = BcelWorld.makeBcelType(fromType);
String name = fromType.toString() + "Object";
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
Type.OBJECT,
new Type[] { from },
Constants.INVOKESTATIC));
} else if (toType.getWorld().behaveInJava5Way && validBoxing.get(toType.getSignature()+fromType.getSignature())!=null) {
// XXX could optimize by using any java boxing code that may be just before the call...
Type from = BcelWorld.makeBcelType(fromType);
Type to = BcelWorld.makeBcelType(toType);
String name = (String)validBoxing.get(toType.getSignature()+fromType.getSignature());
if (toType.isPrimitive()) {
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
to,
new Type[]{Type.OBJECT},
Constants.INVOKESTATIC));
} else {
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
Type.OBJECT,
new Type[] { from },
Constants.INVOKESTATIC));
il.append(fact.createCheckCast((ReferenceType) to));
}
} else if (fromType.isPrimitive()) {
// assert toType.isPrimitive()
Type from = BcelWorld.makeBcelType(fromType);
Type to = BcelWorld.makeBcelType(toType);
try {
il.append(fact.createCast(from, to));
} catch (RuntimeException e) {
il.append(fact.createCast(from, Type.INT));
il.append(fact.createCast(Type.INT, to));
}
} else {
Type to = BcelWorld.makeBcelType(toType);
// assert ! fromType.isPrimitive() && ! toType.isPrimitive()
il.append(fact.createCheckCast((ReferenceType) to));
}
}
public static InstructionList createConversion(
InstructionFactory fact,
Type fromType,
Type toType) {
//System.out.println("cast to: " + toType);
InstructionList il = new InstructionList();
//PR71273
if ((fromType.equals(Type.BYTE) || fromType.equals(Type.CHAR) || fromType.equals(Type.SHORT)) &&
(toType.equals(Type.INT))) {
return il;
}
if (fromType.equals(toType))
return il;
if (toType.equals(Type.VOID)) {
il.append(InstructionFactory.createPop(fromType.getSize()));
return il;
}
if (fromType.equals(Type.VOID)) {
if (toType instanceof BasicType)
throw new BCException("attempting to cast from void to basic type");
il.append(InstructionFactory.createNull(Type.OBJECT));
return il;
}
if (fromType.equals(Type.OBJECT)) {
if (toType instanceof BasicType) {
String name = toType.toString() + "Value";
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
toType,
new Type[] { Type.OBJECT },
Constants.INVOKESTATIC));
return il;
}
}
if (toType.equals(Type.OBJECT)) {
if (fromType instanceof BasicType) {
String name = fromType.toString() + "Object";
il.append(
fact.createInvoke(
"org.aspectj.runtime.internal.Conversions",
name,
Type.OBJECT,
new Type[] { fromType },
Constants.INVOKESTATIC));
return il;
} else if (fromType instanceof ReferenceType) {
return il;
} else {
throw new RuntimeException();
}
}
if (fromType instanceof ReferenceType
&& ((ReferenceType)fromType).isAssignmentCompatibleWith(toType)) {
return il;
}
il.append(fact.createCast(fromType, toType));
return il;
}
public static Instruction createConstant(
InstructionFactory fact,
int i) {
Instruction inst;
switch(i) {
case -1: inst = InstructionConstants.ICONST_M1; break;
case 0: inst = InstructionConstants.ICONST_0; break;
case 1: inst = InstructionConstants.ICONST_1; break;
case 2: inst = InstructionConstants.ICONST_2; break;
case 3: inst = InstructionConstants.ICONST_3; break;
case 4: inst = InstructionConstants.ICONST_4; break;
case 5: inst = InstructionConstants.ICONST_5; break;
}
if (i <= Byte.MAX_VALUE && i >= Byte.MIN_VALUE) {
inst = new BIPUSH((byte)i);
} else if (i <= Short.MAX_VALUE && i >= Short.MIN_VALUE) {
inst = new SIPUSH((short)i);
} else {
inst = new LDC(fact.getClassGen().getConstantPool().addInteger(i));
}
return inst;
}
public static JavaClass makeJavaClass(String filename, byte[] bytes) {
try {
ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), filename);
return parser.parse();
} catch (IOException e) {
throw new BCException("malformed class file");
}
}
public static String arrayToString(int[] a) {
int len = a.length;
if (len == 0) return "[]";
StringBuffer buf = new StringBuffer("[");
buf.append(a[0]);
for (int i = 1; i < len; i++) {
buf.append(", ");
buf.append(a[i]);
}
buf.append("]");
return buf.toString();
}
/**
* replace an instruction handle with another instruction, in this case, a branch instruction.
*
* @param ih the instruction handle to replace.
* @param branchInstruction the branch instruction to replace ih with
* @param enclosingMethod where to find ih's instruction list.
*/
public static void replaceInstruction(
InstructionHandle ih,
BranchInstruction branchInstruction,
LazyMethodGen enclosingMethod)
{
InstructionList il = enclosingMethod.getBody();
InstructionHandle fresh = il.append(ih, branchInstruction);
deleteInstruction(ih, fresh, enclosingMethod);
}
/** delete an instruction handle and retarget all targeters of the deleted instruction
* to the next instruction. Obviously, this should not be used to delete
* a control transfer instruction unless you know what you're doing.
*
* @param ih the instruction handle to delete.
* @param enclosingMethod where to find ih's instruction list.
*/
public static void deleteInstruction(
InstructionHandle ih,
LazyMethodGen enclosingMethod)
{
deleteInstruction(ih, ih.getNext(), enclosingMethod);
}
/** delete an instruction handle and retarget all targeters of the deleted instruction
* to the provided target.
*
* @param ih the instruction handle to delete
* @param retargetTo the instruction handle to retarget targeters of ih to.
* @param enclosingMethod where to find ih's instruction list.
*/
public static void deleteInstruction(
InstructionHandle ih,
InstructionHandle retargetTo,
LazyMethodGen enclosingMethod)
{
InstructionList il = enclosingMethod.getBody();
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int i = targeters.length - 1; i >= 0; i--) {
InstructionTargeter targeter = targeters[i];
targeter.updateTarget(ih, retargetTo);
}
ih.removeAllTargeters();
}
try {
il.delete(ih);
} catch (TargetLostException e) {
throw new BCException("this really can't happen");
}
}
/**
* Fix for Bugzilla #39479, #40109 patch contributed by Andy Clement
*
* Need to manually copy Select instructions - if we rely on the the 'fresh' object
* created by copy(), the InstructionHandle array 'targets' inside the Select
* object will not have been deep copied, so modifying targets in fresh will modify
* the original Select - not what we want ! (It is a bug in BCEL to do with cloning
* Select objects).
*
* <pre>
* declare error:
* call(* Instruction.copy()) && within(org.aspectj.weaver)
* && !withincode(* Utility.copyInstruction(Instruction)):
* "use Utility.copyInstruction to work-around bug in Select.copy()";
* </pre>
*/
public static Instruction copyInstruction(Instruction i) {
if (i instanceof Select) {
Select freshSelect = (Select)i;
// Create a new targets array that looks just like the existing one
InstructionHandle[] targets = new InstructionHandle[freshSelect.getTargets().length];
for (int ii = 0; ii < targets.length; ii++) {
targets[ii] = freshSelect.getTargets()[ii];
}
// Create a new select statement with the new targets array
SWITCH switchStatement =
new SWITCH(freshSelect.getMatchs(), targets, freshSelect.getTarget());
return (Select)switchStatement.getInstruction();
} else {
return i.copy(); // Use clone for shallow copy...
}
}
/** returns -1 if no source line attribute */
// this naive version overruns the JVM stack size, if only Java understood tail recursion...
// public static int getSourceLine(InstructionHandle ih) {
// if (ih == null) return -1;
//
// InstructionTargeter[] ts = ih.getTargeters();
// if (ts != null) {
// for (int j = ts.length - 1; j >= 0; j--) {
// InstructionTargeter t = ts[j];
// if (t instanceof LineNumberTag) {
// return ((LineNumberTag)t).getLineNumber();
// }
// }
// }
// return getSourceLine(ih.getNext());
// }
public static int getSourceLine(InstructionHandle ih) {
int lookahead=0;
// arbitrary rule that we will never lookahead more than 100 instructions for a line #
while (lookahead++ < 100) {
if (ih == null) return -1;
InstructionTargeter[] ts = ih.getTargeters();
if (ts != null) {
for (int j = ts.length - 1; j >= 0; j--) {
InstructionTargeter t = ts[j];
if (t instanceof LineNumberTag) {
return ((LineNumberTag)t).getLineNumber();
}
}
}
ih = ih.getNext();
}
//System.err.println("no line information available for: " + ih);
return -1;
}
// assumes that there is no already extant source line tag. Otherwise we'll have to be better.
public static void setSourceLine(InstructionHandle ih, int lineNumber) {
ih.addTargeter(new LineNumberTag(lineNumber));
}
public static int makePublic(int i) {
return i & ~(Modifier.PROTECTED | Modifier.PRIVATE) | Modifier.PUBLIC;
}
public static int makePrivate(int i) {
return i & ~(Modifier.PROTECTED | Modifier.PUBLIC) | Modifier.PRIVATE;
}
public static BcelVar[] pushAndReturnArrayOfVars(
ResolvedTypeX[] proceedParamTypes,
InstructionList il,
InstructionFactory fact,
LazyMethodGen enclosingMethod)
{
int len = proceedParamTypes.length;
BcelVar[] ret = new BcelVar[len];
for (int i = len - 1; i >= 0; i--) {
ResolvedTypeX typeX = proceedParamTypes[i];
Type type = BcelWorld.makeBcelType(typeX);
int local = enclosingMethod.allocateLocal(type);
il.append(InstructionFactory.createStore(type, local));
ret[i] = new BcelVar(typeX, local);
}
return ret;
}
public static boolean isConstantPushInstruction(Instruction i) {
return (i instanceof ConstantPushInstruction) || (i instanceof LDC);
}
/**
* Check if the annotations contain a SuppressAjWarnings annotation and
* if that annotation specifies that the given lint message (identified
* by its key) should be ignored.
*
*/
public static boolean isSuppressing(AnnotationX[] anns,String lintkey) {
if (anns == null) return false;
boolean suppressed = false;
// Go through the annotation types on the advice
for (int i = 0;!suppressed && i<anns.length;i++) {
// Check for the SuppressAjWarnings annotation
if (TypeX.SUPPRESS_AJ_WARNINGS.getSignature().equals(anns[i].getBcelAnnotation().getTypeSignature())) {
// Two possibilities:
// 1. there are no values specified (i.e. @SuppressAjWarnings)
// 2. there are values specified (i.e. @SuppressAjWarnings("A") or @SuppressAjWarnings({"A","B"})
List vals = anns[i].getBcelAnnotation().getValues();
if (vals == null || vals.size()==0) { // (1)
suppressed = true;
} else { // (2)
// We know the value is an array value
ArrayElementValue array = (ArrayElementValue)((ElementNameValuePair)vals.get(0)).getValue();
ElementValue[] values = array.getElementValuesArray();
for (int j = 0; j < values.length; j++) {
// We know values in the array are strings
SimpleElementValue value = (SimpleElementValue)values[j];
if (value.getValueString().equals(lintkey)) {
suppressed = true;
}
}
}
}
}
return suppressed;
}
}
|
91,719 |
Bug 91719 Work with Oli B to pull in examples of generating all the LINT messages
| null |
resolved fixed
|
70b9ffd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-04T14:37:41Z | 2005-04-18T10:26:40Z |
tests/bugs/seven/lint/Main.java
| |
91,719 |
Bug 91719 Work with Oli B to pull in examples of generating all the LINT messages
| null |
resolved fixed
|
70b9ffd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-04T14:37:41Z | 2005-04-18T10:26:40Z |
tests/src/org/aspectj/systemtest/xlint/XLintTests.java
|
/* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* ******************************************************************/
package org.aspectj.systemtest.xlint;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class XLintTests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(XLintTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/xlint/xlint.xml");
}
public void test001(){
runTest("options -Xlint args()");
}
public void test002(){
runTest("options declare field on bad type");
}
public void test003(){
runTest("options declare method on bad type");
}
public void test004(){
runTest("options -Xlint declare parent");
}
public void test005(){
runTest("options -Xlint target()");
}
public void test006(){
runTest("options -Xlint this()");
}
public void test007(){
runTest("options negative -Xlint args()");
}
public void test008(){
runTest("options negative -Xlint declare parent");
}
public void test009(){
runTest("options negative -Xlint target()");
}
public void test010(){
runTest("options negative -Xlint this()");
}
public void test011(){
runTest("unmatched type name in a declare parents should result in a warning in -Xlint mode");
}
public void test012(){
runTest("privileged access to code outside the control of the compiler");
}
public void test013(){
runTest("Unexpected Xlint:unresolvableMember warning with withincode");
}
public void test014(){
runTest("valid XLintWarningTest file, default level of warning");
}
public void test015(){
runTest("XLint:ignore suppresses XLint warnings");
}
public void test016(){
runTest("XLint:error promotes XLint warnings to error");
}
public void test017(){
runTest("alias getCause for getWrappedThrowable in SoftException");
}
public void test018(){
runTest("XLint warning for call PCD's using subtype of defining type");
}
public void test019(){
runTest("XLint warning for call PCD's using subtype of defining type (-1.3 -Xlint:ignore)");
}
}
|
91,267 |
Bug 91267 NPE at EclipseFactory.java:143 when using generic methods in aspects
|
When I compile any of these two aspects with ajc -1.5, an exception is thrown by the compiler: import java.util.*; public aspect TestBug1 { static <T> void addToEnv(Map<String,T> env, String key, T value) { env.put(key, value); } } import java.util.*; public aspect TestBug2 { static <T> T lookupEnv(Map<String,T> env, String key) { return env.get(key); } } If the methods are placed into classes instead of aspects, all works fine. The exception thrown is the following: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.getName(EclipseFactory.java:143) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:166) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBindings(EclipseFactory.java:176) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:254) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:249) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.fillDeclaredMembers(EclipseSourceType.java:115) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.getDeclaredPointcuts(EclipseSourceType.java:146) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTypeAndPerClause(AspectDeclaration.java:977) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildInterTypeAndPerClause(AjLookupEnvironment.java:303) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:119) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:331) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:348) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:683) 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) at org.aspectj.tools.ajc.Main.runMain(Main.java:227) at org.aspectj.tools.ajc.Main.main(Main.java:80)
|
resolved fixed
|
7389d9f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-06T10:21:26Z | 2005-04-13T13:46:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten 2004-07-26 extended to allow overloading of
* hierarchy builder
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.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;
/**
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
private AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private boolean xSerializableAspects;
private World world;
private AsmHierarchyBuilder asmHierarchyBuilder;
private Map/*TypeX, TypeBinding*/ typexToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedTypeX*/ bindingToResolvedTypeX = new HashMap();
public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) {
AjLookupEnvironment aenv = (AjLookupEnvironment)env;
return aenv.factory;
}
public static EclipseFactory fromScopeLookupEnvironment(Scope scope) {
return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment);
}
public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) {
this.lookupEnvironment = lookupEnvironment;
this.buildManager = buildManager;
this.world = buildManager.getWorld();
this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects();
}
public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) {
this.lookupEnvironment = lookupEnvironment;
this.world = world;
this.xSerializableAspects = xSer;
this.buildManager = null;
}
public World getWorld() {
return world;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedTypeX fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedTypeX.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedTypeX ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedTypeX fromTypeBindingToRTX(TypeBinding tb) {
if (tb == null) return ResolvedTypeX.MISSING;
ResolvedTypeX ret = getWorld().resolve(fromBinding(tb));
return ret;
}
public ResolvedTypeX[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedTypeX.NONE;
}
int len = bindings.length;
ResolvedTypeX[] ret = new ResolvedTypeX[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
private static String getName(TypeBinding binding) {
if (binding instanceof ReferenceBinding) {
return new String(
CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.'));
}
String packageName = new String(binding.qualifiedPackageName());
String className = new String(binding.qualifiedSourceName()).replace('.', '$');
if (packageName.length() > 0) {
className = packageName + "." + className;
}
//XXX doesn't handle arrays correctly (or primitives?)
return new String(className);
}
//??? going back and forth between strings and bindings is a waste of cycles
public static TypeX fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedTypeX.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
// this is a type variable...
TypeVariableBinding tvb = (TypeVariableBinding) binding;
return TypeX.forName(getName(tvb.firstBound)); // XXX needs more investigation as to whether this is correct in all cases
}
// FIXME asc/amc cope properly with RawTypeBindings
if (binding instanceof ParameterizedTypeBinding && !(binding instanceof RawTypeBinding)) {
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
String[] arguments = new String[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (ptb.arguments[i] instanceof WildcardBinding) {
WildcardBinding wcb = (WildcardBinding) ptb.arguments[i];
arguments[i] = getName(((TypeVariableBinding)wcb.typeVariable()).firstBound);
} else {
arguments[i] = getName(ptb.arguments[i]);
}
}
return TypeX.forParameterizedTypeNames(getName(binding), arguments);
}
return TypeX.forName(getName(binding));
}
public static TypeX[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return TypeX.NONE;
int len = bindings.length;
TypeX[] ret = new TypeX[len];
for (int i=0; i<len; i++) {
ret[i] = fromBinding(bindings[i]);
}
return ret;
}
public static ASTNode astForLocation(IHasPosition location) {
return new EmptyStatement(location.getStart(), location.getEnd());
}
public Collection getDeclareParents() {
return getWorld().getDeclareParents();
}
public Collection getDeclareAnnotationOnTypes() {
return getWorld().getDeclareAnnotationOnTypes();
}
public Collection getDeclareAnnotationOnFields() {
return getWorld().getDeclareAnnotationOnFields();
}
public Collection getDeclareAnnotationOnMethods() {
return getWorld().getDeclareAnnotationOnMethods();
}
public Collection finishedTypeMungers = null;
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers =
getWorld().getCrosscuttingMembersSet().getTypeMungers();
for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next();
EclipseTypeMunger etm = makeEclipseTypeMunger(munger);
if (etm != null) ret.add(etm);
}
finishedTypeMungers = ret;
}
public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) {
//System.err.println("make munger: " + concrete);
//!!! can't do this if we want incremental to work right
//if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete;
//System.err.println(" was not eclipse");
if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) {
AbstractMethodDeclaration method = null;
if (concrete instanceof EclipseTypeMunger) {
method = ((EclipseTypeMunger)concrete).getSourceMethod();
}
EclipseTypeMunger ret =
new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method);
if (ret.getSourceLocation() == null) {
ret.setSourceLocation(concrete.getSourceLocation());
}
return ret;
} else {
return null;
}
}
public Collection getTypeMungers() {
//??? assert finishedTypeMungers != null
return finishedTypeMungers;
}
public static ResolvedMember makeResolvedMember(MethodBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public static ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
ResolvedMember ret = new ResolvedMember(
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD,
fromBinding(declaringType),
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions));
return ret;
}
public static ResolvedMember makeResolvedMember(FieldBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public static ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) {
return new ResolvedMember(
Member.FIELD,
fromBinding(receiverType),
binding.modifiers,
fromBinding(binding.type),
new String(binding.name),
TypeX.NONE);
}
public TypeBinding makeTypeBinding(TypeX typeX) {
TypeBinding ret = (TypeBinding)typexToBinding.get(typeX);
if (ret == null) {
ret = makeTypeBinding1(typeX);
typexToBinding.put(typeX, ret);
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
private TypeBinding makeTypeBinding1(TypeX typeX) {
if (typeX.isPrimitive()) {
if (typeX == ResolvedTypeX.BOOLEAN) return BaseTypes.BooleanBinding;
if (typeX == ResolvedTypeX.BYTE) return BaseTypes.ByteBinding;
if (typeX == ResolvedTypeX.CHAR) return BaseTypes.CharBinding;
if (typeX == ResolvedTypeX.DOUBLE) return BaseTypes.DoubleBinding;
if (typeX == ResolvedTypeX.FLOAT) return BaseTypes.FloatBinding;
if (typeX == ResolvedTypeX.INT) return BaseTypes.IntBinding;
if (typeX == ResolvedTypeX.LONG) return BaseTypes.LongBinding;
if (typeX == ResolvedTypeX.SHORT) return BaseTypes.ShortBinding;
if (typeX == ResolvedTypeX.VOID) return BaseTypes.VoidBinding;
throw new RuntimeException("weird primitive type " + typeX);
} else if (typeX.isArray()) {
int dim = 0;
while (typeX.isArray()) {
dim++;
typeX = typeX.getComponentType();
}
return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim);
} else if (typeX.isParameterized()){
TypeX[] typeParameters = typeX.getTypeParameters();
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
ReferenceBinding[] argumentBindings = new ReferenceBinding[typeParameters.length];
for (int i = 0; i < argumentBindings.length; i++) {
argumentBindings[i] = lookupBinding(typeParameters[i].getName());
}
ParameterizedTypeBinding ptb =
lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType());
return ptb;
} else {
return lookupBinding(typeX.getName());
}
}
private ReferenceBinding lookupBinding(String sname) {
char[][] name = CharOperation.splitOn('.', sname.toCharArray());
ReferenceBinding rb = lookupEnvironment.getType(name);
// XXX We do this because the pertypewithin aspectOf(Class) generated method needs it. Without this
// we don't get a 'rawtype' as the argument type for a messagesend to aspectOf() and this leads to
// a compile error if some client class calls aspectOf(A.class) or similar as it says Class<A> isn't
// compatible with Class<T>
if (sname.equals("java.lang.Class"))
rb = lookupEnvironment.createRawType(rb,rb.enclosingType());
return rb;
}
public TypeBinding[] makeTypeBindings(TypeX[] types) {
int len = types.length;
TypeBinding[] ret = new TypeBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeBinding(types[i]);
}
return ret;
}
// just like the code above except it returns an array of ReferenceBindings
private ReferenceBinding[] makeReferenceBindings(TypeX[] types) {
int len = types.length;
ReferenceBinding[] ret = new ReferenceBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = (ReferenceBinding)makeTypeBinding(types[i]);
}
return ret;
}
public FieldBinding makeFieldBinding(ResolvedMember member) {
return new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()),
Constant.NotAConstant);
}
public MethodBinding makeMethodBinding(ResolvedMember member) {
return new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public MethodBinding makeMethodBindingForCall(Member member) {
return new MethodBinding(member.getCallsiteModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
new ReferenceBinding[0],
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public void finishedCompilationUnit(CompilationUnitDeclaration unit) {
if ((buildManager != null) && buildManager.doGenerateModel()) {
AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig);
}
}
public void addTypeBinding(TypeBinding binding) {
typexToBinding.put(fromBinding(binding), binding);
}
public Shadow makeShadow(ASTNode location, ReferenceContext context) {
return EclipseShadow.makeShadow(this, location, context);
}
public Shadow makeShadow(ReferenceContext context) {
return EclipseShadow.makeShadow(this, (ASTNode) context, context);
}
public void addSourceTypeBinding(SourceTypeBinding binding) {
TypeDeclaration decl = binding.scope.referenceContext;
ResolvedTypeX.Name name = getWorld().lookupOrCreateName(TypeX.forName(getName(binding)));
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl);
name.setDelegate(t);
if (decl instanceof AspectDeclaration) {
((AspectDeclaration)decl).typeX = name;
((AspectDeclaration)decl).concreteName = t;
}
ReferenceBinding[] memberTypes = binding.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addSourceTypeBinding((SourceTypeBinding) memberTypes[i]);
}
}
// XXX this doesn't feel like it belongs here, but it breaks a hard dependency on
// exposing AjBuildManager (needed by AspectDeclaration).
public boolean isXSerializableAspects() {
return xSerializableAspects;
}
}
|
91,267 |
Bug 91267 NPE at EclipseFactory.java:143 when using generic methods in aspects
|
When I compile any of these two aspects with ajc -1.5, an exception is thrown by the compiler: import java.util.*; public aspect TestBug1 { static <T> void addToEnv(Map<String,T> env, String key, T value) { env.put(key, value); } } import java.util.*; public aspect TestBug2 { static <T> T lookupEnv(Map<String,T> env, String key) { return env.get(key); } } If the methods are placed into classes instead of aspects, all works fine. The exception thrown is the following: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.getName(EclipseFactory.java:143) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:166) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBindings(EclipseFactory.java:176) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:254) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:249) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.fillDeclaredMembers(EclipseSourceType.java:115) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.getDeclaredPointcuts(EclipseSourceType.java:146) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTypeAndPerClause(AspectDeclaration.java:977) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildInterTypeAndPerClause(AjLookupEnvironment.java:303) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:119) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:331) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:348) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:683) 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) at org.aspectj.tools.ajc.Main.runMain(Main.java:227) at org.aspectj.tools.ajc.Main.main(Main.java:80)
|
resolved fixed
|
7389d9f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-06T10:21:26Z | 2005-04-13T13:46:40Z |
tests/src/org/aspectj/systemtest/ajc150/GenericsTests.java
|
package org.aspectj.systemtest.ajc150;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class GenericsTests extends XMLBasedAjcTestCase {
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");
}
}
|
91,267 |
Bug 91267 NPE at EclipseFactory.java:143 when using generic methods in aspects
|
When I compile any of these two aspects with ajc -1.5, an exception is thrown by the compiler: import java.util.*; public aspect TestBug1 { static <T> void addToEnv(Map<String,T> env, String key, T value) { env.put(key, value); } } import java.util.*; public aspect TestBug2 { static <T> T lookupEnv(Map<String,T> env, String key) { return env.get(key); } } If the methods are placed into classes instead of aspects, all works fine. The exception thrown is the following: java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.getName(EclipseFactory.java:143) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:166) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBindings(EclipseFactory.java:176) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:254) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.makeResolvedMember(EclipseFactory.java:249) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.fillDeclaredMembers(EclipseSourceType.java:115) at org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType.getDeclaredPointcuts(EclipseSourceType.java:146) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTypeAndPerClause(AspectDeclaration.java:977) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildInterTypeAndPerClause(AjLookupEnvironment.java:303) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:119) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:331) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:348) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:683) 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) at org.aspectj.tools.ajc.Main.runMain(Main.java:227) at org.aspectj.tools.ajc.Main.main(Main.java:80)
|
resolved fixed
|
7389d9f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-06T10:21:26Z | 2005-04-13T13:46:40Z |
weaver/src/org/aspectj/weaver/TypeX.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Iterator;
public class TypeX implements AnnotatedElement {
/**
* This is the bytecode string representation of this Type
*/
protected String signature;
/**
* If this is a parameterized type, these are its parameters
*/
protected TypeX[] typeParameters;
/**
* @param signature the bytecode string representation of this Type
*/
protected TypeX(String signature) {
super();
this.signature = signature;
}
// ---- Things we can do without a world
/**
* This is the size of this type as used in JVM.
*/
public int getSize() {
return 1;
}
/**
* Equality is checked based on the underlying signature.
* {@link ResolvedType} objects' equals is by reference.
*/
public boolean equals(Object other) {
if (! (other instanceof TypeX)) return false;
return signature.equals(((TypeX) other).signature);
}
/**
* Equality is checked based on the underlying signature, so the hash code
* of a particular type is the hash code of its signature string.
*/
public final int hashCode() {
return signature.hashCode();
}
public static TypeX makeArray(TypeX base, int dims) {
StringBuffer sig = new StringBuffer();
for (int i=0; i < dims; i++) sig.append("[");
sig.append(base.getSignature());
return TypeX.forSignature(sig.toString());
}
/**
* NOTE: Use forSignature() if you can, it'll be cheaper !
* Constructs a TypeX for a java language type name. For example:
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]")
* TypeX.forName("int")
* </pre></blockquote>
*
* Types may equivalently be produced by this or by {@link #forSignature(String)}.
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;")
* TypeX.forName("int").equals(Type.forSignature("I"))
* </pre></blockquote>
*
* @param name the java language type name in question.
* @return a type object representing that java language type.
*/
public static TypeX forName(String name) {
return forSignature(nameToSignature(name));
}
/** Constructs a TypeX for each java language type name in an incoming array.
*
* @param names an array of java language type names.
* @return an array of TypeX objects.
* @see #forName(String)
*/
public static TypeX[] forNames(String[] names) {
TypeX[] ret = new TypeX[names.length];
for (int i = 0, len = names.length; i < len; i++) {
ret[i] = TypeX.forName(names[i]);
}
return ret;
}
/**
* Makes a parameterized type with the given name
* and parameterized type names.
*/
public static TypeX forParameterizedTypeNames(String name, String[] paramTypeNames) {
TypeX ret = TypeX.forName(name);
ret.typeParameters = new TypeX[paramTypeNames.length];
for (int i = 0; i < paramTypeNames.length; i++) {
ret.typeParameters[i] = TypeX.forName(paramTypeNames[i]);
}
// sig for e.g. List<String> is Ljava/util/List<Ljava/lang/String;>;
StringBuffer sigAddition = new StringBuffer();
sigAddition.append("<");
for (int i = 0; i < ret.typeParameters.length; i++) {
sigAddition.append(ret.typeParameters[i].signature);
sigAddition.append(">");
sigAddition.append(";");
}
ret.signature = ret.signature + sigAddition.toString();
return ret;
}
/**
* Creates a new type array with a fresh type appended to the end.
*
* @param types the left hand side of the new array
* @param end the right hand side of the new array
*/
public static TypeX[] add(TypeX[] types, TypeX end) {
int len = types.length;
TypeX[] ret = new TypeX[len + 1];
System.arraycopy(types, 0, ret, 0, len);
ret[len] = end;
return ret;
}
/**
* Creates a new type array with a fresh type inserted at the beginning.
*
*
* @param start the left hand side of the new array
* @param types the right hand side of the new array
*/
public static TypeX[] insert(TypeX start, TypeX[] types) {
int len = types.length;
TypeX[] ret = new TypeX[len + 1];
ret[0] = start;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
/**
* Constructs a Type for a JVM bytecode signature string. For example:
*
* <blockquote><pre>
* TypeX.forSignature("[Ljava/lang/Thread;")
* TypeX.forSignature("I");
* </pre></blockquote>
*
* Types may equivalently be produced by this or by {@link #forName(String)}.
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;")
* TypeX.forName("int").equals(Type.forSignature("I"))
* </pre></blockquote>
*
* @param signature the JVM bytecode signature string for the desired type.
* @return a type object represnting that JVM bytecode signature.
*/
public static TypeX forSignature(String signature) {
switch (signature.charAt(0)) {
case 'B': return ResolvedTypeX.BYTE;
case 'C': return ResolvedTypeX.CHAR;
case 'D': return ResolvedTypeX.DOUBLE;
case 'F': return ResolvedTypeX.FLOAT;
case 'I': return ResolvedTypeX.INT;
case 'J': return ResolvedTypeX.LONG;
case 'L':
return new TypeX(signature);
case 'S': return ResolvedTypeX.SHORT;
case 'V': return ResolvedTypeX.VOID;
case 'Z': return ResolvedTypeX.BOOLEAN;
case '[':
return new TypeX(signature);
default:
throw new BCException("Bad type signature " + signature);
}
}
/** Constructs a TypeX for each JVM bytecode type signature in an incoming array.
*
* @param names an array of JVM bytecode type signatures
* @return an array of TypeX objects.
* @see #forSignature(String)
*/
public static TypeX[] forSignatures(String[] sigs) {
TypeX[] ret = new TypeX[sigs.length];
for (int i = 0, len = sigs.length; i < len; i++) {
ret[i] = TypeX.forSignature(sigs[i]);
}
return ret;
}
/**
* Returns the name of this type in java language form. For all
* TypeX t:
*
* <blockquote><pre>
* TypeX.forName(t.getName()).equals(t)
* </pre></blockquote>
*
* and for all String s where s is a lexically valid java language typename:
*
* <blockquote><pre>
* TypeX.forName(s).getName().equals(s)
* </pre></blockquote>
*
* This produces a more esthetically pleasing string than
* {@link java.lang.Class#getName()}.
*
* @return the java language name of this type.
*/
public String getName() {
return signatureToName(signature);
}
public String getBaseName() {
String name = getName();
if (isParameterized()) {
return name.substring(0,name.indexOf("<"));
} else {
return name;
}
}
/**
* Returns an array of strings representing the java langauge names of
* an array of types.
*
* @param types an array of TypeX objects
* @return an array of Strings fo the java language names of types.
* @see #getName()
*/
public static String[] getNames(TypeX[] types) {
String[] ret = new String[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = types[i].getName();
}
return ret;
}
/**
* Returns the name of this type in JVM signature form. For all
* TypeX t:
*
* <blockquote><pre>
* TypeX.forSignature(t.getSignature()).equals(t)
* </pre></blockquote>
*
* and for all String s where s is a lexically valid JVM type signature string:
*
* <blockquote><pre>
* TypeX.forSignature(s).getSignature().equals(s)
* </pre></blockquote>
*
* @return the java JVM signature string for this type.
*/
public String getSignature() {
return signature;
}
/**
* Determins if this represents an array type.
*
* @return true iff this represents an array type.
*/
public final boolean isArray() {
return signature.startsWith("[");
}
/**
* Determines if this represents a parameterized type.
*/
public final boolean isParameterized() {
return signature.indexOf("<") != -1;
//(typeParameters != null) && (typeParameters.length > 0);
}
/**
* Returns a TypeX object representing the effective outermost enclosing type
* for a name type. For all other types, this will return the type itself.
*
* The only guarantee is given in JLS 13.1 where code generated according to
* those rules will have type names that can be split apart in this way.
* @return the outermost enclosing TypeX object or this.
*/
public TypeX getOutermostType() {
if (isArray() || isPrimitive()) return this;
String sig = getSignature();
int dollar = sig.indexOf('$');
if (dollar != -1) {
return TypeX.forSignature(sig.substring(0, dollar) + ';');
} else {
return this;
}
}
/**
* Returns a TypeX object representing the component type of this array, or
* null if this type does not represent an array type.
*
* @return the component TypeX object, or null.
*/
public TypeX getComponentType() {
if (isArray()) {
return forSignature(signature.substring(1));
} else {
return null;
}
}
/**
* Determines if this represents a primitive type. A primitive type
* is one of nine predefined resolved types.
*
* @return true iff this type represents a primitive type
*
* @see ResolvedTypeX#Boolean
* @see ResolvedTypeX#Character
* @see ResolvedTypeX#Byte
* @see ResolvedTypeX#Short
* @see ResolvedTypeX#Integer
* @see ResolvedTypeX#Long
* @see ResolvedTypeX#Float
* @see ResolvedTypeX#Double
* @see ResolvedTypeX#Void
*/
public boolean isPrimitive() {
return false;
}
/**
* Returns a java language string representation of this type.
*/
public String toString() {
return getName();
}
// ---- requires worlds
/**
* Types may have pointcuts just as they have methods and fields.
*/
public ResolvedPointcutDefinition findPointcut(String name, World world) {
return world.findPointcut(this, name);
}
/**
* 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(TypeX other, World world) {
if (this.equals(OBJECT)) return true;
if (this.isPrimitive() || other.isPrimitive()) return this.isAssignableFrom(other, world);
return this.isCoerceableFrom(other, world);
}
/**
* Determines if variables of this type could be assigned values of another
* without any conversion computation of any kind. For primitive types
* this means equality, and for reference types it means assignability.
*
* @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 any conversion computation
*/
public boolean needsNoConversionFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive()) return false;
return world.needsNoConversionFrom(this, other);
}
/**
* Determines if the variables of this type could be assigned values
* of another type without casting. This still allows for assignment conversion
* as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER).
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other without casting
* @exception NullPointerException if other is null
*/
public boolean isAssignableFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive() && !world.behaveInJava5Way) return false;
return world.isAssignableFrom(this, other);
}
/**
* Determines if values of another type could possibly be cast to
* this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion".
*
* <p> This method should be commutative, i.e., for all TypeX a, b and all World w:
*
* <blockquote><pre>
* a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w)
* </pre></blockquote>
*
* @param other the other type
* @param world the {@link World} in which the possible coersion should be checked.
* @return true iff values of other could possibly be cast to this type.
* @exception NullPointerException if other is null.
*/
public boolean isCoerceableFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive()) return false;
return world.isCoerceableFrom(this, other);
}
/**
* Determines if this represents an interface type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents an interface type.
*/
public final boolean isInterface(World world) {
return world.resolve(this).isInterface();
}
/**
* Determines if this represents a class type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents a class type.
*/
public final boolean isClass(World world) {
return world.resolve(this).isClass();
}
/**
* Determines if this class represents an enum type.
*/
public final boolean isEnum(World world) {
return world.resolve(this).isEnum();
}
/**
* Determines if this class represents an annotation type.
*/
public final boolean isAnnotation(World world) {
return world.resolve(this).isAnnotation();
}
/**
* Determine if this class represents an annotation type that has runtime retention
*/
public final boolean isAnnotationWithRuntimeRetention(World world) {
return world.resolve(this).isAnnotationWithRuntimeRetention();
}
/**
* Determines if this represents an aspect type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents an aspect type.
*/
public final boolean isAspect(World world) {
return world.resolve(this).isAspect();
}
/**
* Returns a TypeX 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.
*
* <p>
* This differs from {@link java.lang.class#getSuperclass()} in that
* this returns a TypeX object representing java.lang.Object for interfaces instead
* of returning null.
*
* @param world the {@link World} in which the lookup should be made.
* @return this type's superclass, or null if none exists.
*/
public TypeX getSuperclass(World world) {
return world.getSuperclass(this);
}
/**
* Returns an array of TypeX objects representing the declared interfaces
* of this type.
*
* <p>
* If this object represents a class, the declared interfaces are those it
* implements. If this object represents an interface, the declared interfaces
* are those it extends. If this object represents a primitive, an empty
* array is returned. If this object represents an array, an array
* containing types for java.lang.Cloneable and java.io.Serializable is returned.
*
* @param world the {@link World} in which the lookup should be made.
* @return an iterator through the declared interfaces of this type.
*/
public TypeX[] getDeclaredInterfaces(World world) {
return world.getDeclaredInterfaces(this);
}
/**
* Returns an iterator through TypeX objects representing all the direct
* supertypes of this type. That is, through the superclass, if any, and
* all declared interfaces.
*
* @param world the {@link World} in which the lookup should be made.
* @return an iterator through the direct supertypes of this type.
*/
public Iterator getDirectSupertypes(World world) {
return world.resolve(this).getDirectSupertypes();
}
/**
* Returns the modifiers for this type.
*
* See {@link java.lang.Class#getModifiers()} for a description
* of the weirdness of this methods on primitives and arrays.
*
* @param world the {@link World} in which the lookup is made.
* @return an int representing the modifiers for this type
* @see java.lang.reflect.Modifier
*/
public int getModifiers(World world) {
return world.getModifiers(this);
}
/**
* Returns an array representing the declared fields of this object. This may include
* non-user-visible fields.
* This method returns an
* empty array if it represents an array type or a primitive type, so
* the implicit length field of arrays is just that, implicit.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared fields of this type
*/
public ResolvedMember[] getDeclaredFields(World world) {
return world.getDeclaredFields(this);
}
/**
* Returns an array representing the declared methods of this object. This includes
* constructors and the static initialzation method. This also includes all
* shadowMungers in an aspect. So it may include more than the user-visible methods.
* This method returns an
* empty array if it represents an array type or a primitive type.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared methods of this type
*/
public ResolvedMember[] getDeclaredMethods(World world) {
return world.getDeclaredMethods(this);
}
/**
* Returns an array representing the declared pointcuts of this object.
* This method returns an
* empty array if it represents an array type or a primitive type.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared pointcuts of this type
*/
public ResolvedMember[] getDeclaredPointcuts(World world) {
return world.getDeclaredPointcuts(this);
}
/**
* Returns a resolved version of this type according to a particular world.
*
* @param world thie {@link World} within which to resolve.
* @return a resolved type representing this type in the appropriate world.
*/
public ResolvedTypeX resolve(World world) {
return world.resolve(this);
}
public boolean hasAnnotation(TypeX ofType) {
throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result...");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.AnnotatedElement#getAnnotationTypes()
*/
public ResolvedTypeX[] getAnnotationTypes() {
throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result...");
}
// ---- fields
public static final TypeX[] NONE = new TypeX[0];
public static final TypeX OBJECT = forSignature("Ljava/lang/Object;");
public static final TypeX OBJECTARRAY = forSignature("[Ljava/lang/Object;");
public static final TypeX CLONEABLE = forSignature("Ljava/lang/Cloneable;");
public static final TypeX SERIALIZABLE = forSignature("Ljava/io/Serializable;");
public static final TypeX THROWABLE = forSignature("Ljava/lang/Throwable;");
public static final TypeX RUNTIME_EXCEPTION = forSignature("Ljava/lang/RuntimeException;");
public static final TypeX ERROR = forSignature("Ljava/lang/Error;");
public static final TypeX AT_INHERITED = forSignature("Ljava/lang/annotation/Inherited;");
public static final TypeX AT_RETENTION = forSignature("Ljava/lang/annotation/Retention;");
public static final TypeX ENUM = forSignature("Ljava/lang/Enum;");
public static final TypeX ANNOTATION = forSignature("Ljava/lang/annotation/Annotation;");
public static final TypeX JAVA_LANG_CLASS = forSignature("Ljava/lang/Class;");
public static final TypeX JAVA_LANG_EXCEPTION = forSignature("Ljava/lang/Exception;");
public static final TypeX JAVA_LANG_REFLECT_METHOD = forSignature("Ljava/lang/reflect/Method;");
public static final TypeX SUPPRESS_AJ_WARNINGS = forSignature("Lorg/aspectj/lang/annotation/SuppressAjWarnings;");
public static final TypeX AT_TARGET = forSignature("Ljava/lang/annotation/Target;");
// ---- helpers
private static String signatureToName(String signature) {
switch (signature.charAt(0)) {
case 'B': return "byte";
case 'C': return "char";
case 'D': return "double";
case 'F': return "float";
case 'I': return "int";
case 'J': return "long";
case 'L':
String name = signature.substring(1, signature.length() - 1).replace('/', '.');
if (name.indexOf("<") == -1) return name;
// signature for parameterized types is e.g.
// List<String> -> Ljava/util/List<Ljava/lang/String;>;
// Map<String,List<Integer>> -> Ljava/util/Map<java/lang/String;Ljava/util/List<Ljava/lang/Integer;>;>;
StringBuffer nameBuff = new StringBuffer();
boolean justSeenLeftArrowChar = false;
boolean justSeenSemiColon= false;
int paramNestLevel = 0;
for (int i = 0 ; i < name.length(); i++) {
char c = name.charAt(i);
switch (c) {
case '<' :
justSeenLeftArrowChar = true;
paramNestLevel++;
nameBuff.append(c);
break;
case ';' :
justSeenSemiColon = true;
break;
case '>' :
paramNestLevel--;
nameBuff.append(c);
break;
case 'L' :
if (justSeenLeftArrowChar) {
justSeenLeftArrowChar = false;
break;
}
if (justSeenSemiColon) {
nameBuff.append(",");
} else {
nameBuff.append("L");
}
break;
default:
justSeenSemiColon = false;
justSeenLeftArrowChar = false;
nameBuff.append(c);
}
}
return nameBuff.toString();
case 'S': return "short";
case 'V': return "void";
case 'Z': return "boolean";
case '[':
return signatureToName(signature.substring(1, signature.length())) + "[]";
default:
throw new BCException("Bad type signature: " + signature);
}
}
private static String nameToSignature(String name) {
if (name.equals("byte")) return "B";
if (name.equals("char")) return "C";
if (name.equals("double")) return "D";
if (name.equals("float")) return "F";
if (name.equals("int")) return "I";
if (name.equals("long")) return "J";
if (name.equals("short")) return "S";
if (name.equals("boolean")) return "Z";
if (name.equals("void")) return "V";
if (name.endsWith("[]"))
return "[" + nameToSignature(name.substring(0, name.length() - 2));
if (name.length() != 0) {
// lots more tests could be made here...
// 1) If it is already an array type, do not mess with it.
if (name.charAt(0)=='[' && name.charAt(name.length()-1)==';') return name;
else {
if (name.indexOf("<") == -1) {
// not parameterised
return "L" + name.replace('.', '/') + ";";
} else {
StringBuffer nameBuff = new StringBuffer();
nameBuff.append("L");
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
switch (c) {
case '.' : nameBuff.append('/'); break;
case '<' : nameBuff.append("<L"); break;
case '>' : nameBuff.append(";>"); break;
case ',' : nameBuff.append(";L"); break;
default: nameBuff.append(c);
}
}
nameBuff.append(";");
return nameBuff.toString();
}
}
}
else
throw new BCException("Bad type name: " + name);
}
public void write(DataOutputStream s) throws IOException {
s.writeUTF(signature);
}
public static TypeX read(DataInputStream s) throws IOException {
String sig = s.readUTF();
if (sig.equals(MISSING_NAME)) {
return ResolvedTypeX.MISSING;
} else {
return TypeX.forSignature(sig);
}
}
public static void writeArray(TypeX[] types, DataOutputStream s) throws IOException {
int len = types.length;
s.writeShort(len);
for (int i=0; i < len; i++) {
types[i].write(s);
}
}
public static TypeX[] readArray(DataInputStream s) throws IOException {
int len = s.readShort();
TypeX[] types = new TypeX[len];
for (int i=0; i < len; i++) {
types[i] = TypeX.read(s);
}
return types;
}
/**
* For debugging purposes
*/
public void dump(World world) {
if (isAspect(world)) System.out.print("aspect ");
else if (isInterface(world)) System.out.print("interface ");
else if (isClass(world)) System.out.print("class ");
System.out.println(toString());
dumpResolvedMembers("fields", getDeclaredFields(world));
dumpResolvedMembers("methods", getDeclaredMethods(world));
dumpResolvedMembers("pointcuts", getDeclaredPointcuts(world));
}
private void dumpResolvedMembers(String label, ResolvedMember[] l) {
final String indent = " ";
System.out.println(label);
if (l == null) {
System.out.println(indent + "null");
return;
}
for (int i=0, len=l.length; i < len; i++) {
System.out.println(indent + l[i]);
}
}
// ----
public String getNameAsIdentifier() {
return getName().replace('.', '_');
}
public String getPackageNameAsIdentifier() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return "";
} else {
return name.substring(0, index).replace('.', '_');
}
}
public String getPackageName() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return null;
} else {
return name.substring(0, index);
}
}
public TypeX[] getTypeParameters() {
return typeParameters == null ? new TypeX[0] : typeParameters;
}
/**
* Doesn't include the package
*/
public String getClassName() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return name;
} else {
return name.substring(index+1);
}
}
public static final String MISSING_NAME = "<missing>";
}
|
91,053 |
Bug 91053 Generics problem with Set - does not compile with AspectJ 5
|
I tried different things to remove compiler warnings about generics which you get when you switch to JDK 5 and use collections. At last I fall back to JDK 1.4. The following code compiles with AspectJ 5 and JDK compliance level 1.4: public aspect SubjectAspect { private Set Subject.observers = new HashSet(); public void Subject.addObserver(SubjectObserver observer) { observers.add(observer); } ... } After switching to compliance level 5.0 I get an error message "The method add(E) in the type Set<E> is not applicable for the arguments (SubjectObserver)". I don't know if it is a similar problem like #87550 but I means for older projects which use collections that they can't switch to JDK 1.5
|
resolved fixed
|
952dda9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-06T15:18:54Z | 2005-04-11T20:06:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten 2004-07-26 extended to allow overloading of
* hierarchy builder
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.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;
/**
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
private AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private boolean xSerializableAspects;
private World world;
private AsmHierarchyBuilder asmHierarchyBuilder;
private Map/*TypeX, TypeBinding*/ typexToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedTypeX*/ bindingToResolvedTypeX = new HashMap();
public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) {
AjLookupEnvironment aenv = (AjLookupEnvironment)env;
return aenv.factory;
}
public static EclipseFactory fromScopeLookupEnvironment(Scope scope) {
return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment);
}
public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) {
this.lookupEnvironment = lookupEnvironment;
this.buildManager = buildManager;
this.world = buildManager.getWorld();
this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects();
}
public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) {
this.lookupEnvironment = lookupEnvironment;
this.world = world;
this.xSerializableAspects = xSer;
this.buildManager = null;
}
public World getWorld() {
return world;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedTypeX fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedTypeX.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedTypeX ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedTypeX fromTypeBindingToRTX(TypeBinding tb) {
if (tb == null) return ResolvedTypeX.MISSING;
ResolvedTypeX ret = getWorld().resolve(fromBinding(tb));
return ret;
}
public ResolvedTypeX[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedTypeX.NONE;
}
int len = bindings.length;
ResolvedTypeX[] ret = new ResolvedTypeX[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
private static String getName(TypeBinding binding) {
if (binding instanceof 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 TypeX and that would seem a bad thing - but I've yet to see the reason we need to
* remember the type variable.
*/
//??? going back and forth between strings and bindings is a waste of cycles
public static TypeX fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedTypeX.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
// this is a type variable...
TypeVariableBinding tvb = (TypeVariableBinding) binding;
// This code causes us to forget its a TVB which we will need when going back the other way...
if (tvb.firstBound!=null) {
return TypeX.forName(getName(tvb.firstBound)); // XXX needs more investigation as to whether this is correct in all cases
} else {
return TypeX.forName(getName(tvb.superclass));
}
}
// FIXME asc/amc cope properly with RawTypeBindings
if (binding instanceof ParameterizedTypeBinding && !(binding instanceof RawTypeBinding)) {
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
String[] arguments = new String[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (ptb.arguments[i] instanceof WildcardBinding) {
WildcardBinding wcb = (WildcardBinding) ptb.arguments[i];
arguments[i] = getName(((TypeVariableBinding)wcb.typeVariable()).firstBound);
} else {
arguments[i] = getName(ptb.arguments[i]);
}
}
return TypeX.forParameterizedTypeNames(getName(binding), arguments);
}
return TypeX.forName(getName(binding));
}
public static TypeX[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return TypeX.NONE;
int len = bindings.length;
TypeX[] ret = new TypeX[len];
for (int i=0; i<len; i++) {
ret[i] = fromBinding(bindings[i]);
}
return ret;
}
public static ASTNode astForLocation(IHasPosition location) {
return new EmptyStatement(location.getStart(), location.getEnd());
}
public Collection getDeclareParents() {
return getWorld().getDeclareParents();
}
public Collection getDeclareAnnotationOnTypes() {
return getWorld().getDeclareAnnotationOnTypes();
}
public Collection getDeclareAnnotationOnFields() {
return getWorld().getDeclareAnnotationOnFields();
}
public Collection getDeclareAnnotationOnMethods() {
return getWorld().getDeclareAnnotationOnMethods();
}
public Collection finishedTypeMungers = null;
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers =
getWorld().getCrosscuttingMembersSet().getTypeMungers();
for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next();
EclipseTypeMunger etm = makeEclipseTypeMunger(munger);
if (etm != null) ret.add(etm);
}
finishedTypeMungers = ret;
}
public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) {
//System.err.println("make munger: " + concrete);
//!!! can't do this if we want incremental to work right
//if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete;
//System.err.println(" was not eclipse");
if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) {
AbstractMethodDeclaration method = null;
if (concrete instanceof EclipseTypeMunger) {
method = ((EclipseTypeMunger)concrete).getSourceMethod();
}
EclipseTypeMunger ret =
new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method);
if (ret.getSourceLocation() == null) {
ret.setSourceLocation(concrete.getSourceLocation());
}
return ret;
} else {
return null;
}
}
public Collection getTypeMungers() {
//??? assert finishedTypeMungers != null
return finishedTypeMungers;
}
public static ResolvedMember makeResolvedMember(MethodBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public static ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
ResolvedMember ret = new ResolvedMember(
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD,
fromBinding(declaringType),
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions));
return ret;
}
public static ResolvedMember makeResolvedMember(FieldBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public static ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) {
return new ResolvedMember(
Member.FIELD,
fromBinding(receiverType),
binding.modifiers,
fromBinding(binding.type),
new String(binding.name),
TypeX.NONE);
}
public TypeBinding makeTypeBinding(TypeX typeX) {
TypeBinding ret = (TypeBinding)typexToBinding.get(typeX);
if (ret == null) {
ret = makeTypeBinding1(typeX);
typexToBinding.put(typeX, ret);
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
private TypeBinding makeTypeBinding1(TypeX typeX) {
if (typeX.isPrimitive()) {
if (typeX == ResolvedTypeX.BOOLEAN) return BaseTypes.BooleanBinding;
if (typeX == ResolvedTypeX.BYTE) return BaseTypes.ByteBinding;
if (typeX == ResolvedTypeX.CHAR) return BaseTypes.CharBinding;
if (typeX == ResolvedTypeX.DOUBLE) return BaseTypes.DoubleBinding;
if (typeX == ResolvedTypeX.FLOAT) return BaseTypes.FloatBinding;
if (typeX == ResolvedTypeX.INT) return BaseTypes.IntBinding;
if (typeX == ResolvedTypeX.LONG) return BaseTypes.LongBinding;
if (typeX == ResolvedTypeX.SHORT) return BaseTypes.ShortBinding;
if (typeX == ResolvedTypeX.VOID) return BaseTypes.VoidBinding;
throw new RuntimeException("weird primitive type " + typeX);
} else if (typeX.isArray()) {
int dim = 0;
while (typeX.isArray()) {
dim++;
typeX = typeX.getComponentType();
}
return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim);
} else if (typeX.isParameterized()){
TypeX[] typeParameters = typeX.getTypeParameters();
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
ReferenceBinding[] argumentBindings = new ReferenceBinding[typeParameters.length];
for (int i = 0; i < argumentBindings.length; i++) {
argumentBindings[i] = lookupBinding(typeParameters[i].getName());
}
ParameterizedTypeBinding ptb =
lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType());
return ptb;
} else {
return lookupBinding(typeX.getName());
}
}
private ReferenceBinding lookupBinding(String sname) {
char[][] name = CharOperation.splitOn('.', sname.toCharArray());
ReferenceBinding rb = lookupEnvironment.getType(name);
// XXX We do this because the pertypewithin aspectOf(Class) generated method needs it. Without this
// we don't get a 'rawtype' as the argument type for a messagesend to aspectOf() and this leads to
// a compile error if some client class calls aspectOf(A.class) or similar as it says Class<A> isn't
// compatible with Class<T>
if (sname.equals("java.lang.Class"))
rb = lookupEnvironment.createRawType(rb,rb.enclosingType());
return rb;
}
public TypeBinding[] makeTypeBindings(TypeX[] types) {
int len = types.length;
TypeBinding[] ret = new TypeBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeBinding(types[i]);
}
return ret;
}
// just like the code above except it returns an array of ReferenceBindings
private ReferenceBinding[] makeReferenceBindings(TypeX[] types) {
int len = types.length;
ReferenceBinding[] ret = new ReferenceBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = (ReferenceBinding)makeTypeBinding(types[i]);
}
return ret;
}
public FieldBinding makeFieldBinding(ResolvedMember member) {
return new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()),
Constant.NotAConstant);
}
public MethodBinding makeMethodBinding(ResolvedMember member) {
return new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public MethodBinding makeMethodBindingForCall(Member member) {
return new MethodBinding(member.getCallsiteModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
new ReferenceBinding[0],
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public void finishedCompilationUnit(CompilationUnitDeclaration unit) {
if ((buildManager != null) && buildManager.doGenerateModel()) {
AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig);
}
}
public void addTypeBinding(TypeBinding binding) {
typexToBinding.put(fromBinding(binding), binding);
}
public Shadow makeShadow(ASTNode location, ReferenceContext context) {
return EclipseShadow.makeShadow(this, location, context);
}
public Shadow makeShadow(ReferenceContext context) {
return EclipseShadow.makeShadow(this, (ASTNode) context, context);
}
public void addSourceTypeBinding(SourceTypeBinding binding) {
TypeDeclaration decl = binding.scope.referenceContext;
ResolvedTypeX.Name name = getWorld().lookupOrCreateName(TypeX.forName(getName(binding)));
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl);
name.setDelegate(t);
if (decl instanceof AspectDeclaration) {
((AspectDeclaration)decl).typeX = name;
((AspectDeclaration)decl).concreteName = t;
}
ReferenceBinding[] memberTypes = binding.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addSourceTypeBinding((SourceTypeBinding) memberTypes[i]);
}
}
// XXX this doesn't feel like it belongs here, but it breaks a hard dependency on
// exposing AjBuildManager (needed by AspectDeclaration).
public boolean isXSerializableAspects() {
return xSerializableAspects;
}
}
|
91,053 |
Bug 91053 Generics problem with Set - does not compile with AspectJ 5
|
I tried different things to remove compiler warnings about generics which you get when you switch to JDK 5 and use collections. At last I fall back to JDK 1.4. The following code compiles with AspectJ 5 and JDK compliance level 1.4: public aspect SubjectAspect { private Set Subject.observers = new HashSet(); public void Subject.addObserver(SubjectObserver observer) { observers.add(observer); } ... } After switching to compliance level 5.0 I get an error message "The method add(E) in the type Set<E> is not applicable for the arguments (SubjectObserver)". I don't know if it is a similar problem like #87550 but I means for older projects which use collections that they can't switch to JDK 1.5
|
resolved fixed
|
952dda9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-06T15:18:54Z | 2005-04-11T20:06:40Z |
tests/src/org/aspectj/systemtest/ajc150/GenericsTests.java
|
package org.aspectj.systemtest.ajc150;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class GenericsTests extends XMLBasedAjcTestCase {
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 testPR91267_2() {
runTest("NPE using generic methods in aspects 2");
}
}
|
91,053 |
Bug 91053 Generics problem with Set - does not compile with AspectJ 5
|
I tried different things to remove compiler warnings about generics which you get when you switch to JDK 5 and use collections. At last I fall back to JDK 1.4. The following code compiles with AspectJ 5 and JDK compliance level 1.4: public aspect SubjectAspect { private Set Subject.observers = new HashSet(); public void Subject.addObserver(SubjectObserver observer) { observers.add(observer); } ... } After switching to compliance level 5.0 I get an error message "The method add(E) in the type Set<E> is not applicable for the arguments (SubjectObserver)". I don't know if it is a similar problem like #87550 but I means for older projects which use collections that they can't switch to JDK 1.5
|
resolved fixed
|
952dda9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-06T15:18:54Z | 2005-04-11T20:06:40Z |
weaver/src/org/aspectj/weaver/TypeX.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Iterator;
public class TypeX implements AnnotatedElement {
/**
* This is the bytecode string representation of this Type
*/
protected String signature;
/**
* If this is a parameterized type, these are its parameters
*/
protected TypeX[] typeParameters;
/**
* @param signature the bytecode string representation of this Type
*/
protected TypeX(String signature) {
super();
this.signature = signature;
}
// ---- Things we can do without a world
/**
* This is the size of this type as used in JVM.
*/
public int getSize() {
return 1;
}
/**
* Equality is checked based on the underlying signature.
* {@link ResolvedType} objects' equals is by reference.
*/
public boolean equals(Object other) {
if (! (other instanceof TypeX)) return false;
return signature.equals(((TypeX) other).signature);
}
/**
* Equality is checked based on the underlying signature, so the hash code
* of a particular type is the hash code of its signature string.
*/
public final int hashCode() {
return signature.hashCode();
}
public static TypeX makeArray(TypeX base, int dims) {
StringBuffer sig = new StringBuffer();
for (int i=0; i < dims; i++) sig.append("[");
sig.append(base.getSignature());
return TypeX.forSignature(sig.toString());
}
/**
* NOTE: Use forSignature() if you can, it'll be cheaper !
* Constructs a TypeX for a java language type name. For example:
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]")
* TypeX.forName("int")
* </pre></blockquote>
*
* Types may equivalently be produced by this or by {@link #forSignature(String)}.
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;")
* TypeX.forName("int").equals(Type.forSignature("I"))
* </pre></blockquote>
*
* @param name the java language type name in question.
* @return a type object representing that java language type.
*/
public static TypeX forName(String name) {
return forSignature(nameToSignature(name));
}
/** Constructs a TypeX for each java language type name in an incoming array.
*
* @param names an array of java language type names.
* @return an array of TypeX objects.
* @see #forName(String)
*/
public static TypeX[] forNames(String[] names) {
TypeX[] ret = new TypeX[names.length];
for (int i = 0, len = names.length; i < len; i++) {
ret[i] = TypeX.forName(names[i]);
}
return ret;
}
/**
* Makes a parameterized type with the given name
* and parameterized type names.
*/
public static TypeX forParameterizedTypeNames(String name, String[] paramTypeNames) {
TypeX ret = TypeX.forName(name);
ret.typeParameters = new TypeX[paramTypeNames.length];
for (int i = 0; i < paramTypeNames.length; i++) {
ret.typeParameters[i] = TypeX.forName(paramTypeNames[i]);
}
// sig for e.g. List<String> is Ljava/util/List<Ljava/lang/String;>;
StringBuffer sigAddition = new StringBuffer();
sigAddition.append("<");
for (int i = 0; i < ret.typeParameters.length; i++) {
sigAddition.append(ret.typeParameters[i].signature);
}
sigAddition.append(">");
sigAddition.append(";");
ret.signature = ret.signature + sigAddition.toString();
return ret;
}
/**
* Creates a new type array with a fresh type appended to the end.
*
* @param types the left hand side of the new array
* @param end the right hand side of the new array
*/
public static TypeX[] add(TypeX[] types, TypeX end) {
int len = types.length;
TypeX[] ret = new TypeX[len + 1];
System.arraycopy(types, 0, ret, 0, len);
ret[len] = end;
return ret;
}
/**
* Creates a new type array with a fresh type inserted at the beginning.
*
*
* @param start the left hand side of the new array
* @param types the right hand side of the new array
*/
public static TypeX[] insert(TypeX start, TypeX[] types) {
int len = types.length;
TypeX[] ret = new TypeX[len + 1];
ret[0] = start;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
/**
* Constructs a Type for a JVM bytecode signature string. For example:
*
* <blockquote><pre>
* TypeX.forSignature("[Ljava/lang/Thread;")
* TypeX.forSignature("I");
* </pre></blockquote>
*
* Types may equivalently be produced by this or by {@link #forName(String)}.
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;")
* TypeX.forName("int").equals(Type.forSignature("I"))
* </pre></blockquote>
*
* @param signature the JVM bytecode signature string for the desired type.
* @return a type object represnting that JVM bytecode signature.
*/
public static TypeX forSignature(String signature) {
switch (signature.charAt(0)) {
case 'B': return ResolvedTypeX.BYTE;
case 'C': return ResolvedTypeX.CHAR;
case 'D': return ResolvedTypeX.DOUBLE;
case 'F': return ResolvedTypeX.FLOAT;
case 'I': return ResolvedTypeX.INT;
case 'J': return ResolvedTypeX.LONG;
case 'L':
return new TypeX(signature);
case 'S': return ResolvedTypeX.SHORT;
case 'V': return ResolvedTypeX.VOID;
case 'Z': return ResolvedTypeX.BOOLEAN;
case '[':
return new TypeX(signature);
default:
throw new BCException("Bad type signature " + signature);
}
}
/** Constructs a TypeX for each JVM bytecode type signature in an incoming array.
*
* @param names an array of JVM bytecode type signatures
* @return an array of TypeX objects.
* @see #forSignature(String)
*/
public static TypeX[] forSignatures(String[] sigs) {
TypeX[] ret = new TypeX[sigs.length];
for (int i = 0, len = sigs.length; i < len; i++) {
ret[i] = TypeX.forSignature(sigs[i]);
}
return ret;
}
/**
* Returns the name of this type in java language form. For all
* TypeX t:
*
* <blockquote><pre>
* TypeX.forName(t.getName()).equals(t)
* </pre></blockquote>
*
* and for all String s where s is a lexically valid java language typename:
*
* <blockquote><pre>
* TypeX.forName(s).getName().equals(s)
* </pre></blockquote>
*
* This produces a more esthetically pleasing string than
* {@link java.lang.Class#getName()}.
*
* @return the java language name of this type.
*/
public String getName() {
return signatureToName(signature);
}
public String getBaseName() {
String name = getName();
if (isParameterized()) {
return name.substring(0,name.indexOf("<"));
} else {
return name;
}
}
/**
* Returns an array of strings representing the java langauge names of
* an array of types.
*
* @param types an array of TypeX objects
* @return an array of Strings fo the java language names of types.
* @see #getName()
*/
public static String[] getNames(TypeX[] types) {
String[] ret = new String[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = types[i].getName();
}
return ret;
}
/**
* Returns the name of this type in JVM signature form. For all
* TypeX t:
*
* <blockquote><pre>
* TypeX.forSignature(t.getSignature()).equals(t)
* </pre></blockquote>
*
* and for all String s where s is a lexically valid JVM type signature string:
*
* <blockquote><pre>
* TypeX.forSignature(s).getSignature().equals(s)
* </pre></blockquote>
*
* @return the java JVM signature string for this type.
*/
public String getSignature() {
return signature;
}
/**
* Determins if this represents an array type.
*
* @return true iff this represents an array type.
*/
public final boolean isArray() {
return signature.startsWith("[");
}
/**
* Determines if this represents a parameterized type.
*/
public final boolean isParameterized() {
return signature.indexOf("<") != -1;
//(typeParameters != null) && (typeParameters.length > 0);
}
/**
* Returns a TypeX object representing the effective outermost enclosing type
* for a name type. For all other types, this will return the type itself.
*
* The only guarantee is given in JLS 13.1 where code generated according to
* those rules will have type names that can be split apart in this way.
* @return the outermost enclosing TypeX object or this.
*/
public TypeX getOutermostType() {
if (isArray() || isPrimitive()) return this;
String sig = getSignature();
int dollar = sig.indexOf('$');
if (dollar != -1) {
return TypeX.forSignature(sig.substring(0, dollar) + ';');
} else {
return this;
}
}
/**
* Returns a TypeX object representing the component type of this array, or
* null if this type does not represent an array type.
*
* @return the component TypeX object, or null.
*/
public TypeX getComponentType() {
if (isArray()) {
return forSignature(signature.substring(1));
} else {
return null;
}
}
/**
* Determines if this represents a primitive type. A primitive type
* is one of nine predefined resolved types.
*
* @return true iff this type represents a primitive type
*
* @see ResolvedTypeX#Boolean
* @see ResolvedTypeX#Character
* @see ResolvedTypeX#Byte
* @see ResolvedTypeX#Short
* @see ResolvedTypeX#Integer
* @see ResolvedTypeX#Long
* @see ResolvedTypeX#Float
* @see ResolvedTypeX#Double
* @see ResolvedTypeX#Void
*/
public boolean isPrimitive() {
return false;
}
/**
* Returns a java language string representation of this type.
*/
public String toString() {
return getName();
}
// ---- requires worlds
/**
* Types may have pointcuts just as they have methods and fields.
*/
public ResolvedPointcutDefinition findPointcut(String name, World world) {
return world.findPointcut(this, name);
}
/**
* 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(TypeX other, World world) {
if (this.equals(OBJECT)) return true;
if (this.isPrimitive() || other.isPrimitive()) return this.isAssignableFrom(other, world);
return this.isCoerceableFrom(other, world);
}
/**
* Determines if variables of this type could be assigned values of another
* without any conversion computation of any kind. For primitive types
* this means equality, and for reference types it means assignability.
*
* @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 any conversion computation
*/
public boolean needsNoConversionFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive()) return false;
return world.needsNoConversionFrom(this, other);
}
/**
* Determines if the variables of this type could be assigned values
* of another type without casting. This still allows for assignment conversion
* as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER).
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other without casting
* @exception NullPointerException if other is null
*/
public boolean isAssignableFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive() && !world.behaveInJava5Way) return false;
return world.isAssignableFrom(this, other);
}
/**
* Determines if values of another type could possibly be cast to
* this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion".
*
* <p> This method should be commutative, i.e., for all TypeX a, b and all World w:
*
* <blockquote><pre>
* a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w)
* </pre></blockquote>
*
* @param other the other type
* @param world the {@link World} in which the possible coersion should be checked.
* @return true iff values of other could possibly be cast to this type.
* @exception NullPointerException if other is null.
*/
public boolean isCoerceableFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive()) return false;
return world.isCoerceableFrom(this, other);
}
/**
* Determines if this represents an interface type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents an interface type.
*/
public final boolean isInterface(World world) {
return world.resolve(this).isInterface();
}
/**
* Determines if this represents a class type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents a class type.
*/
public final boolean isClass(World world) {
return world.resolve(this).isClass();
}
/**
* Determines if this class represents an enum type.
*/
public final boolean isEnum(World world) {
return world.resolve(this).isEnum();
}
/**
* Determines if this class represents an annotation type.
*/
public final boolean isAnnotation(World world) {
return world.resolve(this).isAnnotation();
}
/**
* Determine if this class represents an annotation type that has runtime retention
*/
public final boolean isAnnotationWithRuntimeRetention(World world) {
return world.resolve(this).isAnnotationWithRuntimeRetention();
}
/**
* Determines if this represents an aspect type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents an aspect type.
*/
public final boolean isAspect(World world) {
return world.resolve(this).isAspect();
}
/**
* Returns a TypeX 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.
*
* <p>
* This differs from {@link java.lang.class#getSuperclass()} in that
* this returns a TypeX object representing java.lang.Object for interfaces instead
* of returning null.
*
* @param world the {@link World} in which the lookup should be made.
* @return this type's superclass, or null if none exists.
*/
public TypeX getSuperclass(World world) {
return world.getSuperclass(this);
}
/**
* Returns an array of TypeX objects representing the declared interfaces
* of this type.
*
* <p>
* If this object represents a class, the declared interfaces are those it
* implements. If this object represents an interface, the declared interfaces
* are those it extends. If this object represents a primitive, an empty
* array is returned. If this object represents an array, an array
* containing types for java.lang.Cloneable and java.io.Serializable is returned.
*
* @param world the {@link World} in which the lookup should be made.
* @return an iterator through the declared interfaces of this type.
*/
public TypeX[] getDeclaredInterfaces(World world) {
return world.getDeclaredInterfaces(this);
}
/**
* Returns an iterator through TypeX objects representing all the direct
* supertypes of this type. That is, through the superclass, if any, and
* all declared interfaces.
*
* @param world the {@link World} in which the lookup should be made.
* @return an iterator through the direct supertypes of this type.
*/
public Iterator getDirectSupertypes(World world) {
return world.resolve(this).getDirectSupertypes();
}
/**
* Returns the modifiers for this type.
*
* See {@link java.lang.Class#getModifiers()} for a description
* of the weirdness of this methods on primitives and arrays.
*
* @param world the {@link World} in which the lookup is made.
* @return an int representing the modifiers for this type
* @see java.lang.reflect.Modifier
*/
public int getModifiers(World world) {
return world.getModifiers(this);
}
/**
* Returns an array representing the declared fields of this object. This may include
* non-user-visible fields.
* This method returns an
* empty array if it represents an array type or a primitive type, so
* the implicit length field of arrays is just that, implicit.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared fields of this type
*/
public ResolvedMember[] getDeclaredFields(World world) {
return world.getDeclaredFields(this);
}
/**
* Returns an array representing the declared methods of this object. This includes
* constructors and the static initialzation method. This also includes all
* shadowMungers in an aspect. So it may include more than the user-visible methods.
* This method returns an
* empty array if it represents an array type or a primitive type.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared methods of this type
*/
public ResolvedMember[] getDeclaredMethods(World world) {
return world.getDeclaredMethods(this);
}
/**
* Returns an array representing the declared pointcuts of this object.
* This method returns an
* empty array if it represents an array type or a primitive type.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared pointcuts of this type
*/
public ResolvedMember[] getDeclaredPointcuts(World world) {
return world.getDeclaredPointcuts(this);
}
/**
* Returns a resolved version of this type according to a particular world.
*
* @param world thie {@link World} within which to resolve.
* @return a resolved type representing this type in the appropriate world.
*/
public ResolvedTypeX resolve(World world) {
return world.resolve(this);
}
public boolean hasAnnotation(TypeX ofType) {
throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result...");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.AnnotatedElement#getAnnotationTypes()
*/
public ResolvedTypeX[] getAnnotationTypes() {
throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result...");
}
// ---- fields
public static final TypeX[] NONE = new TypeX[0];
public static final TypeX OBJECT = forSignature("Ljava/lang/Object;");
public static final TypeX OBJECTARRAY = forSignature("[Ljava/lang/Object;");
public static final TypeX CLONEABLE = forSignature("Ljava/lang/Cloneable;");
public static final TypeX SERIALIZABLE = forSignature("Ljava/io/Serializable;");
public static final TypeX THROWABLE = forSignature("Ljava/lang/Throwable;");
public static final TypeX RUNTIME_EXCEPTION = forSignature("Ljava/lang/RuntimeException;");
public static final TypeX ERROR = forSignature("Ljava/lang/Error;");
public static final TypeX AT_INHERITED = forSignature("Ljava/lang/annotation/Inherited;");
public static final TypeX AT_RETENTION = forSignature("Ljava/lang/annotation/Retention;");
public static final TypeX ENUM = forSignature("Ljava/lang/Enum;");
public static final TypeX ANNOTATION = forSignature("Ljava/lang/annotation/Annotation;");
public static final TypeX JAVA_LANG_CLASS = forSignature("Ljava/lang/Class;");
public static final TypeX JAVA_LANG_EXCEPTION = forSignature("Ljava/lang/Exception;");
public static final TypeX JAVA_LANG_REFLECT_METHOD = forSignature("Ljava/lang/reflect/Method;");
public static final TypeX SUPPRESS_AJ_WARNINGS = forSignature("Lorg/aspectj/lang/annotation/SuppressAjWarnings;");
public static final TypeX AT_TARGET = forSignature("Ljava/lang/annotation/Target;");
// ---- helpers
private static String signatureToName(String signature) {
switch (signature.charAt(0)) {
case 'B': return "byte";
case 'C': return "char";
case 'D': return "double";
case 'F': return "float";
case 'I': return "int";
case 'J': return "long";
case 'L':
String name = signature.substring(1, signature.length() - 1).replace('/', '.');
if (name.indexOf("<") == -1) return name;
// signature for parameterized types is e.g.
// List<String> -> Ljava/util/List<Ljava/lang/String;>;
// Map<String,List<Integer>> -> Ljava/util/Map<java/lang/String;Ljava/util/List<Ljava/lang/Integer;>;>;
StringBuffer nameBuff = new StringBuffer();
boolean justSeenLeftArrowChar = false;
boolean justSeenSemiColon= false;
int paramNestLevel = 0;
for (int i = 0 ; i < name.length(); i++) {
char c = name.charAt(i);
switch (c) {
case '<' :
justSeenLeftArrowChar = true;
paramNestLevel++;
nameBuff.append(c);
break;
case ';' :
justSeenSemiColon = true;
break;
case '>' :
paramNestLevel--;
nameBuff.append(c);
break;
case 'L' :
if (justSeenLeftArrowChar) {
justSeenLeftArrowChar = false;
break;
}
if (justSeenSemiColon) {
nameBuff.append(",");
} else {
nameBuff.append("L");
}
break;
default:
justSeenSemiColon = false;
justSeenLeftArrowChar = false;
nameBuff.append(c);
}
}
return nameBuff.toString();
case 'S': return "short";
case 'V': return "void";
case 'Z': return "boolean";
case '[':
return signatureToName(signature.substring(1, signature.length())) + "[]";
default:
throw new BCException("Bad type signature: " + signature);
}
}
private static String nameToSignature(String name) {
if (name.equals("byte")) return "B";
if (name.equals("char")) return "C";
if (name.equals("double")) return "D";
if (name.equals("float")) return "F";
if (name.equals("int")) return "I";
if (name.equals("long")) return "J";
if (name.equals("short")) return "S";
if (name.equals("boolean")) return "Z";
if (name.equals("void")) return "V";
if (name.endsWith("[]"))
return "[" + nameToSignature(name.substring(0, name.length() - 2));
if (name.length() != 0) {
// lots more tests could be made here...
// 1) If it is already an array type, do not mess with it.
if (name.charAt(0)=='[' && name.charAt(name.length()-1)==';') return name;
else {
if (name.indexOf("<") == -1) {
// not parameterised
return "L" + name.replace('.', '/') + ";";
} else {
StringBuffer nameBuff = new StringBuffer();
nameBuff.append("L");
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
switch (c) {
case '.' : nameBuff.append('/'); break;
case '<' : nameBuff.append("<L"); break;
case '>' : nameBuff.append(";>"); break;
case ',' : nameBuff.append(";L"); break;
default: nameBuff.append(c);
}
}
nameBuff.append(";");
return nameBuff.toString();
}
}
}
else
throw new BCException("Bad type name: " + name);
}
public void write(DataOutputStream s) throws IOException {
s.writeUTF(signature);
}
public static TypeX read(DataInputStream s) throws IOException {
String sig = s.readUTF();
if (sig.equals(MISSING_NAME)) {
return ResolvedTypeX.MISSING;
} else {
return TypeX.forSignature(sig);
}
}
public static void writeArray(TypeX[] types, DataOutputStream s) throws IOException {
int len = types.length;
s.writeShort(len);
for (int i=0; i < len; i++) {
types[i].write(s);
}
}
public static TypeX[] readArray(DataInputStream s) throws IOException {
int len = s.readShort();
TypeX[] types = new TypeX[len];
for (int i=0; i < len; i++) {
types[i] = TypeX.read(s);
}
return types;
}
/**
* For debugging purposes
*/
public void dump(World world) {
if (isAspect(world)) System.out.print("aspect ");
else if (isInterface(world)) System.out.print("interface ");
else if (isClass(world)) System.out.print("class ");
System.out.println(toString());
dumpResolvedMembers("fields", getDeclaredFields(world));
dumpResolvedMembers("methods", getDeclaredMethods(world));
dumpResolvedMembers("pointcuts", getDeclaredPointcuts(world));
}
private void dumpResolvedMembers(String label, ResolvedMember[] l) {
final String indent = " ";
System.out.println(label);
if (l == null) {
System.out.println(indent + "null");
return;
}
for (int i=0, len=l.length; i < len; i++) {
System.out.println(indent + l[i]);
}
}
// ----
public String getNameAsIdentifier() {
return getName().replace('.', '_');
}
public String getPackageNameAsIdentifier() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return "";
} else {
return name.substring(0, index).replace('.', '_');
}
}
public String getPackageName() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return null;
} else {
return name.substring(0, index);
}
}
public TypeX[] getTypeParameters() {
return typeParameters == null ? new TypeX[0] : typeParameters;
}
/**
* Doesn't include the package
*/
public String getClassName() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return name;
} else {
return name.substring(index+1);
}
}
public static final String MISSING_NAME = "<missing>";
}
|
91,053 |
Bug 91053 Generics problem with Set - does not compile with AspectJ 5
|
I tried different things to remove compiler warnings about generics which you get when you switch to JDK 5 and use collections. At last I fall back to JDK 1.4. The following code compiles with AspectJ 5 and JDK compliance level 1.4: public aspect SubjectAspect { private Set Subject.observers = new HashSet(); public void Subject.addObserver(SubjectObserver observer) { observers.add(observer); } ... } After switching to compliance level 5.0 I get an error message "The method add(E) in the type Set<E> is not applicable for the arguments (SubjectObserver)". I don't know if it is a similar problem like #87550 but I means for older projects which use collections that they can't switch to JDK 1.5
|
resolved fixed
|
952dda9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-06T15:18:54Z | 2005-04-11T20:06:40Z |
weaver/src/org/aspectj/weaver/World.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.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import org.aspectj.asm.IHierarchy;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.PerClause;
public abstract class World implements Dump.INode {
protected IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
protected ICrossReferenceHandler xrefHandler = null;
protected TypeMap typeMap = new TypeMap(); // Signature to ResolvedType
protected CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this);
protected IHierarchy model = null;
protected Lint lint = new Lint(this);
protected boolean XnoInline;
protected boolean XlazyTjp;
public boolean behaveInJava5Way = false;
private List dumpState_cantFindTypeExceptions = null;
protected World() {
super();
Dump.registerNode(this.getClass(),this);
typeMap.put("B", ResolvedTypeX.BYTE);
typeMap.put("S", ResolvedTypeX.SHORT);
typeMap.put("I", ResolvedTypeX.INT);
typeMap.put("J", ResolvedTypeX.LONG);
typeMap.put("F", ResolvedTypeX.FLOAT);
typeMap.put("D", ResolvedTypeX.DOUBLE);
typeMap.put("C", ResolvedTypeX.CHAR);
typeMap.put("Z", ResolvedTypeX.BOOLEAN);
typeMap.put("V", ResolvedTypeX.VOID);
}
public void accept (Dump.IVisitor visitor) {
visitor.visitString("Shadow mungers:");
visitor.visitList(crosscuttingMembersSet.getShadowMungers());
visitor.visitString("Type mungers:");
visitor.visitList(crosscuttingMembersSet.getTypeMungers());
if (dumpState_cantFindTypeExceptions!=null) {
visitor.visitString("Cant find type problems:");
visitor.visitList(dumpState_cantFindTypeExceptions);
dumpState_cantFindTypeExceptions = null;
}
}
public ResolvedTypeX[] resolve(TypeX[] types) {
int len = types.length;
ResolvedTypeX[] ret = new ResolvedTypeX[len];
for (int i=0; i<len; i++) {
ret[i] = resolve(types[i]);
}
return ret;
}
/**
* 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 ResolvedTypeX resolve(TypeX ty,ISourceLocation isl) {
ResolvedTypeX ret = resolve(ty,true);
if (ty == ResolvedTypeX.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;
}
public ResolvedTypeX resolve(TypeX ty) {
return resolve(ty, false);
}
public ResolvedTypeX getCoreType(TypeX tx) {
ResolvedTypeX coreTy = resolve(tx,true);
if (coreTy == ResolvedTypeX.MISSING) {
MessageUtil.error(messageHandler,
WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName()));
}
return coreTy;
}
public ResolvedTypeX resolve(TypeX ty, boolean allowMissing) {
//System.out.println("resolve: " + ty + " world " + typeMap.keySet());
String signature = ty.getSignature();
ResolvedTypeX ret = typeMap.get(signature);
if (ret != null) { ret.world = this; return ret; } // Set the world for the RTX
if (ty.isArray()) {
ret = new ResolvedTypeX.Array(signature, this, resolve(ty.getComponentType(), allowMissing));
} else {
ret = resolveObjectType(ty);
if (!allowMissing && ret == ResolvedTypeX.MISSING) {
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()));
}
}
if (ty.isParameterized()) {
for (int i = 0; i < ty.typeParameters.length; i++) {
ty.typeParameters[i] = resolve(ty.typeParameters[i],allowMissing);
}
}
//System.out.println("ret: " + ret);
typeMap.put(signature, ret);
return ret;
}
//XXX helper method might be bad
public ResolvedTypeX resolve(String name) {
return resolve(TypeX.forName(name));
}
protected final ResolvedTypeX resolveObjectType(TypeX ty) {
String signature = ty.getSignature();
if (signature.indexOf("<") != -1) {
// extract the raw type...
// XXX - might need to do more in the future to propagate full parameterized info...
signature = signature.substring(0,signature.indexOf("<"));
}
ResolvedTypeX.Name name = new ResolvedTypeX.Name(signature, this);
ResolvedTypeX.ConcreteName concreteName = resolveObjectType(name);
if (concreteName == null) return ResolvedTypeX.MISSING;
name.setDelegate(concreteName);
return name;
}
protected abstract ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty);
protected final boolean isCoerceableFrom(TypeX type, TypeX other) {
return resolve(type).isCoerceableFrom(other);
}
protected final boolean isAssignableFrom(TypeX type, TypeX other) {
return resolve(type).isAssignableFrom(resolve(other));
}
public boolean needsNoConversionFrom(TypeX type, TypeX other) {
return resolve(type).needsNoConversionFrom(other);
}
protected final boolean isInterface(TypeX type) {
return resolve(type).isInterface();
}
protected final ResolvedTypeX getSuperclass(TypeX type) {
return resolve(type).getSuperclass();
}
protected final TypeX[] getDeclaredInterfaces(TypeX type) {
return resolve(type).getDeclaredInterfaces();
}
protected final int getModifiers(TypeX type) {
return resolve(type).getModifiers();
}
protected final ResolvedMember[] getDeclaredFields(TypeX type) {
return resolve(type).getDeclaredFields();
}
protected final ResolvedMember[] getDeclaredMethods(TypeX type) {
return resolve(type).getDeclaredMethods();
}
protected final ResolvedMember[] getDeclaredPointcuts(TypeX type) {
return resolve(type).getDeclaredPointcuts();
}
// ---- members
// XXX should we worry about dealing with context and looking up access?
public ResolvedMember resolve(Member member) {
ResolvedTypeX declaring = member.getDeclaringType().resolve(this);
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);
}
protected int getModifiers(Member member) {
ResolvedMember r = resolve(member);
if (r == null) throw new BCException("bad resolve of " + member);
return r.getModifiers();
}
protected String[] getParameterNames(Member member) {
return resolve(member).getParameterNames();
}
protected TypeX[] getExceptions(Member member) {
return resolve(member).getExceptions();
}
// ---- pointcuts
public ResolvedPointcutDefinition findPointcut(TypeX typeX, String name) {
throw new RuntimeException("not implemented yet");
}
/**
* Get the shadow mungers of this world.
*
* @return a list of {@link IShadowMunger}s appropriate for this world.
*/
//public abstract List getShadowMungers();
// ---- empty world
// public static final World EMPTY = new World() {
// public List getShadowMungers() { return Collections.EMPTY_LIST; }
// public ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty) {
// return null;
// }
// public Advice concreteAdvice(AjAttribute.AdviceAttribute attribute, Pointcut p, Member m) {
// throw new RuntimeException("unimplemented");
// }
// public ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType) {
// throw new RuntimeException("unimplemented");
// }
// };
public abstract Advice concreteAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature);
public final Advice concreteAdvice(
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 concreteAdvice(attribute, p, signature);
}
public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) {
throw new RuntimeException("unimplemented");
}
public ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField) {
throw new RuntimeException("unimplemented");
}
/**
* Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed
* @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedTypeX, org.aspectj.weaver.patterns.PerClause.Kind)
*
* @param aspect
* @param kind
* @return
*/
public ConcreteTypeMunger makePerClauseAspect(ResolvedTypeX aspect, PerClause.Kind kind) {
throw new RuntimeException("unimplemented");
}
public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType);
/**
* Nobody should hold onto a copy of this message handler, or setMessageHandler won't
* work right.
*/
public IMessageHandler getMessageHandler() {
return messageHandler;
}
public void setMessageHandler(IMessageHandler messageHandler) {
this.messageHandler = messageHandler;
}
public void setXRefHandler(ICrossReferenceHandler xrefHandler) {
this.xrefHandler = xrefHandler;
}
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 addDeclare(ResolvedTypeX onType, Declare declare, boolean forWeaving) {
// // this is not extensible, oh well
// if (declare instanceof DeclareErrorOrWarning) {
// ShadowMunger m = new Checker((DeclareErrorOrWarning)declare);
// onType.addShadowMunger(m);
// } else if (declare instanceof DeclareDominates) {
// declareDominates.add(declare);
// } else if (declare instanceof DeclareParents) {
// declareParents.add(declare);
// } else if (declare instanceof DeclareSoft) {
// DeclareSoft d = (DeclareSoft)declare;
// declareSoft.add(d);
// if (forWeaving) {
// ShadowMunger m = Advice.makeSoftener(this, d.getPointcut().concretize(onType, 0), d.getException());
// onType.addShadowMunger(m);
// }
// } else {
// throw new RuntimeException("unimplemented");
// }
// }
/**
* Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
*/
public int compareByDominates(ResolvedTypeX aspect1, ResolvedTypeX aspect2) {
//System.out.println("dom compare: " + aspect1 + " with " + aspect2);
//System.out.println(crosscuttingMembersSet.getDeclareDominates());
//??? We probably want to cache this result. This is order N where N is the
//??? number of dominates declares in the whole system.
//??? This method can be called a large number of times.
int order = 0;
DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering
for (Iterator i = crosscuttingMembersSet.getDeclareDominates().iterator(); i.hasNext(); ) {
DeclarePrecedence d = (DeclarePrecedence)i.next();
int thisOrder = d.compare(aspect1, aspect2);
//System.out.println("comparing: " + thisOrder + ": " + d);
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: "+
aspect1.getName()+" and "+aspect2.getName(),null,true,isls);
messageHandler.handleMessage(m);
// throw new BCException("conflicting dominates orders"+d.getSourceLocation());
} else {
order = thisOrder;
}
}
}
return order;
}
public int comparePrecedence(ResolvedTypeX aspect1, ResolvedTypeX aspect2) {
//System.err.println("compare precedence " + aspect1 + ", " + aspect2);
if (aspect1.equals(aspect2)) return 0;
int ret = compareByDominates(aspect1, aspect2);
if (ret != 0) return ret;
if (aspect1.isAssignableFrom(aspect2)) return -1;
else if (aspect2.isAssignableFrom(aspect1)) return +1;
return 0;
}
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 ResolvedTypeX.Name lookupOrCreateName(TypeX ty) {
String signature = ty.getSignature();
ResolvedTypeX.Name ret = (ResolvedTypeX.Name)typeMap.get(signature);
if (ret == null) {
ret = new ResolvedTypeX.Name(signature, this);
typeMap.put(signature, ret);
}
return ret;
}
// public void clearUnexposed() {
// List toRemove = new ArrayList();
// for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) {
// String sig = (String) iter.next();
// ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig);
// if (!x.isExposedToWeaver() && (!x.isPrimitive())) toRemove.add(sig);
// }
// for (Iterator iter = toRemove.iterator(); iter.hasNext();) {
// typeMap.remove(iter.next());
// }
// }
//
// // for testing...
// public void dumpTypeMap() {
// int exposed = 0;
// for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) {
// String sig = (String) iter.next();
// ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig);
// if (x.isExposedToWeaver()) exposed++;
// }
// System.out.println("type map contains " + typeMap.size() + " entries, " + exposed + " exposed to weaver");
// }
//
// public void deepDumpTypeMap() {
// for (Iterator iter = typeMap.keySet().iterator(); iter.hasNext();) {
// String sig = (String) iter.next();
// ResolvedTypeX x = (ResolvedTypeX) typeMap.get(sig);
// if (! (x instanceof ResolvedTypeX.Name)) {
// System.out.println(sig + " -> " + x.getClass().getName() + ", " + x.getClassName());
// } else {
// ResolvedTypeX.ConcreteName cname = ((ResolvedTypeX.Name)x).getDelegate();
// System.out.println(sig + " -> " + cname.getClass().getName() + ", " + cname.toString());
// }
// }
//
// }
// Map of types in the world, with soft links to expendable ones
protected static class TypeMap {
private Map tMap = new HashMap();
private Map expendableMap = new WeakHashMap();
public ResolvedTypeX put(String key, ResolvedTypeX type) {
if (isExpendable(type)) {
return (ResolvedTypeX) expendableMap.put(key,type);
} else {
return (ResolvedTypeX) tMap.put(key,type);
}
}
public ResolvedTypeX get(String key) {
ResolvedTypeX ret = (ResolvedTypeX) tMap.get(key);
if (ret == null) ret = (ResolvedTypeX) expendableMap.get(key);
return ret;
}
public ResolvedTypeX remove(String key) {
ResolvedTypeX ret = (ResolvedTypeX) tMap.remove(key);
if (ret == null) ret = (ResolvedTypeX) expendableMap.remove(key);
return ret;
}
private boolean isExpendable(ResolvedTypeX type) {
return (
(type != null) &&
(!type.isExposedToWeaver()) &&
(!type.isPrimitive())
);
}
}
public void setBehaveInJava5Way(boolean b) {
behaveInJava5Way = b;
}
}
|
87,282 |
Bug 87282 Compilation error on generic member introduction
|
The compiler aborts with the following introduction code: aspect introductionToA{ private ArrayList<B> A.m_Array = new ArrayList<B>(); public void A.addB(B tmp){ m_Array.add(tmp); } } The error message is "[error] The method add(E) in the type ArrayList<E> is not applicable for the arguments (B) m_Array.add(tmp)" Compiling with AspectJ Development version (2005/02/18).
|
resolved fixed
|
51c018d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-06T15:42:28Z | 2005-03-07T15:40:00Z |
tests/src/org/aspectj/systemtest/ajc150/GenericsTests.java
|
package org.aspectj.systemtest.ajc150;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class GenericsTests extends XMLBasedAjcTestCase {
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 testPR91267_2() {
runTest("NPE using generic methods in aspects 2");
}
public void testPR91053() {
runTest("Generics problem with Set");
}
}
|
93,345 |
Bug 93345 unresolved joinpoint in cflow causes ClassCastException on BcelWeaver:933
|
I'm getting ClassCastException while compiling following code: ---- Test.java ---- class AClass { // void method() {} } aspect AnAspect { pointcut annt() : cflow( execution(* *(..)) ); before() : annt() { System.out.println("before annt"); } } ---- Here's output of the compiler: --- out --- java.lang.ClassCastException: org.aspectj.weaver.ResolvedMember at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:933) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:244) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:119) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:385) [cut] ------ The problem is caused by cflow on unresolved (not existing) jointpoint. When you uncomment the method() in AnClass, the problem disappears. I found this bug when I was introducing an aspect (which has pointcuts based on annotations) to fresh object-oriented system without annotated classes. When I started to annotate the classes problem disappeared. Following code illustates (simplified) situation: --- Test2.java --- import java.lang.annotation.*; @Target(ElementType.METHOD) @interface Ann {} class AClass { // @Ann void method() {} } aspect AnAspect { pointcut annt() : cflow( execution(@Ann * *(..)) ); before() : annt() { System.out.println("before annt"); } } ---- I'm attaching those sources and ajcore files. Best regards, Michal
|
resolved fixed
|
f603458
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-09T11:08:28Z | 2005-04-30T14:06:40Z |
tests/src/org/aspectj/systemtest/ajc150/AllTestsAspectJ150.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 org.aspectj.systemtest.ajc150.ataspectj.AtAjSyntaxTests;
import org.aspectj.systemtest.ajc150.ataspectj.AtAjMisuseTests;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* This pulls together tests we have written for AspectJ 1.5.0 that don't need Java 1.5 to run
*/
public class AllTestsAspectJ150 {
public static Test suite() {
TestSuite suite = new TestSuite("Java5/AspectJ5 tests");
//$JUnit-BEGIN$
suite.addTestSuite(MigrationTests.class);
suite.addTest(Ajc150Tests.suite());
suite.addTestSuite(SCCSFixTests.class);
suite.addTest(AccBridgeMethods.suite());
suite.addTestSuite(CovarianceTests.class);
suite.addTestSuite(Enums.class);
suite.addTest(AnnotationsBinaryWeaving.suite());
suite.addTest(AnnotationPointcutsTests.suite());
suite.addTestSuite(VarargsTests.class);
suite.addTest(AnnotationRuntimeTests.suite());
suite.addTestSuite(PerTypeWithinTests.class);
suite.addTest(Autoboxing.suite());
suite.addTest(Annotations.suite());
suite.addTest(AnnotationBinding.suite());
suite.addTest(SuppressedWarnings.suite());
suite.addTest(DeclareAnnotationTests.suite());
suite.addTest(GenericsTests.suite());
suite.addTest(AtAjSyntaxTests.suite());
suite.addTest(AtAjMisuseTests.suite());
//$JUnit-END$
return suite;
}
}
|
93,345 |
Bug 93345 unresolved joinpoint in cflow causes ClassCastException on BcelWeaver:933
|
I'm getting ClassCastException while compiling following code: ---- Test.java ---- class AClass { // void method() {} } aspect AnAspect { pointcut annt() : cflow( execution(* *(..)) ); before() : annt() { System.out.println("before annt"); } } ---- Here's output of the compiler: --- out --- java.lang.ClassCastException: org.aspectj.weaver.ResolvedMember at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:933) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:244) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:119) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:385) [cut] ------ The problem is caused by cflow on unresolved (not existing) jointpoint. When you uncomment the method() in AnClass, the problem disappears. I found this bug when I was introducing an aspect (which has pointcuts based on annotations) to fresh object-oriented system without annotated classes. When I started to annotate the classes problem disappeared. Following code illustates (simplified) situation: --- Test2.java --- import java.lang.annotation.*; @Target(ElementType.METHOD) @interface Ann {} class AClass { // @Ann void method() {} } aspect AnAspect { pointcut annt() : cflow( execution(@Ann * *(..)) ); before() : annt() { System.out.println("before annt"); } } ---- I'm attaching those sources and ajcore files. Best regards, Michal
|
resolved fixed
|
f603458
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-09T11:08:28Z | 2005-04-30T14:06:40Z |
tests/src/org/aspectj/systemtest/ajc150/StaticImports.java
| |
93,345 |
Bug 93345 unresolved joinpoint in cflow causes ClassCastException on BcelWeaver:933
|
I'm getting ClassCastException while compiling following code: ---- Test.java ---- class AClass { // void method() {} } aspect AnAspect { pointcut annt() : cflow( execution(* *(..)) ); before() : annt() { System.out.println("before annt"); } } ---- Here's output of the compiler: --- out --- java.lang.ClassCastException: org.aspectj.weaver.ResolvedMember at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:933) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:244) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:119) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:385) [cut] ------ The problem is caused by cflow on unresolved (not existing) jointpoint. When you uncomment the method() in AnClass, the problem disappears. I found this bug when I was introducing an aspect (which has pointcuts based on annotations) to fresh object-oriented system without annotated classes. When I started to annotate the classes problem disappeared. Following code illustates (simplified) situation: --- Test2.java --- import java.lang.annotation.*; @Target(ElementType.METHOD) @interface Ann {} class AClass { // @Ann void method() {} } aspect AnAspect { pointcut annt() : cflow( execution(@Ann * *(..)) ); before() : annt() { System.out.println("before annt"); } } ---- I'm attaching those sources and ajcore files. Best regards, Michal
|
resolved fixed
|
f603458
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-09T11:08:28Z | 2005-04-30T14:06:40Z |
tests/src/org/aspectj/systemtest/ajc150/SuppressedWarnings.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class SuppressedWarnings extends XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(SuppressedWarnings.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
// Check basic suppression
public void testSuppression1() {
runTest("suppressing non-matching advice warnings");
}
// Checks source contexts aren't put out incorrectly
// NOTE: Source contexts only come out if the primary source location in a message
// matches the file currently being dealt with. Because advice not matching
// messages come out at the last stage of compilation, you currently only
// get sourcecontext for advice not matching messages that point to places in
// the last file being processed. You do get source locations in all cases -
// you just don't always get context, we could revisit this sometime...
// (see bug 62073 reference in WeaverMessageHandler.handleMessage())
public void testSuppression2() {
runTest("suppressing non-matching advice warnings when multiple source files involved");
}
}
|
93,345 |
Bug 93345 unresolved joinpoint in cflow causes ClassCastException on BcelWeaver:933
|
I'm getting ClassCastException while compiling following code: ---- Test.java ---- class AClass { // void method() {} } aspect AnAspect { pointcut annt() : cflow( execution(* *(..)) ); before() : annt() { System.out.println("before annt"); } } ---- Here's output of the compiler: --- out --- java.lang.ClassCastException: org.aspectj.weaver.ResolvedMember at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:933) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:244) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:119) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:385) [cut] ------ The problem is caused by cflow on unresolved (not existing) jointpoint. When you uncomment the method() in AnClass, the problem disappears. I found this bug when I was introducing an aspect (which has pointcuts based on annotations) to fresh object-oriented system without annotated classes. When I started to annotate the classes problem disappeared. Following code illustates (simplified) situation: --- Test2.java --- import java.lang.annotation.*; @Target(ElementType.METHOD) @interface Ann {} class AClass { // @Ann void method() {} } aspect AnAspect { pointcut annt() : cflow( execution(@Ann * *(..)) ); before() : annt() { System.out.println("before annt"); } } ---- I'm attaching those sources and ajcore files. Best regards, Michal
|
resolved fixed
|
f603458
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-09T11:08:28Z | 2005-04-30T14:06:40Z |
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.jar.Attributes.Name;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.util.FileUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AnnotationOnTypeMunger;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.CrosscuttingMembersSet;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.IWeaver;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverMetrics;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.BindingAnnotationTypePattern;
import org.aspectj.weaver.patterns.BindingTypePattern;
import org.aspectj.weaver.patterns.CflowPointcut;
import org.aspectj.weaver.patterns.ConcreteCflowPointcut;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.FastMatchInfo;
import org.aspectj.weaver.patterns.IfPointcut;
import org.aspectj.weaver.patterns.KindedPointcut;
import org.aspectj.weaver.patterns.NameBindingPointcut;
import org.aspectj.weaver.patterns.NotPointcut;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.PointcutRewriter;
import org.aspectj.weaver.patterns.WithinPointcut;
public class BcelWeaver implements IWeaver {
private BcelWorld world;
private CrosscuttingMembersSet xcutSet;
private IProgressListener progressListener = null;
private double progressMade;
private double progressPerClassFile;
private boolean inReweavableMode = false;
public BcelWeaver(BcelWorld world) {
super();
WeaverMetrics.reset();
this.world = world;
this.xcutSet = world.getCrosscuttingMembersSet();
}
public BcelWeaver() {
this(new BcelWorld());
}
// ---- fields
// private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */
private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */
private List deletedTypenames = new ArrayList(); /* List<String> */
// private Map resources = new HashMap(); /* String -> UnwovenClassFile */
private Manifest manifest = null;
private boolean needToReweaveWorld = false;
private List shadowMungerList = null; // setup by prepareForWeave
private List typeMungerList = null; // setup by prepareForWeave
private List declareParentsList = null; // setup by prepareForWeave
private ZipOutputStream zipOutputStream;
// ----
// only called for testing
public void setShadowMungers(List l) {
shadowMungerList = l;
}
/**
* Add the given aspect to the weaver.
* The type is resolved to support DOT for static inner classes as well as DOLLAR
*
* @param aspectName
*/
public void addLibraryAspect(String aspectName) {
// 1 - resolve as is
ResolvedTypeX type = world.resolve(TypeX.forName(aspectName), true);
if (type.equals(ResolvedTypeX.MISSING)) {
// fallback on inner class lookup mechanism
String fixedName = aspectName;
int hasDot = fixedName.lastIndexOf('.');
while (hasDot > 0) {
//System.out.println("BcelWeaver.addLibraryAspect " + fixedName);
char[] fixedNameChars = fixedName.toCharArray();
fixedNameChars[hasDot] = '$';
fixedName = new String(fixedNameChars);
hasDot = fixedName.lastIndexOf('.');
type = world.resolve(TypeX.forName(fixedName), true);
if (!type.equals(ResolvedTypeX.MISSING)) {
break;
}
}
}
//System.out.println("type: " + type + " for " + aspectName);
if (type.isAspect()) {
xcutSet.addOrReplaceAspect(type);
} else {
// FIXME : Alex: better warning upon no such aspect from aop.xml
throw new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName);
}
}
public void addLibraryJarFile(File inFile) throws IOException {
List addedAspects = null;
if (inFile.isDirectory()) {
addedAspects = addAspectsFromDirectory(inFile);
} else {
addedAspects = addAspectsFromJarFile(inFile);
}
for (Iterator i = addedAspects.iterator(); i.hasNext();) {
ResolvedTypeX aspectX = (ResolvedTypeX) i.next();
xcutSet.addOrReplaceAspect(aspectX);
}
}
private List addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException {
ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered
List addedAspects = new ArrayList();
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
continue;
}
// FIXME ASC performance? of this alternative soln.
ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName());
JavaClass jc = parser.parse();
inStream.closeEntry();
ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX();
if (type.isAspect()) {
addedAspects.add(type);
}
}
inStream.close();
return addedAspects;
}
private List addAspectsFromDirectory(File dir) throws FileNotFoundException, IOException{
List addedAspects = new ArrayList();
File[] classFiles = FileUtil.listFiles(dir,new FileFilter(){
public boolean accept(File pathname) {
return pathname.getName().endsWith(".class");
}
});
for (int i = 0; i < classFiles.length; i++) {
FileInputStream fis = new FileInputStream(classFiles[i]);
byte[] bytes = FileUtil.readAsByteArray(fis);
addIfAspect(bytes,classFiles[i].getAbsolutePath(),addedAspects);
}
return addedAspects;
}
private void addIfAspect(byte[] bytes, String name, List toList) throws IOException {
ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes),name);
JavaClass jc = parser.parse();
ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX();
if (type.isAspect()) {
toList.add(type);
}
}
// // The ANT copy task should be used to copy resources across.
// private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false;
private Set alreadyConfirmedReweavableState;
/**
* Add any .class files in the directory to the outdir. Anything other than .class files in
* the directory (or its subdirectories) are considered resources and are also copied.
*
*/
public List addDirectoryContents(File inFile,File outDir) throws IOException {
List addedClassFiles = new ArrayList();
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(inFile,new FileFilter() {
public boolean accept(File f) {
boolean accept = !f.isDirectory();
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
addedClassFiles.add(addClassFile(files[i],inFile,outDir));
}
return addedClassFiles;
}
/** Adds all class files in the jar
*/
public List addJarFile(File inFile, File outDir, boolean canBeDirectory){
// System.err.println("? addJarFile(" + inFile + ", " + outDir + ")");
List addedClassFiles = new ArrayList();
needToReweaveWorld = true;
JarFile inJar = null;
try {
// Is this a directory we are looking at?
if (inFile.isDirectory() && canBeDirectory) {
addedClassFiles.addAll(addDirectoryContents(inFile,outDir));
} else {
inJar = new JarFile(inFile);
addManifest(inJar.getManifest());
Enumeration entries = inJar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = (JarEntry)entries.nextElement();
InputStream inStream = inJar.getInputStream(entry);
byte[] bytes = FileUtil.readAsByteArray(inStream);
String filename = entry.getName();
// System.out.println("? addJarFile() filename='" + filename + "'");
UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes);
if (filename.endsWith(".class")) {
this.addClassFile(classFile);
addedClassFiles.add(classFile);
}
// else if (!entry.isDirectory()) {
//
// /* bug-44190 Copy meta-data */
// addResource(filename,classFile);
// }
inStream.close();
}
inJar.close();
}
} catch (FileNotFoundException ex) {
IMessage message = new Message(
"Could not find input jar file " + inFile.getPath() + ", ignoring",
new SourceLocation(inFile,0),
false);
world.getMessageHandler().handleMessage(message);
} catch (IOException ex) {
IMessage message = new Message(
"Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
new SourceLocation(inFile,0),
true);
world.getMessageHandler().handleMessage(message);
} finally {
if (inJar != null) {
try {inJar.close();}
catch (IOException ex) {
IMessage message = new Message(
"Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
new SourceLocation(inFile,0),
true);
world.getMessageHandler().handleMessage(message);
}
}
}
return addedClassFiles;
}
// public void addResource(String name, File inPath, File outDir) throws IOException {
//
// /* Eliminate CVS files. Relative paths use "/" */
// if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
//// System.err.println("? addResource('" + name + "')");
//// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath));
//// byte[] bytes = new byte[(int)inPath.length()];
//// inStream.read(bytes);
//// inStream.close();
// byte[] bytes = FileUtil.readAsByteArray(inPath);
// UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes);
// addResource(name,resourceFile);
// }
// }
public boolean needToReweaveWorld() {
return needToReweaveWorld;
}
/** Should be addOrReplace
*/
public void addClassFile(UnwovenClassFile classFile) {
addedClasses.add(classFile);
// if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) {
//// throw new RuntimeException(classFile.getClassName());
// }
world.addSourceObjectType(classFile.getJavaClass());
}
public UnwovenClassFile addClassFile(File classFile, File inPathDir, File outDir) throws IOException {
FileInputStream fis = new FileInputStream(classFile);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = classFile.getAbsolutePath().substring(
inPathDir.getAbsolutePath().length()+1);
UnwovenClassFile ucf = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes);
if (filename.endsWith(".class")) {
// System.err.println("BCELWeaver: processing class from input directory "+classFile);
this.addClassFile(ucf);
}
fis.close();
return ucf;
}
public void deleteClassFile(String typename) {
deletedTypenames.add(typename);
// sourceJavaClasses.remove(typename);
world.deleteSourceObjectType(TypeX.forName(typename));
}
// public void addResource (String name, UnwovenClassFile resourceFile) {
// /* bug-44190 Change error to warning and copy first resource */
// if (!resources.containsKey(name)) {
// resources.put(name, resourceFile);
// }
// else {
// world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'",
// null, null);
// }
// }
// ---- weave preparation
public void prepareForWeave() {
needToReweaveWorld = false;
CflowPointcut.clearCaches();
// update mungers
for (Iterator i = addedClasses.iterator(); i.hasNext(); ) {
UnwovenClassFile jc = (UnwovenClassFile)i.next();
String name = jc.getClassName();
ResolvedTypeX type = world.resolve(name);
//System.err.println("added: " + type + " aspect? " + type.isAspect());
if (type.isAspect()) {
needToReweaveWorld |= xcutSet.addOrReplaceAspect(type);
}
}
for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) {
String name = (String)i.next();
if (xcutSet.deleteAspect(TypeX.forName(name))) needToReweaveWorld = true;
}
shadowMungerList = xcutSet.getShadowMungers();
rewritePointcuts(shadowMungerList);
typeMungerList = xcutSet.getTypeMungers();
declareParentsList = xcutSet.getDeclareParents();
// The ordering here used to be based on a string compare on toString() for the two mungers -
// that breaks for the @AJ style where advice names aren't programmatically generated. So we
// have changed the sorting to be based on source location in the file - this is reliable, in
// the case of source locations missing, we assume they are 'sorted' - i.e. the order in
// which they were added to the collection is correct, this enables the @AJ stuff to work properly.
// When @AJ processing starts filling in source locations for mungers, this code may need
// a bit of alteration...
Collections.sort(
shadowMungerList,
new Comparator() {
public int compare(Object o1, Object o2) {
ShadowMunger sm1 = (ShadowMunger)o1;
ShadowMunger sm2 = (ShadowMunger)o2;
if (sm1.getSourceLocation()==null) return (sm2.getSourceLocation()==null?0:1);
if (sm2.getSourceLocation()==null) return -1;
return (sm2.getSourceLocation().getOffset()-sm1.getSourceLocation().getOffset());
}
});
}
/*
* Rewrite all of the pointcuts in the world into their most efficient
* form for subsequent matching. Also ensure that if pc1.equals(pc2)
* then pc1 == pc2 (for non-binding pcds) by making references all
* point to the same instance.
* Since pointcuts remember their match decision on the last shadow,
* this makes matching faster when many pointcuts share common elements,
* or even when one single pointcut has one common element (which can
* be a side-effect of DNF rewriting).
*/
private void rewritePointcuts(List/*ShadowMunger*/ shadowMungers) {
PointcutRewriter rewriter = new PointcutRewriter();
for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
Pointcut p = munger.getPointcut();
Pointcut newP = rewriter.rewrite(p);
// validateBindings now whilst we still have around the pointcut
// that resembles what the user actually wrote in their program
// text.
if (munger instanceof Advice) {
Advice advice = (Advice) munger;
if (advice.getSignature() != null) {
final int numFormals;
final String names[];
//ATAJ for @AJ aspect, the formal have to be checked according to the argument number
// since xxxJoinPoint presence or not have side effects
if (advice.getConcreteAspect().isAnnotationStyleAspect()) {
numFormals = advice.getBaseParameterCount();
int numArgs = advice.getSignature().getParameterTypes().length;
if (numFormals > 0) {
names = advice.getSignature().getParameterNames(world);
validateBindings(newP,p,numArgs,names);
}
} else {
numFormals = advice.getBaseParameterCount();
if (numFormals > 0) {
names = advice.getBaseParameterNames(world);
validateBindings(newP,p,numFormals,names);
}
}
}
}
munger.setPointcut(newP);
}
// now that we have optimized individual pointcuts, optimize
// across the set of pointcuts....
// Use a map from key based on pc equality, to value based on
// pc identity.
Map/*<Pointcut,Pointcut>*/ pcMap = new HashMap();
for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
Pointcut p = munger.getPointcut();
munger.setPointcut(shareEntriesFromMap(p,pcMap));
}
}
private Pointcut shareEntriesFromMap(Pointcut p,Map pcMap) {
// some things cant be shared...
if (p instanceof NameBindingPointcut) return p;
if (p instanceof IfPointcut) return p;
if (p instanceof ConcreteCflowPointcut) return p;
if (p instanceof AndPointcut) {
AndPointcut apc = (AndPointcut) p;
Pointcut left = shareEntriesFromMap(apc.getLeft(),pcMap);
Pointcut right = shareEntriesFromMap(apc.getRight(),pcMap);
return new AndPointcut(left,right);
} else if (p instanceof OrPointcut) {
OrPointcut opc = (OrPointcut) p;
Pointcut left = shareEntriesFromMap(opc.getLeft(),pcMap);
Pointcut right = shareEntriesFromMap(opc.getRight(),pcMap);
return new OrPointcut(left,right);
} else if (p instanceof NotPointcut) {
NotPointcut npc = (NotPointcut) p;
Pointcut not = shareEntriesFromMap(npc.getNegatedPointcut(),pcMap);
return new NotPointcut(not);
} else {
// primitive pcd
if (pcMap.containsKey(p)) { // based on equality
return (Pointcut) pcMap.get(p); // same instance (identity)
} else {
pcMap.put(p,p);
return p;
}
}
}
// userPointcut is the pointcut that the user wrote in the program text.
// dnfPointcut is the same pointcut rewritten in DNF
// numFormals is the number of formal parameters in the pointcut
// if numFormals > 0 then every branch of a disjunction must bind each formal once and only once.
// in addition, the left and right branches of a disjunction must hold on join point kinds in
// common.
private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) {
if (numFormals == 0) return; // nothing to check
if (dnfPointcut.couldMatchKinds().isEmpty()) return; // cant have problems if you dont match!
if (dnfPointcut instanceof OrPointcut) {
OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut;
Pointcut[] leftBindings = new Pointcut[numFormals];
Pointcut[] rightBindings = new Pointcut[numFormals];
validateOrBranch(orBasedDNFPointcut,userPointcut,numFormals,names,leftBindings,rightBindings);
} else {
Pointcut[] bindings = new Pointcut[numFormals];
validateSingleBranch(dnfPointcut, userPointcut, numFormals, names,bindings);
}
}
private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals,
String[] names, Pointcut[] leftBindings, Pointcut[] rightBindings) {
Pointcut left = pc.getLeft();
Pointcut right = pc.getRight();
if (left instanceof OrPointcut) {
Pointcut[] newRightBindings = new Pointcut[numFormals];
validateOrBranch((OrPointcut)left,userPointcut,numFormals,names,leftBindings,newRightBindings);
} else {
if (left.couldMatchKinds().size() > 0)
validateSingleBranch(left, userPointcut, numFormals, names, leftBindings);
}
if (right instanceof OrPointcut) {
Pointcut[] newLeftBindings = new Pointcut[numFormals];
validateOrBranch((OrPointcut)right,userPointcut,numFormals,names,newLeftBindings,rightBindings);
} else {
if (right.couldMatchKinds().size() > 0)
validateSingleBranch(right, userPointcut, numFormals, names, rightBindings);
}
Set kindsInCommon = left.couldMatchKinds();
kindsInCommon.retainAll(right.couldMatchKinds());
if (!kindsInCommon.isEmpty() && couldEverMatchSameJoinPoints(left,right)) {
// we know that every branch binds every formal, so there is no ambiguity
// if each branch binds it in exactly the same way...
List ambiguousNames = new ArrayList();
for (int i = 0; i < numFormals; i++) {
if (!leftBindings[i].equals(rightBindings[i])) {
ambiguousNames.add(names[i]);
}
}
if (!ambiguousNames.isEmpty())
raiseAmbiguityInDisjunctionError(userPointcut,ambiguousNames);
}
}
// pc is a pointcut that does not contain any disjunctions
// check that every formal is bound (negation doesn't count).
// we know that numFormals > 0 or else we would not be called
private void validateSingleBranch(Pointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] bindings) {
boolean[] foundFormals = new boolean[numFormals];
for (int i = 0; i < foundFormals.length; i++) {
foundFormals[i] = false;
}
validateSingleBranchRecursion(pc, userPointcut, foundFormals, names, bindings);
for (int i = 0; i < foundFormals.length; i++) {
if (!foundFormals[i]) {
boolean ignore = false;
// ATAJ soften the unbound error for implicit bindings like JoinPoint in @AJ style
for (int j = 0; j < userPointcut.m_ignoreUnboundBindingForNames.length; j++) {
if (names[i] != null && names[i].equals(userPointcut.m_ignoreUnboundBindingForNames[j])) {
ignore = true;
break;
}
}
if (!ignore) {
raiseUnboundFormalError(names[i],userPointcut);
}
}
}
}
// each formal must appear exactly once
private void validateSingleBranchRecursion(Pointcut pc, Pointcut userPointcut, boolean[] foundFormals, String[] names, Pointcut[] bindings) {
if (pc instanceof NotPointcut) {
// nots can only appear at leaves in DNF
NotPointcut not = (NotPointcut) pc;
if (not.getNegatedPointcut() instanceof NameBindingPointcut) {
NameBindingPointcut nnbp = (NameBindingPointcut) not.getNegatedPointcut();
if (!nnbp.getBindingAnnotationTypePatterns().isEmpty() && !nnbp.getBindingTypePatterns().isEmpty())
raiseNegationBindingError(userPointcut);
}
} else if (pc instanceof AndPointcut) {
AndPointcut and = (AndPointcut) pc;
validateSingleBranchRecursion(and.getLeft(), userPointcut,foundFormals,names,bindings);
validateSingleBranchRecursion(and.getRight(),userPointcut,foundFormals,names,bindings);
} else if (pc instanceof NameBindingPointcut) {
List/*BindingTypePattern*/ btps = ((NameBindingPointcut)pc).getBindingTypePatterns();
for (Iterator iter = btps.iterator(); iter.hasNext();) {
BindingTypePattern btp = (BindingTypePattern) iter.next();
int index = btp.getFormalIndex();
bindings[index] = pc;
if (foundFormals[index]) {
raiseAmbiguousBindingError(names[index],userPointcut);
} else {
foundFormals[index] = true;
}
}
List/*BindingAnnotationTypePattern*/ baps = ((NameBindingPointcut)pc).getBindingAnnotationTypePatterns();
for (Iterator iter = baps.iterator(); iter.hasNext();) {
BindingAnnotationTypePattern bap = (BindingAnnotationTypePattern) iter.next();
int index = bap.getFormalIndex();
bindings[index] = pc;
if (foundFormals[index]) {
raiseAmbiguousBindingError(names[index],userPointcut);
} else {
foundFormals[index] = true;
}
}
} else if (pc instanceof ConcreteCflowPointcut) {
ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc;
int[] slots = cfp.getUsedFormalSlots();
for (int i = 0; i < slots.length; i++) {
bindings[slots[i]] = cfp;
if (foundFormals[slots[i]]) {
raiseAmbiguousBindingError(names[slots[i]],userPointcut);
} else {
foundFormals[slots[i]] = true;
}
}
}
}
// By returning false from this method, we are allowing binding of the same
// variable on either side of an or.
// Be conservative :- have to consider overriding, varargs, autoboxing,
// the effects of itds (on within for example), interfaces, the fact that
// join points can have multiple signatures and so on.
private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) {
if ((left instanceof OrPointcut) || (right instanceof OrPointcut)) return true;
// look for withins
WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left,WithinPointcut.class);
WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right,WithinPointcut.class);
if ((leftWithin != null) && (rightWithin != null)) {
if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) return false;
}
// look for kinded
KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left,KindedPointcut.class);
KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right,KindedPointcut.class);
if ((leftKind != null) && (rightKind != null)) {
if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) return false;
}
return true;
}
private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) {
if (toSearch instanceof NotPointcut) return null;
if (toLookFor.isInstance(toSearch)) return toSearch;
if (toSearch instanceof AndPointcut) {
AndPointcut apc = (AndPointcut) toSearch;
Pointcut left = findFirstPointcutIn(apc.getLeft(),toLookFor);
if (left != null) return left;
return findFirstPointcutIn(apc.getRight(),toLookFor);
}
return null;
}
/**
* @param userPointcut
*/
private void raiseNegationBindingError(Pointcut userPointcut) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING),
userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
}
/**
* @param name
* @param userPointcut
*/
private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING,
name),
userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
}
/**
* @param userPointcut
*/
private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List names) {
StringBuffer formalNames = new StringBuffer(names.get(0).toString());
for (int i = 1; i < names.size(); i++) {
formalNames.append(", ");
formalNames.append(names.get(i));
}
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING_IN_OR,formalNames),
userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
}
/**
* @param name
* @param userPointcut
*/
private void raiseUnboundFormalError(String name, Pointcut userPointcut) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.UNBOUND_FORMAL,
name),
userPointcut.getSourceContext().makeSourceLocation(userPointcut),null);
}
// public void dumpUnwoven(File file) throws IOException {
// BufferedOutputStream os = FileUtil.makeOutputStream(file);
// this.zipOutputStream = new ZipOutputStream(os);
// dumpUnwoven();
// /* BUG 40943*/
// dumpResourcesToOutJar();
// zipOutputStream.close(); //this flushes and closes the acutal file
// }
//
//
// public void dumpUnwoven() throws IOException {
// Collection filesToDump = new HashSet(sourceJavaClasses.values());
// for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// dumpUnchanged(classFile);
// }
// }
// public void dumpResourcesToOutPath() throws IOException {
//// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet());
// Iterator i = resources.keySet().iterator();
// while (i.hasNext()) {
// UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next());
// dumpUnchanged(res);
// }
// //resources = new HashMap();
// }
//
/* BUG #40943 */
// public void dumpResourcesToOutJar() throws IOException {
//// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet());
// Iterator i = resources.keySet().iterator();
// while (i.hasNext()) {
// String name = (String)i.next();
// UnwovenClassFile res = (UnwovenClassFile)resources.get(name);
// writeZipEntry(name,res.getBytes());
// }
// resources = new HashMap();
// }
//
// // halfway house for when the jar is managed outside of the weaver, but the resources
// // to be copied are known in the weaver.
// public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException {
// this.zipOutputStream = zos;
// dumpResourcesToOutJar();
// }
public void addManifest (Manifest newManifest) {
// System.out.println("? addManifest() newManifest=" + newManifest);
if (manifest == null) {
manifest = newManifest;
}
}
public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
private static final String WEAVER_MANIFEST_VERSION = "1.0";
private static final Attributes.Name CREATED_BY = new Name("Created-By");
private static final String WEAVER_CREATED_BY = "AspectJ Compiler";
public Manifest getManifest (boolean shouldCreate) {
if (manifest == null && shouldCreate) {
manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Name.MANIFEST_VERSION,WEAVER_MANIFEST_VERSION);
attributes.put(CREATED_BY,WEAVER_CREATED_BY);
}
return manifest;
}
// ---- weaving
// Used by some test cases only...
public Collection weave(File file) throws IOException {
OutputStream os = FileUtil.makeOutputStream(file);
this.zipOutputStream = new ZipOutputStream(os);
prepareForWeave();
Collection c = weave( new IClassFileProvider() {
public Iterator getClassFileIterator() {
return addedClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(UnwovenClassFile result) {
try {
writeZipEntry(result.filename, result.bytes);
} catch(IOException ex) {}
}
public void processingReweavableState() {}
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {}
};
}
});
// /* BUG 40943*/
// dumpResourcesToOutJar();
zipOutputStream.close(); //this flushes and closes the acutal file
return c;
}
// public Collection weave() throws IOException {
// prepareForWeave();
// Collection filesToWeave;
//
// if (needToReweaveWorld) {
// filesToWeave = sourceJavaClasses.values();
// } else {
// filesToWeave = addedClasses;
// }
//
// Collection wovenClassNames = new ArrayList();
// world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave +
// "(world=" + needToReweaveWorld + ")", null, null);
//
//
// //System.err.println("typeMungers: " + typeMungerList);
//
// prepareToProcessReweavableState();
// // clear all state from files we'll be reweaving
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = getClassType(className);
// processReweavableStateIfPresent(className, classType);
// }
//
//
//
// //XXX this isn't quite the right place for this...
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// addTypeMungers(className);
// }
//
// // first weave into aspects
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
// if (classType.isAspect()) {
// weave(classFile, classType);
// wovenClassNames.add(className);
// }
// }
//
// // then weave into non-aspects
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
// if (! classType.isAspect()) {
// weave(classFile, classType);
// wovenClassNames.add(className);
// }
// }
//
// if (zipOutputStream != null && !needToReweaveWorld) {
// Collection filesToDump = new HashSet(sourceJavaClasses.values());
// filesToDump.removeAll(filesToWeave);
// for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// dumpUnchanged(classFile);
// }
// }
//
// addedClasses = new ArrayList();
// deletedTypenames = new ArrayList();
//
// return wovenClassNames;
// }
// variation of "weave" that sources class files from an external source.
public Collection weave(IClassFileProvider input) throws IOException {
Collection wovenClassNames = new ArrayList();
IWeaveRequestor requestor = input.getRequestor();
requestor.processingReweavableState();
prepareToProcessReweavableState();
// clear all state from files we'll be reweaving
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = getClassType(className);
processReweavableStateIfPresent(className, classType);
}
requestor.addingTypeMungers();
// We process type mungers in two groups, first mungers that change the type
// hierarchy, then 'normal' ITD type mungers.
// Process the types in a predictable order (rather than the order encountered).
// For class A, the order is superclasses of A then superinterfaces of A
// (and this mechanism is applied recursively)
List typesToProcess = new ArrayList();
for (Iterator iter = input.getClassFileIterator(); iter.hasNext();) {
UnwovenClassFile clf = (UnwovenClassFile) iter.next();
typesToProcess.add(clf.getClassName());
}
while (typesToProcess.size()>0) {
weaveParentsFor(typesToProcess,(String)typesToProcess.get(0));
}
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
addNormalTypeMungers(className);
}
requestor.weavingAspects();
// first weave into aspects
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
if (classType.isAspect()) {
weaveAndNotify(classFile, classType,requestor);
wovenClassNames.add(className);
}
}
requestor.weavingClasses();
// then weave into non-aspects
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
if (! classType.isAspect()) {
weaveAndNotify(classFile, classType, requestor);
wovenClassNames.add(className);
}
}
addedClasses = new ArrayList();
deletedTypenames = new ArrayList();
// if a piece of advice hasn't matched anywhere and we are in -1.5 mode, put out a warning
if (world.behaveInJava5Way &&
world.getLint().adviceDidNotMatch.isEnabled()) {
List l = world.getCrosscuttingMembersSet().getShadowMungers();
for (Iterator iter = l.iterator(); iter.hasNext();) {
ShadowMunger element = (ShadowMunger) iter.next();
if (element instanceof BcelAdvice) { // This will stop us incorrectly reporting deow Checkers
BcelAdvice ba = (BcelAdvice)element;
if (!ba.hasMatchedSomething()) {
BcelMethod meth = (BcelMethod)ba.getSignature();
if (meth!=null) {
AnnotationX[] anns = (AnnotationX[])meth.getAnnotations();
// Check if they want to suppress the warning on this piece of advice
if (!Utility.isSuppressing(anns,"adviceDidNotMatch")) {
world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(),element.getSourceLocation());
}
}
}
}
}
}
requestor.weaveCompleted();
return wovenClassNames;
}
/**
* 'typeToWeave' is one from the 'typesForWeaving' list. This routine ensures we process
* supertypes (classes/interfaces) of 'typeToWeave' that are in the
* 'typesForWeaving' list before 'typeToWeave' itself. 'typesToWeave' is then removed from
* the 'typesForWeaving' list.
*
* Note: Future gotcha in here ... when supplying partial hierarchies, this algorithm may
* break down. If you have a hierarchy A>B>C and only give A and C to the weaver, it
* may choose to weave them in either order - but you'll probably have other problems if
* you are supplying partial hierarchies like that !
*/
private void weaveParentsFor(List typesForWeaving,String typeToWeave) {
// Look at the supertype first
ResolvedTypeX rtx = world.resolve(typeToWeave);
ResolvedTypeX superType = rtx.getSuperclass();
if (superType!=null && typesForWeaving.contains(superType.getClassName())) {
weaveParentsFor(typesForWeaving,superType.getClassName());
}
// Then look at the superinterface list
ResolvedTypeX[] interfaceTypes = rtx.getDeclaredInterfaces();
for (int i = 0; i < interfaceTypes.length; i++) {
ResolvedTypeX rtxI = interfaceTypes[i];
if (typesForWeaving.contains(rtxI.getClassName())) {
weaveParentsFor(typesForWeaving,rtxI.getClassName());
}
}
weaveParentTypeMungers(rtx); // Now do this type
typesForWeaving.remove(typeToWeave); // and remove it from the list of those to process
}
public void prepareToProcessReweavableState() {
if (inReweavableMode)
world.showMessage(IMessage.INFO,
WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE),
null, null);
alreadyConfirmedReweavableState = new HashSet();
}
public void processReweavableStateIfPresent(String className, BcelObjectType classType) {
// If the class is marked reweavable, check any aspects around when it was built are in this world
WeaverStateInfo wsi = classType.getWeaverState();
if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around!
world.showMessage(IMessage.INFO,
WeaverMessages.format(WeaverMessages.PROCESSING_REWEAVABLE,className,classType.getSourceLocation().getSourceFile()),
null,null);
Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType();
if (aspectsPreviouslyInWorld!=null) {
for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) {
String requiredTypeName = (String) iter.next();
if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) {
ResolvedTypeX rtx = world.resolve(TypeX.forName(requiredTypeName),true);
boolean exists = rtx!=ResolvedTypeX.MISSING;
if (!exists) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,requiredTypeName,className),
classType.getSourceLocation(), null);
} else {
if (!world.getMessageHandler().isIgnoring(IMessage.INFO))
world.showMessage(IMessage.INFO,
WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,requiredTypeName,rtx.getSourceLocation().getSourceFile()),
null,null);
alreadyConfirmedReweavableState.add(requiredTypeName);
}
}
}
}
classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData()));
} else {
classType.resetState();
}
}
private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType,
IWeaveRequestor requestor) throws IOException {
LazyClassGen clazz = weaveWithoutDump(classFile,classType);
classType.finishedWith();
//clazz is null if the classfile was unchanged by weaving...
if (clazz != null) {
UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
for (int i = 0; i < newClasses.length; i++) {
requestor.acceptResult(newClasses[i]);
}
} else {
requestor.acceptResult(classFile);
}
}
// helper method
public BcelObjectType getClassType(String forClass) {
return BcelWorld.getBcelObjectType(world.resolve(forClass));
}
public void addParentTypeMungers(String typeName) {
weaveParentTypeMungers(world.resolve(typeName));
}
public void addNormalTypeMungers(String typeName) {
weaveNormalTypeMungers(world.resolve(typeName));
}
public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) {
List childClasses = clazz.getChildClasses(world);
UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes());
int index = 1;
for (Iterator iter = childClasses.iterator(); iter.hasNext();) {
UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next();
UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
ret[index++] = childClass;
}
return ret;
}
/**
* Weaves new parents and annotations onto a type ("declare parents" and "declare @type")
*
* Algorithm:
* 1. First pass, do parents then do annotations. During this pass record:
* - any parent mungers that don't match but have a non-wild annotation type pattern
* - any annotation mungers that don't match
* 2. Multiple subsequent passes which go over the munger lists constructed in the first
* pass, repeatedly applying them until nothing changes.
* FIXME asc confirm that algorithm is optimal ??
*/
public void weaveParentTypeMungers(ResolvedTypeX onType) {
onType.clearInterTypeMungers();
List decpToRepeat = new ArrayList();
List decaToRepeat = new ArrayList();
boolean aParentChangeOccurred = false;
boolean anAnnotationChangeOccurred = false;
// First pass - apply all decp mungers
for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) {
DeclareParents decp = (DeclareParents)i.next();
boolean typeChanged = applyDeclareParents(decp,onType);
if (typeChanged) {
aParentChangeOccurred = true;
} else { // Perhaps it would have matched if a 'dec @type' had modified the type
if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp);
}
}
// Still first pass - apply all dec @type mungers
for (Iterator i = xcutSet.getDeclareAnnotationOnTypes().iterator();i.hasNext();) {
DeclareAnnotation decA = (DeclareAnnotation)i.next();
boolean typeChanged = applyDeclareAtType(decA,onType,true);
if (typeChanged) {
anAnnotationChangeOccurred = true;
}
}
while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
anAnnotationChangeOccurred = aParentChangeOccurred = false;
List decpToRepeatNextTime = new ArrayList();
for (Iterator iter = decpToRepeat.iterator(); iter.hasNext();) {
DeclareParents decp = (DeclareParents) iter.next();
boolean typeChanged = applyDeclareParents(decp,onType);
if (typeChanged) {
aParentChangeOccurred = true;
} else {
decpToRepeatNextTime.add(decp);
}
}
for (Iterator iter = xcutSet.getDeclareAnnotationOnTypes().iterator(); iter.hasNext();) {
DeclareAnnotation decA = (DeclareAnnotation) iter.next();
boolean typeChanged = applyDeclareAtType(decA,onType,false);
if (typeChanged) {
anAnnotationChangeOccurred = true;
}
}
decpToRepeat = decpToRepeatNextTime;
}
}
/**
* Apply a declare @type - return true if we change the type
*/
private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedTypeX onType,boolean reportProblems) {
boolean didSomething = false;
if (decA.matches(onType)) {
// FIXME asc important this should be guarded by the 'already has annotation' check below but isn't since the compiler is producing classfiles with deca affected things in...
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),onType.getSourceLocation());
// FIXME asc same comment above applies here
// TAG: WeavingMessage
if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){
getWorld().getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES,
new String[]{
onType.toString(),
Utility.beautifyLocation(onType.getSourceLocation()),
decA.getAnnotationString(),
"type",
decA.getAspect().toString(),
Utility.beautifyLocation(decA.getSourceLocation())
}));
}
if (onType.hasAnnotation(decA.getAnnotationX().getSignature())) {
// FIXME asc Could put out a lint here for an already annotated type - the problem is that it may have
// picked up the annotation during 'source weaving' in which case the message is misleading. Leaving it
// off for now...
// if (reportProblems) {
// world.getLint().elementAlreadyAnnotated.signal(
// new String[]{onType.toString(),decA.getAnnotationTypeX().toString()},
// onType.getSourceLocation(),new ISourceLocation[]{decA.getSourceLocation()});
// }
return false;
}
AnnotationX annoX = decA.getAnnotationX();
// check the annotation is suitable for the target
boolean problemReported = verifyTargetIsOK(decA, onType, annoX,reportProblems);
if (!problemReported) {
didSomething = true;
ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
newAnnotationTM.setSourceLocation(decA.getSourceLocation());
onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM,decA.getAspect().resolve(world)));
decA.copyAnnotationTo(onType);
}
}
return didSomething;
}
/**
* Checks for an @target() on the annotation and if found ensures it allows the annotation
* to be attached to the target type that matched.
*/
private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedTypeX onType, AnnotationX annoX,boolean outputProblems) {
boolean problemReported = false;
if (annoX.specifiesTarget()) {
if ( (onType.isAnnotation() && !annoX.allowedOnAnnotationType()) ||
(!annoX.allowedOnRegularType())) {
if (outputProblems) {
if (decA.isExactPattern()) {
world.getMessageHandler().handleMessage(MessageUtil.error(
WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,
onType.getName(),annoX.stringify(),annoX.getValidTargets()),decA.getSourceLocation()));
} else {
if (world.getLint().invalidTargetForAnnotation.isEnabled()) {
world.getLint().invalidTargetForAnnotation.signal(
new String[]{onType.getName(),annoX.stringify(),annoX.getValidTargets()},decA.getSourceLocation(),new ISourceLocation[]{onType.getSourceLocation()});
}
}
}
problemReported = true;
}
}
return problemReported;
}
/**
* Apply a single declare parents - return true if we change the type
*/
private boolean applyDeclareParents(DeclareParents p, ResolvedTypeX onType) {
boolean didSomething = false;
List newParents = p.findMatchingNewParents(onType,true);
if (!newParents.isEmpty()) {
didSomething=true;
BcelObjectType classType = BcelWorld.getBcelObjectType(onType);
//System.err.println("need to do declare parents for: " + onType);
for (Iterator j = newParents.iterator(); j.hasNext(); ) {
ResolvedTypeX newParent = (ResolvedTypeX)j.next();
// We set it here so that the imminent matching for ITDs can succeed - we
// still haven't done the necessary changes to the class file itself
// (like transform super calls) - that is done in BcelTypeMunger.mungeNewParent()
classType.addParent(newParent);
ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent);
newParentMunger.setSourceLocation(p.getSourceLocation());
onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)));
}
}
return didSomething;
}
public void weaveNormalTypeMungers(ResolvedTypeX onType) {
for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
if (m.matches(onType)) {
onType.addInterTypeMunger(m);
}
}
}
// exposed for ClassLoader dynamic weaving
public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
return weave(classFile, classType, false);
}
// non-private for testing
LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
LazyClassGen ret = weave(classFile, classType, true);
if (progressListener != null) {
progressMade += progressPerClassFile;
progressListener.setProgress(progressMade);
progressListener.setText("woven: " + classFile.getFilename());
}
return ret;
}
private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
if (classType.isSynthetic()) {
if (dump) dumpUnchanged(classFile);
return null;
}
// JavaClass javaClass = classType.getJavaClass();
List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX());
List typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
classType.getResolvedTypeX().checkInterTypeMungers();
LazyClassGen clazz = null;
if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect() ||
world.getDeclareAnnotationOnMethods().size()>0 || world.getDeclareAnnotationOnFields().size()>0 ) {
clazz = classType.getLazyClassGen();
//System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState());
try {
boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers);
if (isChanged) {
if (dump) dump(classFile, clazz);
return clazz;
}
} catch (RuntimeException re) {
System.err.println("trouble in: ");
clazz.print(System.err);
re.printStackTrace();
throw re;
} catch (Error re) {
System.err.println("trouble in: ");
clazz.print(System.err);
throw re;
}
}
// this is very odd return behavior trying to keep everyone happy
if (dump) {
dumpUnchanged(classFile);
return clazz;
} else {
// ATAJ: the class was not weaved, but since it gets there early it may have new generated inner classes
// attached to it to support LTW perX aspectOf support (see BcelPerClauseAspectAdder)
// that aggressively defines the inner <aspect>$mayHaveAspect interface.
if (clazz != null && !clazz.getChildClasses(world).isEmpty()) {
return clazz;
}
return null;
}
}
// ---- writing
private void dumpUnchanged(UnwovenClassFile classFile) throws IOException {
if (zipOutputStream != null) {
writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes());
} else {
classFile.writeUnchangedBytes();
}
}
private String getEntryName(String className) {
//XXX what does bcel's getClassName do for inner names
return className.replace('.', '/') + ".class";
}
private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException {
if (zipOutputStream != null) {
String mainClassName = classFile.getJavaClass().getClassName();
writeZipEntry(getEntryName(mainClassName),
clazz.getJavaClass(world).getBytes());
if (!clazz.getChildClasses(world).isEmpty()) {
for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) {
UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next();
writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
}
}
} else {
classFile.writeWovenBytes(
clazz.getJavaClass(world).getBytes(),
clazz.getChildClasses(world)
);
}
}
private void writeZipEntry(String name, byte[] bytes) throws IOException {
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zipOutputStream.putNextEntry(newEntry);
zipOutputStream.write(bytes);
zipOutputStream.closeEntry();
}
private List fastMatch(List list, ResolvedTypeX type) {
if (list == null) return Collections.EMPTY_LIST;
// here we do the coarsest grained fast match with no kind constraints
// this will remove all obvious non-matches and see if we need to do any weaving
FastMatchInfo info = new FastMatchInfo(type, null);
List result = new ArrayList();
Iterator iter = list.iterator();
while (iter.hasNext()) {
ShadowMunger munger = (ShadowMunger)iter.next();
FuzzyBoolean fb = munger.getPointcut().fastMatch(info);
WeaverMetrics.recordFastMatchTypeResult(fb); // Could pass: munger.getPointcut().toString(),info
if (fb.maybeTrue()) {
result.add(munger);
}
}
return result;
}
public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) {
progressListener = listener;
this.progressMade = previousProgress;
this.progressPerClassFile = progressPerClassFile;
}
public void setReweavableMode(boolean mode,boolean compress) {
inReweavableMode = mode;
WeaverStateInfo.setReweavableModeDefaults(mode,compress);
BcelClassWeaver.setReweavableMode(mode,compress);
}
public boolean isReweavable() {
return inReweavableMode;
}
public World getWorld() {
return world;
}
}
|
82,755 |
Bug 82755 [ajdoc] update ajdoc to support Java 5 language features
|
Java 5 langauge features such as enums and annotations need to be supported by ajdoc.
|
resolved fixed
|
7b7c7b2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-12T06:53:15Z | 2005-01-13T15:26:40Z |
ajdoc/src/org/aspectj/tools/ajdoc/Declaration.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Mik Kersten port to AspectJ 1.1+ code base
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.aspectj.asm.IProgramElement;
/**
* @author Mik Kersten
* @deprecated org.aspectj.asm.IProgramElement should be used instead
*/
public class Declaration implements Serializable {
private int beginLine;
private int endLine;
private int beginColumn;
private int endColumn;
private String modifiers;
private String fullSignature;
private String signature;
private String crosscutDesignator;
private String packageName;
private String kind;
private String declaringType;
private String filename;
private String formalComment;
private Declaration[] declarations;
private Handle crosscutDeclarationHandle;
private Handle[] pointedToByHandles;
private Handle[] pointsToHandles;
transient private Declaration crosscutDeclaration;
transient private Declaration[] pointedToBy = null;
transient private Declaration[] pointsTo = null;
private Declaration parentDeclaration = null;
private IProgramElement node;
public Declaration(int beginLine, int endLine, int beginColumn, int endColumn,
String modifiers, String signature, String fullSignature,
String crosscutDesignator,
String declaringType, String kind,
String filename, String formalComment,
String packageName,
IProgramElement node)
{
this.beginLine = beginLine;
this.endLine = endLine;
this.beginColumn = beginColumn;
this.endColumn = endColumn;
this.modifiers = modifiers;
this.signature = signature;
this.fullSignature = fullSignature;
this.crosscutDesignator = crosscutDesignator;
this.declaringType = declaringType;
this.kind = kind;
this.filename = filename;
this.formalComment = formalComment;
this.packageName = packageName;
this.pointedToByHandles = new Handle[0];
this.pointsToHandles = new Handle[0];
//???
this.declarations = new Declaration[0];
this.node = node;
}
public int getBeginLine() { return beginLine; }
public int getEndLine() { return endLine; }
public int getBeginColumn() { return beginColumn; }
public int getEndColumn() { return endColumn; }
public String getModifiers() { return modifiers; }
public String getFullSignature() { return fullSignature; }
public String getSignature() { return signature; }
public String getPackageName() { return packageName; }
public String getCrosscutDesignator() { return crosscutDesignator; }
public Declaration getParentDeclaration() { return parentDeclaration; }
public Declaration getCrosscutDeclaration() {
if (crosscutDeclaration == null && crosscutDeclarationHandle != null) {
crosscutDeclaration = crosscutDeclarationHandle.resolve();
}
return crosscutDeclaration;
}
public void setCrosscutDeclaration(Declaration _crosscutDeclaration) {
crosscutDeclaration = _crosscutDeclaration;
}
public String getDeclaringType() { return declaringType; }
public String getKind() {
if (kind.startsWith("introduced-")) {
return kind.substring(11);
} else {
return kind;
}
}
public String getFilename() { return filename; }
public String getFormalComment() { return formalComment; }
public Declaration[] getDeclarations() {
return declarations;
}
public void setDeclarations(Declaration[] decs) {
declarations = decs;
if (decs != null) {
for (int i = 0; i < decs.length; i++) {
decs[i].parentDeclaration = this;
}
}
}
public void setPointedToBy(Declaration[] decs) { pointedToBy = decs; }
public void setPointsTo(Declaration[] decs) { pointsTo = decs; }
public Declaration[] getPointedToBy() {
if (pointedToBy == null) {
pointedToBy = resolveHandles(pointedToByHandles);
}
return pointedToBy; //.elements();
}
public Declaration[] getPointsTo() {
if (pointsTo == null) {
pointsTo = resolveHandles(pointsToHandles);
}
return pointsTo; //.elements();
}
private Declaration[] filterTypes(Declaration[] a_decs) {
List decs = new LinkedList(Arrays.asList(a_decs));
for(Iterator i = decs.iterator(); i.hasNext(); ) {
Declaration dec = (Declaration)i.next();
if (!dec.isType()) i.remove();
}
return (Declaration[])decs.toArray(new Declaration[decs.size()]);
}
public Declaration[] getTargets() {
Declaration[] pointsTo = getPointsTo();
if (kind.equals("advice")) {
return pointsTo;
} else if (kind.equals("introduction")) {
return filterTypes(pointsTo);
} else {
return new Declaration[0];
}
}
// Handles are used to deal with dependencies between Declarations in different files
private Handle getHandle() {
return new Handle(filename, beginLine, beginColumn);
}
private Declaration[] resolveHandles(Handle[] handles) {
Declaration[] declarations = new Declaration[handles.length];
int missed = 0;
for(int i=0; i<handles.length; i++) {
//if (handles[i] == null) continue;
declarations[i] = handles[i].resolve();
if (declarations[i] == null) missed++;
}
if (missed > 0) {
Declaration[] decs = new Declaration[declarations.length - missed];
for (int i=0, j=0; i < declarations.length; i++) {
if (declarations[i] != null) decs[j++] = declarations[i];
}
declarations = decs;
}
return declarations;
}
private Handle[] getHandles(Declaration[] declarations) {
Handle[] handles = new Handle[declarations.length];
for(int i=0; i<declarations.length; i++) {
//if (declarations[i] == null) continue;
handles[i] = declarations[i].getHandle();
}
return handles;
}
// Make sure that all decs are convertted to handles before serialization
private void writeObject(ObjectOutputStream out) throws IOException {
pointedToByHandles = getHandles(getPointedToBy());
pointsToHandles = getHandles(getPointsTo());
if (crosscutDeclaration != null) {
crosscutDeclarationHandle = crosscutDeclaration.getHandle();
}
out.defaultWriteObject();
}
// support functions
public Declaration[] getCrosscutDeclarations() {
return getDeclarationsHelper("pointcut");
}
public Declaration[] getAdviceDeclarations() {
return getDeclarationsHelper("advice");
}
public Declaration[] getIntroductionDeclarations() {
return getDeclarationsHelper("introduction");
}
private Declaration[] getDeclarationsHelper(String kind) {
Declaration[] decls = getDeclarations();
List result = new ArrayList();
for ( int i = 0; i < decls.length; i++ ) {
Declaration decl = decls[i];
if ( decl.getKind().equals(kind) ) {
result.add(decl);
}
}
return (Declaration[])result.toArray(new Declaration[result.size()]);
}
public boolean isType() {
return getKind().equals("interface") || getKind().equals("class") || getKind().equals("aspect");
}
public boolean hasBody() {
String kind = getKind();
return kind.equals("class") || kind.endsWith("constructor") ||
(kind.endsWith("method") && getModifiers().indexOf("abstract") == -1 &&
getModifiers().indexOf("native") == -1);
}
public boolean isIntroduced() {
return kind.startsWith("introduced-");
}
public boolean hasSignature() {
String kind = getKind();
if ( kind.equals( "class" ) ||
kind.equals( "interface" ) ||
kind.equals( "initializer" ) ||
kind.equals( "field" ) ||
kind.equals( "constructor" ) ||
kind.equals( "method" ) ) {
return true;
}
else {
return false;
}
}
private static class Handle implements Serializable {
public String filename;
public int line, column;
public Handle(String filename, int line, int column) {
this.filename = filename;
this.line = line;
this.column = column;
}
public Declaration resolve() {
SymbolManager manager = SymbolManager.getDefault();
return manager.getDeclarationAtPoint(filename, line, column);
}
}
public IProgramElement getNode() {
return node;
}
}
|
82,755 |
Bug 82755 [ajdoc] update ajdoc to support Java 5 language features
|
Java 5 langauge features such as enums and annotations need to be supported by ajdoc.
|
resolved fixed
|
7b7c7b2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-12T06:53:15Z | 2005-01-13T15:26:40Z |
ajdoc/src/org/aspectj/tools/ajdoc/StubFileGenerator.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* Mik Kersten port to AspectJ 1.1+ code base
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.*;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
/**
* @author Mik Kersten
*/
class StubFileGenerator {
static Hashtable declIDTable = null;
static void doFiles(Hashtable table,
SymbolManager symbolManager,
File[] inputFiles,
File[] signatureFiles) {
declIDTable = table;
for (int i = 0; i < inputFiles.length; i++) {
processFile(symbolManager, inputFiles[i], signatureFiles[i]);
}
}
static void processFile(SymbolManager symbolManager, File inputFile, File signatureFile) {
try {
String path = StructureUtil.translateAjPathName(signatureFile.getCanonicalPath());
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(path)));
String packageName = StructureUtil.getPackageDeclarationFromFile(inputFile);
if (packageName != null && packageName != "") {
writer.println( "package " + packageName + ";" );
}
IProgramElement fileNode = (IProgramElement)AsmManager.getDefault().getHierarchy().findElementForSourceFile(inputFile.getAbsolutePath());
for (Iterator it = fileNode.getChildren().iterator(); it.hasNext(); ) {
IProgramElement node = (IProgramElement)it.next();
if (node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) {
processImportDeclaration(node, writer);
} else {
processTypeDeclaration(node, writer);
}
}
// if we got an error we don't want the contents of the file
writer.close();
} catch (IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
private static void processImportDeclaration(IProgramElement node, PrintWriter writer) throws IOException {
List imports = node.getChildren();
for (Iterator i = imports.iterator(); i.hasNext();) {
IProgramElement importNode = (IProgramElement) i.next();
writer.print("import ");
writer.print(importNode.getName());
writer.println(';');
}
}
private static void processTypeDeclaration(IProgramElement classNode, PrintWriter writer) throws IOException {
String formalComment = addDeclID(classNode, classNode.getFormalComment());
writer.println(formalComment);
String signature = genSourceSignature(classNode);// StructureUtil.genSignature(classNode);
// System.err.println("######" + signature + ", " + classNode.getName());
if (!StructureUtil.isAnonymous(classNode) && !classNode.getName().equals("<undefined>")) {
writer.println(signature + " {" );
processMembers(classNode.getChildren(), writer, classNode.getKind().equals(IProgramElement.Kind.INTERFACE));
writer.println();
writer.println("}");
}
}
private static void processMembers(List/*IProgramElement*/ members, PrintWriter writer, boolean declaringTypeIsInterface) throws IOException {
for (Iterator it = members.iterator(); it.hasNext();) {
IProgramElement member = (IProgramElement) it.next();
if (member.getKind().isType()) {
if (!member.getParent().getKind().equals(IProgramElement.Kind.METHOD)
&& !StructureUtil.isAnonymous(member)) {// don't print anonymous types
// System.err.println(">>>>>>>>>>>>>" + member.getName() + "<<<<" + member.getParent());
processTypeDeclaration(member, writer);
}
} else {
String formalComment = addDeclID(member, member.getFormalComment());;
writer.println(formalComment);
String signature = "";
if (!member.getKind().equals(IProgramElement.Kind.POINTCUT)
&& !member.getKind().equals(IProgramElement.Kind.ADVICE)) {
signature = member.getSourceSignature();//StructureUtil.genSignature(member);
}
if (member.getKind().isDeclare()) {
System.err.println("> Skipping declare (ajdoc limitation): " + member.toLabelString());
} else if (signature != null &&
signature != "" &&
!member.getKind().isInterTypeMember() &&
!member.getKind().equals(IProgramElement.Kind.INITIALIZER) &&
!StructureUtil.isAnonymous(member)) {
writer.print(signature);
} else {
// System.err.println(">> skipping: " + member.getKind());
}
if (member.getKind().equals(IProgramElement.Kind.METHOD) ||
member.getKind().equals(IProgramElement.Kind.CONSTRUCTOR)) {
if (member.getParent().getKind().equals(IProgramElement.Kind.INTERFACE) ||
signature.indexOf("abstract ") != -1) {
writer.println(";");
} else {
writer.println(" { }");
}
} else if (member.getKind().equals(IProgramElement.Kind.FIELD)) {
// writer.println(";");
}
}
}
}
/**
* Translates "aspect" to "class", as long as its not ".aspect"
*/
private static String genSourceSignature(IProgramElement classNode) {
String signature = classNode.getSourceSignature();
int index = signature.indexOf("aspect");
if (index != -1 && signature.charAt(index-1) != '.') {
signature = signature.substring(0, index) +
"class " +
signature.substring(index + 6, signature.length());
}
return signature;
}
static int nextDeclID = 0;
static String addDeclID(IProgramElement decl, String formalComment) {
String declID = "" + ++nextDeclID;
declIDTable.put(declID, decl);
return addToFormal(formalComment, Config.DECL_ID_STRING + declID + Config.DECL_ID_TERMINATOR);
}
/**
* We want to go:
* just before the first period
* just before the first @
* just before the end of the comment
*
* Adds a place holder for the period ('#') if one will need to be
* replaced.
*/
static String addToFormal(String formalComment, String string) {
boolean appendPeriod = true;
if ( (formalComment == null) || formalComment.equals("")) {
//formalComment = "/**\n * . \n */\n";
formalComment = "/**\n * \n */\n";
appendPeriod = false;
}
formalComment = formalComment.trim();
int atsignPos = formalComment.indexOf('@');
int endPos = formalComment.indexOf("*/");
int periodPos = formalComment.indexOf("/**")+2;
int position = 0;
String periodPlaceHolder = "";
if ( periodPos != -1 ) {
position = periodPos+1;
}
else if ( atsignPos != -1 ) {
string = string + "\n * ";
position = atsignPos;
}
else if ( endPos != -1 ) {
string = "* " + string + "\n";
position = endPos;
}
else {
// !!! perhaps this error should not be silent
throw new Error("Failed to append to formal comment for comment: " +
formalComment );
}
return
formalComment.substring(0, position) + periodPlaceHolder +
string +
formalComment.substring(position);
}
}
|
82,755 |
Bug 82755 [ajdoc] update ajdoc to support Java 5 language features
|
Java 5 langauge features such as enums and annotations need to be supported by ajdoc.
|
resolved fixed
|
7b7c7b2
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-12T06:53:15Z | 2005-01-13T15:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten revisions, added additional relationships
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.IOException;
import java.util.*;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.asm.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemHandler;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
/**
* At each iteration of <CODE>processCompilationUnit</CODE> the declarations for a
* particular compilation unit are added to the hierarchy passed as a a parameter.
* <p>
* Clients who extend this class need to ensure that they do not override any of the existing
* behavior. If they do, the structure model will not be built properly and tools such as IDE
* structure views and ajdoc will fail.
* <p>
* <b>Note:</b> this class is not considered public API and the overridable
* methods are subject to change.
*
* @author Mik Kersten
*/
public class AsmHierarchyBuilder extends ASTVisitor {
protected AsmElementFormatter formatter = new AsmElementFormatter();
/**
* Reset for every compilation unit.
*/
protected AjBuildConfig buildConfig;
/**
* Reset for every compilation unit.
*/
protected Stack stack;
/**
* Reset for every compilation unit.
*/
private CompilationResult currCompilationResult;
/**
*
* @param cuDeclaration
* @param buildConfig
* @param structureModel hiearchy to add this unit's declarations to
*/
public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) {
currCompilationResult = cuDeclaration.compilationResult();
LangUtil.throwIaxIfNull(currCompilationResult, "result");
stack = new Stack();
this.buildConfig = buildConfig;
internalBuild(cuDeclaration, structureModel);
// throw new RuntimeException("not implemented");
}
private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) {
LangUtil.throwIaxIfNull(structureModel, "structureModel");
if (!currCompilationResult.equals(unit.compilationResult())) {
throw new IllegalArgumentException("invalid unit: " + unit);
}
// ---- summary
// add unit to package (or root if no package),
// first removing any duplicate (XXX? removes children if 3 classes in same file?)
// push the node on the stack
// and traverse
// -- create node to add
final File file = new File(new String(unit.getFileName()));
final IProgramElement cuNode;
{
// AMC - use the source start and end from the compilation unit decl
int startLine = getStartLine(unit);
int endLine = getEndLine(unit);
SourceLocation sourceLocation
= new SourceLocation(file, startLine, endLine);
sourceLocation.setOffset(unit.sourceStart);
cuNode = new ProgramElement(
new String(file.getName()),
IProgramElement.Kind.FILE_JAVA,
sourceLocation,
0,
"",
new ArrayList());
}
cuNode.addChild(new ProgramElement(
"import declarations",
IProgramElement.Kind.IMPORT_REFERENCE,
null,
0,
"",
new ArrayList()));
final IProgramElement addToNode = genAddToNode(unit, structureModel);
// -- remove duplicates before adding (XXX use them instead?)
if (addToNode!=null && addToNode.getChildren()!=null) {
for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) {
IProgramElement child = (IProgramElement)itt.next();
ISourceLocation childLoc = child.getSourceLocation();
if (null == childLoc) {
// XXX ok, packages have null source locations
// signal others?
} else if (childLoc.getSourceFile().equals(file)) {
itt.remove();
}
}
}
// -- add and traverse
addToNode.addChild(cuNode);
stack.push(cuNode);
unit.traverse(this, unit.scope);
// -- update file map (XXX do this before traversal?)
try {
structureModel.addToFileMap(file.getCanonicalPath(), cuNode);
} catch (IOException e) {
System.err.println("IOException " + e.getMessage()
+ " creating path for " + file );
// XXX signal IOException when canonicalizing file path
}
}
/**
* Get/create the node (package or root) to add to.
*/
private IProgramElement genAddToNode(
CompilationUnitDeclaration unit,
IHierarchy structureModel) {
final IProgramElement addToNode;
{
ImportReference currentPackage = unit.currentPackage;
if (null == currentPackage) {
addToNode = structureModel.getRoot();
} else {
String pkgName;
{
StringBuffer nameBuffer = new StringBuffer();
final char[][] importName = currentPackage.getImportName();
final int last = importName.length-1;
for (int i = 0; i < importName.length; i++) {
nameBuffer.append(new String(importName[i]));
if (i < last) {
nameBuffer.append('.');
}
}
pkgName = nameBuffer.toString();
}
IProgramElement pkgNode = null;
if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) {
for (Iterator it = structureModel.getRoot().getChildren().iterator();
it.hasNext(); ) {
IProgramElement currNode = (IProgramElement)it.next();
if (pkgName.equals(currNode.getName())) {
pkgNode = currNode;
break;
}
}
}
if (pkgNode == null) {
// note packages themselves have no source location
pkgNode = new ProgramElement(
pkgName,
IProgramElement.Kind.PACKAGE,
new ArrayList()
);
structureModel.getRoot().addChild(pkgNode);
}
addToNode = pkgNode;
}
}
return addToNode;
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
String name = new String(typeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (typeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (typeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (typeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(typeDeclaration),
typeDeclaration.modifiers,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(typeDeclaration));
peNode.setFormalComment(generateJavadocComment(typeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
stack.pop();
}
// ??? share impl with visit(TypeDeclaration, ..) ?
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
String name = new String(memberTypeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
String fullName = "<undefined>";
if (memberTypeDeclaration.allocation != null
&& memberTypeDeclaration.allocation.type != null) {
// Create a name something like 'new Runnable() {..}'
fullName = "new "+memberTypeDeclaration.allocation.type.toString()+"() {..}";
} else if (memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
// If we couldn't find a nice name like 'new Runnable() {..}' then use the number after the $
fullName = new String(memberTypeDeclaration.binding.constantPoolName());
int dollar = fullName.indexOf('$');
fullName = fullName.substring(dollar+1);
}
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
IProgramElement peNode = new ProgramElement(
fullName,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,
"",
new ArrayList());
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
stack.pop();
}
private String genSourceSignature(TypeDeclaration typeDeclaration) {
StringBuffer output = new StringBuffer();
typeDeclaration.printHeader(0, output);
return output.toString();
}
private IProgramElement findEnclosingClass(Stack stack) {
for (int i = stack.size()-1; i >= 0; i--) {
IProgramElement pe = (IProgramElement)stack.get(i);
if (pe.getKind() == IProgramElement.Kind.CLASS) {
return pe;
}
}
return (IProgramElement)stack.peek();
}
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
IProgramElement peNode = null;
// For intertype decls, use the modifiers from the original signature, not the generated method
if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration;
ResolvedMember sig = itd.getSignature();
peNode = new ProgramElement(
"",
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
(sig!=null?sig.getModifiers():0),
"",
new ArrayList());
} else {
peNode = new ProgramElement(
"",
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
methodDeclaration.modifiers,
"",
new ArrayList());
}
formatter.genLabelAndKind(methodDeclaration, peNode);
genBytecodeInfo(methodDeclaration, peNode);
List namedPointcuts = genNamedPointcuts(methodDeclaration);
addUsesPointcutRelationsForNode(peNode, namedPointcuts, methodDeclaration);
if (methodDeclaration.returnType!=null) {
peNode.setCorrespondingType(methodDeclaration.returnType.toString());
} else {
peNode.setCorrespondingType(null);
}
peNode.setSourceSignature(genSourceSignature(methodDeclaration));
peNode.setFormalComment(generateJavadocComment(methodDeclaration));
// TODO: add return type test
if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) {
if (peNode.toLabelString().equals("main(String[])")
&& peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC)
&& peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) {
((IProgramElement)stack.peek()).setRunnable(true);
}
}
stack.push(peNode);
return true;
}
private void addUsesPointcutRelationsForNode(IProgramElement peNode, List namedPointcuts, MethodDeclaration declaration) {
for (Iterator it = namedPointcuts.iterator(); it.hasNext();) {
ReferencePointcut rp = (ReferencePointcut) it.next();
ResolvedMember member = getPointcutDeclaration(rp, declaration);
if (member != null) {
IRelationship foreward = AsmManager.getDefault().getRelationshipMap().get(peNode.getHandleIdentifier(), IRelationship.Kind.USES_POINTCUT, "uses pointcut", false, true);
foreward.addTarget(AsmManager.getDefault().getHandleProvider().createHandleIdentifier(member.getSourceLocation()));
IRelationship back = AsmManager.getDefault().getRelationshipMap().get(AsmManager.getDefault().getHandleProvider().createHandleIdentifier(member.getSourceLocation()), IRelationship.Kind.USES_POINTCUT, "pointcut used by", false, true);
back.addTarget(peNode.getHandleIdentifier());
}
}
}
private ResolvedMember getPointcutDeclaration(ReferencePointcut rp, MethodDeclaration declaration) {
World world = ((AjLookupEnvironment)declaration.scope.environment()).factory.getWorld();
TypeX onType = rp.onType;
if (onType == null) {
if (declaration.binding != null) {
Member member = EclipseFactory.makeResolvedMember(declaration.binding);
onType = member.getDeclaringType();
} else {
return null;
}
}
ResolvedMember[] members = onType.getDeclaredPointcuts(world);
if (members != null) {
for (int i = 0; i < members.length; i++) {
if (members[i].getName().equals(rp.name)) {
return members[i];
}
}
}
return null;
}
/**
* @param methodDeclaration
* @return all of the named pointcuts referenced by the PCD of this declaration
*/
private List genNamedPointcuts(MethodDeclaration methodDeclaration) {
List pointcuts = new ArrayList();
if (methodDeclaration instanceof AdviceDeclaration) {
if (((AdviceDeclaration)methodDeclaration).pointcutDesignator != null)
addAllNamed(((AdviceDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts);
} else if (methodDeclaration instanceof PointcutDeclaration) {
if (((PointcutDeclaration)methodDeclaration).pointcutDesignator != null)
addAllNamed(((PointcutDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts);
}
return pointcuts;
}
/**
* @param left
* @param pointcuts accumulator for named pointcuts
*/
private void addAllNamed(Pointcut pointcut, List pointcuts) {
if (pointcut == null) return;
if (pointcut instanceof ReferencePointcut) {
ReferencePointcut rp = (ReferencePointcut)pointcut;
pointcuts.add(rp);
} else if (pointcut instanceof AndPointcut) {
AndPointcut ap = (AndPointcut)pointcut;
addAllNamed(ap.getLeft(), pointcuts);
addAllNamed(ap.getRight(), pointcuts);
} else if (pointcut instanceof OrPointcut) {
OrPointcut op = (OrPointcut)pointcut;
addAllNamed(op.getLeft(), pointcuts);
addAllNamed(op.getRight(), pointcuts);
}
}
private String genSourceSignature(MethodDeclaration methodDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(methodDeclaration.modifiers, output);
methodDeclaration.printReturnType(0, output).append(methodDeclaration.selector).append('(');
if (methodDeclaration.arguments != null) {
for (int i = 0; i < methodDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (methodDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < methodDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) {
if (methodDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
Member member = EclipseFactory.makeResolvedMember(methodDeclaration.binding);
memberName = member.getName();
memberBytecodeSignature = member.getSignature();
} catch (BCException bce) { // bad type name
memberName = "<undefined>";
} catch (NullPointerException npe) {
memberName = "<undefined>";
}
peNode.setBytecodeName(memberName);
peNode.setBytecodeSignature(memberBytecodeSignature);
}
((IProgramElement)stack.peek()).addChild(peNode);
}
public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
IProgramElement peNode = new ProgramElement(
new String(importRef.toString()),
IProgramElement.Kind.IMPORT_REFERENCE,
makeLocation(importRef),
0,
"",
new ArrayList());
ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0);
imports.addChild(0, peNode);
stack.push(peNode);
}
return true;
}
public void endVisit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
stack.pop();
}
}
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
IProgramElement peNode = null;
if (fieldDeclaration.type == null) { // The field represents an enum value
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.ENUM_VALUE,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
"", new ArrayList());
peNode.setCorrespondingType(fieldDeclaration.binding.type.debugName());
} else {
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.FIELD,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
"", new ArrayList());
peNode.setCorrespondingType(fieldDeclaration.type.toString());
}
peNode.setSourceSignature(genSourceSignature(fieldDeclaration));
peNode.setFormalComment(generateJavadocComment(fieldDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
stack.pop();
}
/**
* Checks if comments should be added to the model before generating.
*/
protected String generateJavadocComment(ASTNode astNode) {
if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null;
StringBuffer sb = new StringBuffer(); // !!! specify length?
boolean completed = false;
int startIndex = -1;
if (astNode instanceof MethodDeclaration) {
startIndex = ((MethodDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof FieldDeclaration) {
startIndex = ((FieldDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof TypeDeclaration) {
startIndex = ((TypeDeclaration)astNode).declarationSourceStart;
}
if (startIndex == -1) {
return null;
} else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /**
&& currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*'
&& currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') {
for (int i = startIndex; i < astNode.sourceStart && !completed; i++) {
char curr = currCompilationResult.compilationUnit.getContents()[i];
if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */
sb.append(currCompilationResult.compilationUnit.getContents()[i]);
}
return sb.toString();
} else {
return null;
}
}
/**
* Doesn't print qualified allocation expressions.
*/
protected String genSourceSignature(FieldDeclaration fieldDeclaration) {
StringBuffer output = new StringBuffer();
FieldDeclaration.printModifiers(fieldDeclaration.modifiers, output);
if (fieldDeclaration.type == null) { // This is an enum value
output.append(fieldDeclaration.binding.type.debugName()).append(" ").append(fieldDeclaration.name);
} else {
fieldDeclaration.type.print(0, output).append(' ').append(fieldDeclaration.name);
}
if (fieldDeclaration.initialization != null
&& !(fieldDeclaration.initialization instanceof QualifiedAllocationExpression)) {
output.append(" = "); //$NON-NLS-1$
if (fieldDeclaration.initialization instanceof ExtendedStringLiteral) {
output.append("\"<extended string literal>\"");
} else {
fieldDeclaration.initialization.printExpression(0, output);
}
}
output.append(';');
return output.toString();
}
// public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// new String(importRef.toString()),
// ProgramElementNode.Kind.,
// makeLocation(importRef),
// 0,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(0, peNode);
// stack.push(peNode);
// return true;
// }
// public void endVisit(ImportReference importRef,CompilationUnitScope scope) {
// stack.pop();
// }
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
if (constructorDeclaration.isDefaultConstructor) {
stack.push(null); // a little wierd but does the job
return true;
}
StringBuffer argumentsSignature = new StringBuffer();
argumentsSignature.append("(");
if (constructorDeclaration.arguments!=null) {
for (int i = 0;i<constructorDeclaration.arguments.length;i++) {
argumentsSignature.append(constructorDeclaration.arguments[i].type);
if (i+1<constructorDeclaration.arguments.length) argumentsSignature.append(",");
}
}
argumentsSignature.append(")");
IProgramElement peNode = new ProgramElement(
new String(constructorDeclaration.selector)+argumentsSignature,
IProgramElement.Kind.CONSTRUCTOR,
makeLocation(constructorDeclaration),
constructorDeclaration.modifiers,
"",
new ArrayList());
peNode.setModifiers(constructorDeclaration.modifiers);
peNode.setSourceSignature(genSourceSignature(constructorDeclaration));
// Fix to enable us to anchor things from ctor nodes
if (constructorDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
Member member = EclipseFactory.makeResolvedMember(constructorDeclaration.binding);
memberName = member.getName();
memberBytecodeSignature = member.getSignature();
} catch (BCException bce) { // bad type name
memberName = "<undefined>";
} catch (NullPointerException npe) {
memberName = "<undefined>";
}
peNode.setBytecodeName(memberName);
peNode.setBytecodeSignature(memberBytecodeSignature);
}
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
stack.pop();
}
private String genSourceSignature(ConstructorDeclaration constructorDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(constructorDeclaration.modifiers, output);
output.append(constructorDeclaration.selector).append('(');
if (constructorDeclaration.arguments != null) {
for (int i = 0; i < constructorDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (constructorDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < constructorDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
// public boolean visit(Clinit clinit, ClassScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// "<clinit>",
// ProgramElementNode.Kind.INITIALIZER,
// makeLocation(clinit),
// clinit.modifiers,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(peNode);
// stack.push(peNode);
// return false;
// }
// public void endVisit(Clinit clinit, ClassScope scope) {
// stack.pop();
// }
/** This method works-around an odd traverse implementation on Initializer
*/
private Initializer inInitializer = null;
public boolean visit(Initializer initializer, MethodScope scope) {
if (initializer == inInitializer) return false;
inInitializer = initializer;
IProgramElement peNode = new ProgramElement(
"...",
IProgramElement.Kind.INITIALIZER,
makeLocation(initializer),
initializer.modifiers,
"",
new ArrayList());
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
initializer.block.traverse(this, scope);
stack.pop();
return false;
}
// ??? handle non-existant files
protected ISourceLocation makeLocation(ASTNode node) {
String fileName = "";
if (currCompilationResult.getFileName() != null) {
fileName = new String(currCompilationResult.getFileName());
}
// AMC - different strategies based on node kind
int startLine = getStartLine(node);
int endLine = getEndLine(node);
SourceLocation loc = null;
if ( startLine <= endLine ) {
// found a valid end line for this node...
loc = new SourceLocation(new File(fileName), startLine, endLine);
loc.setOffset(node.sourceStart);
} else {
loc = new SourceLocation(new File(fileName), startLine);
loc.setOffset(node.sourceStart);
}
return loc;
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getStartLine( ASTNode n){
// if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n);
// if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n);
// if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
n.sourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getEndLine( ASTNode n){
if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n);
if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n);
if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
n.sourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractVariableDeclaration avd ) {
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// avd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractVariableDeclaration avd ){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
avd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractMethodDeclaration amd ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// amd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractMethodDeclaration amd) {
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
amd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( TypeDeclaration td ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// td.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( TypeDeclaration td){
return ProblemHandler.searchLineNumber(
currCompilationResult.lineSeparatorPositions,
td.declarationSourceEnd);
}
}
|
86,832 |
Bug 86832 Internal compiler error (generics?)
|
Attached is project that will generate an "Internal compiler error" for a single class that extends "ArrayList<Object>". If the class extends just "ArrayList" the compiler error does not occur. Note that the "extends ArrayList<Object>" class compiles successuflly without the aspectj nature. --- exception --- Severity Description Resource In Folder Location Creation Time 2 Internal compiler error java.lang.NullPointerException at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope.detectHierarchyCycle(ClassScope.java:945) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference.internalResolveType(ParameterizedSingleTypeReference.java:143) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference.resolveType(ParameterizedSingleTypeReference.java:208) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference.resolveSuperType(TypeReference.java:112) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope.findSupertype(ClassScope.java:1092) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope.connectSuperclass(ClassScope.java:747) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope.connectTypeHierarchy(ClassScope.java:884) at org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope.connectTypeHierarchy(CompilationUnitScope.java:249) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:91) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:331) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:348) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:682) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:168) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:102) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:165) FlattenedListExtendsArrayListObject.java opentrader.infra/src/org/opentrader/infra/springframework February 28, 2005 9:59:42 AM
|
resolved fixed
|
0cb826c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-12T09:32:03Z | 2005-02-28T14:13:20Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void testPerTypeWithinMissesNamedInnerTypes() {
runTest("pertypewithin() handing of inner classes (1)");
}
public void testPerTypeWithinMissesAnonymousInnerTypes() {
runTest("pertypewithin() handing of inner classes (2)");
}
public void testPerTypeWithinIncorrectlyMatchingInterfaces() {
runTest("pertypewithin({interface}) illegal field modifier");
}
public void test051_arrayCloningInJava5() {
runTest("AJC possible bug with static nested classes");
}
public void testBadASMforEnums() throws IOException {
runTest("bad asm for enums");
if (System.getProperty("java.vm.version").startsWith("1.5")) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
AsmManager.dumptree(pw,AsmManager.getDefault().getHierarchy().getRoot(),0);
pw.flush();
String tree = baos.toString();
assertTrue("Expected 'Red [enumvalue]' somewhere in here:"+tree,tree.indexOf("Red [enumvalue]")!=-1);
}
}
public void npeOnTypeNotFound() {
runTest("structure model npe on type not found");
}
public void testNoRuntimeExceptionSoftening() {
runTest("declare soft of runtime exception");
}
public void testRuntimeNoSoftenWithHandler() {
runTest("declare soft w. catch block");
}
public void testSyntaxError() {
runTest("invalid cons syntax");
}
public void testVarargsInConsBug() {
runTest("varargs in constructor sig");
}
public void testAspectpathdirs() {
runTest("dirs on aspectpath");
}
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");
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
84,312 |
Bug 84312 Finish implementation of *runtime* retention checking
|
See FIXME in BindingAnnotationTypePattern.resolveBinding() and EclipseSourceType.getAnnotationTypes()
|
resolved fixed
|
f9eebd4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-12T13:00:07Z | 2005-02-03T11:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.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.util.*;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
import org.aspectj.bridge.IMessage;
//import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.PerSingleton;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.*;
/**
* Supports viewing eclipse TypeDeclarations/SourceTypeBindings as a ResolvedTypeX
*
* @author Jim Hugunin
*/
public class EclipseSourceType extends ResolvedTypeX.ConcreteName {
private static final char[] pointcutSig = "Lorg/aspectj/lang/annotation/Pointcut;".toCharArray();
protected ResolvedPointcutDefinition[] declaredPointcuts = null;
protected ResolvedMember[] declaredMethods = null;
protected ResolvedMember[] declaredFields = null;
public List declares = new ArrayList();
public List typeMungers = new ArrayList();
private EclipseFactory factory;
private SourceTypeBinding binding;
private TypeDeclaration declaration;
private boolean annotationsResolved = false;
private ResolvedTypeX[] resolvedAnnotations = null;
protected EclipseFactory eclipseWorld() {
return factory;
}
public EclipseSourceType(ResolvedTypeX.Name resolvedTypeX, EclipseFactory factory,
SourceTypeBinding binding, TypeDeclaration declaration)
{
super(resolvedTypeX, true);
this.factory = factory;
this.binding = binding;
this.declaration = declaration;
resolvedTypeX.setSourceContext(new EclipseSourceContext(declaration.compilationResult));
resolvedTypeX.setStartPos(declaration.sourceStart);
resolvedTypeX.setEndPos(declaration.sourceEnd);
}
public boolean isAspect() {
return declaration instanceof AspectDeclaration;
}
// FIXME ATAJ isAnnotationStyleAspect() needs implementing?
public boolean isAnnotationStyleAspect() {
if (declaration.annotations == null) {
return false;
}
for (int i = 0; i < declaration.annotations.length; i++) {
Annotation annotation = declaration.annotations[i];
// do something there
;
}
return false;
}
private boolean isAnnotationStylePointcut(Annotation[] annotations) {
if (annotations == null) return false;
for (int i = 0; i < annotations.length; i++) {
if (annotations[i].resolvedType == null) continue; // XXX happens if we do this very early from buildInterTypeandPerClause
// may prevent us from resolving references made in @Pointcuts to
// an @Pointcut in a code-style aspect
char[] sig = annotations[i].resolvedType.signature();
if (CharOperation.equals(pointcutSig,sig)) {
return true;
}
}
return false;
}
public WeaverStateInfo getWeaverState() {
return null;
}
public ResolvedTypeX getSuperclass() {
if (binding.isInterface()) return getResolvedTypeX().getWorld().getCoreType(TypeX.OBJECT);
//XXX what about java.lang.Object
return eclipseWorld().fromEclipse(binding.superclass());
}
public ResolvedTypeX[] getDeclaredInterfaces() {
return eclipseWorld().fromEclipse(binding.superInterfaces());
}
protected void fillDeclaredMembers() {
List declaredPointcuts = new ArrayList();
List declaredMethods = new ArrayList();
List declaredFields = new ArrayList();
binding.methods(); // the important side-effect of this call is to make sure bindings are completed
AbstractMethodDeclaration[] methods = declaration.methods;
if (methods != null) {
for (int i=0, len=methods.length; i < len; i++) {
AbstractMethodDeclaration amd = methods[i];
if (amd == null || amd.ignoreFurtherInvestigation) continue;
if (amd instanceof PointcutDeclaration) {
PointcutDeclaration d = (PointcutDeclaration)amd;
ResolvedPointcutDefinition df = d.makeResolvedPointcutDefinition();
declaredPointcuts.add(df);
} else if (amd instanceof InterTypeDeclaration) {
// these are handled in a separate pass
continue;
} else if (amd instanceof DeclareDeclaration &&
!(amd instanceof DeclareAnnotationDeclaration)) { // surfaces the annotated ajc$ method
// these are handled in a separate pass
continue;
} else if (amd instanceof AdviceDeclaration) {
// these are ignored during compilation and only used during weaving
continue;
} else if ((amd.annotations != null) && isAnnotationStylePointcut(amd.annotations)) {
// consider pointcuts defined via annotations
ResolvedPointcutDefinition df = makeResolvedPointcutDefinition(amd);
declaredPointcuts.add(df);
} else {
if (amd.binding == null || !amd.binding.isValidBinding()) continue;
declaredMethods.add(EclipseFactory.makeResolvedMember(amd.binding));
}
}
}
FieldBinding[] fields = binding.fields();
for (int i=0, len=fields.length; i < len; i++) {
FieldBinding f = fields[i];
declaredFields.add(EclipseFactory.makeResolvedMember(f));
}
this.declaredPointcuts = (ResolvedPointcutDefinition[])
declaredPointcuts.toArray(new ResolvedPointcutDefinition[declaredPointcuts.size()]);
this.declaredMethods = (ResolvedMember[])
declaredMethods.toArray(new ResolvedMember[declaredMethods.size()]);
this.declaredFields = (ResolvedMember[])
declaredFields.toArray(new ResolvedMember[declaredFields.size()]);
}
private ResolvedPointcutDefinition makeResolvedPointcutDefinition(AbstractMethodDeclaration md) {
ResolvedPointcutDefinition resolvedPointcutDeclaration = new ResolvedPointcutDefinition(
EclipseFactory.fromBinding(md.binding.declaringClass),
md.modifiers,
new String(md.selector),
EclipseFactory.fromBindings(md.binding.parameters),
null); //??? might want to use null
resolvedPointcutDeclaration.setPosition(md.sourceStart, md.sourceEnd);
resolvedPointcutDeclaration.setSourceContext(new EclipseSourceContext(md.compilationResult));
return resolvedPointcutDeclaration;
}
public ResolvedMember[] getDeclaredFields() {
if (declaredFields == null) fillDeclaredMembers();
return declaredFields;
}
public ResolvedMember[] getDeclaredMethods() {
if (declaredMethods == null) fillDeclaredMembers();
return declaredMethods;
}
public ResolvedMember[] getDeclaredPointcuts() {
if (declaredPointcuts == null) fillDeclaredMembers();
return declaredPointcuts;
}
public int getModifiers() {
// only return the real Java modifiers, not the extra eclipse ones
return binding.modifiers & CompilerModifiers.AccJustFlag;
}
public String toString() {
return "EclipseSourceType(" + new String(binding.sourceName()) + ")";
}
//XXX make sure this is applied to classes and interfaces
public void checkPointcutDeclarations() {
ResolvedMember[] pointcuts = getDeclaredPointcuts();
boolean sawError = false;
for (int i=0, len=pointcuts.length; i < len; i++) {
if (pointcuts[i].isAbstract()) {
if (!this.isAspect()) {
eclipseWorld().showMessage(IMessage.ERROR,
"abstract pointcut only allowed in aspect" + pointcuts[i].getName(),
pointcuts[i].getSourceLocation(), null);
sawError = true;
} else if (!binding.isAbstract()) {
eclipseWorld().showMessage(IMessage.ERROR,
"abstract pointcut in concrete aspect" + pointcuts[i],
pointcuts[i].getSourceLocation(), null);
sawError = true;
}
}
for (int j=i+1; j < len; j++) {
if (pointcuts[i].getName().equals(pointcuts[j].getName())) {
eclipseWorld().showMessage(IMessage.ERROR,
"duplicate pointcut name: " + pointcuts[j].getName(),
pointcuts[i].getSourceLocation(), pointcuts[j].getSourceLocation());
sawError = true;
}
}
}
//now check all inherited pointcuts to be sure that they're handled reasonably
if (sawError || !isAspect()) return;
// find all pointcuts that override ones from super and check override is legal
// i.e. same signatures and greater or equal visibility
// find all inherited abstract pointcuts and make sure they're concretized if I'm concrete
// find all inherited pointcuts and make sure they don't conflict
getResolvedTypeX().getExposedPointcuts(); //??? this is an odd construction
}
//???
// public CrosscuttingMembers collectCrosscuttingMembers() {
// return crosscuttingMembers;
// }
// public ISourceLocation getSourceLocation() {
// TypeDeclaration dec = binding.scope.referenceContext;
// return new EclipseSourceLocation(dec.compilationResult, dec.sourceStart, dec.sourceEnd);
// }
public boolean isInterface() {
return binding.isInterface();
}
// XXXAJ5: Should be constants in the eclipse compiler somewhere, once it supports 1.5
public final static short ACC_ANNOTATION = 0x2000;
public final static short ACC_ENUM = 0x4000;
public boolean isEnum() {
return (binding.getAccessFlags() & ACC_ENUM)!=0;
}
public boolean isAnnotation() {
return (binding.getAccessFlags() & ACC_ANNOTATION)!=0;
}
public void addAnnotation(AnnotationX annotationX) {
// XXX Big hole here - annotationX holds a BCEL annotation but
// we need an Eclipse one here, we haven't written the conversion utils
// yet. Not sure if this method will be called in practice...
throw new RuntimeException("EclipseSourceType.addAnnotation() not implemented");
}
public boolean isAnnotationWithRuntimeRetention() {
if (!isAnnotation()) {
return false;
} else {
return (binding.getAnnotationTagBits() & TagBits.AnnotationRuntimeRetention)!=0;
}
}
public boolean hasAnnotation(TypeX ofType) {
// Make sure they are resolved
if (!annotationsResolved) {
TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding);
annotationsResolved = true;
}
Annotation[] as = declaration.annotations;
if (as == null) return false;
for (int i = 0; i < as.length; i++) {
Annotation annotation = as[i];
if (annotation.resolvedType == null) {
// Something has gone wrong - probably we have a 1.4 rt.jar around
// which will result in a separate error message.
return false;
}
String tname = CharOperation.charToString(annotation.resolvedType.constantPoolName());
if (TypeX.forName(tname).equals(ofType)) {
return true;
}
}
return false;
}
public AnnotationX[] getAnnotations() {
throw new RuntimeException("Missing implementation");
}
public ResolvedTypeX[] getAnnotationTypes() {
if (resolvedAnnotations!=null) return resolvedAnnotations;
// Make sure they are resolved
if (!annotationsResolved) {
TypeDeclaration.resolveAnnotations(declaration.staticInitializerScope, declaration.annotations, binding);
annotationsResolved = true;
}
if (declaration.annotations == null) {
resolvedAnnotations = new ResolvedTypeX[0];
} else {
resolvedAnnotations = new ResolvedTypeX[declaration.annotations.length];
Annotation[] as = declaration.annotations;
for (int i = 0; i < as.length; i++) {
Annotation annotation = as[i];
resolvedAnnotations[i] =factory.fromTypeBindingToRTX(annotation.type.resolvedType);
}
}
return resolvedAnnotations;
}
public PerClause getPerClause() {
//should probably be: ((AspectDeclaration)declaration).perClause;
// but we don't need this level of detail, and working with real per clauses
// at this stage of compilation is not worth the trouble
return new PerSingleton();
}
protected Collection getDeclares() {
return declares;
}
protected Collection getPrivilegedAccesses() {
return Collections.EMPTY_LIST;
}
protected Collection getTypeMungers() {
return typeMungers;
}
public boolean doesNotExposeShadowMungers() {
return true;
}
}
|
84,312 |
Bug 84312 Finish implementation of *runtime* retention checking
|
See FIXME in BindingAnnotationTypePattern.resolveBinding() and EclipseSourceType.getAnnotationTypes()
|
resolved fixed
|
f9eebd4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-12T13:00:07Z | 2005-02-03T11:26:40Z |
weaver/src/org/aspectj/weaver/patterns/BindingAnnotationTypePattern.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 org.aspectj.bridge.IMessage;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
public class BindingAnnotationTypePattern extends ExactAnnotationTypePattern implements BindingPattern {
private int formalIndex;
/**
* @param annotationType
*/
public BindingAnnotationTypePattern(TypeX annotationType, int index) {
super(annotationType);
this.formalIndex = index;
}
public BindingAnnotationTypePattern(FormalBinding binding) {
this(binding.getType(),binding.getIndex());
}
public void resolveBinding(World world) {
if (resolved) return;
resolved = true;
annotationType = annotationType.resolve(world);
if (!annotationType.isAnnotation(world)) {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE,annotationType.getName()),
getSourceLocation());
world.getMessageHandler().handleMessage(m);
resolved = false;
}
if (!annotationType.hasAnnotation(TypeX.AT_RETENTION)) {
// default is class visibility
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.BINDING_NON_RUNTIME_RETENTION_ANNOTATION,annotationType.getName()),
getSourceLocation());
world.getMessageHandler().handleMessage(m);
resolved = false;
} else {
// Get the retention policy annotation, and check the value is RetentionPolicy.RUNTIME;
// FIXME asc invention required, implement this !
// if (!annotationType.hasRuntimeRetention()) {
// ResolvedTypeX[] allAs = annotationType.getAnnotationTypes();
// for (int i = 0; i < allAs.length; i++) {
// ResolvedTypeX ann = allAs[i];
// if ()
// }
}
}
public int getFormalIndex() {
return formalIndex;
}
public boolean equals(Object obj) {
if (!(obj instanceof BindingAnnotationTypePattern)) return false;
BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern) obj;
return (super.equals(btp) && (btp.formalIndex == formalIndex));
}
public int hashCode() {
return super.hashCode()*37 + formalIndex;
}
public AnnotationTypePattern remapAdviceFormals(IntMap bindings) {
if (!bindings.hasKey(formalIndex)) {
return new ExactAnnotationTypePattern(annotationType);
} else {
int newFormalIndex = bindings.get(formalIndex);
return new BindingAnnotationTypePattern(annotationType, newFormalIndex);
}
}
private static final byte VERSION = 1; // rev if serialised form changed
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.ExactAnnotationTypePattern#write(java.io.DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(AnnotationTypePattern.BINDING);
s.writeByte(VERSION);
annotationType.write(s);
s.writeShort((short)formalIndex);
writeLocation(s);
}
public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException {
byte version = s.readByte();
if (version > VERSION) {
throw new BCException("BindingAnnotationTypePattern was written by a more recent version of AspectJ");
}
AnnotationTypePattern ret = new BindingAnnotationTypePattern(TypeX.read(s),s.readShort());
ret.readLocation(context,s);
return ret;
}
}
|
94,086 |
Bug 94086 Exploding compile time with if() statements in pointcut
|
Compile time explodes when adding if(...) statements to pointcuts. This is the same with ajc 1.2.1 and 1.5M2 although 1.5M2 is a little bit faster, but compile time still explodes. Example: pointcut pc2() : (execution(* Test.a(..)) && if(sl.isEnabled()) ) || (execution(* Test.a(..)) && if(sl.isEnabled()) ) compiled in about 1 second. Up to 7 such conditions , eg. pointcut Pc7() : (execution(* Test.a(..)) && if (sl.isEnabled())) || (execution(* Test.b(..)) && if (sl.isEnabled())) || (execution(* Test.c(..)) && if (sl.isEnabled())) || (execution(* Test.d(..)) && if (sl.isEnabled())) || (execution(* Test.e(..)) && if (sl.isEnabled())) || (execution(* Test.f(..)) && if (sl.isEnabled())) || (execution(* Test.g(..)) && if (sl.isEnabled())); are also compiled quite quickly (~ 3 seconds with both ajc 1.2.1 and 1.5M2). Now, adding another condition (8 lines) causes 6 seconds compile time. Adding yet another condition line (= 9 ex. lines) causes ~ 1 min compile time! (10 such lines even more than 8 minutes) Sample source code below ------------------------ // ########## Aspect.aj ############### public aspect Aspect { private static final SimpleLogger sl = new SimpleLogger(); pointcut PC() : (execution(* Test.a(..)) && if (sl.isEnabled())) || (execution(* Test.b(..)) && if (sl.isEnabled())) || (execution(* Test.c(..)) && if (sl.isEnabled())) || (execution(* Test.d(..)) && if (sl.isEnabled())) || (execution(* Test.e(..)) && if (sl.isEnabled())) || (execution(* Test.f(..)) && if (sl.isEnabled())) || (execution(* Test.g(..)) && if (sl.isEnabled())) || (execution(* Test.h(..)) && if (sl.isEnabled())) || (execution(* Test.i(..)) && if (sl.isEnabled())) || (execution(* Test.j(..)) && if (sl.isEnabled())) ; before() : PC() { sl.log("Before"); } after() : PC() { sl.log("After"); } } // ########## Test.java ###############
|
resolved fixed
|
88d477d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-16T10:55:24Z | 2005-05-09T09:13:20Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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");
}
// 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);
}
}
|
94,086 |
Bug 94086 Exploding compile time with if() statements in pointcut
|
Compile time explodes when adding if(...) statements to pointcuts. This is the same with ajc 1.2.1 and 1.5M2 although 1.5M2 is a little bit faster, but compile time still explodes. Example: pointcut pc2() : (execution(* Test.a(..)) && if(sl.isEnabled()) ) || (execution(* Test.a(..)) && if(sl.isEnabled()) ) compiled in about 1 second. Up to 7 such conditions , eg. pointcut Pc7() : (execution(* Test.a(..)) && if (sl.isEnabled())) || (execution(* Test.b(..)) && if (sl.isEnabled())) || (execution(* Test.c(..)) && if (sl.isEnabled())) || (execution(* Test.d(..)) && if (sl.isEnabled())) || (execution(* Test.e(..)) && if (sl.isEnabled())) || (execution(* Test.f(..)) && if (sl.isEnabled())) || (execution(* Test.g(..)) && if (sl.isEnabled())); are also compiled quite quickly (~ 3 seconds with both ajc 1.2.1 and 1.5M2). Now, adding another condition (8 lines) causes 6 seconds compile time. Adding yet another condition line (= 9 ex. lines) causes ~ 1 min compile time! (10 such lines even more than 8 minutes) Sample source code below ------------------------ // ########## Aspect.aj ############### public aspect Aspect { private static final SimpleLogger sl = new SimpleLogger(); pointcut PC() : (execution(* Test.a(..)) && if (sl.isEnabled())) || (execution(* Test.b(..)) && if (sl.isEnabled())) || (execution(* Test.c(..)) && if (sl.isEnabled())) || (execution(* Test.d(..)) && if (sl.isEnabled())) || (execution(* Test.e(..)) && if (sl.isEnabled())) || (execution(* Test.f(..)) && if (sl.isEnabled())) || (execution(* Test.g(..)) && if (sl.isEnabled())) || (execution(* Test.h(..)) && if (sl.isEnabled())) || (execution(* Test.i(..)) && if (sl.isEnabled())) || (execution(* Test.j(..)) && if (sl.isEnabled())) ; before() : PC() { sl.log("Before"); } after() : PC() { sl.log("After"); } } // ########## Test.java ###############
|
resolved fixed
|
88d477d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-16T10:55:24Z | 2005-05-09T09:13:20Z |
weaver/src/org/aspectj/weaver/patterns/IfPointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Member;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.lang.JoinPoint;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Expr;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.ast.Var;
public class IfPointcut extends Pointcut {
public ResolvedMember testMethod;
public int extraParameterFlags;
public Pointcut residueSource;
int baseArgsCount;
//XXX some way to compute args
public IfPointcut(ResolvedMember testMethod, int extraParameterFlags) {
this.testMethod = testMethod;
this.extraParameterFlags = extraParameterFlags;
this.pointcutKind = IF;
}
public Set couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS;
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
//??? this is not maximally efficient
return FuzzyBoolean.MAYBE;
}
public boolean alwaysFalse() {
return false;
}
public boolean alwaysTrue() {
return false;
}
// enh 76055
public Pointcut getResidueSource() {
return residueSource;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#matchesDynamically(java.lang.Object, java.lang.Object, java.lang.Object[])
*/
public boolean matchesDynamically(Object thisObject, Object targetObject,
Object[] args) {
throw new UnsupportedOperationException("If pointcut matching not supported by this operation");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.Pointcut#matchesStatically(java.lang.String, java.lang.reflect.Member, java.lang.Class, java.lang.Class, java.lang.reflect.Member)
*/
public FuzzyBoolean matchesStatically(
String joinpointKind, Member member, Class thisClass,
Class targetClass, Member withinCode) {
throw new UnsupportedOperationException("If pointcut matching not supported by this operation");
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.IF);
testMethod.write(s);
s.writeByte(extraParameterFlags);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
IfPointcut ret = new IfPointcut(ResolvedMember.readResolvedMember(s, context), s.readByte());
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
//??? all we need is good error messages in here in cflow contexts
}
public void resolveBindingsFromRTTI() {}
public boolean equals(Object other) {
if (!(other instanceof IfPointcut)) return false;
IfPointcut o = (IfPointcut)other;
return o.testMethod.equals(this.testMethod);
}
public int hashCode() {
int result = 17;
result = 37*result + testMethod.hashCode();
return result;
}
public String toString() {
return "if(" + testMethod + ")";
}
//??? The implementation of name binding and type checking in if PCDs is very convoluted
// There has to be a better way...
private boolean findingResidue = false;
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
if (findingResidue) return Literal.TRUE;
findingResidue = true;
try {
ExposedState myState = new ExposedState(baseArgsCount);
//System.out.println(residueSource);
//??? we throw out the test that comes from this walk. All we want here
// is bindings for the arguments
residueSource.findResidue(shadow, myState);
//System.out.println(myState);
Test ret = Literal.TRUE;
List args = new ArrayList();
for (int i=0; i < baseArgsCount; i++) {
Var v = myState.get(i);
args.add(v);
ret = Test.makeAnd(ret,
Test.makeInstanceof(v,
testMethod.getParameterTypes()[i].resolve(shadow.getIWorld())));
}
// handle thisJoinPoint parameters
if ((extraParameterFlags & Advice.ThisJoinPoint) != 0) {
args.add(shadow.getThisJoinPointVar());
}
if ((extraParameterFlags & Advice.ThisJoinPointStaticPart) != 0) {
args.add(shadow.getThisJoinPointStaticPartVar());
}
if ((extraParameterFlags & Advice.ThisEnclosingJoinPointStaticPart) != 0) {
args.add(shadow.getThisEnclosingJoinPointStaticPartVar());
}
ret = Test.makeAnd(ret, Test.makeCall(testMethod, (Expr[])args.toArray(new Expr[args.size()])));
return ret;
} finally {
findingResidue = false;
}
}
// amc - the only reason this override seems to be here is to stop the copy, but
// that can be prevented by overriding shouldCopyLocationForConcretization,
// allowing me to make the method final in Pointcut.
// public Pointcut concretize(ResolvedTypeX inAspect, IntMap bindings) {
// return this.concretize1(inAspect, bindings);
// }
protected boolean shouldCopyLocationForConcretize() {
return false;
}
private IfPointcut partiallyConcretized = null;
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
//System.err.println("concretize: " + this + " already: " + partiallyConcretized);
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.IF_IN_DECLARE),
bindings.getEnclosingAdvice().getSourceLocation(),
null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
if (partiallyConcretized != null) {
return partiallyConcretized;
}
IfPointcut ret = new IfPointcut(testMethod, extraParameterFlags);
ret.copyLocationFrom(this);
partiallyConcretized = ret;
// It is possible to directly code your pointcut expression in a per clause
// rather than defining a pointcut declaration and referencing it in your
// per clause. If you do this, we have problems (bug #62458). For now,
// let's police that you are trying to code a pointcut in a per clause and
// put out a compiler error.
if (bindings.directlyInAdvice() && bindings.getEnclosingAdvice()==null) {
// Assumption: if() is in a per clause if we say we are directly in advice
// but we have no enclosing advice.
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.IF_IN_PERCLAUSE),
this.getSourceLocation(),null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
if (bindings.directlyInAdvice()) {
ShadowMunger advice = bindings.getEnclosingAdvice();
if (advice instanceof Advice) {
ret.baseArgsCount = ((Advice)advice).getBaseParameterCount();
} else {
ret.baseArgsCount = 0;
}
ret.residueSource = advice.getPointcut().concretize(inAspect, ret.baseArgsCount, advice);
} else {
ResolvedPointcutDefinition def = bindings.peekEnclosingDefinitition();
if (def == CflowPointcut.CFLOW_MARKER) {
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.IF_LEXICALLY_IN_CFLOW),
getSourceLocation(), null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
ret.baseArgsCount = def.getParameterTypes().length;
IntMap newBindings = IntMap.idMap(ret.baseArgsCount);
newBindings.copyContext(bindings);
ret.residueSource = def.getPointcut().concretize(inAspect, newBindings);
}
return ret;
}
// public static Pointcut MatchesNothing = new MatchesNothingPointcut();
// ??? there could possibly be some good optimizations to be done at this point
public static IfPointcut makeIfFalsePointcut(State state) {
IfPointcut ret = new IfFalsePointcut();
ret.state = state;
return ret;
}
private static class IfFalsePointcut extends IfPointcut {
public IfFalsePointcut() {
super(null,0);
}
public Set couldMatchKinds() {
return Collections.EMPTY_SET;
}
public boolean alwaysFalse() {
return true;
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
return Literal.FALSE; // can only get here if an earlier error occurred
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.NO;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
return FuzzyBoolean.NO;
}
public FuzzyBoolean match(JoinPoint.StaticPart jpsp) {
return FuzzyBoolean.NO;
}
public void resolveBindings(IScope scope, Bindings bindings) {
}
public void resolveBindingsFromRTTI() {
}
public void postRead(ResolvedTypeX enclosingType) {
}
public Pointcut concretize1(
ResolvedTypeX inAspect,
IntMap bindings) {
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.IF_IN_DECLARE),
bindings.getEnclosingAdvice().getSourceLocation(),
null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
return makeIfFalsePointcut(state);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.IF_FALSE);
}
public int hashCode() {
int result = 17;
return result;
}
public String toString() {
return "if(false)";
}
}
public static IfPointcut makeIfTruePointcut(State state) {
IfPointcut ret = new IfTruePointcut();
ret.state = state;
return ret;
}
private static class IfTruePointcut extends IfPointcut {
public IfTruePointcut() {
super(null,0);
}
public boolean alwaysTrue() {
return true;
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
return Literal.TRUE; // can only get here if an earlier error occurred
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.YES;
}
protected FuzzyBoolean matchInternal(Shadow shadow) {
return FuzzyBoolean.YES;
}
public FuzzyBoolean match(JoinPoint.StaticPart jpsp) {
return FuzzyBoolean.YES;
}
public void resolveBindings(IScope scope, Bindings bindings) {
}
public void resolveBindingsFromRTTI() {
}
public void postRead(ResolvedTypeX enclosingType) {
}
public Pointcut concretize1(
ResolvedTypeX inAspect,
IntMap bindings) {
if (isDeclare(bindings.getEnclosingAdvice())) {
// Enforce rule about which designators are supported in declare
inAspect.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.IF_IN_DECLARE),
bindings.getEnclosingAdvice().getSourceLocation(),
null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
return makeIfTruePointcut(state);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(IF_TRUE);
}
public int hashCode() {
int result = 37;
return result;
}
public String toString() {
return "if(true)";
}
}
}
|
96,371 |
Bug 96371 Patch to support loading aop.xml properly
|
AspectJ 5 load-time weaving in CVS HEAD isn't loading aop.xml files properly from a jar file without specifying the global -D flag. The following patch fixes the problem for me so I can load aop.xml files from jars on the classpath without a global flag: ClassLoaderWeavingAdaptor.java:109: - Enumeration xmls = loader.getResources("/META-INF/aop.xml"); + Enumeration xmls = loader.getResources("META-INF/aop.xml"); I.e., getResources doesn't work with a leading separator, at least not on the Sun VM or JRockIt on Windows. Writing a unit test for this would require significant changes to the loadtime module, so I wrote a standalone test of the API: public class TestApi extends TestCase { public void testLoadResource() throws Exception { URL urlList[] = { new URL ("file:testsrc/org/aspectj/weaver/loadtime/test/sample.jar") }; ClassLoader loader = new URLClassLoader(urlList); Enumeration xmls = loader.getResources("META-INF/aop.xml"); //this version fails: //Enumeration xmls = loader.getResources("/META-INF/aop.xml"); assertTrue(xmls.hasMoreElements()); } }
|
resolved fixed
|
f14646f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-30T10:00:21Z | 2005-05-23T20:26: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
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.loadtime.definition.Definition;
import org.aspectj.weaver.loadtime.definition.DocumentParser;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.tools.GeneratedClassHandler;
import org.aspectj.weaver.tools.WeavingAdaptor;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class ClassLoaderWeavingAdaptor extends WeavingAdaptor {
//ATAJ LTW include/exclude
private List m_includeTypePattern = new ArrayList();
private List m_excludeTypePattern = new ArrayList();
private List m_aspectExcludeTypePattern = new ArrayList();
public void addIncludeTypePattern(TypePattern typePattern) {
m_includeTypePattern.add(typePattern);
}
public void addExcludeTypePattern(TypePattern typePattern) {
m_excludeTypePattern.add(typePattern);
}
public void addAspectExcludeTypePattern(TypePattern typePattern) {
m_aspectExcludeTypePattern.add(typePattern);
}
public ClassLoaderWeavingAdaptor(final ClassLoader loader) {
super(null);// at this stage we don't have yet a generatedClassHandler to define to the VM the closures
this.generatedClassHandler = new GeneratedClassHandler() {
/**
* Callback when we need to define a Closure in the JVM
*
* @param name
* @param bytes
*/
public void acceptClass(String name, byte[] bytes) {
//TODO av make dump configurable
try {
Aj.__dump(name, bytes);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
Aj.defineClass(loader, name, bytes);// could be done lazily using the hook
}
};
bcelWorld = new BcelWorld(
loader, messageHandler, new ICrossReferenceHandler() {
public void addCrossReference(ISourceLocation from, ISourceLocation to, IRelationship.Kind kind, boolean runtimeTest) {
;// for tools only
}
}
);
// //TODO this AJ code will call
// //org.aspectj.apache.bcel.Repository.setRepository(this);
// //ie set some static things
// //==> bogus as Bcel is expected to be
// org.aspectj.apache.bcel.Repository.setRepository(new ClassLoaderRepository(loader));
weaver = new BcelWeaver(bcelWorld);
// register the definitions
registerDefinitions(weaver, loader);
// 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 {
//TODO av underoptimized: we will parse each XML once per CL that see it
Enumeration xmls = loader.getResources("/META-INF/aop.xml");
List definitions = new ArrayList();
//TODO av dev mode needed ? TBD -Daj5.def=...
if (loader != null && loader != ClassLoader.getSystemClassLoader().getParent()) {
String file = System.getProperty("aj5.def", null);
if (file != null) {
definitions.add(DocumentParser.parse((new File(file)).toURL()));
}
}
while (xmls.hasMoreElements()) {
URL xml = (URL) xmls.nextElement();
definitions.add(DocumentParser.parse(xml));
}
// still go thru if definitions is empty since we will configure
// the default message handler in there
registerOptions(weaver, loader, definitions);
registerAspectExclude(weaver, loader, definitions);
registerAspects(weaver, loader, definitions);
registerIncludeExclude(weaver, loader, definitions);
} 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);
weaver.setReweavableMode(weaverOption.reWeavable, false);
world.setXnoInline(weaverOption.noInline);
world.setBehaveInJava5Way(weaverOption.java5);
//TODO proceedOnError option
}
private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getAspectExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_aspectExcludeTypePattern.add(excludePattern);
}
}
}
/**
* Register the aspect, following include / exclude rules
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
//TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
// if not, review the getResource so that we track which resource is defined by which CL
//it aspectClassNames
//exclude if in any of the exclude list
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator aspects = definition.getAspectClassNames().iterator(); aspects.hasNext();) {
String aspectClassName = (String) aspects.next();
if (acceptAspect(aspectClassName)) {
weaver.addLibraryAspect(aspectClassName);
}
}
}
//it concreteAspects
//exclude if in any of the exclude list
//TODO
}
/**
* Register the include / exclude filters
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List definitions) {
for (Iterator iterator = definitions.iterator(); iterator.hasNext();) {
Definition definition = (Definition) iterator.next();
for (Iterator iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
String include = (String) iterator1.next();
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_includeTypePattern.add(includePattern);
}
for (Iterator iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
String exclude = (String) iterator1.next();
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_excludeTypePattern.add(excludePattern);
}
}
}
protected boolean accept(String className) {
// avoid ResolvedType if not needed
if (m_excludeTypePattern.isEmpty() && m_includeTypePattern.isEmpty()) {
return true;
}
//TODO AV - optimize for className.startWith only
ResolvedTypeX classInfo = weaver.getWorld().getCoreType(TypeX.forName(className));
//exclude
for (Iterator iterator = m_excludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
for (Iterator iterator = m_includeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (! typePattern.matchesStatically(classInfo)) {
// include does not match - skip
return false;
}
}
return true;
}
private boolean acceptAspect(String aspectClassName) {
// avoid ResolvedType if not needed
if (m_aspectExcludeTypePattern.isEmpty()) {
return true;
}
//TODO AV - optimize for className.startWith only
ResolvedTypeX classInfo = weaver.getWorld().getCoreType(TypeX.forName(aspectClassName));
//exclude
for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
return true;
}
}
|
96,371 |
Bug 96371 Patch to support loading aop.xml properly
|
AspectJ 5 load-time weaving in CVS HEAD isn't loading aop.xml files properly from a jar file without specifying the global -D flag. The following patch fixes the problem for me so I can load aop.xml files from jars on the classpath without a global flag: ClassLoaderWeavingAdaptor.java:109: - Enumeration xmls = loader.getResources("/META-INF/aop.xml"); + Enumeration xmls = loader.getResources("META-INF/aop.xml"); I.e., getResources doesn't work with a leading separator, at least not on the Sun VM or JRockIt on Windows. Writing a unit test for this would require significant changes to the loadtime module, so I wrote a standalone test of the API: public class TestApi extends TestCase { public void testLoadResource() throws Exception { URL urlList[] = { new URL ("file:testsrc/org/aspectj/weaver/loadtime/test/sample.jar") }; ClassLoader loader = new URLClassLoader(urlList); Enumeration xmls = loader.getResources("META-INF/aop.xml"); //this version fails: //Enumeration xmls = loader.getResources("/META-INF/aop.xml"); assertTrue(xmls.hasMoreElements()); } }
|
resolved fixed
|
f14646f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-30T10:00:21Z | 2005-05-23T20:26:40Z |
loadtime5/java5-src/org/aspectj/weaver/loadtime/ClassPreProcessorAgentAdapter.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.weaver.loadtime.Aj;
import org.aspectj.weaver.loadtime.ClassPreProcessor;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
/**
* Java 1.5 adapter for class pre processor
*
* @author <a href="mailto:[email protected]">Alexandre Vasseur</a>
*/
public class ClassPreProcessorAgentAdapter implements ClassFileTransformer {
/**
* Concrete preprocessor.
*/
private static ClassPreProcessor s_preProcessor;
static {
try {
s_preProcessor = new Aj();
s_preProcessor.initialize();
} catch (Exception e) {
throw new ExceptionInInitializerError("could not initialize JSR163 preprocessor due to: " + e.toString());
}
}
/**
* Weaving delegation
*
* @param loader the defining class loader
* @param className the name of class beeing loaded
* @param classBeingRedefined when hotswap is called
* @param protectionDomain
* @param bytes the bytecode before weaving
* @return the weaved bytecode
*/
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {
if (classBeingRedefined == null) {
return s_preProcessor.preProcess(className, bytes, loader);
} else {
//FIXME av for now we skip hotswap. We should think more about that
new Exception("AspectJ5 does not weave hotswapped class (" + className + ")").printStackTrace();
return bytes;
}
}
}
|
96,371 |
Bug 96371 Patch to support loading aop.xml properly
|
AspectJ 5 load-time weaving in CVS HEAD isn't loading aop.xml files properly from a jar file without specifying the global -D flag. The following patch fixes the problem for me so I can load aop.xml files from jars on the classpath without a global flag: ClassLoaderWeavingAdaptor.java:109: - Enumeration xmls = loader.getResources("/META-INF/aop.xml"); + Enumeration xmls = loader.getResources("META-INF/aop.xml"); I.e., getResources doesn't work with a leading separator, at least not on the Sun VM or JRockIt on Windows. Writing a unit test for this would require significant changes to the loadtime module, so I wrote a standalone test of the API: public class TestApi extends TestCase { public void testLoadResource() throws Exception { URL urlList[] = { new URL ("file:testsrc/org/aspectj/weaver/loadtime/test/sample.jar") }; ClassLoader loader = new URLClassLoader(urlList); Enumeration xmls = loader.getResources("META-INF/aop.xml"); //this version fails: //Enumeration xmls = loader.getResources("/META-INF/aop.xml"); assertTrue(xmls.hasMoreElements()); } }
|
resolved fixed
|
f14646f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-05-30T10:00:21Z | 2005-05-23T20:26:40Z |
tests/java5/ataspectj/ataspectj/SingletonAspectBindingsTest.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 ataspectj;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.DeclarePrecedence;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.runtime.internal.AroundClosure;
import junit.framework.TestCase;
/**
* Test various advice and JoinPoint + binding, without pc ref
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class SingletonAspectBindingsTest extends TestCase {
static StringBuffer s_log = new StringBuffer();
static void log(String s) {
s_log.append(s).append(" ");
}
public static void main(String[] args) {
TestHelper.runAndThrowOnFailure(suite());
}
public static junit.framework.Test suite() {
return new junit.framework.TestSuite(SingletonAspectBindingsTest.class);
}
public void hello() {
log("hello");
}
public void hello(String s) {
log("hello-");
log(s);
}
public void testExecutionWithThisBinding() {
s_log = new StringBuffer();
SingletonAspectBindingsTest me = new SingletonAspectBindingsTest();
me.hello();
// see here advice precedence as in source code order
//TODO check around relative order
// see fix in BcelWeaver sorting shadowMungerList
//assertEquals("around2_ around_ before hello after _around _around2 ", s_log.toString());
assertEquals("around_ around2_ before hello _around2 _around after ", s_log.toString());
}
public void testExecutionWithArgBinding() {
s_log = new StringBuffer();
SingletonAspectBindingsTest me = new SingletonAspectBindingsTest();
me.hello("x");
assertEquals("before- x hello- x ", s_log.toString());
}
@Aspect
public static class TestAspect {
static int s = 0;
static {
s++;
}
public TestAspect() {
// assert clinit has run when singleton aspectOf reaches that
assertTrue(s>0);
}
//public static TestAspect aspectOf() {return null;}
@Around("execution(* ataspectj.SingletonAspectBindingsTest.hello())")
public void aaround(ProceedingJoinPoint jp) {
log("around_");
try {
jp.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
log("_around");
}
@Around("execution(* ataspectj.SingletonAspectBindingsTest.hello()) && this(t)")
public void around2(ProceedingJoinPoint jp, Object t) {
log("around2_");
assertEquals(SingletonAspectBindingsTest.class.getName(), t.getClass().getName());
try {
jp.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
log("_around2");
}
@Before("execution(* ataspectj.SingletonAspectBindingsTest.hello())")
public void before(JoinPoint.StaticPart sjp) {
log("before");
assertEquals("hello", sjp.getSignature().getName());
}
@After("execution(* ataspectj.SingletonAspectBindingsTest.hello())")
public void after(JoinPoint.StaticPart sjp) {
log("after");
assertEquals("execution(public void ataspectj.SingletonAspectBindingsTest.hello())", sjp.toLongString());
}
//TODO see String alias, see before advice name clash - all that works
// 1/ String is in java.lang.* - see SimpleScope.javalangPrefix array
// 2/ the advice is register thru its Bcel Method mirror
@Before("execution(* ataspectj.SingletonAspectBindingsTest.hello(String)) && args(s)")
public void before(String s, JoinPoint.StaticPart sjp) {
log("before-");
log(s);
assertEquals("hello", sjp.getSignature().getName());
}
}
}
|
81,846 |
Bug 81846 EclipseAdapterUtils.java:83
|
java.lang.ArrayIndexOutOfBoundsException: 3 Unfortunately I can't provide much more information, please see the attached compiler dump.
|
resolved fixed
|
a675b65
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-01T16:12:58Z | 2004-12-23T11:06:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.core.compiler.IProblem;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
/**
*
*/
public class EclipseAdapterUtils {
//XXX some cut-and-paste from eclipse sources
public static String makeLocationContext(ICompilationUnit compilationUnit, IProblem problem) {
//extra from the source the innacurate token
//and "highlight" it using some underneath ^^^^^
//put some context around too.
//this code assumes that the font used in the console is fixed size
//sanity .....
int startPosition = problem.getSourceStart();
int endPosition = problem.getSourceEnd();
if ((startPosition > endPosition)
|| ((startPosition <= 0) && (endPosition <= 0))
|| compilationUnit==null)
//return Util.bind("problem.noSourceInformation"); //$NON-NLS-1$
return "(no source information available)";
final char SPACE = '\u0020';
final char MARK = '^';
final char TAB = '\t';
char[] source = compilationUnit.getContents();
//the next code tries to underline the token.....
//it assumes (for a good display) that token source does not
//contain any \r \n. This is false on statements !
//(the code still works but the display is not optimal !)
//compute the how-much-char we are displaying around the inaccurate token
int begin = startPosition >= source.length ? source.length - 1 : startPosition;
int relativeStart = 0;
int end = endPosition >= source.length ? source.length - 1 : endPosition;
int relativeEnd = 0;
label : for (relativeStart = 0;; relativeStart++) {
if (begin == 0)
break label;
if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r'))
break label;
begin--;
}
label : for (relativeEnd = 0;; relativeEnd++) {
if ((end + 1) >= source.length)
break label;
if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) {
break label;
}
end++;
}
//extract the message form the source
char[] extract = new char[end - begin + 1];
System.arraycopy(source, begin, extract, 0, extract.length);
char c;
//remove all SPACE and TAB that begin the error message...
int trimLeftIndex = 0;
while (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) {
};
System.arraycopy(
extract,
trimLeftIndex - 1,
extract = new char[extract.length - trimLeftIndex + 1],
0,
extract.length);
relativeStart -= trimLeftIndex;
//buffer spaces and tabs in order to reach the error position
int pos = 0;
char[] underneath = new char[extract.length]; // can't be bigger
for (int i = 0; i <= relativeStart; i++) {
if (extract[i] == TAB) {
underneath[pos++] = TAB;
} else {
underneath[pos++] = SPACE;
}
}
//mark the error position
for (int i = startPosition + trimLeftIndex; // AMC if we took stuff off the start, take it into account!
i <= (endPosition >= source.length ? source.length - 1 : endPosition);
i++)
underneath[pos++] = MARK;
//resize underneathto remove 'null' chars
System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos);
return new String(extract) + "\n" + new String(underneath); //$NON-NLS-2$ //$NON-NLS-1$
}
/**
* Extract source location file, start and end lines, and context.
* Column is not extracted correctly.
* @return ISourceLocation with correct file and lines but not column.
*/
public static ISourceLocation makeSourceLocation(ICompilationUnit unit, IProblem problem) {
int line = problem.getSourceLineNumber();
File file = new File(new String(problem.getOriginatingFileName()));
String context = makeLocationContext(unit, problem);
// XXX 0 column is wrong but recoverable from makeLocationContext
return new SourceLocation(file, line, line, 0, context);
}
/**
* Extract message text and source location, including context.
*/
public static IMessage makeMessage(ICompilationUnit unit, IProblem problem) {
ISourceLocation sourceLocation = makeSourceLocation(unit, problem);
IProblem[] seeAlso = problem.seeAlso();
ISourceLocation[] seeAlsoLocations = new ISourceLocation[seeAlso.length];
for (int i = 0; i < seeAlso.length; i++) {
seeAlsoLocations[i] = new SourceLocation(new File(new String(seeAlso[i].getOriginatingFileName())),
seeAlso[i].getSourceLineNumber());
}
// We transform messages from AJ types to eclipse IProblems
// and back to AJ types. During their time as eclipse problems,
// we remember whether the message originated from a declare
// in the extraDetails.
String extraDetails = problem.getSupplementaryMessageInfo();
boolean declared = false;
if (extraDetails!=null && extraDetails.endsWith("[deow=true]")) {
declared = true;
extraDetails = extraDetails.substring(0,extraDetails.length()-"[deow=true]".length());
}
// If the 'problem' represents a TO DO kind of thing then use the message kind that
// represents this so AJDT sees it correctly.
IMessage.Kind kind;
if (problem.getID()==IProblem.Task) {
kind=IMessage.TASKTAG;
} else {
if (problem.isError()) { kind = IMessage.ERROR; }
else { kind = IMessage.WARNING; }
}
IMessage msg = new Message(problem.getMessage(),
extraDetails,
kind,
sourceLocation,
null,
seeAlsoLocations,
declared,
problem.getID(),
problem.getSourceStart(),problem.getSourceEnd());
return msg;
}
public static IMessage makeErrorMessage(ICompilationUnit unit, String text, Exception ex) {
ISourceLocation loc = new SourceLocation(new File(new String(unit.getFileName())),
0,0,0,"");
IMessage msg = new Message(text,IMessage.ERROR,ex,loc);
return msg;
}
public static IMessage makeErrorMessage(String srcFile, String text, Exception ex) {
ISourceLocation loc = new SourceLocation(new File(srcFile),
0,0,0,"");
IMessage msg = new Message(text,IMessage.ERROR,ex,loc);
return msg;
}
private EclipseAdapterUtils() {
}
}
|
94,167 |
Bug 94167 NPE in reflect implementation
|
Proposed fix (I'd like input on how to best add test cases for this so I can submit a tested patch); I believe this will work because if you uncomment the work-around line, it works): Change line 63 from: method = declaringType.getDeclaredMethod (getName(),getParameterTypes()); to method = getDeclaringType().getDeclaredMethod (getName(),getParameterTypes()); Test source: package reflect; import org.aspectj.lang.*; import org.aspectj.lang.reflect.*; import java.lang.reflect.*; aspect Test { before() : call(* *(..)) && !within(Test) { MethodSignature sig = (MethodSignature)thisJoinPoint.getSignature(); //sig.getDeclaringType(); // uncomment to work-around Method method = sig.getMethod(); } } public class MinimalErr { public static void main(String args[]) { try { Inner.foo(); } catch (Throwable t) { t.printStackTrace(); } } public static class Inner { public static void foo() {} } }
|
resolved fixed
|
3824b1c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-07T12:17:30Z | 2005-05-09T17:33:20Z |
runtime/src/org/aspectj/runtime/reflect/AdviceSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import java.lang.reflect.Method;
import org.aspectj.lang.reflect.AdviceSignature;
class AdviceSignatureImpl extends CodeSignatureImpl implements AdviceSignature {
Class returnType;
private Method adviceMethod = null;
AdviceSignatureImpl(int modifiers, String name, Class declaringType,
Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes,
Class returnType)
{
super(modifiers, name, declaringType, parameterTypes, parameterNames,
exceptionTypes);
this.returnType = returnType;
}
AdviceSignatureImpl(String stringRep) {
super(stringRep);
}
/* name is consistent with reflection API
before and after always return Void.TYPE
(some around also return Void.Type) */
public Class getReturnType() {
if (returnType == null) returnType = extractType(6);
return returnType;
}
protected String createToString(StringMaker sm) {
//XXX this signature needs a lot of work
StringBuffer buf = new StringBuffer("ADVICE: ");
buf.append(sm.makeModifiersString(getModifiers()));
if (sm.includeArgs) buf.append(sm.makeTypeName(getReturnType()));
if (sm.includeArgs) buf.append(" ");
buf.append(sm.makePrimaryTypeName(getDeclaringType(),getDeclaringTypeName()));
buf.append(".");
buf.append(getName());
sm.addSignature(buf, getParameterTypes());
sm.addThrows(buf, getExceptionTypes());
return buf.toString();
}
/* (non-Javadoc)
* @see org.aspectj.runtime.reflect.MemberSignatureImpl#createAccessibleObject()
*/
public Method getAdvice() {
if (adviceMethod == null) {
try {
adviceMethod = declaringType.getDeclaredMethod(getName(),getParameterTypes());
} catch (Exception ex) {
; // nothing we can do, caller will see null
}
}
return adviceMethod;
}
}
|
94,167 |
Bug 94167 NPE in reflect implementation
|
Proposed fix (I'd like input on how to best add test cases for this so I can submit a tested patch); I believe this will work because if you uncomment the work-around line, it works): Change line 63 from: method = declaringType.getDeclaredMethod (getName(),getParameterTypes()); to method = getDeclaringType().getDeclaredMethod (getName(),getParameterTypes()); Test source: package reflect; import org.aspectj.lang.*; import org.aspectj.lang.reflect.*; import java.lang.reflect.*; aspect Test { before() : call(* *(..)) && !within(Test) { MethodSignature sig = (MethodSignature)thisJoinPoint.getSignature(); //sig.getDeclaringType(); // uncomment to work-around Method method = sig.getMethod(); } } public class MinimalErr { public static void main(String args[]) { try { Inner.foo(); } catch (Throwable t) { t.printStackTrace(); } } public static class Inner { public static void foo() {} } }
|
resolved fixed
|
3824b1c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-07T12:17:30Z | 2005-05-09T17:33:20Z |
runtime/src/org/aspectj/runtime/reflect/MethodSignatureImpl.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.runtime.reflect;
import java.lang.reflect.Method;
import org.aspectj.lang.reflect.MethodSignature;
class MethodSignatureImpl extends CodeSignatureImpl implements MethodSignature {
private Method method;
Class returnType;
MethodSignatureImpl(int modifiers, String name, Class declaringType,
Class[] parameterTypes, String[] parameterNames, Class[] exceptionTypes,
Class returnType)
{
super(modifiers, name, declaringType, parameterTypes, parameterNames,
exceptionTypes);
this.returnType = returnType;
}
MethodSignatureImpl(String stringRep) {
super(stringRep);
}
/* name is consistent with reflection API */
public Class getReturnType() {
if (returnType == null) returnType = extractType(6);
return returnType;
}
protected String createToString(StringMaker sm) {
StringBuffer buf = new StringBuffer();
buf.append(sm.makeModifiersString(getModifiers()));
if (sm.includeArgs) buf.append(sm.makeTypeName(getReturnType()));
if (sm.includeArgs) buf.append(" ");
buf.append(sm.makePrimaryTypeName(getDeclaringType(),getDeclaringTypeName()));
buf.append(".");
buf.append(getName());
sm.addSignature(buf, getParameterTypes());
sm.addThrows(buf, getExceptionTypes());
return buf.toString();
}
/* (non-Javadoc)
* @see org.aspectj.lang.reflect.MemberSignature#getAccessibleObject()
*/
public Method getMethod() {
if (method == null) {
try {
method = declaringType.getDeclaredMethod(getName(),getParameterTypes());
} catch (NoSuchMethodException nsmEx) {
; // nothing we can do, user will see null return
}
}
return method;
}
}
|
94,167 |
Bug 94167 NPE in reflect implementation
|
Proposed fix (I'd like input on how to best add test cases for this so I can submit a tested patch); I believe this will work because if you uncomment the work-around line, it works): Change line 63 from: method = declaringType.getDeclaredMethod (getName(),getParameterTypes()); to method = getDeclaringType().getDeclaredMethod (getName(),getParameterTypes()); Test source: package reflect; import org.aspectj.lang.*; import org.aspectj.lang.reflect.*; import java.lang.reflect.*; aspect Test { before() : call(* *(..)) && !within(Test) { MethodSignature sig = (MethodSignature)thisJoinPoint.getSignature(); //sig.getDeclaringType(); // uncomment to work-around Method method = sig.getMethod(); } } public class MinimalErr { public static void main(String args[]) { try { Inner.foo(); } catch (Throwable t) { t.printStackTrace(); } } public static class Inner { public static void foo() {} } }
|
resolved fixed
|
3824b1c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-07T12:17:30Z | 2005-05-09T17:33:20Z |
tests/bugs150/PR94167.java
| |
94,167 |
Bug 94167 NPE in reflect implementation
|
Proposed fix (I'd like input on how to best add test cases for this so I can submit a tested patch); I believe this will work because if you uncomment the work-around line, it works): Change line 63 from: method = declaringType.getDeclaredMethod (getName(),getParameterTypes()); to method = getDeclaringType().getDeclaredMethod (getName(),getParameterTypes()); Test source: package reflect; import org.aspectj.lang.*; import org.aspectj.lang.reflect.*; import java.lang.reflect.*; aspect Test { before() : call(* *(..)) && !within(Test) { MethodSignature sig = (MethodSignature)thisJoinPoint.getSignature(); //sig.getDeclaringType(); // uncomment to work-around Method method = sig.getMethod(); } } public class MinimalErr { public static void main(String args[]) { try { Inner.foo(); } catch (Throwable t) { t.printStackTrace(); } } public static class Inner { public static void foo() {} } }
|
resolved fixed
|
3824b1c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-07T12:17:30Z | 2005-05-09T17: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 junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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");
}
/**
* 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 testIfEvaluationExplosiion_PR94086() {
runTest("Exploding compile time with if() statements in pointcut");
}
// 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);
}
}
|
98,646 |
Bug 98646 parser cannot parse varargs correctly
|
the following cannot be parsed: call(* *(int, Integer...)) see in modules/weaver/.../PointcutVisitorTest (uncomment the testTemp()) See "FIXME AV for Adrian" comments in PatternParser. Half fix but then fails for other tests. Adrian can you have a look at it ? Thanks
|
resolved fixed
|
743566f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-07T13:12:51Z | 2005-06-07T10:26:40Z |
weaver/src/org/aspectj/weaver/patterns/BasicTokenSource.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.util.ArrayList;
import java.util.List;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
public class BasicTokenSource implements ITokenSource {
private int index = 0;
private IToken[] tokens;
private ISourceContext sourceContext;
public BasicTokenSource(IToken[] tokens, ISourceContext sourceContext) {
this.tokens = tokens;
this.sourceContext = sourceContext;
}
public int getIndex() {
return index;
}
public void setIndex(int newIndex) {
this.index = newIndex;
}
public IToken next() {
try {
return tokens[index++];
} catch (ArrayIndexOutOfBoundsException e) {
return IToken.EOF;
}
}
public IToken peek() {
try {
return tokens[index];
} catch (ArrayIndexOutOfBoundsException e) {
return IToken.EOF;
}
}
public IToken peek(int offset) {
try {
return tokens[index+offset];
} catch (ArrayIndexOutOfBoundsException e) {
return IToken.EOF;
}
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("[");
for (int i = 0; i < tokens.length; i++) {
IToken t = tokens[i];
if (t == null)
break;
if (i > 0)
buf.append(", ");
buf.append(t.toString());
}
buf.append("]");
return buf.toString();
}
//////////////////////////////////////////////////////
// Convenience, maybe just for testing
static ITokenSource makeTokenSource(String input, ISourceContext context) {
char[] chars = input.toCharArray();
int i = 0;
List tokens = new ArrayList();
while (i < chars.length) {
char ch = chars[i++];
switch(ch) {
case ' ':
case '\t':
case '\n':
case '\r':
continue;
case '*':
case '.':
case '(':
case ')':
case '+':
case '[':
case ']':
case ',':
case '!':
case ':':
case '@':
tokens.add(BasicToken.makeOperator(makeString(ch), i-1, i-1));
continue;
case '&':
case '|':
if (i == chars.length) {
throw new BCException("bad " + ch);
}
char nextChar = chars[i++];
if (nextChar == ch) {
tokens.add(BasicToken.makeOperator(makeString(ch, 2), i-2, i-1));
} else {
throw new RuntimeException("bad " + ch);
}
continue;
case '\"':
int start0 = i-1;
while (i < chars.length && !(chars[i]=='\"')) i++;
i += 1;
tokens.add(BasicToken.makeLiteral(new String(chars, start0+1, i-start0-2), "string", start0, i-1));
continue;
default:
int start = i-1;
while (i < chars.length && Character.isJavaIdentifierPart(chars[i])) { i++; }
tokens.add(BasicToken.makeIdentifier(new String(chars, start, i-start), start, i-1));
}
}
//System.out.println(tokens);
return new BasicTokenSource((IToken[])tokens.toArray(new IToken[tokens.size()]), context);
}
private static String makeString(char ch) {
// slightly inefficient ;-)
return new String(new char[] {ch});
}
private static String makeString(char ch, int count) {
// slightly inefficient ;-)
char[] chars = new char[count];
for (int i=0; i<count; i++) { chars[i] = ch; }
return new String(chars);
}
public ISourceContext getSourceContext() {
return sourceContext;
}
public void setSourceContext(ISourceContext context) {
this.sourceContext = context;
}
}
|
98,646 |
Bug 98646 parser cannot parse varargs correctly
|
the following cannot be parsed: call(* *(int, Integer...)) see in modules/weaver/.../PointcutVisitorTest (uncomment the testTemp()) See "FIXME AV for Adrian" comments in PatternParser. Half fix but then fails for other tests. Adrian can you have a look at it ? Thanks
|
resolved fixed
|
743566f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-07T13:12:51Z | 2005-06-07T10:26:40Z |
weaver/src/org/aspectj/weaver/patterns/PatternParser.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.util.ArrayList;
import java.util.List;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
//XXX doesn't handle errors for extra tokens very well (sometimes ignores)
public class PatternParser {
private ITokenSource tokenSource;
private ISourceContext sourceContext;
/**
* Constructor for PatternParser.
*/
public PatternParser(ITokenSource tokenSource) {
super();
this.tokenSource = tokenSource;
this.sourceContext = tokenSource.getSourceContext();
}
public PerClause maybeParsePerClause() {
IToken tok = tokenSource.peek();
if (tok == IToken.EOF) return null;
if (tok.isIdentifier()) {
String name = tok.getString();
if (name.equals("issingleton")) {
return parsePerSingleton();
} else if (name.equals("perthis")) {
return parsePerObject(true);
} else if (name.equals("pertarget")) {
return parsePerObject(false);
} else if (name.equals("percflow")) {
return parsePerCflow(false);
} else if (name.equals("percflowbelow")) {
return parsePerCflow(true);
} else if (name.equals("pertypewithin")) { // PTWIMPL Parse the pertypewithin clause
return parsePerTypeWithin();
} else {
return null;
}
}
return null;
}
private PerClause parsePerCflow(boolean isBelow) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new PerCflow(entry, isBelow);
}
private PerClause parsePerObject(boolean isThis) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new PerObject(entry, isThis);
}
private PerClause parsePerTypeWithin() {
parseIdentifier();
eat("(");
TypePattern withinTypePattern = parseTypePattern();
eat(")");
return new PerTypeWithin(withinTypePattern);
}
private PerClause parsePerSingleton() {
parseIdentifier();
eat("(");
eat(")");
return new PerSingleton();
}
public Declare parseDeclare() {
int startPos = tokenSource.peek().getStart();
eatIdentifier("declare");
String kind = parseIdentifier();
eat(":");
Declare ret;
if (kind.equals("error")) {
ret = parseErrorOrWarning(true);
} else if (kind.equals("warning")) {
ret = parseErrorOrWarning(false);
} else if (kind.equals("precedence")) {
ret = parseDominates();
} else if (kind.equals("dominates")) {
throw new ParserException("name changed to declare precedence", tokenSource.peek(-2));
} else if (kind.equals("parents")) {
ret = parseParents();
} else if (kind.equals("soft")) {
ret = parseSoft();
} else {
throw new ParserException("expected one of error, warning, parents, soft, dominates",
tokenSource.peek(-1));
}
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
public Declare parseDeclareAnnotation() {
int startPos = tokenSource.peek().getStart();
eatIdentifier("declare");
eat("@");
String kind = parseIdentifier();
eat(":");
Declare ret;
if (kind.equals("type")) {
ret = parseDeclareAtType();
} else if (kind.equals("method")) {
ret = parseDeclareAtMethod(true);
} else if (kind.equals("field")) {
ret = parseDeclareAtField();
} else if (kind.equals("constructor")) {
ret = parseDeclareAtMethod(false);
} else {
throw new ParserException("one of type, method, field, constructor",tokenSource.peek(-1));
}
eat(";");
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
public DeclareAnnotation parseDeclareAtType() {
return new DeclareAnnotation(DeclareAnnotation.AT_TYPE,parseTypePattern());
}
public DeclareAnnotation parseDeclareAtMethod(boolean isMethod) {
SignaturePattern sp = parseMethodOrConstructorSignaturePattern();
boolean isConstructorPattern = (sp.getKind() == Member.CONSTRUCTOR);
if (isMethod && isConstructorPattern) {
throw new ParserException("method signature pattern",tokenSource.peek(-1));
}
if (!isMethod && !isConstructorPattern) {
throw new ParserException("constructor signature pattern",tokenSource.peek(-1));
}
if (isConstructorPattern) return new DeclareAnnotation(DeclareAnnotation.AT_CONSTRUCTOR,sp);
else return new DeclareAnnotation(DeclareAnnotation.AT_METHOD,sp);
}
public DeclareAnnotation parseDeclareAtField() {
return new DeclareAnnotation(DeclareAnnotation.AT_FIELD,parseFieldSignaturePattern());
}
public DeclarePrecedence parseDominates() {
List l = new ArrayList();
do {
l.add(parseTypePattern());
} while (maybeEat(","));
return new DeclarePrecedence(l);
}
private Declare parseParents() {
TypePattern p = parseTypePattern();
IToken t = tokenSource.next();
if (!(t.getString().equals("extends") || t.getString().equals("implements"))) {
throw new ParserException("extends or implements", t);
}
List l = new ArrayList();
do {
l.add(parseTypePattern());
} while (maybeEat(","));
//XXX somewhere in the chain we need to enforce that we have only ExactTypePatterns
return new DeclareParents(p, l);
}
private Declare parseSoft() {
TypePattern p = parseTypePattern();
eat(":");
Pointcut pointcut = parsePointcut();
return new DeclareSoft(p, pointcut);
}
private Declare parseErrorOrWarning(boolean isError) {
Pointcut pointcut = parsePointcut();
eat(":");
String message = parsePossibleStringSequence(true);
return new DeclareErrorOrWarning(isError, pointcut, message);
}
public Pointcut parsePointcut() {
Pointcut p = parseAtomicPointcut();
if (maybeEat("&&")) {
p = new AndPointcut(p, parseNotOrPointcut());
}
if (maybeEat("||")) {
p = new OrPointcut(p, parsePointcut());
}
return p;
}
private Pointcut parseNotOrPointcut() {
Pointcut p = parseAtomicPointcut();
if (maybeEat("&&")) {
p = new AndPointcut(p, parsePointcut());
}
return p;
}
private Pointcut parseAtomicPointcut() {
if (maybeEat("!")) {
int startPos = tokenSource.peek(-1).getStart();
Pointcut p = new NotPointcut(parseAtomicPointcut(), startPos);
return p;
}
if (maybeEat("(")) {
Pointcut p = parsePointcut();
eat(")");
return p;
}
if (maybeEat("@")) {
int startPos = tokenSource.peek().getStart();
Pointcut p = parseAnnotationPointcut();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext, startPos, endPos);
return p;
}
int startPos = tokenSource.peek().getStart();
Pointcut p = parseSinglePointcut();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext, startPos, endPos);
return p;
}
public Pointcut parseSinglePointcut() {
int start = tokenSource.getIndex();
IToken t = tokenSource.peek();
Pointcut p = t.maybeGetParsedPointcut();
if (p != null) {
tokenSource.next();
return p;
}
String kind = parseIdentifier();
tokenSource.setIndex(start);
if (kind.equals("execution") || kind.equals("call") ||
kind.equals("get") || kind.equals("set")) {
return parseKindedPointcut();
} else if (kind.equals("args")) {
return parseArgsPointcut();
} else if (kind.equals("this") || kind.equals("target")) {
return parseThisOrTargetPointcut();
} else if (kind.equals("within")) {
return parseWithinPointcut();
} else if (kind.equals("withincode")) {
return parseWithinCodePointcut();
} else if (kind.equals("cflow")) {
return parseCflowPointcut(false);
} else if (kind.equals("cflowbelow")) {
return parseCflowPointcut(true);
} else if (kind.equals("adviceexecution")) {
parseIdentifier(); eat("(");
eat(")");
return new KindedPointcut(Shadow.AdviceExecution,
new SignaturePattern(Member.ADVICE, ModifiersPattern.ANY,
TypePattern.ANY, TypePattern.ANY, NamePattern.ANY,
TypePatternList.ANY,
ThrowsPattern.ANY,
AnnotationTypePattern.ANY));
} else if (kind.equals("handler")) {
parseIdentifier(); eat("(");
TypePattern typePat = parseTypePattern();
eat(")");
return new HandlerPointcut(typePat);
} else if (kind.equals("initialization")) {
parseIdentifier(); eat("(");
SignaturePattern sig = parseConstructorSignaturePattern();
eat(")");
return new KindedPointcut(Shadow.Initialization, sig);
} else if (kind.equals("staticinitialization")) {
parseIdentifier(); eat("(");
TypePattern typePat = parseTypePattern();
eat(")");
return new KindedPointcut(Shadow.StaticInitialization,
new SignaturePattern(Member.STATIC_INITIALIZATION, ModifiersPattern.ANY,
TypePattern.ANY, typePat, NamePattern.ANY, TypePatternList.EMPTY,
ThrowsPattern.ANY,AnnotationTypePattern.ANY));
} else if (kind.equals("preinitialization")) {
parseIdentifier(); eat("(");
SignaturePattern sig = parseConstructorSignaturePattern();
eat(")");
return new KindedPointcut(Shadow.PreInitialization, sig);
} else {
return parseReferencePointcut();
}
}
public Pointcut parseAnnotationPointcut() {
int start = tokenSource.getIndex();
IToken t = tokenSource.peek();
String kind = parseIdentifier();
tokenSource.setIndex(start);
if (kind.equals("annotation")) {
return parseAtAnnotationPointcut();
} else if (kind.equals("args")) {
return parseArgsAnnotationPointcut();
} else if (kind.equals("this") || kind.equals("target")) {
return parseThisOrTargetAnnotationPointcut();
} else if (kind.equals("within")) {
return parseWithinAnnotationPointcut();
} else if (kind.equals("withincode")) {
return parseWithinCodeAnnotationPointcut();
} throw new ParserException("pointcut name", t);
}
private Pointcut parseAtAnnotationPointcut() {
parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("@AnnotationName or parameter", tokenSource.peek());
}
ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new AnnotationPointcut(type);
}
private SignaturePattern parseConstructorSignaturePattern() {
SignaturePattern ret = parseMethodOrConstructorSignaturePattern();
if (ret.getKind() == Member.CONSTRUCTOR) return ret;
throw new ParserException("constructor pattern required, found method pattern",
ret);
}
private Pointcut parseWithinCodePointcut() {
parseIdentifier();
eat("(");
SignaturePattern sig = parseMethodOrConstructorSignaturePattern();
eat(")");
return new WithincodePointcut(sig);
}
private Pointcut parseCflowPointcut(boolean isBelow) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new CflowPointcut(entry, isBelow, null);
}
/**
* Method parseWithinPointcut.
* @return Pointcut
*/
private Pointcut parseWithinPointcut() {
parseIdentifier();
eat("(");
TypePattern type = parseTypePattern();
eat(")");
return new WithinPointcut(type);
}
/**
* Method parseThisOrTargetPointcut.
* @return Pointcut
*/
private Pointcut parseThisOrTargetPointcut() {
String kind = parseIdentifier();
eat("(");
TypePattern type = parseTypePattern();
eat(")");
return new ThisOrTargetPointcut(kind.equals("this"), type);
}
private Pointcut parseThisOrTargetAnnotationPointcut() {
String kind = parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek());
}
ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new ThisOrTargetAnnotationPointcut(kind.equals("this"),type);
}
private Pointcut parseWithinAnnotationPointcut() {
String kind = parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek());
}
AnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new WithinAnnotationPointcut(type);
}
private Pointcut parseWithinCodeAnnotationPointcut() {
String kind = parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek());
}
ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new WithinCodeAnnotationPointcut(type);
}
/**
* Method parseArgsPointcut.
* @return Pointcut
*/
private Pointcut parseArgsPointcut() {
parseIdentifier();
TypePatternList arguments = parseArgumentsPattern();
return new ArgsPointcut(arguments);
}
private Pointcut parseArgsAnnotationPointcut() {
parseIdentifier();
AnnotationPatternList arguments = parseArgumentsAnnotationPattern();
return new ArgsAnnotationPointcut(arguments);
}
private Pointcut parseReferencePointcut() {
TypePattern onType = parseTypePattern();
NamePattern name = tryToExtractName(onType);
if (name == null) {
throw new ParserException("name pattern", tokenSource.peek());
}
if (onType.toString().equals("")) {
onType = null;
}
TypePatternList arguments = parseArgumentsPattern();
return new ReferencePointcut(onType, name.maybeGetSimpleName(), arguments);
}
public List parseDottedIdentifier() {
List ret = new ArrayList();
ret.add(parseIdentifier());
while (maybeEat(".")) {
ret.add(parseIdentifier());
}
return ret;
}
private KindedPointcut parseKindedPointcut() {
String kind = parseIdentifier();
eat("(");
SignaturePattern sig;
Shadow.Kind shadowKind = null;
if (kind.equals("execution")) {
sig = parseMethodOrConstructorSignaturePattern();
if (sig.getKind() == Member.METHOD) {
shadowKind = Shadow.MethodExecution;
} else if (sig.getKind() == Member.CONSTRUCTOR) {
shadowKind = Shadow.ConstructorExecution;
}
} else if (kind.equals("call")) {
sig = parseMethodOrConstructorSignaturePattern();
if (sig.getKind() == Member.METHOD) {
shadowKind = Shadow.MethodCall;
} else if (sig.getKind() == Member.CONSTRUCTOR) {
shadowKind = Shadow.ConstructorCall;
}
} else if (kind.equals("get")) {
sig = parseFieldSignaturePattern();
shadowKind = Shadow.FieldGet;
} else if (kind.equals("set")) {
sig = parseFieldSignaturePattern();
shadowKind = Shadow.FieldSet;
} else {
throw new ParserException("bad kind: " + kind, tokenSource.peek());
}
eat(")");
return new KindedPointcut(shadowKind, sig);
}
public TypePattern parseTypePattern() {
TypePattern p = parseAtomicTypePattern();
if (maybeEat("&&")) {
p = new AndTypePattern(p, parseNotOrTypePattern());
}
if (maybeEat("||")) {
p = new OrTypePattern(p, parseTypePattern());
}
return p;
}
private TypePattern parseNotOrTypePattern() {
TypePattern p = parseAtomicTypePattern();
if (maybeEat("&&")) {
p = new AndTypePattern(p, parseTypePattern());
}
return p;
}
private TypePattern parseAtomicTypePattern() {
AnnotationTypePattern ap = maybeParseAnnotationPattern();
if (maybeEat("!")) {
//int startPos = tokenSource.peek(-1).getStart();
//??? we lose source location for true start of !type
TypePattern p = new NotTypePattern(parseAtomicTypePattern());
p = setAnnotationPatternForTypePattern(p,ap);
return p;
}
if (maybeEat("(")) {
TypePattern p = parseTypePattern();
p = setAnnotationPatternForTypePattern(p,ap);
eat(")");
boolean isVarArgs = maybeEat("...");
p.setIsVarArgs(isVarArgs);
return p;
}
int startPos = tokenSource.peek().getStart();
TypePattern p = parseSingleTypePattern();
int endPos = tokenSource.peek(-1).getEnd();
p = setAnnotationPatternForTypePattern(p,ap);
p.setLocation(sourceContext, startPos, endPos);
return p;
}
private TypePattern setAnnotationPatternForTypePattern(TypePattern t, AnnotationTypePattern ap) {
TypePattern ret = t;
if (ap != AnnotationTypePattern.ANY) {
if (t == TypePattern.ANY) {
ret = new WildTypePattern(new NamePattern[] {NamePattern.ANY},false,0,false);
}
if (t.annotationPattern == AnnotationTypePattern.ANY) {
ret.setAnnotationTypePattern(ap);
} else {
ret.setAnnotationTypePattern(new AndAnnotationTypePattern(ap,t.annotationPattern)); //???
}
}
return ret;
}
public AnnotationTypePattern maybeParseAnnotationPattern() {
AnnotationTypePattern ret = AnnotationTypePattern.ANY;
AnnotationTypePattern nextPattern = null;
while ((nextPattern = maybeParseSingleAnnotationPattern()) != null) {
if (ret == AnnotationTypePattern.ANY) {
ret = nextPattern;
} else {
ret = new AndAnnotationTypePattern(ret,nextPattern);
}
}
return ret;
}
public AnnotationTypePattern maybeParseSingleAnnotationPattern() {
AnnotationTypePattern ret = null;
// LALR(2) - fix by making "!@" a single token
int startIndex = tokenSource.getIndex();
if (maybeEat("!")) {
if (maybeEat("@")) {
if (maybeEat("(")) {
TypePattern p = parseTypePattern();
ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p));
eat(")");
return ret;
} else {
TypePattern p = parseSingleTypePattern();
ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p));
return ret;
}
} else {
tokenSource.setIndex(startIndex); // not for us!
return ret;
}
}
if (maybeEat("@")) {
if (maybeEat("(")) {
TypePattern p = parseTypePattern();
ret = new WildAnnotationTypePattern(p);
eat(")");
return ret;
} else {
TypePattern p = parseSingleTypePattern();
ret = new WildAnnotationTypePattern(p);
return ret;
}
} else {
tokenSource.setIndex(startIndex); // not for us!
return ret;
}
}
public TypePattern parseSingleTypePattern() {
List names = parseDottedNamePattern();
// new ArrayList();
// NamePattern p1 = parseNamePattern();
// names.add(p1);
// while (maybeEat(".")) {
// if (maybeEat(".")) {
// names.add(NamePattern.ELLIPSIS);
// }
// NamePattern p2 = parseNamePattern();
// names.add(p2);
// }
int dim = 0;
while (maybeEat("[")) {
eat("]");
dim++;
}
// FIXME AV for Adrian - varargs need special handling since Token are 3x"." and not "..."
// the following works for 'call(* *(int, Integer...))' but not in the general case (see testAJDKExamples test f.e.)
// and the current code does not work for 'call(* *(int, Integer...))'
// int varargDot = 0;
// while (maybeEat(".")) {
// varargDot++;
// }
// boolean isVarArgs = false;
// if (varargDot > 0) {
// if (varargDot == 3) {
// isVarArgs = true;
// } else {
// throw new ParserException("Invalid varargs", tokenSource.peek());
// }
// }
boolean isVarArgs = maybeEat("...");
boolean includeSubtypes = maybeEat("+");
int endPos = tokenSource.peek(-1).getEnd();
//??? what about the source location of any's????
if (names.size() == 1 && ((NamePattern)names.get(0)).isAny() && dim == 0 && !isVarArgs) return TypePattern.ANY;
// Notice we increase the dimensions if varargs is set. this is to allow type matching to
// succeed later: The actual signature at runtime of a method declared varargs is an array type of
// the original declared type (so Integer... becomes Integer[] in the bytecode). So, here for the
// pattern 'Integer...' we create a WildTypePattern 'Integer[]' with varargs set. If this matches
// during shadow matching, we confirm that the varargs flags match up before calling it a successful
// match.
return new WildTypePattern(names, includeSubtypes, dim+(isVarArgs?1:0), endPos,isVarArgs);
}
// private AnnotationTypePattern completeAnnotationPattern(AnnotationTypePattern p) {
// if (maybeEat("&&")) {
// return new AndAnnotationTypePattern(p,parseNotOrAnnotationPattern());
// }
// if (maybeEat("||")) {
// return new OrAnnotationTypePattern(p,parseAnnotationTypePattern());
// }
// return p;
// }
//
// protected AnnotationTypePattern parseAnnotationTypePattern() {
// AnnotationTypePattern ap = parseAtomicAnnotationPattern();
// if (maybeEat("&&")) {
// ap = new AndAnnotationTypePattern(ap, parseNotOrAnnotationPattern());
// }
//
// if (maybeEat("||")) {
// ap = new OrAnnotationTypePattern(ap, parseAnnotationTypePattern());
// }
// return ap;
// }
//
// private AnnotationTypePattern parseNotOrAnnotationPattern() {
// AnnotationTypePattern p = parseAtomicAnnotationPattern();
// if (maybeEat("&&")) {
// p = new AndAnnotationTypePattern(p,parseAnnotationTypePattern());
// }
// return p;
// }
protected ExactAnnotationTypePattern parseAnnotationNameOrVarTypePattern() {
ExactAnnotationTypePattern p = null;
int startPos = tokenSource.peek().getStart();
if (maybeEat("@")) {
throw new ParserException("@Foo form was deprecated in AspectJ 5 M2: annotation name or var ",tokenSource.peek(-1));
}
p = parseSimpleAnnotationName();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext,startPos,endPos);
return p;
}
/**
* @return
*/
private ExactAnnotationTypePattern parseSimpleAnnotationName() {
// the @ has already been eaten...
ExactAnnotationTypePattern p;
StringBuffer annotationName = new StringBuffer();
annotationName.append(parseIdentifier());
while (maybeEat(".")) {
annotationName.append('.');
annotationName.append(parseIdentifier());
}
TypeX type = TypeX.forName(annotationName.toString());
p = new ExactAnnotationTypePattern(type);
return p;
}
// private AnnotationTypePattern parseAtomicAnnotationPattern() {
// if (maybeEat("!")) {
// //int startPos = tokenSource.peek(-1).getStart();
// //??? we lose source location for true start of !type
// AnnotationTypePattern p = new NotAnnotationTypePattern(parseAtomicAnnotationPattern());
// return p;
// }
// if (maybeEat("(")) {
// AnnotationTypePattern p = parseAnnotationTypePattern();
// eat(")");
// return p;
// }
// int startPos = tokenSource.peek().getStart();
// eat("@");
// StringBuffer annotationName = new StringBuffer();
// annotationName.append(parseIdentifier());
// while (maybeEat(".")) {
// annotationName.append('.');
// annotationName.append(parseIdentifier());
// }
// TypeX type = TypeX.forName(annotationName.toString());
// AnnotationTypePattern p = new ExactAnnotationTypePattern(type);
// int endPos = tokenSource.peek(-1).getEnd();
// p.setLocation(sourceContext, startPos, endPos);
// return p;
// }
private boolean isAnnotationPattern(PatternNode p) {
return (p instanceof AnnotationTypePattern);
}
public List parseDottedNamePattern() {
List names = new ArrayList();
StringBuffer buf = new StringBuffer();
IToken previous = null;
boolean justProcessedEllipsis = false; // Remember if we just dealt with an ellipsis (PR61536)
boolean justProcessedDot = false;
boolean onADot = false;
while (true) {
IToken tok = null;
int startPos = tokenSource.peek().getStart();
String afterDot = null;
while (true) {
if (previous !=null && previous.getString().equals(".")) justProcessedDot = true;
tok = tokenSource.peek();
onADot = (tok.getString().equals("."));
if (previous != null) {
if (!isAdjacent(previous, tok)) break;
}
if (tok.getString() == "*" || tok.isIdentifier()) {
buf.append(tok.getString());
} else if (tok.getLiteralKind() != null) {
//System.err.println("literal kind: " + tok.getString());
String s = tok.getString();
int dot = s.indexOf('.');
if (dot != -1) {
buf.append(s.substring(0, dot));
afterDot = s.substring(dot+1);
previous = tokenSource.next();
break;
}
buf.append(s); // ??? so-so
} else {
break;
}
previous = tokenSource.next();
//XXX need to handle floats and other fun stuff
}
int endPos = tokenSource.peek(-1).getEnd();
if (buf.length() == 0 && names.isEmpty()) {
throw new ParserException("name pattern", tok);
}
if (buf.length() == 0 && justProcessedEllipsis) {
throw new ParserException("name pattern cannot finish with ..", tok);
}
if (buf.length() == 0 && justProcessedDot && !onADot) {
throw new ParserException("name pattern cannot finish with .", tok);
}
if (buf.length() == 0) {
names.add(NamePattern.ELLIPSIS);
justProcessedEllipsis = true;
} else {
checkLegalName(buf.toString(), previous);
NamePattern ret = new NamePattern(buf.toString());
ret.setLocation(sourceContext, startPos, endPos);
names.add(ret);
justProcessedEllipsis = false;
}
if (afterDot == null) {
buf.setLength(0);
// //FIXME AV for Adrian - the following does not works in the general case
// //varargs lookahead
// IToken next_1 = tokenSource.peek();
// if (!IToken.EOF.equals(next_1) && next_1.getString().equals(".")) {
// IToken next_2 = tokenSource.peek(1);
// if (!IToken.EOF.equals(next_2) && next_2.getString().equals(".")) {
// IToken next_3 = tokenSource.peek(2);
// if (!IToken.EOF.equals(next_3) && next_3.getString().equals(".")) {
// // happens to be a varargs
// break;
// }
// }
// }
// no elipsis or dotted name part
if (!maybeEat(".")) break;
// go on
else previous = tokenSource.peek(-1);
} else {
buf.setLength(0);
buf.append(afterDot);
afterDot = null;
}
}
//System.err.println("parsed: " + names);
return names;
}
public NamePattern parseNamePattern() {
StringBuffer buf = new StringBuffer();
IToken previous = null;
IToken tok;
int startPos = tokenSource.peek().getStart();
while (true) {
tok = tokenSource.peek();
if (previous != null) {
if (!isAdjacent(previous, tok)) break;
}
if (tok.getString() == "*" || tok.isIdentifier()) {
buf.append(tok.getString());
} else if (tok.getLiteralKind() != null) {
//System.err.println("literal kind: " + tok.getString());
String s = tok.getString();
if (s.indexOf('.') != -1) break;
buf.append(s); // ??? so-so
} else {
break;
}
previous = tokenSource.next();
//XXX need to handle floats and other fun stuff
}
int endPos = tokenSource.peek(-1).getEnd();
if (buf.length() == 0) {
throw new ParserException("name pattern", tok);
}
checkLegalName(buf.toString(), previous);
NamePattern ret = new NamePattern(buf.toString());
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private void checkLegalName(String s, IToken tok) {
char ch = s.charAt(0);
if (!(ch == '*' || Character.isJavaIdentifierStart(ch))) {
throw new ParserException("illegal identifier start (" + ch + ")", tok);
}
for (int i=1, len=s.length(); i < len; i++) {
ch = s.charAt(i);
if (!(ch == '*' || Character.isJavaIdentifierPart(ch))) {
throw new ParserException("illegal identifier character (" + ch + ")", tok);
}
}
}
private boolean isAdjacent(IToken first, IToken second) {
return first.getEnd() == second.getStart()-1;
}
public ModifiersPattern parseModifiersPattern() {
int requiredFlags = 0;
int forbiddenFlags = 0;
int start;
while (true) {
start = tokenSource.getIndex();
boolean isForbidden = false;
isForbidden = maybeEat("!");
IToken t = tokenSource.next();
int flag = ModifiersPattern.getModifierFlag(t.getString());
if (flag == -1) break;
if (isForbidden) forbiddenFlags |= flag;
else requiredFlags |= flag;
}
tokenSource.setIndex(start);
if (requiredFlags == 0 && forbiddenFlags == 0) {
return ModifiersPattern.ANY;
} else {
return new ModifiersPattern(requiredFlags, forbiddenFlags);
}
}
public TypePatternList parseArgumentsPattern() {
List patterns = new ArrayList();
eat("(");
if (maybeEat(")")) {
return new TypePatternList();
}
do {
if (maybeEat(".")) {
eat(".");
patterns.add(TypePattern.ELLIPSIS);
} else {
patterns.add(parseTypePattern());
}
} while (maybeEat(","));
eat(")");
return new TypePatternList(patterns);
}
public AnnotationPatternList parseArgumentsAnnotationPattern() {
List patterns = new ArrayList();
eat("(");
if (maybeEat(")")) {
return new AnnotationPatternList();
}
do {
if (maybeEat(".")) {
eat(".");
patterns.add(AnnotationTypePattern.ELLIPSIS);
} else if (maybeEat("*")) {
patterns.add(AnnotationTypePattern.ANY);
} else {
patterns.add(parseAnnotationNameOrVarTypePattern());
}
} while (maybeEat(","));
eat(")");
return new AnnotationPatternList(patterns);
}
public ThrowsPattern parseOptionalThrowsPattern() {
IToken t = tokenSource.peek();
if (t.isIdentifier() && t.getString().equals("throws")) {
tokenSource.next();
List required = new ArrayList();
List forbidden = new ArrayList();
do {
boolean isForbidden = maybeEat("!");
//???might want an error for a second ! without a paren
TypePattern p = parseTypePattern();
if (isForbidden) forbidden.add(p);
else required.add(p);
} while (maybeEat(","));
return new ThrowsPattern(new TypePatternList(required), new TypePatternList(forbidden));
}
return ThrowsPattern.ANY;
}
public SignaturePattern parseMethodOrConstructorSignaturePattern() {
int startPos = tokenSource.peek().getStart();
AnnotationTypePattern annotationPattern = maybeParseAnnotationPattern();
ModifiersPattern modifiers = parseModifiersPattern();
TypePattern returnType = parseTypePattern();
TypePattern declaringType;
NamePattern name = null;
Member.Kind kind;
// here we can check for 'new'
if (maybeEatNew(returnType)) {
kind = Member.CONSTRUCTOR;
if (returnType.toString().length() == 0) {
declaringType = TypePattern.ANY;
} else {
declaringType = returnType;
}
returnType = TypePattern.ANY;
name = NamePattern.ANY;
} else {
kind = Member.METHOD;
IToken nameToken = tokenSource.peek();
declaringType = parseTypePattern();
if (maybeEat(".")) {
nameToken = tokenSource.peek();
name = parseNamePattern();
} else {
name = tryToExtractName(declaringType);
if (declaringType.toString().equals("")) {
declaringType = TypePattern.ANY;
}
}
if (name == null) {
throw new ParserException("name pattern", tokenSource.peek());
}
String simpleName = name.maybeGetSimpleName();
//XXX should add check for any Java keywords
if (simpleName != null && simpleName.equals("new")) {
throw new ParserException("method name (not constructor)",
nameToken);
}
}
TypePatternList parameterTypes = parseArgumentsPattern();
ThrowsPattern throwsPattern = parseOptionalThrowsPattern();
SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType, name, parameterTypes, throwsPattern, annotationPattern);
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private boolean maybeEatNew(TypePattern returnType) {
if (returnType instanceof WildTypePattern) {
WildTypePattern p = (WildTypePattern)returnType;
if (p.maybeExtractName("new")) return true;
}
int start = tokenSource.getIndex();
if (maybeEat(".")) {
String id = maybeEatIdentifier();
if (id != null && id.equals("new")) return true;
tokenSource.setIndex(start);
}
return false;
}
public SignaturePattern parseFieldSignaturePattern() {
int startPos = tokenSource.peek().getStart();
AnnotationTypePattern annotationPattern = maybeParseAnnotationPattern();
ModifiersPattern modifiers = parseModifiersPattern();
TypePattern returnType = parseTypePattern();
TypePattern declaringType = parseTypePattern();
NamePattern name;
//System.err.println("parsed field: " + declaringType.toString());
if (maybeEat(".")) {
name = parseNamePattern();
} else {
name = tryToExtractName(declaringType);
if (declaringType.toString().equals("")) {
declaringType = TypePattern.ANY;
}
}
SignaturePattern ret = new SignaturePattern(Member.FIELD, modifiers, returnType,
declaringType, name, TypePatternList.ANY, ThrowsPattern.ANY,annotationPattern);
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private NamePattern tryToExtractName(TypePattern nextType) {
if (nextType == TypePattern.ANY) {
return NamePattern.ANY;
} else if (nextType instanceof WildTypePattern) {
WildTypePattern p = (WildTypePattern)nextType;
return p.extractName();
} else {
return null;
}
}
public String parsePossibleStringSequence(boolean shouldEnd) {
StringBuffer result = new StringBuffer();
IToken token = tokenSource.next();
if (token.getLiteralKind()==null) {
throw new ParserException("string",token);
}
while (token.getLiteralKind().equals("string")) {
result.append(token.getString());
boolean plus = maybeEat("+");
if (!plus) break;
token = tokenSource.next();
if (token.getLiteralKind()==null) {
throw new ParserException("string",token);
}
}
eatIdentifier(";");
IToken t = tokenSource.next();
if (shouldEnd && t!=IToken.EOF) {
throw new ParserException("<string>;",token);
}
return result.toString();
}
public String parseStringLiteral() {
IToken token = tokenSource.next();
String literalKind = token.getLiteralKind();
if (literalKind == "string") {
return token.getString();
}
throw new ParserException("string", token);
}
public String parseIdentifier() {
IToken token = tokenSource.next();
if (token.isIdentifier()) return token.getString();
throw new ParserException("identifier", token);
}
public void eatIdentifier(String expectedValue) {
IToken next = tokenSource.next();
if (!next.getString().equals(expectedValue)) {
throw new ParserException(expectedValue, next);
}
}
public boolean maybeEatIdentifier(String expectedValue) {
IToken next = tokenSource.peek();
if (next.getString().equals(expectedValue)) {
tokenSource.next();
return true;
} else {
return false;
}
}
public void eat(String expectedValue) {
IToken next = tokenSource.next();
if (next.getString() != expectedValue) {
throw new ParserException(expectedValue, next);
}
}
public boolean maybeEat(String token) {
IToken next = tokenSource.peek();
if (next.getString() == token) {
tokenSource.next();
return true;
} else {
return false;
}
}
public String maybeEatIdentifier() {
IToken next = tokenSource.peek();
if (next.isIdentifier()) {
tokenSource.next();
return next.getString();
} else {
return null;
}
}
public boolean peek(String token) {
IToken next = tokenSource.peek();
return next.getString() == token;
}
public PatternParser(String data) {
this(BasicTokenSource.makeTokenSource(data,null));
}
public PatternParser(String data, ISourceContext context) {
this(BasicTokenSource.makeTokenSource(data,context));
}
}
|
98,646 |
Bug 98646 parser cannot parse varargs correctly
|
the following cannot be parsed: call(* *(int, Integer...)) see in modules/weaver/.../PointcutVisitorTest (uncomment the testTemp()) See "FIXME AV for Adrian" comments in PatternParser. Half fix but then fails for other tests. Adrian can you have a look at it ? Thanks
|
resolved fixed
|
743566f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-07T13:12:51Z | 2005-06-07T10:26:40Z |
weaver/testsrc/org/aspectj/weaver/patterns/VisitorTestCase.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 junit.framework.TestCase;
import java.util.HashSet;
import java.util.Set;
import java.util.Iterator;
import java.io.LineNumberReader;
import java.io.FileReader;
/**
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class VisitorTestCase extends TestCase {
private Set pointcuts = new HashSet();
private Set typePatterns = new HashSet();
protected void setUp() throws Exception {
super.setUp();
LineNumberReader rp = new LineNumberReader(new FileReader("../weaver/testdata/visitor.pointcuts.txt"));
feed(rp, pointcuts);
rp.close();
LineNumberReader rt = new LineNumberReader(new FileReader("../weaver/testdata/visitor.typepatterns.txt"));
feed(rt, typePatterns);
rt.close();
}
private void feed(LineNumberReader r, Set set) throws Exception {
for (String line = r.readLine(); line != null; line = r.readLine()) {
set.add(line);
}
}
public void testMock() {
//empty so that JUnit does not complain about no test cases in there - this one beeing already in the suite
}
// public void testTemp() {
// Pointcut.fromString("call(* *(int, Integer...))");
// }
// public void testPointcuts() {
// if (pointcuts.isEmpty()) {
// fail("Empty pointcuts file!");
// }
// for (Iterator iterator = pointcuts.iterator(); iterator.hasNext();) {
// String pointcut = (String) iterator.next();
// try {
// PointcutVisitor.DumpPointcutVisitor.check(pointcut);
// } catch (Throwable t) {
// t.printStackTrace();
// fail("Failed on '"+pointcut+"': " +t.toString());
// }
// }
// }
//
// public void testTypePatterns() {
// if (typePatterns.isEmpty()) {
// fail("Empty typePatterns file!");
// }
// for (Iterator iterator = typePatterns.iterator(); iterator.hasNext();) {
// String tp = (String) iterator.next();
// try {
// TypePattern p = new PatternParser(tp).parseTypePattern();
// PointcutVisitor.DumpPointcutVisitor.check(p, true);
// } catch (Throwable t) {
// fail("Failed on '"+tp+"': " +t.toString());
// }
// }
// }
}
|
84,260 |
Bug 84260 import static fails when importing a method
|
I got the following error: ============================================== MyClass2.java:3 [error] The import MyClass.myMethod cannot be resolved import static MyClass.myMethod; ============================================== other import static statements (Strings/Enums) appear to work.
|
resolved fixed
|
f747b82
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-08T10:48:50Z | 2005-02-02T18:46:40Z |
tests/bugs150/pr84260/A.java
| |
84,260 |
Bug 84260 import static fails when importing a method
|
I got the following error: ============================================== MyClass2.java:3 [error] The import MyClass.myMethod cannot be resolved import static MyClass.myMethod; ============================================== other import static statements (Strings/Enums) appear to work.
|
resolved fixed
|
f747b82
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-08T10:48:50Z | 2005-02-02T18:46:40Z |
tests/bugs150/pr84260/I1.java
| |
84,260 |
Bug 84260 import static fails when importing a method
|
I got the following error: ============================================== MyClass2.java:3 [error] The import MyClass.myMethod cannot be resolved import static MyClass.myMethod; ============================================== other import static statements (Strings/Enums) appear to work.
|
resolved fixed
|
f747b82
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-08T10:48:50Z | 2005-02-02T18:46:40Z |
tests/bugs150/pr84260/I2.java
| |
84,260 |
Bug 84260 import static fails when importing a method
|
I got the following error: ============================================== MyClass2.java:3 [error] The import MyClass.myMethod cannot be resolved import static MyClass.myMethod; ============================================== other import static statements (Strings/Enums) appear to work.
|
resolved fixed
|
f747b82
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-08T10:48:50Z | 2005-02-02T18:46:40Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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");
}
/**
* 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");
}
// helper methods.....
public SyntheticRepository createRepos(File cpentry) {
ClassPath cp = new ClassPath(cpentry+File.pathSeparator+System.getProperty("java.class.path"));
return SyntheticRepository.getInstance(cp);
}
protected JavaClass getClassFrom(File where,String clazzname) throws ClassNotFoundException {
SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
}
|
99,168 |
Bug 99168 [generics][itds] ITD on generic inner class crashes ajc
|
inter-type declaration on a generic inner class crashes the compiler: class Outer { class Inner {} class Generic_Inner<T> {} } class Generic_Outer<T> { } aspect Injector { int Outer.outer; // works int Outer.Inner.inner; // works int Generic_Outer.outer; // works int Outer.Generic_Inner.inner; // crashes } /home/user/sgelin3/dev/java/ajc/new_bug/Bug.java [error] Internal compiler error java.lang.RuntimeException: can't handle: class Generic_Inner#RAW extends NULL TYPENULL SUPERINTERFACES enclosing type : OuterNULL FIELDSNULL METHODS at org.aspectj.ajdt.internal.compiler.lookup.InterTypeScope.makeSourceTypeBinding(InterTypeScope.java:35) at org.aspectj.ajdt.internal.compiler.lookup.InterTypeScope.<init>(InterTypeScope.java:28) at org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration.resolve(InterTypeDeclaration.java:101) at org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration.resolve(InterTypeFieldDeclaration.java:141) 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:110) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1125) ...
|
resolved fixed
|
588023e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-14T14:53:37Z | 2005-06-09T15:13:20Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeScope.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.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
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;
public class InterTypeScope extends ClassScope {
ReferenceBinding onType;
public InterTypeScope(Scope parent, ReferenceBinding onType) {
super(parent, null);
referenceContext = new TypeDeclaration(null);
referenceContext.binding = makeSourceTypeBinding(onType);
this.onType = onType;
}
// this method depends on the fact that BinaryTypeBinding extends SourceTypeBinding
private SourceTypeBinding makeSourceTypeBinding(ReferenceBinding onType) {
if (onType instanceof SourceTypeBinding) return (SourceTypeBinding)onType;
else throw new RuntimeException("can't handle: " + onType);
}
public SourceTypeBinding invocationType() {
return parent.enclosingSourceType();
}
public int addDepth() {
return 0;
}
}
|
100,227 |
Bug 100227 [generics][itds] inner class with generic enclosing class
|
ajc crashes with a NullPointerException when an intertype declaration tries to modify an inner class, if the enclosing (outer) class is generic: class Outer { class Inner {} } class Generic_Outer<T> { class Inner {} } aspect Injector { int Outer.outer; // works int Outer.Inner.inner; // works int Generic_Outer.outer; // works int Generic_Outer.Inner.inner; // crashes } /home/user/sgelin3/dev/java/ajc/new_bug/Bug.java [error] Internal compiler error java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:202) at org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration.build(InterTypeFieldDeclaration.java:173) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTypeAndPerClause(AspectDeclaration.java:1020) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildInterTypeAndPerClause(AjLookupEnvironment.java:306) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:122) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:302) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:316) ...
|
resolved fixed
|
7d5002a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-16T08:30:14Z | 2005-06-15T15:40:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten 2004-07-26 extended to allow overloading of
* hierarchy builder
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.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;
/**
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
private AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private boolean xSerializableAspects;
private World world;
private AsmHierarchyBuilder asmHierarchyBuilder;
private Map/*TypeX, TypeBinding*/ typexToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedTypeX*/ bindingToResolvedTypeX = new HashMap();
public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) {
AjLookupEnvironment aenv = (AjLookupEnvironment)env;
return aenv.factory;
}
public static EclipseFactory fromScopeLookupEnvironment(Scope scope) {
return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment);
}
public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) {
this.lookupEnvironment = lookupEnvironment;
this.buildManager = buildManager;
this.world = buildManager.getWorld();
this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects();
}
public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) {
this.lookupEnvironment = lookupEnvironment;
this.world = world;
this.xSerializableAspects = xSer;
this.buildManager = null;
}
public World getWorld() {
return world;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedTypeX fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedTypeX.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedTypeX ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedTypeX fromTypeBindingToRTX(TypeBinding tb) {
if (tb == null) return ResolvedTypeX.MISSING;
ResolvedTypeX ret = getWorld().resolve(fromBinding(tb));
return ret;
}
public ResolvedTypeX[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedTypeX.NONE;
}
int len = bindings.length;
ResolvedTypeX[] ret = new ResolvedTypeX[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
private static String getName(TypeBinding binding) {
if (binding instanceof 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 TypeX and that would seem a bad thing - but I've yet to see the reason we need to
* remember the type variable.
*/
//??? going back and forth between strings and bindings is a waste of cycles
public static TypeX fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedTypeX.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
// this is a type variable...
TypeVariableBinding tvb = (TypeVariableBinding) binding;
// This code causes us to forget its a TVB which we will need when going back the other way...
if (tvb.firstBound!=null) {
return TypeX.forName(getName(tvb.firstBound)); // XXX needs more investigation as to whether this is correct in all cases
} else {
return TypeX.forName(getName(tvb.superclass));
}
}
if (binding instanceof ParameterizedTypeBinding) {
if (binding instanceof RawTypeBinding) {
// special case where no parameters are specified!
return TypeX.forRawTypeNames(getName(binding));
}
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
String[] arguments = new String[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (ptb.arguments[i] instanceof WildcardBinding) {
WildcardBinding wcb = (WildcardBinding) ptb.arguments[i];
arguments[i] = getName(((TypeVariableBinding)wcb.typeVariable()).firstBound);
} else {
arguments[i] = fromBinding(ptb.arguments[i]).getName();
}
}
return TypeX.forParameterizedTypeNames(getName(binding), arguments);
}
return TypeX.forName(getName(binding));
}
public static TypeX[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return TypeX.NONE;
int len = bindings.length;
TypeX[] ret = new TypeX[len];
for (int i=0; i<len; i++) {
ret[i] = fromBinding(bindings[i]);
}
return ret;
}
public static ASTNode astForLocation(IHasPosition location) {
return new EmptyStatement(location.getStart(), location.getEnd());
}
public Collection getDeclareParents() {
return getWorld().getDeclareParents();
}
public Collection getDeclareAnnotationOnTypes() {
return getWorld().getDeclareAnnotationOnTypes();
}
public Collection getDeclareAnnotationOnFields() {
return getWorld().getDeclareAnnotationOnFields();
}
public Collection getDeclareAnnotationOnMethods() {
return getWorld().getDeclareAnnotationOnMethods();
}
public Collection finishedTypeMungers = null;
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers();
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 static ResolvedMember makeResolvedMember(MethodBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public static ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
ResolvedMember ret = new ResolvedMember(
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD,
fromBinding(declaringType),
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions));
return ret;
}
public static ResolvedMember makeResolvedMember(FieldBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public static ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) {
return new ResolvedMember(
Member.FIELD,
fromBinding(receiverType),
binding.modifiers,
fromBinding(binding.type),
new String(binding.name),
TypeX.NONE);
}
public TypeBinding makeTypeBinding(TypeX typeX) {
TypeBinding ret = (TypeBinding)typexToBinding.get(typeX);
if (ret == null) {
ret = makeTypeBinding1(typeX);
typexToBinding.put(typeX, ret);
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
private TypeBinding makeTypeBinding1(TypeX typeX) {
if (typeX.isPrimitive()) {
if (typeX == ResolvedTypeX.BOOLEAN) return BaseTypes.BooleanBinding;
if (typeX == ResolvedTypeX.BYTE) return BaseTypes.ByteBinding;
if (typeX == ResolvedTypeX.CHAR) return BaseTypes.CharBinding;
if (typeX == ResolvedTypeX.DOUBLE) return BaseTypes.DoubleBinding;
if (typeX == ResolvedTypeX.FLOAT) return BaseTypes.FloatBinding;
if (typeX == ResolvedTypeX.INT) return BaseTypes.IntBinding;
if (typeX == ResolvedTypeX.LONG) return BaseTypes.LongBinding;
if (typeX == ResolvedTypeX.SHORT) return BaseTypes.ShortBinding;
if (typeX == ResolvedTypeX.VOID) return BaseTypes.VoidBinding;
throw new RuntimeException("weird primitive type " + typeX);
} else if (typeX.isArray()) {
int dim = 0;
while (typeX.isArray()) {
dim++;
typeX = typeX.getComponentType();
}
return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim);
} else if (typeX.isParameterized()) {
if (typeX.isRawType()) {
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType());
return rtb;
} else {
TypeX[] 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 {
return lookupBinding(typeX.getName());
}
}
private ReferenceBinding lookupBinding(String sname) {
char[][] name = CharOperation.splitOn('.', sname.toCharArray());
ReferenceBinding rb = lookupEnvironment.getType(name);
// XXX We do this because the pertypewithin aspectOf(Class) generated method needs it. Without this
// we don't get a 'rawtype' as the argument type for a messagesend to aspectOf() and this leads to
// a compile error if some client class calls aspectOf(A.class) or similar as it says Class<A> isn't
// compatible with Class<T>
if (sname.equals("java.lang.Class"))
rb = lookupEnvironment.createRawType(rb,rb.enclosingType());
return rb;
}
public TypeBinding[] makeTypeBindings(TypeX[] types) {
int len = types.length;
TypeBinding[] ret = new TypeBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeBinding(types[i]);
}
return ret;
}
// just like the code above except it returns an array of ReferenceBindings
private ReferenceBinding[] makeReferenceBindings(TypeX[] types) {
int len = types.length;
ReferenceBinding[] ret = new ReferenceBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = (ReferenceBinding)makeTypeBinding(types[i]);
}
return ret;
}
public FieldBinding makeFieldBinding(ResolvedMember member) {
return new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()),
Constant.NotAConstant);
}
public MethodBinding makeMethodBinding(ResolvedMember member) {
return new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public MethodBinding makeMethodBindingForCall(Member member) {
return new MethodBinding(member.getCallsiteModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
new ReferenceBinding[0],
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public void finishedCompilationUnit(CompilationUnitDeclaration unit) {
if ((buildManager != null) && buildManager.doGenerateModel()) {
AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig);
}
}
public void addTypeBinding(TypeBinding binding) {
typexToBinding.put(fromBinding(binding), binding);
}
public Shadow makeShadow(ASTNode location, ReferenceContext context) {
return EclipseShadow.makeShadow(this, location, context);
}
public Shadow makeShadow(ReferenceContext context) {
return EclipseShadow.makeShadow(this, (ASTNode) context, context);
}
public void addSourceTypeBinding(SourceTypeBinding binding) {
TypeDeclaration decl = binding.scope.referenceContext;
ResolvedTypeX.Name name = getWorld().lookupOrCreateName(TypeX.forName(getName(binding)));
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl);
name.setDelegate(t);
if (decl instanceof AspectDeclaration) {
((AspectDeclaration)decl).typeX = name;
((AspectDeclaration)decl).concreteName = t;
}
ReferenceBinding[] memberTypes = binding.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addSourceTypeBinding((SourceTypeBinding) memberTypes[i]);
}
}
// XXX this doesn't feel like it belongs here, but it breaks a hard dependency on
// exposing AjBuildManager (needed by AspectDeclaration).
public boolean isXSerializableAspects() {
return xSerializableAspects;
}
}
|
100,227 |
Bug 100227 [generics][itds] inner class with generic enclosing class
|
ajc crashes with a NullPointerException when an intertype declaration tries to modify an inner class, if the enclosing (outer) class is generic: class Outer { class Inner {} } class Generic_Outer<T> { class Inner {} } aspect Injector { int Outer.outer; // works int Outer.Inner.inner; // works int Generic_Outer.outer; // works int Generic_Outer.Inner.inner; // crashes } /home/user/sgelin3/dev/java/ajc/new_bug/Bug.java [error] Internal compiler error java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:202) at org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration.build(InterTypeFieldDeclaration.java:173) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTypeAndPerClause(AspectDeclaration.java:1020) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildInterTypeAndPerClause(AjLookupEnvironment.java:306) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:122) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:302) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:316) ...
|
resolved fixed
|
7d5002a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-16T08:30:14Z | 2005-06-15T15:40:00Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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");
}
/**
* 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 testItdGenerics_pr99228() {runTest("ITD of a field into a generic class");}
public void testItdGenerics_pr98320() {runTest("intertype with nested generic 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);
}
}
|
100,227 |
Bug 100227 [generics][itds] inner class with generic enclosing class
|
ajc crashes with a NullPointerException when an intertype declaration tries to modify an inner class, if the enclosing (outer) class is generic: class Outer { class Inner {} } class Generic_Outer<T> { class Inner {} } aspect Injector { int Outer.outer; // works int Outer.Inner.inner; // works int Generic_Outer.outer; // works int Generic_Outer.Inner.inner; // crashes } /home/user/sgelin3/dev/java/ajc/new_bug/Bug.java [error] Internal compiler error java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.fromBinding(EclipseFactory.java:202) at org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration.build(InterTypeFieldDeclaration.java:173) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.buildInterTypeAndPerClause(AspectDeclaration.java:1020) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.buildInterTypeAndPerClause(AjLookupEnvironment.java:306) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:122) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:302) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:316) ...
|
resolved fixed
|
7d5002a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-16T08:30:14Z | 2005-06-15T15:40:00Z |
weaver/src/org/aspectj/weaver/TypeX.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class TypeX implements AnnotatedElement {
/**
* This is the string representation of this Type, will include parameterization info
*/
protected String signature;
/**
* For parameterized types, this is the signature of the raw type (e.g. Ljava/util/List; )
* For non-parameterized types, it is null.
*/
protected String rawTypeSignature;
/**
* If this is a parameterized type, these are its parameters
*/
protected TypeX[] typeParameters;
private boolean isParameterized = false;
/**
* @param signature the bytecode string representation of this Type
*/
protected TypeX(String signature) {
super();
this.signature = signature;
// avoid treating '<missing>' as a parameterized type ...
if (signature.charAt(0)!='<' && signature.indexOf("<")!=-1) {
// anglies alert - generic/parameterized type
processSignature(signature);
}
}
/**
* Called when processing a parameterized type, sets the raw type for this typeX and calls a subroutine
* to handle sorting out the type parameters for the type.
*/
private void processSignature(String sig) {
// determine the raw type
int parameterTypesStart = signature.indexOf("<");
int parameterTypesEnd = signature.lastIndexOf(">");
StringBuffer rawTypeSb = new StringBuffer();
rawTypeSb.append(signature.substring(0,parameterTypesStart)).append(";");
rawTypeSignature = rawTypeSb.toString();
typeParameters = processParameterization(signature,parameterTypesStart+1,parameterTypesEnd-1);
isParameterized = true;
}
/**
* For a parameterized signature, e.g. <Ljava/langString;Ljava/util/List<Ljava/lang/String;>;>"
* this routine will return an appropriate array of TypeXs representing the top level type parameters.
* Where type parameters are themselves parameterized, we recurse.
*/
public TypeX[] processParameterization(String paramSig,int startpos,int endpos) {
boolean debug = false;
if (debug) {
StringBuffer sb = new StringBuffer();
sb.append(paramSig).append("\n");
for(int i=0;i<paramSig.length();i++) {
if (i==startpos || i==endpos) sb.append("^");
else if (i<startpos || i>endpos) sb.append(" ");
else sb.append("-");
}
sb.append("\n");
System.err.println(sb.toString());
}
int posn = startpos;
List parameterTypes = new ArrayList();
while (posn<endpos && paramSig.charAt(posn)!='>') {
int nextAngly = paramSig.indexOf("<",posn);
int nextSemi = paramSig.indexOf(";",posn);
if (nextAngly==-1 || nextSemi<nextAngly) { // the next type is not parameterized
// simple type
parameterTypes.add(TypeX.forSignature(paramSig.substring(posn,nextSemi+1)));
posn=nextSemi+1; // jump to the next type
} else if (nextAngly!=-1 && nextSemi>nextAngly) { // parameterized type, e.g. Ljava/util/Set<Ljava/util/String;>
int count=1;
int pos=nextAngly+1;
for (;count>0;pos++){
switch (paramSig.charAt(pos)) {
case '<':count++;break;
case '>':count--;break;
default:
}
}
String sub = paramSig.substring(posn,pos+1);
parameterTypes.add(TypeX.forSignature(sub));
posn=pos+1;
} else {
throw new BCException("What the hell do i do with this? ["+paramSig.substring(posn)+"]");
}
}
return (TypeX[])parameterTypes.toArray(new TypeX[]{});
}
// ---- Things we can do without a world
/**
* This is the size of this type as used in JVM.
*/
public int getSize() {
return 1;
}
/**
* Equality is checked based on the underlying signature.
* {@link ResolvedType} objects' equals is by reference.
*/
public boolean equals(Object other) {
if (! (other instanceof TypeX)) return false;
return signature.equals(((TypeX) other).signature);
}
/**
* Equality is checked based on the underlying signature, so the hash code
* of a particular type is the hash code of its signature string.
*/
public final int hashCode() {
return signature.hashCode();
}
public static TypeX makeArray(TypeX base, int dims) {
StringBuffer sig = new StringBuffer();
for (int i=0; i < dims; i++) sig.append("[");
sig.append(base.getSignature());
return TypeX.forSignature(sig.toString());
}
/**
* NOTE: Use forSignature() if you can, it'll be cheaper !
* Constructs a TypeX for a java language type name. For example:
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]")
* TypeX.forName("int")
* </pre></blockquote>
*
* Types may equivalently be produced by this or by {@link #forSignature(String)}.
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;")
* TypeX.forName("int").equals(Type.forSignature("I"))
* </pre></blockquote>
*
* @param name the java language type name in question.
* @return a type object representing that java language type.
*/
public static TypeX forName(String name) {
return forSignature(nameToSignature(name));
}
/** Constructs a TypeX for each java language type name in an incoming array.
*
* @param names an array of java language type names.
* @return an array of TypeX objects.
* @see #forName(String)
*/
public static TypeX[] forNames(String[] names) {
TypeX[] ret = new TypeX[names.length];
for (int i = 0, len = names.length; i < len; i++) {
ret[i] = TypeX.forName(names[i]);
}
return ret;
}
/**
* Makes a parameterized type with the given name
* and parameterized type names.
*/
public static TypeX forParameterizedTypeNames(String name, String[] paramTypeNames) {
TypeX ret = TypeX.forName(name);
ret.setParameterized(true);
ret.typeParameters = new TypeX[paramTypeNames.length];
for (int i = 0; i < paramTypeNames.length; i++) {
ret.typeParameters[i] = TypeX.forName(paramTypeNames[i]);
}
ret.rawTypeSignature = ret.signature;
// sig for e.g. List<String> is Ljava/util/List<Ljava/lang/String;>;
StringBuffer sigAddition = new StringBuffer();
sigAddition.append("<");
for (int i = 0; i < ret.typeParameters.length; i++) {
sigAddition.append(ret.typeParameters[i].signature);
}
sigAddition.append(">");
sigAddition.append(";");
ret.signature = ret.signature.substring(0,ret.signature.length()-1) + sigAddition.toString();
return ret;
}
public static TypeX forRawTypeNames(String name) {
TypeX ret = TypeX.forName(name);
ret.setParameterized(true);
// FIXME asc no need to mess up the signature is there?
// ret.signature = ret.signature+"#RAW";
return ret;
}
/**
* Creates a new type array with a fresh type appended to the end.
*
* @param types the left hand side of the new array
* @param end the right hand side of the new array
*/
public static TypeX[] add(TypeX[] types, TypeX end) {
int len = types.length;
TypeX[] ret = new TypeX[len + 1];
System.arraycopy(types, 0, ret, 0, len);
ret[len] = end;
return ret;
}
/**
* Creates a new type array with a fresh type inserted at the beginning.
*
*
* @param start the left hand side of the new array
* @param types the right hand side of the new array
*/
public static TypeX[] insert(TypeX start, TypeX[] types) {
int len = types.length;
TypeX[] ret = new TypeX[len + 1];
ret[0] = start;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
/**
* Constructs a Type for a JVM bytecode signature string. For example:
*
* <blockquote><pre>
* TypeX.forSignature("[Ljava/lang/Thread;")
* TypeX.forSignature("I");
* </pre></blockquote>
*
* Types may equivalently be produced by this or by {@link #forName(String)}.
*
* <blockquote><pre>
* TypeX.forName("java.lang.Thread[]").equals(Type.forSignature("[Ljava/lang/Thread;")
* TypeX.forName("int").equals(Type.forSignature("I"))
* </pre></blockquote>
*
* @param signature the JVM bytecode signature string for the desired type.
* @return a type object represnting that JVM bytecode signature.
*/
public static TypeX forSignature(String signature) {
switch (signature.charAt(0)) {
case 'B': return ResolvedTypeX.BYTE;
case 'C': return ResolvedTypeX.CHAR;
case 'D': return ResolvedTypeX.DOUBLE;
case 'F': return ResolvedTypeX.FLOAT;
case 'I': return ResolvedTypeX.INT;
case 'J': return ResolvedTypeX.LONG;
case 'L': return new TypeX(signature);
case 'S': return ResolvedTypeX.SHORT;
case 'V': return ResolvedTypeX.VOID;
case 'Z': return ResolvedTypeX.BOOLEAN;
case '[': return new TypeX(signature);
default: throw new BCException("Bad type signature " + signature);
}
}
/** Constructs a TypeX for each JVM bytecode type signature in an incoming array.
*
* @param names an array of JVM bytecode type signatures
* @return an array of TypeX objects.
* @see #forSignature(String)
*/
public static TypeX[] forSignatures(String[] sigs) {
TypeX[] ret = new TypeX[sigs.length];
for (int i = 0, len = sigs.length; i < len; i++) {
ret[i] = TypeX.forSignature(sigs[i]);
}
return ret;
}
/**
* Returns the name of this type in java language form. For all
* TypeX t:
*
* <blockquote><pre>
* TypeX.forName(t.getName()).equals(t)
* </pre></blockquote>
*
* and for all String s where s is a lexically valid java language typename:
*
* <blockquote><pre>
* TypeX.forName(s).getName().equals(s)
* </pre></blockquote>
*
* This produces a more esthetically pleasing string than
* {@link java.lang.Class#getName()}.
*
* @return the java language name of this type.
*/
public String getName() {
return signatureToName(signature);
}
public String getBaseName() {
String name = getName();
if (isParameterized()) {
if (isRawType()) return name;
else return name.substring(0,name.indexOf("<"));
} else {
return name;
}
}
/**
* Returns an array of strings representing the java langauge names of
* an array of types.
*
* @param types an array of TypeX objects
* @return an array of Strings fo the java language names of types.
* @see #getName()
*/
public static String[] getNames(TypeX[] types) {
String[] ret = new String[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = types[i].getName();
}
return ret;
}
/**
* Returns the name of this type in JVM signature form. For all
* TypeX t:
*
* <blockquote><pre>
* TypeX.forSignature(t.getSignature()).equals(t)
* </pre></blockquote>
*
* and for all String s where s is a lexically valid JVM type signature string:
*
* <blockquote><pre>
* TypeX.forSignature(s).getSignature().equals(s)
* </pre></blockquote>
*
* @return the java JVM signature string for this type.
*/
public String getSignature() {
return signature;
}
public String getParameterizedSignature() {
return signature;
}
/**
* For parameterized types, return the signature for the raw type
*/
public String getRawTypeSignature() {
if (!isParameterized() || rawTypeSignature==null) { return signature; }
return rawTypeSignature;
}
/**
* Determins if this represents an array type.
*
* @return true iff this represents an array type.
*/
public final boolean isArray() {
return signature.startsWith("[");
}
/**
* Determines if this represents a parameterized type.
*/
public final boolean isParameterized() {
return isParameterized;
// return signature.indexOf("<") != -1;
// //(typeParameters != null) && (typeParameters.length > 0);
}
public final boolean isRawType() {
return isParameterized && typeParameters==null;
}
private final void setParameterized(boolean b) {
isParameterized=b;
}
/**
* Returns a TypeX object representing the effective outermost enclosing type
* for a name type. For all other types, this will return the type itself.
*
* The only guarantee is given in JLS 13.1 where code generated according to
* those rules will have type names that can be split apart in this way.
* @return the outermost enclosing TypeX object or this.
*/
public TypeX getOutermostType() {
if (isArray() || isPrimitive()) return this;
String sig = getSignature();
int dollar = sig.indexOf('$');
if (dollar != -1) {
return TypeX.forSignature(sig.substring(0, dollar) + ';');
} else {
return this;
}
}
/**
* Returns a TypeX object representing the component type of this array, or
* null if this type does not represent an array type.
*
* @return the component TypeX object, or null.
*/
public TypeX getComponentType() {
if (isArray()) {
return forSignature(signature.substring(1));
} else {
return null;
}
}
/**
* Determines if this represents a primitive type. A primitive type
* is one of nine predefined resolved types.
*
* @return true iff this type represents a primitive type
*
* @see ResolvedTypeX#Boolean
* @see ResolvedTypeX#Character
* @see ResolvedTypeX#Byte
* @see ResolvedTypeX#Short
* @see ResolvedTypeX#Integer
* @see ResolvedTypeX#Long
* @see ResolvedTypeX#Float
* @see ResolvedTypeX#Double
* @see ResolvedTypeX#Void
*/
public boolean isPrimitive() {
return false;
}
/**
* Returns a java language string representation of this type.
*/
public String toString() {
return getName();
}
// ---- requires worlds
/**
* Types may have pointcuts just as they have methods and fields.
*/
public ResolvedPointcutDefinition findPointcut(String name, World world) {
return world.findPointcut(this, name);
}
/**
* 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(TypeX other, World world) {
if (this.equals(OBJECT)) return true;
if (this.isPrimitive() || other.isPrimitive()) return this.isAssignableFrom(other, world);
return this.isCoerceableFrom(other, world);
}
/**
* Determines if variables of this type could be assigned values of another
* without any conversion computation of any kind. For primitive types
* this means equality, and for reference types it means assignability.
*
* @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 any conversion computation
*/
public boolean needsNoConversionFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive()) return false;
return world.needsNoConversionFrom(this, other);
}
/**
* Determines if the variables of this type could be assigned values
* of another type without casting. This still allows for assignment conversion
* as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER).
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other without casting
* @exception NullPointerException if other is null
*/
public boolean isAssignableFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive() && !world.behaveInJava5Way) return false;
return world.isAssignableFrom(this, other);
}
/**
* Determines if values of another type could possibly be cast to
* this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion".
*
* <p> This method should be commutative, i.e., for all TypeX a, b and all World w:
*
* <blockquote><pre>
* a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w)
* </pre></blockquote>
*
* @param other the other type
* @param world the {@link World} in which the possible coersion should be checked.
* @return true iff values of other could possibly be cast to this type.
* @exception NullPointerException if other is null.
*/
public boolean isCoerceableFrom(TypeX other, World world) {
// primitives override this method, so we know we're not primitive.
// So if the other is primitive, don't bother asking the world anything.
if (other.isPrimitive()) return false;
return world.isCoerceableFrom(this, other);
}
/**
* Determines if this represents an interface type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents an interface type.
*/
public final boolean isInterface(World world) {
return world.resolve(this).isInterface();
}
/**
* Determines if this represents a class type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents a class type.
*/
public final boolean isClass(World world) {
return world.resolve(this).isClass();
}
/**
* Determines if this class represents an enum type.
*/
public final boolean isEnum(World world) {
return world.resolve(this).isEnum();
}
/**
* Determines if this class represents an annotation type.
*/
public final boolean isAnnotation(World world) {
return world.resolve(this).isAnnotation();
}
/**
* Determine if this class represents an annotation type that has runtime retention
*/
public final boolean isAnnotationWithRuntimeRetention(World world) {
return world.resolve(this).isAnnotationWithRuntimeRetention();
}
/**
* Determines if this represents an aspect type.
*
* @param world the {@link World} in which we should check.
* @return true iff this represents an aspect type.
*/
public final boolean isAspect(World world) {
return world.resolve(this).isAspect();
}
/**
* Returns a TypeX 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.
*
* <p>
* This differs from {@link java.lang.class#getSuperclass()} in that
* this returns a TypeX object representing java.lang.Object for interfaces instead
* of returning null.
*
* @param world the {@link World} in which the lookup should be made.
* @return this type's superclass, or null if none exists.
*/
public TypeX getSuperclass(World world) {
return world.getSuperclass(this);
}
/**
* Returns an array of TypeX objects representing the declared interfaces
* of this type.
*
* <p>
* If this object represents a class, the declared interfaces are those it
* implements. If this object represents an interface, the declared interfaces
* are those it extends. If this object represents a primitive, an empty
* array is returned. If this object represents an array, an array
* containing types for java.lang.Cloneable and java.io.Serializable is returned.
*
* @param world the {@link World} in which the lookup should be made.
* @return an iterator through the declared interfaces of this type.
*/
public TypeX[] getDeclaredInterfaces(World world) {
return world.getDeclaredInterfaces(this);
}
/**
* Returns an iterator through TypeX objects representing all the direct
* supertypes of this type. That is, through the superclass, if any, and
* all declared interfaces.
*
* @param world the {@link World} in which the lookup should be made.
* @return an iterator through the direct supertypes of this type.
*/
public Iterator getDirectSupertypes(World world) {
return world.resolve(this).getDirectSupertypes();
}
/**
* Returns the modifiers for this type.
*
* See {@link java.lang.Class#getModifiers()} for a description
* of the weirdness of this methods on primitives and arrays.
*
* @param world the {@link World} in which the lookup is made.
* @return an int representing the modifiers for this type
* @see java.lang.reflect.Modifier
*/
public int getModifiers(World world) {
return world.getModifiers(this);
}
/**
* Returns an array representing the declared fields of this object. This may include
* non-user-visible fields.
* This method returns an
* empty array if it represents an array type or a primitive type, so
* the implicit length field of arrays is just that, implicit.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared fields of this type
*/
public ResolvedMember[] getDeclaredFields(World world) {
return world.getDeclaredFields(this);
}
/**
* Returns an array representing the declared methods of this object. This includes
* constructors and the static initialzation method. This also includes all
* shadowMungers in an aspect. So it may include more than the user-visible methods.
* This method returns an
* empty array if it represents an array type or a primitive type.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared methods of this type
*/
public ResolvedMember[] getDeclaredMethods(World world) {
return world.getDeclaredMethods(this);
}
/**
* Returns an array representing the declared pointcuts of this object.
* This method returns an
* empty array if it represents an array type or a primitive type.
*
* @param world the {@link World} in which the lookup is done.
* @return the array representing the declared pointcuts of this type
*/
public ResolvedMember[] getDeclaredPointcuts(World world) {
return world.getDeclaredPointcuts(this);
}
/**
* Returns a resolved version of this type according to a particular world.
*
* @param world thie {@link World} within which to resolve.
* @return a resolved type representing this type in the appropriate world.
*/
public ResolvedTypeX resolve(World world) {
return world.resolve(this);
}
public boolean hasAnnotation(TypeX ofType) {
throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result...");
}
/* (non-Javadoc)
* @see org.aspectj.weaver.AnnotatedElement#getAnnotationTypes()
*/
public ResolvedTypeX[] getAnnotationTypes() {
throw new UnsupportedOperationException("You should resolve this member and call hasAnnotation() on the result...");
}
// ---- fields
public static final TypeX[] NONE = new TypeX[0];
public static final TypeX OBJECT = forSignature("Ljava/lang/Object;");
public static final TypeX OBJECTARRAY = forSignature("[Ljava/lang/Object;");
public static final TypeX CLONEABLE = forSignature("Ljava/lang/Cloneable;");
public static final TypeX SERIALIZABLE = forSignature("Ljava/io/Serializable;");
public static final TypeX THROWABLE = forSignature("Ljava/lang/Throwable;");
public static final TypeX RUNTIME_EXCEPTION = forSignature("Ljava/lang/RuntimeException;");
public static final TypeX ERROR = forSignature("Ljava/lang/Error;");
public static final TypeX AT_INHERITED = forSignature("Ljava/lang/annotation/Inherited;");
public static final TypeX AT_RETENTION = forSignature("Ljava/lang/annotation/Retention;");
public static final TypeX ENUM = forSignature("Ljava/lang/Enum;");
public static final TypeX ANNOTATION = forSignature("Ljava/lang/annotation/Annotation;");
public static final TypeX JAVA_LANG_CLASS = forSignature("Ljava/lang/Class;");
public static final TypeX JAVA_LANG_EXCEPTION = forSignature("Ljava/lang/Exception;");
public static final TypeX JAVA_LANG_REFLECT_METHOD = forSignature("Ljava/lang/reflect/Method;");
public static final TypeX SUPPRESS_AJ_WARNINGS = forSignature("Lorg/aspectj/lang/annotation/SuppressAjWarnings;");
public static final TypeX AT_TARGET = forSignature("Ljava/lang/annotation/Target;");
// ---- helpers
private static String signatureToName(String signature) {
switch (signature.charAt(0)) {
case 'B': return "byte";
case 'C': return "char";
case 'D': return "double";
case 'F': return "float";
case 'I': return "int";
case 'J': return "long";
case 'L':
String name = signature.substring(1, signature.length() - 1).replace('/', '.');
if (name.indexOf("<") == -1) return name;
// signature for parameterized types is e.g.
// List<String> -> Ljava/util/List<Ljava/lang/String;>;
// Map<String,List<Integer>> -> Ljava/util/Map<java/lang/String;Ljava/util/List<Ljava/lang/Integer;>;>;
StringBuffer nameBuff = new StringBuffer();
boolean justSeenLeftArrowChar = false;
boolean justSeenSemiColon= false;
int paramNestLevel = 0;
for (int i = 0 ; i < name.length(); i++) {
char c = name.charAt(i);
switch (c) {
case '<' :
justSeenLeftArrowChar = true;
paramNestLevel++;
nameBuff.append(c);
break;
case ';' :
justSeenSemiColon = true;
break;
case '>' :
paramNestLevel--;
nameBuff.append(c);
break;
case 'L' :
if (justSeenLeftArrowChar) {
justSeenLeftArrowChar = false;
break;
}
if (justSeenSemiColon) {
nameBuff.append(",");
} else {
nameBuff.append("L");
}
break;
default:
justSeenSemiColon = false;
justSeenLeftArrowChar = false;
nameBuff.append(c);
}
}
return nameBuff.toString();
case 'S': return "short";
case 'V': return "void";
case 'Z': return "boolean";
case '[':
return signatureToName(signature.substring(1, signature.length())) + "[]";
default:
throw new BCException("Bad type signature: " + signature);
}
}
private static String nameToSignature(String name) {
if (name.equals("byte")) return "B";
if (name.equals("char")) return "C";
if (name.equals("double")) return "D";
if (name.equals("float")) return "F";
if (name.equals("int")) return "I";
if (name.equals("long")) return "J";
if (name.equals("short")) return "S";
if (name.equals("boolean")) return "Z";
if (name.equals("void")) return "V";
if (name.endsWith("[]"))
return "[" + nameToSignature(name.substring(0, name.length() - 2));
if (name.length() != 0) {
// lots more tests could be made here...
// 1) If it is already an array type, do not mess with it.
if (name.charAt(0)=='[' && name.charAt(name.length()-1)==';') return name;
else {
if (name.indexOf("<") == -1) {
// not parameterised
return "L" + name.replace('.', '/') + ";";
} else {
StringBuffer nameBuff = new StringBuffer();
nameBuff.append("L");
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
switch (c) {
case '.' : nameBuff.append('/'); break;
case '<' : nameBuff.append("<L"); break;
case '>' : nameBuff.append(";>"); break;
case ',' : nameBuff.append(";L"); break;
default: nameBuff.append(c);
}
}
nameBuff.append(";");
return nameBuff.toString();
}
}
}
else
throw new BCException("Bad type name: " + name);
}
public void write(DataOutputStream s) throws IOException {
s.writeUTF(signature);
}
public static TypeX read(DataInputStream s) throws IOException {
String sig = s.readUTF();
if (sig.equals(MISSING_NAME)) {
return ResolvedTypeX.MISSING;
} else {
return TypeX.forSignature(sig);
}
}
public static void writeArray(TypeX[] types, DataOutputStream s) throws IOException {
int len = types.length;
s.writeShort(len);
for (int i=0; i < len; i++) {
types[i].write(s);
}
}
public static TypeX[] readArray(DataInputStream s) throws IOException {
int len = s.readShort();
TypeX[] types = new TypeX[len];
for (int i=0; i < len; i++) {
types[i] = TypeX.read(s);
}
return types;
}
/**
* For debugging purposes
*/
public void dump(World world) {
if (isAspect(world)) System.out.print("aspect ");
else if (isInterface(world)) System.out.print("interface ");
else if (isClass(world)) System.out.print("class ");
System.out.println(toString());
dumpResolvedMembers("fields", getDeclaredFields(world));
dumpResolvedMembers("methods", getDeclaredMethods(world));
dumpResolvedMembers("pointcuts", getDeclaredPointcuts(world));
}
private void dumpResolvedMembers(String label, ResolvedMember[] l) {
final String indent = " ";
System.out.println(label);
if (l == null) {
System.out.println(indent + "null");
return;
}
for (int i=0, len=l.length; i < len; i++) {
System.out.println(indent + l[i]);
}
}
// ----
public String getNameAsIdentifier() {
return getName().replace('.', '_');
}
public String getPackageNameAsIdentifier() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return "";
} else {
return name.substring(0, index).replace('.', '_');
}
}
public String getPackageName() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return null;
} else {
return name.substring(0, index);
}
}
public TypeX[] getTypeParameters() {
return typeParameters == null ? new TypeX[0] : typeParameters;
}
/**
* Doesn't include the package
*/
public String getClassName() {
String name = getName();
int index = name.lastIndexOf('.');
if (index == -1) {
return name;
} else {
return name.substring(index+1);
}
}
/**
* Exposed for testing, dumps the parameterization info for a typeX into a string, so you can check its OK.
*
* For example, calling TypeX.dump() for
* "Ljava/util/Map<Ljava/util/List<Ljava/lang/String;>;Ljava/lang/String;>;"
* results in:
* TypeX: signature=Ljava/util/Map<Ljava/util/List<Ljava/lang/String;>;Ljava/lang/String;>; parameterized=true #params=2
* TypeX: signature=Ljava/util/List<Ljava/lang/String;>; parameterized=true #params=1
* TypeX: signature=Ljava/lang/String; parameterized=false #params=0
* TypeX: signature=Ljava/lang/String; parameterized=false #params=0
*/
public String dump() {
StringBuffer sb = new StringBuffer();
dumpHelper(sb,0);
return sb.toString();
}
private void dumpHelper(StringBuffer collector,int depth) {
collector.append("TypeX: signature="+getSignature()+" parameterized="+isParameterized()+" #params="+getTypeParameters().length);
if (isParameterized()) {
for (int i = 0; i < getTypeParameters().length; i++) {
TypeX tx = getTypeParameters()[i];
collector.append("\n ");for(int ii=0;ii<depth;ii++) collector.append(" ");
tx.dumpHelper(collector,depth+2);
}
}
}
public static final String MISSING_NAME = "<missing>";
}
|
100,260 |
Bug 100260 [generics][itds] methods inherited from a generic parent
|
when using an intertype declaration to add a method to a generic class, the method is not correctly inherited. the bug doesn't apply to fields. Strangely enough, raw types (generic types instantiated without specifying a type parameter) inherit the methods properly: class Generic_Parent<T> {} class Child extends Generic_Parent<Integer> {} class Generic_Child<T> extends Generic_Parent<Integer> {} aspect Injector { public void Generic_Parent.inherited_method() {} public int Generic_Parent.inherited_field; public void test() { int inherited_field; inherited_field = new Generic_Child().inherited_field; // works inherited_field = new Generic_Child<Integer>().inherited_field; // works inherited_field = new Child().inherited_field; // works new Generic_Child().inherited_method(); // works new Generic_Child<Integer>().inherited_method(); // unresolved new Child().inherited_method(); // unresolved } }
|
resolved fixed
|
b54831f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-06-16T11:57:28Z | 2005-06-15T18:26:40Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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");
}
/**
* 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 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");}
// 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);
}
}
|
83,935 |
Bug 83935 @AJ and formal binding impl
|
Some notes on formal binding impl for @AJ In code style, the advice signature is always looking the same (..bindings.., org.aspectj.lang.Part thisJoinPointStaticPart, JoinPoint thisJoinPoint, org.aspectj.lang.Part thisEnclosingJoinPointStaticPart) In @ style, it is user defined. The current impl is handling the formal binding in a way that only args/this/target can be bound. I had to add some conditionals to handles cases like that: void myAdvice(JoinPoint jp, Object target) {..} where target() binding is at index 1, while the index 0 is not an unbound but actually "virtually" bound to the joinpoint. Pointcut are thus having a virtuallyBoundedNames String[] that is the list of arguments for which we don't want any complain if it not bound. This one is populated during @ extraction, and Pointcut.concretize() make sure the info is not lost when composition occurs (with PerClause f.e.) The only issue is that currently, binding JP/SJP/ESJP themselves is not possible f.e. "... && args(jp)" myAdvice(JoinPoint jp, JoinPoint currentJp) Is that a big issue ? May be impact adviceexecution() and could impact some use cases around mock testing.
|
resolved fixed
|
639b4fd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-11T15:05:44Z | 2005-01-28T16:33:20Z |
tests/java5/ataspectj/ataspectj/MultipleBindingTest.java
| |
83,935 |
Bug 83935 @AJ and formal binding impl
|
Some notes on formal binding impl for @AJ In code style, the advice signature is always looking the same (..bindings.., org.aspectj.lang.Part thisJoinPointStaticPart, JoinPoint thisJoinPoint, org.aspectj.lang.Part thisEnclosingJoinPointStaticPart) In @ style, it is user defined. The current impl is handling the formal binding in a way that only args/this/target can be bound. I had to add some conditionals to handles cases like that: void myAdvice(JoinPoint jp, Object target) {..} where target() binding is at index 1, while the index 0 is not an unbound but actually "virtually" bound to the joinpoint. Pointcut are thus having a virtuallyBoundedNames String[] that is the list of arguments for which we don't want any complain if it not bound. This one is populated during @ extraction, and Pointcut.concretize() make sure the info is not lost when composition occurs (with PerClause f.e.) The only issue is that currently, binding JP/SJP/ESJP themselves is not possible f.e. "... && args(jp)" myAdvice(JoinPoint jp, JoinPoint currentJp) Is that a big issue ? May be impact adviceexecution() and could impact some use cases around mock testing.
|
resolved fixed
|
639b4fd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-11T15:05:44Z | 2005-01-28T16:33:20Z |
tests/java5/ataspectj/ataspectj/SingletonAspectBindingsTest.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 ataspectj;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import junit.framework.TestCase;
import java.io.File;
import java.io.FileReader;
/**
* Test various advice and JoinPoint + binding, without pc ref
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class SingletonAspectBindingsTest extends TestCase {
static StringBuffer s_log = new StringBuffer();
static void log(String s) {
s_log.append(s).append(" ");
}
public static void main(String[] args) {
TestHelper.runAndThrowOnFailure(suite());
}
public static junit.framework.Test suite() {
return new junit.framework.TestSuite(SingletonAspectBindingsTest.class);
}
public void hello() {
log("hello");
}
public void hello(String s) {
log("hello-");
log(s);
}
public void testExecutionWithThisBinding() {
s_log = new StringBuffer();
SingletonAspectBindingsTest me = new SingletonAspectBindingsTest();
me.hello();
// see here advice precedence as in source code order
//TODO check around relative order
// see fix in BcelWeaver sorting shadowMungerList
//assertEquals("around2_ around_ before hello after _around _around2 ", s_log.toString());
assertEquals("around_ around2_ before hello _around2 _around after ", s_log.toString());
}
public void testExecutionWithArgBinding() {
s_log = new StringBuffer();
SingletonAspectBindingsTest me = new SingletonAspectBindingsTest();
me.hello("x");
assertEquals("before- x hello- x ", s_log.toString());
}
@Aspect
public static class TestAspect {
static int s = 0;
static {
s++;
}
public TestAspect() {
// assert clinit has run when singleton aspectOf reaches that
assertTrue(s>0);
}
//public static TestAspect aspectOf() {return null;}
@Around("execution(* ataspectj.SingletonAspectBindingsTest.hello())")
public void aaround(ProceedingJoinPoint jp) {
log("around_");
try {
jp.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
log("_around");
}
@Around("execution(* ataspectj.SingletonAspectBindingsTest.hello()) && this(t)")
public void around2(ProceedingJoinPoint jp, Object t) {
log("around2_");
assertEquals(SingletonAspectBindingsTest.class.getName(), t.getClass().getName());
try {
jp.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
log("_around2");
}
@Before("execution(* ataspectj.SingletonAspectBindingsTest.hello())")
public void before(JoinPoint.StaticPart sjp) {
log("before");
assertEquals("hello", sjp.getSignature().getName());
}
@After("execution(* ataspectj.SingletonAspectBindingsTest.hello())")
public void after(JoinPoint.StaticPart sjp) {
log("after");
assertEquals("execution(public void ataspectj.SingletonAspectBindingsTest.hello())", sjp.toLongString());
}
//TODO see String alias, see before advice name clash - all that works
// 1/ String is in java.lang.* - see SimpleScope.javalangPrefix array
// 2/ the advice is register thru its Bcel Method mirror
@Before("execution(* ataspectj.SingletonAspectBindingsTest.hello(String)) && args(s)")
public void before(String s, JoinPoint.StaticPart sjp) {
log("before-");
log(s);
assertEquals("hello", sjp.getSignature().getName());
}
}
// public void testHe() throws Throwable {
// //Allow to look inn file based on advises/advised-by offset numbers
// File f = new File("../tests/java5/ataspectj/ataspectj/SingletonAspectBindingsTest2.aj");
// FileReader r = new FileReader(f);
// int i = 0;
// for (i = 0; i < 2800; i++) {
// r.read();
// }
// for (;i < 2900; i++) {
// if (i == 2817) System.out.print("X");
// System.out.print((char)r.read());
// }
// System.out.print("|DONE");
// r.close();
// }
}
|
83,935 |
Bug 83935 @AJ and formal binding impl
|
Some notes on formal binding impl for @AJ In code style, the advice signature is always looking the same (..bindings.., org.aspectj.lang.Part thisJoinPointStaticPart, JoinPoint thisJoinPoint, org.aspectj.lang.Part thisEnclosingJoinPointStaticPart) In @ style, it is user defined. The current impl is handling the formal binding in a way that only args/this/target can be bound. I had to add some conditionals to handles cases like that: void myAdvice(JoinPoint jp, Object target) {..} where target() binding is at index 1, while the index 0 is not an unbound but actually "virtually" bound to the joinpoint. Pointcut are thus having a virtuallyBoundedNames String[] that is the list of arguments for which we don't want any complain if it not bound. This one is populated during @ extraction, and Pointcut.concretize() make sure the info is not lost when composition occurs (with PerClause f.e.) The only issue is that currently, binding JP/SJP/ESJP themselves is not possible f.e. "... && args(jp)" myAdvice(JoinPoint jp, JoinPoint currentJp) Is that a big issue ? May be impact adviceexecution() and could impact some use cases around mock testing.
|
resolved fixed
|
639b4fd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-11T15:05:44Z | 2005-01-28T16:33:20Z |
tests/src/org/aspectj/systemtest/ajc150/ataspectj/AtAjSyntaxTests.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.systemtest.ajc150.ataspectj;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
import java.io.File;
/**
* A suite for @AspectJ aspects located in java5/ataspectj
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class AtAjSyntaxTests extends XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(AtAjSyntaxTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ataspectj/syntax.xml");
}
public void testSimpleBefore() {
runTest("SimpleBefore");
}
public void testSimpleAfter() {
runTest("SimpleAfter");
}
public void testSingletonAspectBindings() {
//Note AV: uncomment setReporting to get it in modules/tests folder
org.aspectj.asm.AsmManager.setReporting("debug.txt",true,true,true,true);
runTest("singletonAspectBindings");
// same stuff with AJ
//org.aspectj.asm.AsmManager.setReporting("debug-aj.txt",true,true,true,true);
//runTest("singletonAspectBindings2");
}
public void testCflowTest() {
runTest("CflowTest");
}
public void testPointcutReferenceTest() {
runTest("PointcutReferenceTest");
}
public void testXXJoinPointTest() {
runTest("XXJoinPointTest");
}
public void testPrecedenceTest() {
runTest("PrecedenceTest");
}
public void testAfterXTest() {
runTest("AfterXTest");
}
public void testBindingTest() {
runTest("BindingTest");
}
public void testBindingTestNoInline() {
runTest("BindingTest no inline");
}
public void testPerClause() {
runTest("PerClause");
}
public void testAroundInlineMunger_XnoInline() {
runTest("AroundInlineMunger -XnoInline");
}
public void testAroundInlineMunger() {
runTest("AroundInlineMunger");
}
public void testAroundInlineMunger2() {
runTest("AroundInlineMunger2");
}
public void testDeow() {
runTest("Deow");
}
public void testSingletonInheritance() {
runTest("singletonInheritance");
}
public void testPerClauseInheritance() {
runTest("perClauseInheritance");
}
public void testIfPointcut() {
runTest("IfPointcutTest");
}
public void testIfPointcut2() {
runTest("IfPointcut2Test");
}
}
|
83,935 |
Bug 83935 @AJ and formal binding impl
|
Some notes on formal binding impl for @AJ In code style, the advice signature is always looking the same (..bindings.., org.aspectj.lang.Part thisJoinPointStaticPart, JoinPoint thisJoinPoint, org.aspectj.lang.Part thisEnclosingJoinPointStaticPart) In @ style, it is user defined. The current impl is handling the formal binding in a way that only args/this/target can be bound. I had to add some conditionals to handles cases like that: void myAdvice(JoinPoint jp, Object target) {..} where target() binding is at index 1, while the index 0 is not an unbound but actually "virtually" bound to the joinpoint. Pointcut are thus having a virtuallyBoundedNames String[] that is the list of arguments for which we don't want any complain if it not bound. This one is populated during @ extraction, and Pointcut.concretize() make sure the info is not lost when composition occurs (with PerClause f.e.) The only issue is that currently, binding JP/SJP/ESJP themselves is not possible f.e. "... && args(jp)" myAdvice(JoinPoint jp, JoinPoint currentJp) Is that a big issue ? May be impact adviceexecution() and could impact some use cases around mock testing.
|
resolved fixed
|
639b4fd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-11T15:05:44Z | 2005-01-28T16:33: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 org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.patterns.ExactTypePattern;
import org.aspectj.weaver.patterns.ExposedState;
import org.aspectj.weaver.patterns.Pointcut;
/**
* Advice implemented for bcel.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class BcelAdvice extends Advice {
private Test pointcutTest;
private ExposedState exposedState;
private boolean hasMatchedAtLeastOnce = false;
public BcelAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature,
ResolvedTypeX 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, ResolvedTypeX concreteAspect)
{
this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext),
pointcut, signature, concreteAspect);
thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests
}
// ---- implementations of ShadowMunger's methods
public void specializeOn(Shadow shadow) {
if (getKind() == AdviceKind.Around) {
((BcelShadow)shadow).initializeForAroundClosure();
}
//XXX this case is just here for supporting lazy test code
if (getKind() == null) {
exposedState = new ExposedState(0);
return;
}
if (getKind().isPerEntry()) {
exposedState = new ExposedState(0);
} else if (getKind().isCflow()) {
exposedState = new ExposedState(nFreeVars);
} else if (getSignature() != null) {
exposedState = new ExposedState(getSignature());
} else {
exposedState = new ExposedState(0);
return; //XXX this case is just here for supporting lazy test code
}
pointcutTest = getPointcut().findResidue(shadow, exposedState);
// these initializations won't be performed by findResidue, but need to be
// so that the joinpoint is primed for weaving
if (getKind() == AdviceKind.PerThisEntry) {
shadow.getThisVar();
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.getTargetVar();
}
// make sure thisJoinPoint parameters are initialized
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
((BcelShadow)shadow).requireThisJoinPoint(pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around);
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
}
private boolean canInline(Shadow s) {
if (attribute.isProceedInInners()) return false;
//XXX this guard seems to only be needed for bad test cases
if (concreteAspect == null || concreteAspect == ResolvedTypeX.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) {
TypeX catchType =
hasExtraParameter()
? getExtraParameterType()
: TypeX.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(TypeX[] excs) {
if (excs == null || excs.length == 0) return Collections.EMPTY_LIST;
Collection ret = new ArrayList();
World world = concreteAspect.getWorld();
ResolvedTypeX runtimeException = world.getCoreType(TypeX.RUNTIME_EXCEPTION);
ResolvedTypeX error = world.getCoreType(TypeX.ERROR);
for (int i=0, len=excs.length; i < len; i++) {
ResolvedTypeX t = world.resolve(excs[i],true);
if (t == ResolvedTypeX.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) {
// TypeX extraParameterType = getExtraParameterType();
// if (! extraParameterType.equals(TypeX.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) {
TypeX extraParameterType = getExtraParameterType();
if (! extraParameterType.equals(TypeX.OBJECT)
&& ! extraParameterType.isPrimitive()) {
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()));
}
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 (getConcreteAspect()==null || !getConcreteAspect().isAnnotationStyleAspect()) {
;
} else {
// ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
} else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
} else {
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 {
TypeX desiredTy = getSignature().getParameterTypes()[i];
v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
}
}
// ATAJ: for code style aspect, handles the extraFlag as usual ie not
// in the middle of the formal bindings but at the end, in a rock solid ordering
if (getConcreteAspect()==null || !getConcreteAspect().isAnnotationStyleAspect()) {
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
// handle thisJoinPoint parameters
// these need to be in that same order as parameters in
// org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
}
return il;
}
public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
return new InstructionList(
Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getSignature()));
}
public InstructionList getTestInstructions(
BcelShadow shadow,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
//System.err.println("test: " + pointcutTest);
return BcelRenderer.renderTest(
shadow.getFactory(),
shadow.getWorld(),
pointcutTest,
sk,
fk,
next);
}
public int compareTo(Object other) {
if (!(other instanceof BcelAdvice)) return 0;
BcelAdvice o = (BcelAdvice)other;
//System.err.println("compareTo: " + this + ", " + o);
if (kind.getPrecedence() != o.kind.getPrecedence()) {
if (kind.getPrecedence() > o.kind.getPrecedence()) return +1;
else return -1;
}
if (kind.isCflow()) {
// System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
// System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1;
else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1;
else return 0;
}
if (kind.isPerEntry() || kind == AdviceKind.Softener) {
return 0;
}
//System.out.println("compare: " + this + " with " + other);
World world = concreteAspect.getWorld();
int ret =
concreteAspect.getWorld().compareByDominates(
concreteAspect,
o.concreteAspect);
if (ret != 0) return ret;
ResolvedTypeX declaringAspect = getDeclaringAspect().resolve(world);
ResolvedTypeX 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;
}
}
|
103,266 |
Bug 103266 NPE on syntax error
|
This example program generates an NPE on CVS HEAD and M2. I will attach the ajcore file. public abstract aspect WorkerExample { after() returning (RequestContext newContext) : call(RequestContext+.new (..)) { System.out.println("constructing "+newContext+" at "+thisJoinPoint.toLongString()+" from "+thisEnclosingJoinPointStaticPart+":"); } public abstract class RequestContext { public final Object execute() { return doExecute(); } /** template method */ public abstract Object doExecute(); } public static void main(String args[]) { new Runnable() { public void run() {} }.run(); }; } aspect ConcreteAlpha extends WorkerExample { Object around(final Object runnable) : execution(void Runnable.run()) && this(runnable) { System.out.println("monitoring operation: "+runnable+" at "+thisJoinPoint+", for "+thisJoinPoint.getThis()); RequestContext requestContext = new RequestContext() { public Object doExecute() { return proceed(runnable); } }; return requestContext.execute(); } } aspect ConcreteBeta extends WorkerExample { Object around() : call(void awqeyuwqer()) { RequestContext requestContext = new ConnectionRequestContext() { public Object doExecute() { return proceed(); } }; return requestContext.execute(); } }
|
resolved fixed
|
bba9c50
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-18T08:27:44Z | 2005-07-10T04:33:20Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/MakeDeclsPublicVisitor.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.org.eclipse.jdt.internal.compiler.ASTVisitor;
//import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AnonymousLocalTypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
//import org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalTypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodScope;
/**
* Takes a method that already has the three extra parameters
* thisJoinPointStaticPart, thisJoinPoint and thisEnclosingJoinPointStaticPart
*/
public class MakeDeclsPublicVisitor extends ASTVisitor {
public void endVisit(ConstructorDeclaration decl, ClassScope scope) {
decl.binding.modifiers = AstUtil.makePublic(decl.binding.modifiers);
}
public void endVisit(FieldDeclaration decl, MethodScope scope) {
decl.binding.modifiers = AstUtil.makePublic(decl.binding.modifiers);
}
public void endVisit(MethodDeclaration decl, ClassScope scope) {
decl.binding.modifiers = AstUtil.makePublic(decl.binding.modifiers);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ASTVisitor#endVisit(org.eclipse.jdt.internal.compiler.ast.TypeDeclaration, org.eclipse.jdt.internal.compiler.lookup.BlockScope)
*/
public void endVisit(
TypeDeclaration localTypeDeclaration,
BlockScope scope) {
localTypeDeclaration.binding.modifiers = AstUtil.makePublic(localTypeDeclaration.binding.modifiers);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ASTVisitor#endVisit(org.eclipse.jdt.internal.compiler.ast.TypeDeclaration, org.eclipse.jdt.internal.compiler.lookup.ClassScope)
*/
public void endVisit(
TypeDeclaration memberTypeDeclaration,
ClassScope scope) {
memberTypeDeclaration.binding.modifiers = AstUtil.makePublic(memberTypeDeclaration.binding.modifiers);
}
}
|
103,266 |
Bug 103266 NPE on syntax error
|
This example program generates an NPE on CVS HEAD and M2. I will attach the ajcore file. public abstract aspect WorkerExample { after() returning (RequestContext newContext) : call(RequestContext+.new (..)) { System.out.println("constructing "+newContext+" at "+thisJoinPoint.toLongString()+" from "+thisEnclosingJoinPointStaticPart+":"); } public abstract class RequestContext { public final Object execute() { return doExecute(); } /** template method */ public abstract Object doExecute(); } public static void main(String args[]) { new Runnable() { public void run() {} }.run(); }; } aspect ConcreteAlpha extends WorkerExample { Object around(final Object runnable) : execution(void Runnable.run()) && this(runnable) { System.out.println("monitoring operation: "+runnable+" at "+thisJoinPoint+", for "+thisJoinPoint.getThis()); RequestContext requestContext = new RequestContext() { public Object doExecute() { return proceed(runnable); } }; return requestContext.execute(); } } aspect ConcreteBeta extends WorkerExample { Object around() : call(void awqeyuwqer()) { RequestContext requestContext = new ConnectionRequestContext() { public Object doExecute() { return proceed(); } }; return requestContext.execute(); } }
|
resolved fixed
|
bba9c50
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-18T08:27:44Z | 2005-07-10T04: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 junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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");}
// 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);
}
}
|
104,212 |
Bug 104212 static method call from subclass signature is wrong
|
a very bad bug... or ? in the snip below, getMethod() says null and the factory is actually thinking that test() is a static method of AspectJBugMain instead of Assert... wondering why we don't catch that in the test suite or what could happen recently around that. Or is it something I am confused about ? (i doubt a jp.getSignature().getMethod is supposed to return null in some cases though..) @Aspect public class Sam { @Pointcut("call(* *.*(..))") public void methodCalls() { } @Around("methodCalls() && !within(alex.sam.Sam) && within(alex..*)") public Object aroundMethodCalls(ProceedingJoinPoint jp) throws Throwable { String typeName = jp.getSignature().getDeclaringTypeName(); System.out.println("declType " + typeName); System.out.println("method " + ((MethodSignature)jp.getSignature()).getMethod()); return jp.proceed(); } } class Assert { public static void test() { System.out.println("RUN Assert.test"); } } class AspectJBugMain extends Assert { public static void main(String[] args) { test(); } // public static void test() { // System.out.println("RUN AspectJBugMain.test"); // } }
|
resolved fixed
|
619a6ad
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-22T14:57:40Z | 2005-07-18T12:33:20Z |
tests/java5/ataspectj/ataspectj/Bug104212.java
| |
104,212 |
Bug 104212 static method call from subclass signature is wrong
|
a very bad bug... or ? in the snip below, getMethod() says null and the factory is actually thinking that test() is a static method of AspectJBugMain instead of Assert... wondering why we don't catch that in the test suite or what could happen recently around that. Or is it something I am confused about ? (i doubt a jp.getSignature().getMethod is supposed to return null in some cases though..) @Aspect public class Sam { @Pointcut("call(* *.*(..))") public void methodCalls() { } @Around("methodCalls() && !within(alex.sam.Sam) && within(alex..*)") public Object aroundMethodCalls(ProceedingJoinPoint jp) throws Throwable { String typeName = jp.getSignature().getDeclaringTypeName(); System.out.println("declType " + typeName); System.out.println("method " + ((MethodSignature)jp.getSignature()).getMethod()); return jp.proceed(); } } class Assert { public static void test() { System.out.println("RUN Assert.test"); } } class AspectJBugMain extends Assert { public static void main(String[] args) { test(); } // public static void test() { // System.out.println("RUN AspectJBugMain.test"); // } }
|
resolved fixed
|
619a6ad
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-22T14:57:40Z | 2005-07-18T12:33:20Z |
tests/src/org/aspectj/systemtest/ajc150/ataspectj/AtAjSyntaxTests.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.systemtest.ajc150.ataspectj;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
import java.io.File;
/**
* A suite for @AspectJ aspects located in java5/ataspectj
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class AtAjSyntaxTests extends XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(AtAjSyntaxTests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ataspectj/syntax.xml");
}
public void testSimpleBefore() {
runTest("SimpleBefore");
}
public void testSimpleAfter() {
runTest("SimpleAfter");
}
public void testSingletonAspectBindings() {
//Note AV: uncomment setReporting to get it in modules/tests folder
// org.aspectj.asm.AsmManager.setReporting("debug.txt",true,true,true,true);
runTest("singletonAspectBindings");
// same stuff with AJ
//org.aspectj.asm.AsmManager.setReporting("debug-aj.txt",true,true,true,true);
//runTest("singletonAspectBindings2");
}
public void testCflowTest() {
runTest("CflowTest");
}
public void testPointcutReferenceTest() {
runTest("PointcutReferenceTest");
}
public void testXXJoinPointTest() {
runTest("XXJoinPointTest");
}
public void testPrecedenceTest() {
runTest("PrecedenceTest");
}
public void testAfterXTest() {
runTest("AfterXTest");
}
public void testBindingTest() {
runTest("BindingTest");
}
public void testBindingTestNoInline() {
runTest("BindingTest no inline");
}
public void testPerClause() {
runTest("PerClause");
}
public void testAroundInlineMunger_XnoInline() {
runTest("AroundInlineMunger -XnoInline");
}
public void testAroundInlineMunger() {
runTest("AroundInlineMunger");
}
public void testAroundInlineMunger2() {
runTest("AroundInlineMunger2");
}
public void testDeow() {
runTest("Deow");
}
public void testSingletonInheritance() {
runTest("singletonInheritance");
}
public void testPerClauseInheritance() {
runTest("perClauseInheritance");
}
public void testIfPointcut() {
runTest("IfPointcutTest");
}
public void testIfPointcut2() {
runTest("IfPointcut2Test");
}
public void testMultipleBinding() {
runTest("MultipleBinding");
}
}
|
104,212 |
Bug 104212 static method call from subclass signature is wrong
|
a very bad bug... or ? in the snip below, getMethod() says null and the factory is actually thinking that test() is a static method of AspectJBugMain instead of Assert... wondering why we don't catch that in the test suite or what could happen recently around that. Or is it something I am confused about ? (i doubt a jp.getSignature().getMethod is supposed to return null in some cases though..) @Aspect public class Sam { @Pointcut("call(* *.*(..))") public void methodCalls() { } @Around("methodCalls() && !within(alex.sam.Sam) && within(alex..*)") public Object aroundMethodCalls(ProceedingJoinPoint jp) throws Throwable { String typeName = jp.getSignature().getDeclaringTypeName(); System.out.println("declType " + typeName); System.out.println("method " + ((MethodSignature)jp.getSignature()).getMethod()); return jp.proceed(); } } class Assert { public static void test() { System.out.println("RUN Assert.test"); } } class AspectJBugMain extends Assert { public static void main(String[] args) { test(); } // public static void test() { // System.out.println("RUN AspectJBugMain.test"); // } }
|
resolved fixed
|
619a6ad
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-22T14:57:40Z | 2005-07-18T12:33:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.CPInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.IndexedInstruction;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LocalVariableInstruction;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUTFIELD;
import org.aspectj.apache.bcel.generic.PUTSTATIC;
import org.aspectj.apache.bcel.generic.RET;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.Select;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IClassWeaver;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverMetrics;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.Shadow.Kind;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.FastMatchInfo;
class BcelClassWeaver implements IClassWeaver {
/**
* This is called from {@link BcelWeaver} to perform the per-class weaving process.
*/
public static boolean weave(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers,
List lateTypeMungers)
{
boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers).weave();
//System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState());
//clazz.print();
return b;
}
// --------------------------------------------
private final LazyClassGen clazz;
private final List shadowMungers;
private final List typeMungers;
private final List lateTypeMungers;
private final BcelObjectType ty; // alias of clazz.getType()
private final BcelWorld world; // alias of ty.getWorld()
private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen()
private final InstructionFactory fact; // alias of clazz.getFactory();
private final List addedLazyMethodGens = new ArrayList();
private final Set addedDispatchTargets = new HashSet();
// Static setting across BcelClassWeavers
private static boolean inReweavableMode = false;
private static boolean compressReweavableAttributes = false;
private List addedSuperInitializersAsList = null; // List<IfaceInitList>
private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList
private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger>
private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger>
private Map mapToAnnotations = new HashMap();
private BcelShadow clinitShadow = null;
/**
* This holds the initialization and pre-initialization shadows for this class
* that were actually matched by mungers (if no match, then we don't even create the
* shadows really).
*/
private final List initializationShadows = new ArrayList(1);
private BcelClassWeaver(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers,
List lateTypeMungers)
{
super();
// assert world == clazz.getType().getWorld()
this.world = world;
this.clazz = clazz;
this.shadowMungers = shadowMungers;
this.typeMungers = typeMungers;
this.lateTypeMungers = lateTypeMungers;
this.ty = clazz.getBcelObjectType();
this.cpg = clazz.getConstantPoolGen();
this.fact = clazz.getFactory();
fastMatchShadowMungers(shadowMungers);
initializeSuperInitializerMap(ty.getResolvedTypeX());
}
private List[] perKindShadowMungers;
private boolean canMatchBodyShadows = false;
private boolean canMatchInitialization = false;
private void fastMatchShadowMungers(List shadowMungers) {
// beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) !
perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1];
for (int i = 0; i < perKindShadowMungers.length; i++) {
ArrayList mungers = new ArrayList(0);
perKindShadowMungers[i] = new ArrayList(0);
}
for (Iterator iter = shadowMungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
Set couldMatchKinds = munger.getPointcut().couldMatchKinds();
for (Iterator kindIterator = couldMatchKinds.iterator();
kindIterator.hasNext();) {
Shadow.Kind aKind = (Shadow.Kind) kindIterator.next();
perKindShadowMungers[aKind.getKey()].add(munger);
}
}
if (!perKindShadowMungers[Shadow.Initialization.getKey()].isEmpty())
canMatchInitialization = true;
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
Shadow.Kind kind = Shadow.SHADOW_KINDS[i];
if (!kind.isEnclosingKind() && !perKindShadowMungers[i+1].isEmpty()) {
canMatchBodyShadows = true;
}
if (perKindShadowMungers[i+1].isEmpty()) {
perKindShadowMungers[i+1] = null;
}
}
}
private boolean canMatch(Shadow.Kind kind) {
return perKindShadowMungers[kind.getKey()] != null;
}
private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) {
FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind);
for (Iterator i = shadowMungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
FuzzyBoolean fb = munger.getPointcut().fastMatch(info);
WeaverMetrics.recordFastMatchResult(fb);// Could pass: munger.getPointcut().toString()
if (fb.maybeTrue()) mungers.add(munger);
}
}
private void initializeSuperInitializerMap(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) {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
if (l != null) return false;
l = new IfaceInitList(onType);
addedSuperInitializers.put(onType, l);
return true;
}
public void addInitializer(ConcreteTypeMunger cm) {
NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger();
ResolvedType onType = m.getSignature().getDeclaringType().resolve(world);
if (onType.isRawType()) onType = onType.getGenericType();
if (m.getSignature().isStatic()) {
addedClassInitializers.add(cm);
} else {
if (onType == ty.getResolvedTypeX()) {
addedThisInitializers.add(cm);
} else {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
l.list.add(cm);
}
}
}
private static class IfaceInitList implements PartialOrder.PartialComparable {
final ResolvedType onType;
List list = new ArrayList();
IfaceInitList(ResolvedType onType) {
this.onType = onType;
}
public int compareTo(Object other) {
IfaceInitList o = (IfaceInitList)other;
if (onType.isAssignableFrom(o.onType)) return +1;
else if (o.onType.isAssignableFrom(onType)) return -1;
else return 0;
}
public int fallbackCompareTo(Object other) {
return 0;
}
}
// XXX this is being called, but the result doesn't seem to be being used
public boolean addDispatchTarget(ResolvedMember m) {
return addedDispatchTargets.add(m);
}
public void addLazyMethodGen(LazyMethodGen gen) {
addedLazyMethodGens.add(gen);
}
public void addOrReplaceLazyMethodGen(LazyMethodGen mg) {
if (alreadyDefined(clazz, mg)) return;
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (existing.definingType == null) {
// this means existing was introduced on the class itself
return;
} else if (mg.definingType.isAssignableFrom(existing.definingType)) {
// existing is mg's subtype and dominates mg
return;
} else if (existing.definingType.isAssignableFrom(mg.definingType)) {
// mg is existing's subtype and dominates existing
i.remove();
addedLazyMethodGens.add(mg);
return;
} else {
throw new BCException("conflict between: " + mg + " and " + existing);
}
}
}
addedLazyMethodGens.add(mg);
}
private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) {
for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (!mg.isAbstract() && existing.isAbstract()) {
i.remove();
return false;
}
return true;
}
}
return false;
}
private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) {
return mg.getName().equals(existing.getName()) &&
mg.getSignature().equals(existing.getSignature());
}
// ----
public boolean weave() {
if (clazz.isWoven() && !clazz.isReweavable()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ALREADY_WOVEN,clazz.getType().getName()),
ty.getSourceLocation(), null);
return false;
}
Set aspectsAffectingType = null;
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType = new HashSet();
boolean isChanged = false;
// we want to "touch" all aspects
if (clazz.getType().isAspect()) isChanged = true;
// start by munging all typeMungers
for (Iterator i = typeMungers.iterator(); i.hasNext(); ) {
Object o = i.next();
if ( !(o instanceof BcelTypeMunger) ) {
//???System.err.println("surprising: " + o);
continue;
}
BcelTypeMunger munger = (BcelTypeMunger)o;
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
isChanged = true;
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName());
}
}
// Weave special half type/half shadow mungers...
isChanged = weaveDeclareAtMethodCtor(clazz) || isChanged;
isChanged = weaveDeclareAtField(clazz) || isChanged;
// XXX do major sort of stuff
// sort according to: Major: type hierarchy
// within each list: dominates
// don't forget to sort addedThisInitialiers according to dominates
addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values());
addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList);
if (addedSuperInitializersAsList == null) {
throw new BCException("circularity in inter-types");
}
// this will create a static initializer if there isn't one
// this is in just as bad taste as NOPs
LazyMethodGen staticInit = clazz.getStaticInitializer();
staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true));
// now go through each method, and match against each method. This
// sets up each method's {@link LazyMethodGen#matchedShadows} field,
// and it also possibly adds to {@link #initializationShadows}.
List methodGens = new ArrayList(clazz.getMethodGens());
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
boolean shadowMungerMatched = match(mg);
if (shadowMungerMatched) {
// For matching mungers, add their declaring aspects to the list that affected this type
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.addAll(findAspectsForMungers(mg));
isChanged = true;
}
}
// now we weave all but the initialization shadows
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
implement(mg);
}
// if we matched any initialization shadows, we inline and weave
if (! initializationShadows.isEmpty()) {
// Repeat next step until nothing left to inline...cant go on
// infinetly as compiler will have detected and reported
// "Recursive constructor invocation"
while (inlineSelfConstructors(methodGens));
positionAndImplement(initializationShadows);
}
// now proceed with late type mungers
if (lateTypeMungers != null) {
for (Iterator i = lateTypeMungers.iterator(); i.hasNext(); ) {
BcelTypeMunger munger = (BcelTypeMunger)i.next();
if (munger.matches(clazz.getType())) {
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
isChanged = true;
if (inReweavableMode || clazz.getType().isAspect()) aspectsAffectingType.add(munger.getAspectType().getName());
}
}
}
}
//FIXME AV - see #75442, for now this is not enough to fix the bug, comment that out until we really fix it
// // flush to save some memory
// PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType());
// finally, if we changed, we add in the introduced methods.
if (isChanged) {
clazz.getOrCreateWeaverStateInfo();
weaveInAddedMethods(); // FIXME asc are these potentially affected by declare annotation?
}
if (inReweavableMode || clazz.getType().isAspect()) {
WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo();
wsi.addAspectsAffectingType(aspectsAffectingType);
wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes());
wsi.setReweavable(true,compressReweavableAttributes);
} else {
clazz.getOrCreateWeaverStateInfo().setReweavable(false,false);
}
return isChanged;
}
/**
* Weave any declare @method/@ctor statements into the members of the supplied class
*/
private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) {
List reportedProblems = new ArrayList();
List allDecams = world.getDeclareAnnotationOnMethods();
if (allDecams.isEmpty()) return false; // nothing to do
boolean isChanged = false;
// deal with ITDs
List itdMethodsCtors = getITDSubset(clazz,ResolvedTypeMunger.Method);
itdMethodsCtors.addAll(getITDSubset(clazz,ResolvedTypeMunger.Constructor));
if (!itdMethodsCtors.isEmpty()) {
// Can't use the subset called 'decaMs' as it won't be right for ITDs...
isChanged = weaveAtMethodOnITDSRepeatedly(allDecams,itdMethodsCtors,reportedProblems);
}
// deal with all the other methods...
List members = clazz.getMethodGens();
List decaMs = getMatchingSubset(allDecams,clazz.getType());
if (decaMs.isEmpty()) return false; // nothing to do
if (!members.isEmpty()) {
for (int memberCounter = 0;memberCounter<members.size();memberCounter++) {
LazyMethodGen mg = (LazyMethodGen)members.get(memberCounter);
if (!mg.getName().startsWith(NameMangler.PREFIX)) {
// Single first pass
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
for (Iterator iter = decaMs.iterator(); iter.hasNext();) {
DeclareAnnotation decaM = (DeclareAnnotation) iter.next();
if (decaM.matches(mg.getMemberView(),world)) {
if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) continue; // skip this one...
mg.addAnnotation(decaM.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod());
reportMethodCtorWeavingMessage(clazz, mg, decaM);
isChanged = true;
modificationOccured = true;
} else {
if (!decaM.isStarredAnnotationPattern())
worthRetrying.add(decaM); // an annotation is specified that might be put on by a subsequent decaf
}
}
// Multiple secondary passes
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
// lets have another go
List forRemoval = new ArrayList();
for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaM = (DeclareAnnotation) iter.next();
if (decaM.matches(mg.getMemberView(),world)) {
if (doesAlreadyHaveAnnotation(mg.getMemberView(),decaM,reportedProblems)) continue; // skip this one...
mg.addAnnotation(decaM.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaM.getSourceLocation(),clazz.getName(),mg.getMethod());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaM);
}
}
worthRetrying.removeAll(forRemoval);
}
}
}
}
return isChanged;
}
// TAG: WeavingMessage
private void reportMethodCtorWeavingMessage(LazyClassGen clazz, LazyMethodGen mg, DeclareAnnotation decaM) {
if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){
StringBuffer parmString = new StringBuffer("(");
Type[] args = mg.getMethod().getArgumentTypes();
for (int i = 0; i < args.length; i++) {
Type type2 = args[i];
String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type2.getSignature());
if (s.lastIndexOf(".")!=-1) s =s.substring(s.lastIndexOf(".")+1);
parmString.append(s);
if ((i+1)<args.length) parmString.append(",");
}
parmString.append(")");
String methodName = mg.getMethod().getName();
StringBuffer sig = new StringBuffer();
sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(mg.getMethod().getAccessFlags()) );
sig.append(" ");
sig.append(mg.getMethod().getReturnType().toString());
sig.append(" ");
sig.append(clazz.getName());
sig.append(".");
sig.append(methodName.equals("<init>")?"new":methodName);
sig.append(parmString);
StringBuffer loc = new StringBuffer();
if (clazz.getFileName()==null) {
loc.append("no debug info available");
} else {
loc.append(clazz.getFileName());
if (mg.getDeclarationLineNumber()!=-1) {
loc.append(":"+mg.getDeclarationLineNumber());
}
}
getWorld().getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES,
new String[]{
sig.toString(),
loc.toString(),
decaM.getAnnotationString(),
methodName.startsWith("<init>")?"constructor":"method",
decaM.getAspect().toString(),
Utility.beautifyLocation(decaM.getSourceLocation())
}));
}
}
/**
* Looks through a list of declare annotation statements and only returns
* those that could possibly match on a field/method/ctor in type.
*/
private List getMatchingSubset(List declareAnnotations, ResolvedType type) {
List subset = new ArrayList();
for (Iterator iter = declareAnnotations.iterator(); iter.hasNext();) {
DeclareAnnotation da = (DeclareAnnotation) iter.next();
if (da.couldEverMatch(type)) {
subset.add(da);
}
}
return subset;
}
/**
* Get a subset of all the type mungers defined on this aspect
*/
private List getITDSubset(LazyClassGen clazz,ResolvedTypeMunger.Kind wantedKind) {
List subset = new ArrayList();
Collection c = clazz.getBcelObjectType().getTypeMungers();
for (Iterator iter = c.iterator();iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger)iter.next();
if (typeMunger.getMunger().getKind()==wantedKind)
subset.add(typeMunger);
}
return subset;
}
public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz,BcelTypeMunger fieldMunger) {
NewFieldTypeMunger nftm = (NewFieldTypeMunger)fieldMunger.getMunger();
ResolvedMember lookingFor =AjcMemberMaker.interFieldInitializer(nftm.getSignature(),clazz.getType());
List meths = clazz.getMethodGens();
for (Iterator iter = meths.iterator(); iter.hasNext();) {
LazyMethodGen element = (LazyMethodGen) iter.next();
if (element.getName().equals(lookingFor.getName())) return element;
}
return null;
}
// FIXME asc refactor this to neaten it up
public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz,BcelTypeMunger methodCtorMunger) {
if (methodCtorMunger.getMunger() instanceof NewMethodTypeMunger) {
NewMethodTypeMunger nftm = (NewMethodTypeMunger)methodCtorMunger.getMunger();
ResolvedMember lookingFor =AjcMemberMaker.interMethodBody(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 itdIsActually = methodctorMunger.getSignature();
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
for (Iterator iter2 = decaMCs.iterator(); iter2.hasNext();) {
DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next();
if (decaMC.matches(itdIsActually,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz,methodctorMunger);
if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaMC,reportedErrors)) continue; // skip this one...
annotationHolder.addAnnotation(decaMC.getAnnotationX());
itdIsActually.addAnnotation(decaMC.getAnnotationX());
isChanged=true;
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),itdIsActually.getSourceLocation());
modificationOccured = true;
} else {
if (!decaMC.isStarredAnnotationPattern())
worthRetrying.add(decaMC); // an annotation is specified that might be put on by a subsequent decaf
}
}
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
List forRemoval = new ArrayList();
for (Iterator iter2 = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaMC = (DeclareAnnotation) iter2.next();
if (decaMC.matches(itdIsActually,world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz,methodctorMunger);
if (doesAlreadyHaveAnnotation(annotationHolder,itdIsActually,decaMC,reportedErrors)) continue; // skip this one...
annotationHolder.addAnnotation(decaMC.getAnnotationX());
itdIsActually.addAnnotation(decaMC.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaMC.getSourceLocation(),itdIsActually.getSourceLocation());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaMC);
}
worthRetrying.removeAll(forRemoval);
}
}
}
return isChanged;
}
/**
* Weave any declare @field statements into the fields of the supplied class
*
* Interesting case relating to public ITDd fields. The annotations are really stored against
* the interfieldinit method in the aspect, but the public field is placed in the target
* type and then is processed in the 2nd pass over fields that occurs. I think it would be
* more expensive to avoid putting the annotation on that inserted public field than just to
* have it put there as well as on the interfieldinit method.
*/
private boolean weaveDeclareAtField(LazyClassGen clazz) {
// BUGWARNING not getting enough warnings out on declare @field ?
// There is a potential problem here with warnings not coming out - this
// will occur if they are created on the second iteration round this loop.
// We currently deactivate error reporting for the second time round.
// A possible solution is to record what annotations were added by what
// decafs and check that to see if an error needs to be reported - this
// would be expensive so lets skip it for now
List reportedProblems = new ArrayList();
List allDecafs = world.getDeclareAnnotationOnFields();
if (allDecafs.isEmpty()) return false; // nothing to do
boolean isChanged = false;
List itdFields = getITDSubset(clazz,ResolvedTypeMunger.Field);
if (itdFields!=null) {
isChanged = weaveAtFieldRepeatedly(allDecafs,itdFields,reportedProblems);
}
List decaFs = getMatchingSubset(allDecafs,clazz.getType());
if (decaFs.isEmpty()) return false; // nothing more to do
Field[] fields = clazz.getFieldGens();
if (fields!=null) {
for (int fieldCounter = 0;fieldCounter<fields.length;fieldCounter++) {
BcelField aBcelField = new BcelField(clazz.getBcelObjectType(),fields[fieldCounter]);
if (!aBcelField.getName().startsWith(NameMangler.PREFIX)) {
// Single first pass
List worthRetrying = new ArrayList();
boolean modificationOccured = false;
// go through all the declare @field statements
for (Iterator iter = decaFs.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter.next();
if (decaF.matches(aBcelField,world)) {
if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) continue; // skip this one...
aBcelField.addAnnotation(decaF.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]);
reportFieldAnnotationWeavingMessage(clazz, fields, fieldCounter, decaF);
isChanged = true;
modificationOccured = true;
} else {
if (!decaF.isStarredAnnotationPattern())
worthRetrying.add(decaF); // an annotation is specified that might be put on by a subsequent decaf
}
}
// Multiple secondary passes
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
// lets have another go
List forRemoval = new ArrayList();
for (Iterator iter = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = (DeclareAnnotation) iter.next();
if (decaF.matches(aBcelField,world)) {
if (doesAlreadyHaveAnnotation(aBcelField,decaF,reportedProblems)) continue; // skip this one...
aBcelField.addAnnotation(decaF.getAnnotationX());
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decaF.getSourceLocation(),clazz.getName(),fields[fieldCounter]);
isChanged = true;
modificationOccured = true;
forRemoval.add(decaF);
}
}
worthRetrying.removeAll(forRemoval);
}
}
}
}
return isChanged;
}
// TAG: WeavingMessage
private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, Field[] fields, int fieldCounter, DeclareAnnotation decaF) {
if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)){
Field theField = fields[fieldCounter];
world.getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ANNOTATES,
new String[]{
theField.toString() + "' of type '" + clazz.getName(),
clazz.getFileName(),
decaF.getAnnotationString(),
"field",
decaF.getAspect().toString(),
Utility.beautifyLocation(decaF.getSourceLocation())}));
}
}
/**
* Check if a resolved member (field/method/ctor) already has an annotation, if it
* does then put out a warning and return true
*/
private boolean doesAlreadyHaveAnnotation(ResolvedMember rm,DeclareAnnotation deca,List reportedProblems) {
if (rm.hasAnnotation(deca.getAnnotationTypeX())) {
if (world.getLint().elementAlreadyAnnotated.isEnabled()) {
Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode());
if (!reportedProblems.contains(uniqueID)) {
reportedProblems.add(uniqueID);
world.getLint().elementAlreadyAnnotated.signal(
new String[]{rm.toString(),deca.getAnnotationTypeX().toString()},
rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()});
}
}
return true;
}
return false;
}
private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm,ResolvedMember itdfieldsig,DeclareAnnotation deca,List reportedProblems) {
if (rm.hasAnnotation(deca.getAnnotationTypeX())) {
if (world.getLint().elementAlreadyAnnotated.isEnabled()) {
Integer uniqueID = new Integer(rm.hashCode()*deca.hashCode());
if (!reportedProblems.contains(uniqueID)) {
reportedProblems.add(uniqueID);
reportedProblems.add(new Integer(itdfieldsig.hashCode()*deca.hashCode()));
world.getLint().elementAlreadyAnnotated.signal(
new String[]{rm.toString(),deca.getAnnotationTypeX().toString()},
rm.getSourceLocation(),new ISourceLocation[]{deca.getSourceLocation()});
}
}
return true;
}
return false;
}
private Set findAspectsForMungers(LazyMethodGen mg) {
Set aspectsAffectingType = new HashSet();
for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) {
BcelShadow aShadow = (BcelShadow) iter.next();
// Mungers in effect on that shadow
for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) {
ShadowMunger aMunger = (ShadowMunger) iter2.next();
if (aMunger instanceof BcelAdvice) {
BcelAdvice bAdvice = (BcelAdvice)aMunger;
aspectsAffectingType.add(bAdvice.getConcreteAspect().getName());
} else {
// It is a 'Checker' - we don't need to remember aspects that only contributed Checkers...
}
}
}
return aspectsAffectingType;
}
private boolean inlineSelfConstructors(List methodGens) {
boolean inlinedSomething = false;
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen) i.next();
if (! mg.getName().equals("<init>")) continue;
InstructionHandle ih = findSuperOrThisCall(mg);
if (ih != null && isThisCall(ih)) {
LazyMethodGen donor = getCalledMethod(ih);
inlineMethod(donor, mg, ih);
inlinedSomething = true;
}
}
return inlinedSomething;
}
private void positionAndImplement(List initializationShadows) {
for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) {
BcelShadow s = (BcelShadow) i.next();
positionInitializationShadow(s);
//s.getEnclosingMethod().print();
s.implement();
}
}
private void positionInitializationShadow(BcelShadow s) {
LazyMethodGen mg = s.getEnclosingMethod();
InstructionHandle call = findSuperOrThisCall(mg);
InstructionList body = mg.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow((BcelShadow) s);
if (s.getKind() == Shadow.PreInitialization) {
// XXX assert first instruction is an ALOAD_0.
// a pre shadow goes from AFTER the first instruction (which we believe to
// be an ALOAD_0) to just before the call to super
r.associateWithTargets(
Range.genStart(body, body.getStart().getNext()),
Range.genEnd(body, call.getPrev()));
} else {
// assert s.getKind() == Shadow.Initialization
r.associateWithTargets(
Range.genStart(body, call.getNext()),
Range.genEnd(body));
}
}
private boolean isThisCall(InstructionHandle ih) {
INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction();
return inst.getClassName(cpg).equals(clazz.getName());
}
/** inline a particular call in bytecode.
*
* @param donor the method we want to inline
* @param recipient the method containing the call we want to inline
* @param call the instructionHandle in recipient's body holding the call we want to
* inline.
*/
public static void inlineMethod(
LazyMethodGen donor,
LazyMethodGen recipient,
InstructionHandle call)
{
// assert recipient.contains(call)
/* Implementation notes:
*
* We allocate two slots for every tempvar so we don't screw up
* longs and doubles which may share space. This could be conservatively avoided
* (no reference to a long/double instruction, don't do it) or packed later.
* Right now we don't bother to pack.
*
* Allocate a new var for each formal param of the inlined. Fill with stack
* contents. Then copy the inlined instructions in with the appropriate remap
* table. Any framelocs used by locals in inlined are reallocated to top of
* frame,
*/
final InstructionFactory fact = recipient.getEnclosingClass().getFactory();
IntMap frameEnv = new IntMap();
// this also sets up the initial environment
InstructionList argumentStores =
genArgumentStores(donor, recipient, frameEnv, fact);
InstructionList inlineInstructions =
genInlineInstructions(donor, recipient, frameEnv, fact, false);
inlineInstructions.insert(argumentStores);
recipient.getBody().append(call, inlineInstructions);
Utility.deleteInstruction(call, recipient);
}
/** generate the instructions to be inlined.
*
* @param donor the method from which we will copy (and adjust frame and jumps)
* instructions.
* @param recipient the method the instructions will go into. Used to get the frame
* size so we can allocate new frame locations for locals in donor.
* @param frameEnv an environment to map from donor frame to recipient frame,
* initially populated with argument locations.
* @param fact an instruction factory for recipient
*/
static InstructionList genInlineInstructions(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact,
boolean keepReturns)
{
InstructionList footer = new InstructionList();
InstructionHandle end = footer.append(InstructionConstants.NOP);
InstructionList ret = new InstructionList();
InstructionList sourceList = donor.getBody();
Map srcToDest = new HashMap();
ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen();
ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen();
boolean isAcrossClass = donorCpg != recipientCpg;
// first pass: copy the instructions directly, populate the srcToDest map,
// fix frame instructions
for (InstructionHandle src = sourceList.getStart();
src != null;
src = src.getNext())
{
Instruction fresh = Utility.copyInstruction(src.getInstruction());
InstructionHandle dest;
if (fresh instanceof CPInstruction) {
// need to reset index to go to new constant pool. This is totally
// a computation leak... we're testing this LOTS of times. Sigh.
if (isAcrossClass) {
CPInstruction cpi = (CPInstruction) fresh;
cpi.setIndex(
recipientCpg.addConstant(
donorCpg.getConstant(cpi.getIndex()),
donorCpg));
}
}
if (src.getInstruction() == Range.RANGEINSTRUCTION) {
dest = ret.append(Range.RANGEINSTRUCTION);
} else if (fresh instanceof ReturnInstruction) {
if (keepReturns) {
dest = ret.append(fresh);
} else {
dest =
ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end));
}
} else if (fresh instanceof BranchInstruction) {
dest = ret.append((BranchInstruction) fresh);
} else if (
fresh instanceof LocalVariableInstruction || fresh instanceof RET) {
IndexedInstruction indexed = (IndexedInstruction) fresh;
int oldIndex = indexed.getIndex();
int freshIndex;
if (!frameEnv.hasKey(oldIndex)) {
freshIndex = recipient.allocateLocal(2);
frameEnv.put(oldIndex, freshIndex);
} else {
freshIndex = frameEnv.get(oldIndex);
}
indexed.setIndex(freshIndex);
dest = ret.append(fresh);
} else {
dest = ret.append(fresh);
}
srcToDest.put(src, dest);
}
// second pass: retarget branch instructions, copy ranges and tags
Map tagMap = new HashMap();
Map shadowMap = new HashMap();
for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart();
dest != null;
dest = dest.getNext(), src = src.getNext()) {
Instruction inst = dest.getInstruction();
// retarget branches
if (inst instanceof BranchInstruction) {
BranchInstruction branch = (BranchInstruction) inst;
InstructionHandle oldTarget = branch.getTarget();
InstructionHandle newTarget =
(InstructionHandle) srcToDest.get(oldTarget);
if (newTarget == null) {
// assert this is a GOTO
// this was a return instruction we previously replaced
} else {
branch.setTarget(newTarget);
if (branch instanceof Select) {
Select select = (Select) branch;
InstructionHandle[] oldTargets = select.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
select.setTarget(
k,
(InstructionHandle) srcToDest.get(oldTargets[k]));
}
}
}
}
//copy over tags and range attributes
InstructionTargeter[] srcTargeters = src.getTargeters();
if (srcTargeters != null) {
for (int j = srcTargeters.length - 1; j >= 0; j--) {
InstructionTargeter old = srcTargeters[j];
if (old instanceof Tag) {
Tag oldTag = (Tag) old;
Tag fresh = (Tag) tagMap.get(oldTag);
if (fresh == null) {
fresh = oldTag.copy();
tagMap.put(oldTag, fresh);
}
dest.addTargeter(fresh);
} else if (old instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) old;
if (er.getStart() == src) {
ExceptionRange freshEr =
new ExceptionRange(
recipient.getBody(),
er.getCatchType(),
er.getPriority());
freshEr.associateWithTargets(
dest,
(InstructionHandle)srcToDest.get(er.getEnd()),
(InstructionHandle)srcToDest.get(er.getHandler()));
}
} else if (old instanceof ShadowRange) {
ShadowRange oldRange = (ShadowRange) old;
if (oldRange.getStart() == src) {
BcelShadow oldShadow = oldRange.getShadow();
BcelShadow freshEnclosing =
oldShadow.getEnclosingShadow() == null
? null
: (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow());
BcelShadow freshShadow =
oldShadow.copyInto(recipient, freshEnclosing);
ShadowRange freshRange = new ShadowRange(recipient.getBody());
freshRange.associateWithShadow(freshShadow);
freshRange.associateWithTargets(
dest,
(InstructionHandle) srcToDest.get(oldRange.getEnd()));
shadowMap.put(oldRange, freshRange);
//recipient.matchedShadows.add(freshShadow);
// XXX should go through the NEW copied shadow and update
// the thisVar, targetVar, and argsVar
// ??? Might want to also go through at this time and add
// "extra" vars to the shadow.
}
}
}
}
}
if (!keepReturns) ret.append(footer);
return ret;
}
/** generate the argument stores in preparation for inlining.
*
* @param donor the method we will inline from. Used to get the signature.
* @param recipient the method we will inline into. Used to get the frame size
* so we can allocate fresh locations.
* @param frameEnv an empty environment we populate with a map from donor frame to
* recipient frame.
* @param fact an instruction factory for recipient
*/
private static InstructionList genArgumentStores(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact)
{
InstructionList ret = new InstructionList();
int donorFramePos = 0;
// writing ret back to front because we're popping.
if (! donor.isStatic()) {
int targetSlot = recipient.allocateLocal(Type.OBJECT);
ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot));
frameEnv.put(donorFramePos, targetSlot);
donorFramePos += 1;
}
Type[] argTypes = donor.getArgumentTypes();
for (int i = 0, len = argTypes.length; i < len; i++) {
Type argType = argTypes[i];
int argSlot = recipient.allocateLocal(argType);
ret.insert(InstructionFactory.createStore(argType, argSlot));
frameEnv.put(donorFramePos, argSlot);
donorFramePos += argType.getSize();
}
return ret;
}
/** get a called method: Assumes the called method is in this class,
* and the reference to it is exact (a la INVOKESPECIAL).
*
* @param ih The InvokeInstruction instructionHandle pointing to the called method.
*/
private LazyMethodGen getCalledMethod(
InstructionHandle ih)
{
InvokeInstruction inst = (InvokeInstruction) ih.getInstruction();
String methodName = inst.getName(cpg);
String signature = inst.getSignature(cpg);
return clazz.getLazyMethodGen(methodName, signature);
}
private void weaveInAddedMethods() {
Collections.sort(addedLazyMethodGens,
new Comparator() {
public int compare(Object a, Object b) {
LazyMethodGen aa = (LazyMethodGen) a;
LazyMethodGen bb = (LazyMethodGen) b;
int i = aa.getName().compareTo(bb.getName());
if (i != 0) return i;
return aa.getSignature().compareTo(bb.getSignature());
}
}
);
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
clazz.addMethodGen((LazyMethodGen)i.next());
}
}
void addPerSingletonField(Member field) {
ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType());
String aspectName = field.getReturnType().getName();
LazyMethodGen clinit = clazz.getStaticInitializer();
InstructionList setup = new InstructionList();
InstructionFactory fact = clazz.getFactory();
setup.append(fact.createNew(aspectType));
setup.append(InstructionFactory.createDup(1));
setup.append(fact.createInvoke(
aspectName,
"<init>",
Type.VOID,
new Type[0],
Constants.INVOKESPECIAL));
setup.append(
fact.createFieldAccess(
aspectName,
field.getName(),
aspectType,
Constants.PUTSTATIC));
clinit.getBody().insert(setup);
}
/**
* Returns null if this is not a Java constructor, and then we won't
* weave into it at all
*/
private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) {
int depth = 1;
InstructionHandle start = mg.getBody().getStart();
while (true) {
if (start == null) return null;
Instruction inst = start.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth--;
if (depth == 0) return start;
} else if (inst instanceof NEW) {
depth++;
}
start = start.getNext();
}
}
// ----
private boolean match(LazyMethodGen mg) {
BcelShadow enclosingShadow;
List shadowAccumulator = new ArrayList();
// we want to match ajsynthetic constructors...
if (mg.getName().equals("<init>")) {
return matchInit(mg, shadowAccumulator);
} else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) {
return false;
} else {
if (mg.getName().equals("<clinit>")) {
clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg);
//System.err.println(enclosingShadow);
} else if (mg.isAdviceMethod()) {
enclosingShadow = BcelShadow.makeAdviceExecution(world, mg);
} else {
AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature();
if (effective == null) {
enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows);
} else if (effective.isWeaveBody()) {
ResolvedMember rm = effective.getEffectiveSignature();
// Annotations for things with effective signatures are never stored in the effective
// signature itself - we have to hunt for them. Storing them in the effective signature
// would mean keeping two sets up to date (no way!!)
fixAnnotationsForResolvedMember(rm,mg.getMemberView());
enclosingShadow =
BcelShadow.makeShadowForMethod(world,mg,effective.getShadowKind(),rm);
} else {
return false;
}
}
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
match(mg, h, enclosingShadow, shadowAccumulator);
}
}
// FIXME asc change from string match if we can, rather brittle. this check actually prevents field-exec jps
if (canMatch(enclosingShadow.getKind()) && !mg.getName().startsWith("ajc$interFieldInit")) {
if (match(enclosingShadow, shadowAccumulator)) {
enclosingShadow.init();
}
}
mg.matchedShadows = shadowAccumulator;
return !shadowAccumulator.isEmpty();
}
}
private boolean matchInit(LazyMethodGen mg, List shadowAccumulator) {
BcelShadow enclosingShadow;
// XXX the enclosing join point is wrong for things before ignoreMe.
InstructionHandle superOrThisCall = findSuperOrThisCall(mg);
// we don't walk bodies of things where it's a wrong constructor thingie
if (superOrThisCall == null) return false;
enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall);
// walk the body
boolean beforeSuperOrThisCall = true;
if (shouldWeaveBody(mg)) {
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
if (h == superOrThisCall) {
beforeSuperOrThisCall = false;
continue;
}
match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator);
}
}
if (canMatch(Shadow.ConstructorExecution))
match(enclosingShadow, shadowAccumulator);
}
// XXX we don't do pre-inits of interfaces
// now add interface inits
if (superOrThisCall != null && ! isThisCall(superOrThisCall)) {
InstructionHandle curr = enclosingShadow.getRange().getStart();
for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) {
IfaceInitList l = (IfaceInitList) i.next();
Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType);
BcelShadow initShadow =
BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig);
// insert code in place
InstructionList inits = genInitInstructions(l.list, false);
if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) {
initShadow.initIfaceInitializer(curr);
initShadow.getRange().insert(inits, Range.OutsideBefore);
}
}
// now we add our initialization code
InstructionList inits = genInitInstructions(addedThisInitializers, false);
enclosingShadow.getRange().insert(inits, Range.OutsideBefore);
}
// actually, you only need to inline the self constructors that are
// in a particular group (partition the constructors into groups where members
// call or are called only by those in the group). Then only inline
// constructors
// in groups where at least one initialization jp matched. Future work.
boolean addedInitialization =
match(
BcelShadow.makeUnfinishedInitialization(world, mg),
initializationShadows);
addedInitialization |=
match(
BcelShadow.makeUnfinishedPreinitialization(world, mg),
initializationShadows);
mg.matchedShadows = shadowAccumulator;
return addedInitialization || !shadowAccumulator.isEmpty();
}
private boolean shouldWeaveBody(LazyMethodGen mg) {
if (mg.isBridgeMethod()) return false;
if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>");
AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature();
if (a != null) return a.isWeaveBody();
return true;
}
/**
* first sorts the mungers, then gens the initializers in the right order
*/
private InstructionList genInitInstructions(List list, boolean isStatic) {
list = PartialOrder.sort(list);
if (list == null) {
throw new BCException("circularity in inter-types");
}
InstructionList ret = new InstructionList();
for (Iterator i = list.iterator(); i.hasNext();) {
ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next();
NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger();
ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType());
if (!isStatic) ret.append(InstructionConstants.ALOAD_0);
ret.append(Utility.createInvoke(fact, world, initMethod));
}
return ret;
}
private void match(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
Instruction i = ih.getInstruction();
if ((i instanceof FieldInstruction) &&
(canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet))
) {
FieldInstruction fi = (FieldInstruction) i;
if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) {
// check for sets of constant fields. We first check the previous
// instruction. If the previous instruction is a LD_WHATEVER (push
// constant on the stack) then we must resolve the field to determine
// if it's final. If it is final, then we don't generate a shadow.
InstructionHandle prevHandle = ih.getPrev();
Instruction prevI = prevHandle.getInstruction();
if (Utility.isConstantPushInstruction(prevI)) {
Member field = BcelWorld.makeFieldSignature(clazz, (FieldInstruction) i);
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
} else if (Modifier.isFinal(resolvedField.getModifiers())) {
// it's final, so it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
} else {
if (canMatch(Shadow.FieldSet))
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
if (canMatch(Shadow.FieldSet))
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
if (canMatch(Shadow.FieldGet))
matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else if (i instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction) i;
if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) {
if (canMatch(Shadow.ConstructorCall))
match(
BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
} else if (ii instanceof INVOKESPECIAL) {
String onTypeName = ii.getClassName(cpg);
if (onTypeName.equals(mg.getEnclosingClass().getName())) {
// we are private
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
} else {
// we are a super call, and this is not a join point in AspectJ-1.{0,1}
}
} else {
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
}
}
// performance optimization... we only actually care about ASTORE instructions,
// since that's what every javac type thing ever uses to start a handler, but for
// now we'll do this for everybody.
if (!canMatch(Shadow.ExceptionHandler)) return;
if (Range.isRangeHandle(ih)) return;
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int j = 0; j < targeters.length; j++) {
InstructionTargeter t = targeters[j];
if (t instanceof ExceptionRange) {
// assert t.getHandler() == ih
ExceptionRange er = (ExceptionRange) t;
if (er.getCatchType() == null) continue;
if (isInitFailureHandler(ih)) return;
match(
BcelShadow.makeExceptionHandler(
world,
er,
mg, ih, enclosingShadow),
shadowAccumulator);
}
}
}
}
private boolean isInitFailureHandler(InstructionHandle ih) {
// Skip the astore_0 and aload_0 at the start of the handler and
// then check if the instruction following these is
// 'putstatic ajc$initFailureCause'. If it is then we are
// in the handler we created in AspectClinit.generatePostSyntheticCode()
InstructionHandle twoInstructionsAway = ih.getNext().getNext();
if (twoInstructionsAway.getInstruction() instanceof PUTSTATIC) {
String name = ((PUTSTATIC)twoInstructionsAway.getInstruction()).getFieldName(cpg);
if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true;
}
return false;
}
private void matchSetInstruction(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (
Modifier.isFinal(resolvedField.getModifiers())
&& Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) {
// it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(
BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(BcelShadow.makeFieldGet(world, mg, ih, enclosingShadow), shadowAccumulator);
}
}
/**
* 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.interMethodBody(rm,memberHostType);
ResolvedMember resolvedDooberry = world.resolve(realthing);
annotations = resolvedDooberry.getAnnotationTypes();
}
} else if (rm.getKind()==Member.CONSTRUCTOR) {
ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(),rm.getParameterTypes());
ResolvedMember resolvedDooberry = world.resolve(realThing);
annotations = resolvedDooberry.getAnnotationTypes();
}
if (annotations == null)
annotations = new ResolvedType[0];
mapToAnnotations.put(rm,annotations);
}
rm.setAnnotationTypes(annotations);
} catch (Throwable t) {
//FIXME asc remove this catch after more testing has confirmed the above stuff is OK
throw new BCException("Unexpectedly went bang when searching for annotations on "+rm,t);
}
}
private void matchInvokeInstruction(LazyMethodGen mg,
InstructionHandle ih,
InvokeInstruction invoke,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
String methodName = invoke.getName(cpg);
if (methodName.startsWith(NameMangler.PREFIX)) {
Member method =
BcelWorld.makeMethodSignature(clazz, invoke);
ResolvedMember declaredSig = method.resolve(world);
//System.err.println(method + ", declaredSig: " +declaredSig);
if (declaredSig == null) return;
if (declaredSig.getKind() == Member.FIELD) {
Shadow.Kind kind;
if (method.getReturnType().equals(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);
boolean isMatched = false;
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger munger = (ShadowMunger)i.next();
if (munger.match(shadow, world)) {
WeaverMetrics.recordMatchResult(true);// Could pass: munger
shadow.addMunger(munger);
isMatched = true;
if (shadow.getKind() == Shadow.StaticInitialization) {
clazz.warnOnAddedStaticInitializer(shadow,munger.getSourceLocation());
}
} else {
WeaverMetrics.recordMatchResult(false); // Could pass: munger
}
}
if (isMatched) shadowAccumulator.add(shadow);
return isMatched;
}
// ----
private void implement(LazyMethodGen mg) {
List shadows = mg.matchedShadows;
if (shadows == null) return;
// We depend on a partial order such that inner shadows are earlier on the list
// than outer shadows. That's fine. This order is preserved if:
// A preceeds B iff B.getStart() is LATER THAN A.getStart().
for (Iterator i = shadows.iterator(); i.hasNext(); ) {
BcelShadow shadow = (BcelShadow)i.next();
shadow.implement();
}
mg.matchedShadows = null;
}
// ----
public LazyClassGen getLazyClassGen() {
return clazz;
}
public List getShadowMungers() {
return shadowMungers;
}
public BcelWorld getWorld() {
return world;
}
// Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info
public static void setReweavableMode(boolean mode,boolean compress) {
inReweavableMode = mode;
compressReweavableAttributes = compress;
}
}
|
104,212 |
Bug 104212 static method call from subclass signature is wrong
|
a very bad bug... or ? in the snip below, getMethod() says null and the factory is actually thinking that test() is a static method of AspectJBugMain instead of Assert... wondering why we don't catch that in the test suite or what could happen recently around that. Or is it something I am confused about ? (i doubt a jp.getSignature().getMethod is supposed to return null in some cases though..) @Aspect public class Sam { @Pointcut("call(* *.*(..))") public void methodCalls() { } @Around("methodCalls() && !within(alex.sam.Sam) && within(alex..*)") public Object aroundMethodCalls(ProceedingJoinPoint jp) throws Throwable { String typeName = jp.getSignature().getDeclaringTypeName(); System.out.println("declType " + typeName); System.out.println("method " + ((MethodSignature)jp.getSignature()).getMethod()); return jp.proceed(); } } class Assert { public static void test() { System.out.println("RUN Assert.test"); } } class AspectJBugMain extends Assert { public static void main(String[] args) { test(); } // public static void test() { // System.out.println("RUN AspectJBugMain.test"); // } }
|
resolved fixed
|
619a6ad
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-22T14:57:40Z | 2005-07-18T12:33:20Z |
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ALOAD;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LoadInstruction;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.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
// ---- initialization
/**
* This generates an unassociated shadow, rooted in a particular method but not rooted
* to any particular point in the code. It should be given to a rooted ShadowRange
* in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
*/
public BcelShadow(
BcelWorld world,
Kind kind,
Member signature,
LazyMethodGen enclosingMethod,
BcelShadow enclosingShadow)
{
super(kind, signature, enclosingShadow);
this.world = world;
this.enclosingMethod = enclosingMethod;
fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
List src = mungers;
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruciton we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
sources[i].updateTarget(old, fresh);
}
}
}
protected void prepareForMungers() {
// if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
// and store all our
// arguments on the frame.
// ??? This is a bit of a hack (for the Java langauge). We do this because
// we sometime add code "outsideBefore" when dealing with weaving join points. We only
// do this for exposing state that is on the stack. It turns out to just work for
// everything except for constructor calls and exception handlers. If we were to clean
// this up, every ShadowRange would have three instructionHandle points, the start of
// the arg-setup code, the start of the running code, and the end of the running code.
if (getKind() == ConstructorCall) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == PreInitialization) { // pr74952
ShadowRange range = getRange();
range.insert(InstructionConstants.NOP,Range.InsideAfter);
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
// Create a store instruction to put the value from the top of the
// stack into a local variable slot. This is a trimmed version of
// what is in initializeArgVars() (since there is only one argument
// at a handler jp and only before advice is supported) (pr46298)
argVars = new BcelVar[1];
int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
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 = world.isXlazyTjp();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
// Special case first (pr46298). If we are an exception handler and the instruction
// just after the shadow is a POP then we should remove the pop. The code
// above which generated the store instruction has already cleared the stack.
// We also don't generate any code for the arguments in this case as it would be
// an incorrect aload.
if (getKind() == ExceptionHandler
&& range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
// easier than deleting it ...
range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
} else {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
// if the kind of join point for which we are a shadow represents
// a method or constructor execution, then the best source line is
// the one from the enclosingMethod declarationLineNumber if available.
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
return getEnclosingMethod().getDeclarationLineNumber();
}
}
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public 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.makeMethodSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, justBeforeStart.getNext()),
Range.genEnd(body));
return s;
}
public static BcelShadow makeStaticInitialization(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
InstructionList body = enclosingMethod.getBody();
// move the start past ajc$preClinit
InstructionHandle clinitStart = body.getStart();
if (clinitStart.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction();
if (ii
.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen())
.equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
clinitStart = clinitStart.getNext();
}
}
InstructionHandle clinitEnd = body.getEnd();
//XXX should move the end before the postClinit, but the return is then tricky...
// if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
// InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
// if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeMethodSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, clinitStart),
Range.genEnd(body, clinitEnd));
return s;
}
/** Make the shadow for an exception handler. Currently makes an empty shadow that
* only allows before advice to be woven into it.
*/
public static BcelShadow makeExceptionHandler(
BcelWorld world,
ExceptionRange exceptionRange,
LazyMethodGen enclosingMethod,
InstructionHandle startOfHandler,
BcelShadow enclosingShadow)
{
InstructionList body = enclosingMethod.getBody();
UnresolvedType catchType = exceptionRange.getCatchType();
UnresolvedType inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMember sig = Member.makeExceptionHandlerSignature(inType, catchType);
sig.parameterNames = new String[] {findHandlerParamName(startOfHandler)};
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
InstructionHandle start = Range.genStart(body, startOfHandler);
InstructionHandle end = Range.genEnd(body, start);
r.associateWithTargets(start, end);
exceptionRange.updateTarget(startOfHandler, start, body);
return s;
}
private static String findHandlerParamName(InstructionHandle startOfHandler) {
if (startOfHandler.getInstruction() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
return "<missing>";
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
InstructionList body = constructor.getBody();
// 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)
{
return new BcelShadow(
world,
Initialization,
world.makeMethodSignature(constructor),
constructor,
null);
}
public static BcelShadow makeUnfinishedPreinitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
PreInitialization,
world.makeMethodSignature(constructor),
constructor,
null);
ret.fallsThrough = true;
return ret;
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
boolean lazyInit)
{
if (!lazyInit) return makeMethodExecution(world, enclosingMethod);
BcelShadow s =
new BcelShadow(
world,
MethodExecution,
enclosingMethod.getMemberView(),
enclosingMethod,
null);
return s;
}
public void init() {
if (range != null) return;
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
return makeShadowForMethod(world, enclosingMethod, MethodExecution,
enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod));
}
public static BcelShadow makeShadowForMethod(BcelWorld world,
LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
return s;
}
public static BcelShadow makeAdviceExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
AdviceExecution,
world.makeMethodSignature(enclosingMethod, Member.ADVICE),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(Range.genStart(body), Range.genEnd(body));
return s;
}
// constructor call shadows are <em>initially</em> just around the
// call to the constructor. If ANY advice gets put on it, we move
// the NEW instruction inside the join point, which involves putting
// all the arguments in temps.
public static BcelShadow makeConstructorCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
Member sig = BcelWorld.makeMethodSignature(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction());
BcelShadow s =
new BcelShadow(
world,
ConstructorCall,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
BcelWorld.makeMethodSignature(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeShadowForMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow,
Kind kind,
ResolvedMember sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldGet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
BcelWorld.makeFieldSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) getHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, getHandle),
Range.genEnd(body, getHandle));
retargetAllBranches(getHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldSet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
private Map/*<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) {
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
il.append(InstructionConstants.ACONST_NULL);
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
} else {
InstructionFactory fact = getFactory();
InstructionList il = createThisJoinPoint();
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
}
}
private boolean checkLazyTjp() {
// check for around advice
for (Iterator i = mungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger instanceof Advice) {
if ( ((Advice)munger).getKind() == AdviceKind.Around) {
world.getLint().canNotImplementLazyTjp.signal(
new String[] {toString()},
getSourceLocation(),
new ISourceLocation[] { munger.getSourceLocation() }
);
return false;
}
}
}
return true;
}
InstructionList loadThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
if (isThisJoinPointLazy) {
il.append(createThisJoinPoint());
if (lazyTjpConsumers > 1) {
il.append(thisJoinPointVar.createStore(fact));
InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact));
il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end));
il.insert(thisJoinPointVar.createLoad(fact));
}
} else {
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(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...)
}
}
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;
ResolvedMember itdMember =null;
Member relevantMember = getSignature();
ResolvedType relevantType = relevantMember.getDeclaringType().resolve(world);
UnresolvedType aspect = null;
if (getKind() == Shadow.StaticInitialization) {
annotations = relevantType.resolve(world).getAnnotationTypes();
} else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) {
relevantMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(),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 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.interMethodBody(fakerm,typeMunger.getAspectType()));
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
relevantType = typeMunger.getAspectType();
relevantMember = rmm;
}
}
}
}
annotations = relevantMember.getAnnotationTypes();
} 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();
relevantMember = findMethod2(relevantType.getDeclaredMethods(),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 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.interMethodBody(fakerm,typeMunger.getAspectType()));
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
relevantType = typeMunger.getAspectType();
relevantMember = rmm;
}
}
}
}
annotations = relevantMember.getAnnotationTypes();
} 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();
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);
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,
adviceMethod.getReturnType(),
adviceMethodName,
parameterTypes,
new String[0],
getEnclosingClass());
String donorFileName = adviceMethod.getEnclosingClass().getInternalFileName();
String recipientFileName = getEnclosingClass().getInternalFileName();
// System.err.println("donor " + donorFileName);
// System.err.println("recip " + recipientFileName);
if (! donorFileName.equals(recipientFileName)) {
localAdviceMethod.fromFilename = donorFileName;
getEnclosingClass().addInlinedSourceFileInfo(
donorFileName,
adviceMethod.highestLineNumber);
}
getEnclosingClass().addMethodGen(localAdviceMethod);
// create a map that will move all slots in advice method forward by extraParamOffset
// in order to make room for the new proceed-required arguments that are added at
// the beginning of the parameter list
int nVars = adviceMethod.getMaxLocals() + extraParamOffset;
IntMap varMap = IntMap.idMap(nVars);
for (int i=extraParamOffset; i < nVars; i++) {
varMap.put(i-extraParamOffset, i);
}
localAdviceMethod.getBody().insert(
BcelClassWeaver.genInlineInstructions(adviceMethod,
localAdviceMethod, varMap, fact, true));
localAdviceMethod.setMaxLocals(nVars);
//System.err.println(localAdviceMethod);
// the shadow is now empty. First, create a correct call
// to the around advice. This includes both the call (which may involve
// value conversion of the advice arguments) and the return
// (which may involve value conversion of the return value). Right now
// we push a null for the unused closure. It's sad, but there it is.
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
for (Iterator i = argVarList.iterator(); i.hasNext(); ) {
BcelVar var = (BcelVar)i.next();
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
advice.append(
munger.getAdviceArgSetup(
this,
null,
(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(munger.getSignature().getReturnType()),
extractedMethod.getReturnType()));
if (! isFallsThrough()) {
advice.append(InstructionFactory.createReturn(extractedMethod.getReturnType()));
}
}
// now, situate the call inside the possible dynamic tests,
// and actually add the whole mess to the shadow
if (! hasDynamicTest) {
range.append(advice);
} else {
InstructionList afterThingie = new InstructionList(InstructionConstants.NOP);
InstructionList callback = makeCallToCallback(extractedMethod);
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(extractedMethod.getReturnType()));
} else {
//InstructionHandle endNop = range.insert(fact.NOP, Range.InsideAfter);
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
afterThingie.getStart()));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(afterThingie);
}
// now search through the advice, looking for a call to PROCEED.
// Then we replace the call to proceed with some argument setup, and a
// call to the extracted method.
// 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 Member(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 Member(
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[] {});
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();
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);
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
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, 0);
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
}
|
104,212 |
Bug 104212 static method call from subclass signature is wrong
|
a very bad bug... or ? in the snip below, getMethod() says null and the factory is actually thinking that test() is a static method of AspectJBugMain instead of Assert... wondering why we don't catch that in the test suite or what could happen recently around that. Or is it something I am confused about ? (i doubt a jp.getSignature().getMethod is supposed to return null in some cases though..) @Aspect public class Sam { @Pointcut("call(* *.*(..))") public void methodCalls() { } @Around("methodCalls() && !within(alex.sam.Sam) && within(alex..*)") public Object aroundMethodCalls(ProceedingJoinPoint jp) throws Throwable { String typeName = jp.getSignature().getDeclaringTypeName(); System.out.println("declType " + typeName); System.out.println("method " + ((MethodSignature)jp.getSignature()).getMethod()); return jp.proceed(); } } class Assert { public static void test() { System.out.println("RUN Assert.test"); } } class AspectJBugMain extends Assert { public static void main(String[] args) { test(); } // public static void test() { // System.out.println("RUN AspectJBugMain.test"); // } }
|
resolved fixed
|
619a6ad
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-07-22T14:57:40Z | 2005-07-18T12:33: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.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.GETSTATIC;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.PUTSTATIC;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.Repository;
import org.aspectj.apache.bcel.util.ClassLoaderRepository;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.SimpleScope;
import org.aspectj.weaver.patterns.PerClause;
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);
setXRefHandler(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);
setXRefHandler(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);
setXRefHandler(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 = Member.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.getSignature());
}
static Type[] makeBcelTypes(UnresolvedType[] types) {
Type[] ret = new Type[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = makeBcelType(types[i]);
}
return ret;
}
public static UnresolvedType fromBcel(Type t) {
return UnresolvedType.forSignature(t.getSignature());
}
static UnresolvedType[] fromBcel(Type[] ts) {
UnresolvedType[] ret = new UnresolvedType[ts.length];
for (int i = 0, len = ts.length; i < len; i++) {
ret[i] = fromBcel(ts[i]);
}
return ret;
}
public ResolvedType resolve(Type t) {
return resolve(fromBcel(t));
}
protected ReferenceTypeDelegate resolveObjectType(ReferenceType ty) {
String name = ty.getName();
JavaClass jc = null;
//UnwovenClassFile classFile = (UnwovenClassFile)sourceJavaClasses.get(name);
//if (classFile != null) jc = classFile.getJavaClass();
// if (jc == null) {
// jc = lookupJavaClass(aspectPath, name);
// }
if (jc == null) {
jc = lookupJavaClass(classPath, name);
}
if (jc == null) {
return null;
} else {
return makeBcelObjectType(ty, jc, false);
}
}
protected BcelObjectType makeBcelObjectType(ReferenceType resolvedTypeX, JavaClass jc, boolean exposedToWeaver) {
BcelObjectType ret = new BcelObjectType(resolvedTypeX, jc, exposedToWeaver);
return ret;
}
private JavaClass lookupJavaClass(ClassPathManager classPath, String name) {
if (classPath == null) {
try {
return delegate.loadClass(name);
} catch (ClassNotFoundException e) {
return null;
}
}
try {
ClassPathManager.ClassFile file = classPath.find(UnresolvedType.forName(name));
if (file == null) return null;
ClassParser parser = new ClassParser(file.getInputStream(), file.getPath());
JavaClass jc = parser.parse();
file.close();
return jc;
} catch (IOException ioe) {
return null;
}
}
public BcelObjectType addSourceObjectType(JavaClass jc) {
BcelObjectType ret = null;
String signature = UnresolvedType.forName(jc.getClassName()).getSignature();
ReferenceType nameTypeX = (ReferenceType)typeMap.get(signature);
if (nameTypeX == null) {
if (jc.isGeneric()) {
nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(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 makeFieldSignature(LazyClassGen cg, FieldInstruction fi) {
ConstantPoolGen cpg = cg.getConstantPoolGen();
return
Member.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
Member.field(
fi.getClassName(cpg),
(fi instanceof GETSTATIC || fi instanceof PUTSTATIC)
? Modifier.STATIC
: 0,
fi.getName(cpg),
"(" + fi.getSignature(cpg) + ")" +fi.getSignature(cpg));
}
public Member makeMethodSignature(LazyMethodGen mg) {
return makeMethodSignature(mg, null);
}
public Member makeMethodSignature(LazyMethodGen mg, Member.Kind kind) {
ResolvedMember 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 ResolvedMember(kind,
UnresolvedType.forName(mg.getClassName()),
mods,
fromBcel(mg.getReturnType()),
mg.getName(),
fromBcel(mg.getArgumentTypes())
);
} else {
return ret;
}
}
public static Member makeMethodSignature(LazyClassGen cg, InvokeInstruction ii) {
ConstantPoolGen cpg = cg.getConstantPoolGen();
String declaring = ii.getClassName(cpg);
String name = ii.getName(cpg);
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;
return Member.method(UnresolvedType.forName(declaring), 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 Member.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 concreteAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature)
{
//System.err.println("concrete advice: " + signature + " context " + sourceContext);
return new BcelAdvice(attribute, pointcut, signature, null);
}
public ConcreteTypeMunger concreteTypeMunger(
ResolvedTypeMunger munger, ResolvedType aspectType)
{
return new BcelTypeMunger(munger, aspectType);
}
public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) {
return new BcelCflowStackFieldAdder(cflowField);
}
public ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField) {
return new BcelCflowCounterFieldAdder(cflowField);
}
/**
* Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed
*
* @param aspect
* @param kind
* @return
*/
public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind) {
return new BcelPerClauseAspectAdder(aspect, kind);
}
public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) {
//XXX need error checking
return (BcelObjectType) ((ReferenceType)concreteAspect).getDelegate();
}
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");
}
}
|
106,461 |
Bug 106461 org.aspectj.weaver.patterns.WildTypePattern.maybeGetCleanName(WildTypePattern.java:500)
| null |
resolved fixed
|
5735e96
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-10T11:49:34Z | 2005-08-09T12: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 junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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");}
// 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);
}
}
|
106,461 |
Bug 106461 org.aspectj.weaver.patterns.WildTypePattern.maybeGetCleanName(WildTypePattern.java:500)
| null |
resolved fixed
|
5735e96
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-10T11:49:34Z | 2005-08-09T12:20:00Z |
weaver/src/org/aspectj/weaver/patterns/PatternParser.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* 2005 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Adrian Colyer many updates since....
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.UnresolvedType;
//XXX doesn't handle errors for extra tokens very well (sometimes ignores)
public class PatternParser {
private ITokenSource tokenSource;
private ISourceContext sourceContext;
/**
* Constructor for PatternParser.
*/
public PatternParser(ITokenSource tokenSource) {
super();
this.tokenSource = tokenSource;
this.sourceContext = tokenSource.getSourceContext();
}
public PerClause maybeParsePerClause() {
IToken tok = tokenSource.peek();
if (tok == IToken.EOF) return null;
if (tok.isIdentifier()) {
String name = tok.getString();
if (name.equals("issingleton")) {
return parsePerSingleton();
} else if (name.equals("perthis")) {
return parsePerObject(true);
} else if (name.equals("pertarget")) {
return parsePerObject(false);
} else if (name.equals("percflow")) {
return parsePerCflow(false);
} else if (name.equals("percflowbelow")) {
return parsePerCflow(true);
} else if (name.equals("pertypewithin")) { // PTWIMPL Parse the pertypewithin clause
return parsePerTypeWithin();
} else {
return null;
}
}
return null;
}
private PerClause parsePerCflow(boolean isBelow) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new PerCflow(entry, isBelow);
}
private PerClause parsePerObject(boolean isThis) {
parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new PerObject(entry, isThis);
}
private PerClause parsePerTypeWithin() {
parseIdentifier();
eat("(");
TypePattern withinTypePattern = parseTypePattern();
eat(")");
return new PerTypeWithin(withinTypePattern);
}
private PerClause parsePerSingleton() {
parseIdentifier();
eat("(");
eat(")");
return new PerSingleton();
}
public Declare parseDeclare() {
int startPos = tokenSource.peek().getStart();
eatIdentifier("declare");
String kind = parseIdentifier();
Declare ret;
if (kind.equals("error")) {
eat(":");
ret = parseErrorOrWarning(true);
} else if (kind.equals("warning")) {
eat(":");
ret = parseErrorOrWarning(false);
} else if (kind.equals("precedence")) {
eat(":");
ret = parseDominates();
} else if (kind.equals("dominates")) {
throw new ParserException("name changed to declare precedence", tokenSource.peek(-2));
} else if (kind.equals("parents")) {
ret = parseParents();
} else if (kind.equals("soft")) {
eat(":");
ret = parseSoft();
} else {
throw new ParserException("expected one of error, warning, parents, soft, dominates",
tokenSource.peek(-1));
}
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
public Declare parseDeclareAnnotation() {
int startPos = tokenSource.peek().getStart();
eatIdentifier("declare");
eat("@");
String kind = parseIdentifier();
eat(":");
Declare ret;
if (kind.equals("type")) {
ret = parseDeclareAtType();
} else if (kind.equals("method")) {
ret = parseDeclareAtMethod(true);
} else if (kind.equals("field")) {
ret = parseDeclareAtField();
} else if (kind.equals("constructor")) {
ret = parseDeclareAtMethod(false);
} else {
throw new ParserException("one of type, method, field, constructor",tokenSource.peek(-1));
}
eat(";");
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
public DeclareAnnotation parseDeclareAtType() {
return new DeclareAnnotation(DeclareAnnotation.AT_TYPE,parseTypePattern());
}
public DeclareAnnotation parseDeclareAtMethod(boolean isMethod) {
SignaturePattern sp = parseMethodOrConstructorSignaturePattern();
boolean isConstructorPattern = (sp.getKind() == Member.CONSTRUCTOR);
if (isMethod && isConstructorPattern) {
throw new ParserException("method signature pattern",tokenSource.peek(-1));
}
if (!isMethod && !isConstructorPattern) {
throw new ParserException("constructor signature pattern",tokenSource.peek(-1));
}
if (isConstructorPattern) return new DeclareAnnotation(DeclareAnnotation.AT_CONSTRUCTOR,sp);
else return new DeclareAnnotation(DeclareAnnotation.AT_METHOD,sp);
}
public DeclareAnnotation parseDeclareAtField() {
return new DeclareAnnotation(DeclareAnnotation.AT_FIELD,parseFieldSignaturePattern());
}
public DeclarePrecedence parseDominates() {
List l = new ArrayList();
do {
l.add(parseTypePattern());
} while (maybeEat(","));
return new DeclarePrecedence(l);
}
private Declare parseParents() {
/*
* simplified design requires use of raw types for declare parents, no generic spec. allowed
* String[] typeParameters = maybeParseSimpleTypeVariableList();
*/
eat(":");
TypePattern p = parseTypePattern(false);
IToken t = tokenSource.next();
if (!(t.getString().equals("extends") || t.getString().equals("implements"))) {
throw new ParserException("extends or implements", t);
}
List l = new ArrayList();
do {
l.add(parseTypePattern());
} while (maybeEat(","));
//XXX somewhere in the chain we need to enforce that we have only ExactTypePatterns
DeclareParents decp = new DeclareParents(p, l);
return decp;
}
private Declare parseSoft() {
TypePattern p = parseTypePattern();
eat(":");
Pointcut pointcut = parsePointcut();
return new DeclareSoft(p, pointcut);
}
private Declare parseErrorOrWarning(boolean isError) {
Pointcut pointcut = parsePointcut();
eat(":");
String message = parsePossibleStringSequence(true);
return new DeclareErrorOrWarning(isError, pointcut, message);
}
public Pointcut parsePointcut() {
Pointcut p = parseAtomicPointcut();
if (maybeEat("&&")) {
p = new AndPointcut(p, parseNotOrPointcut());
}
if (maybeEat("||")) {
p = new OrPointcut(p, parsePointcut());
}
return p;
}
private Pointcut parseNotOrPointcut() {
Pointcut p = parseAtomicPointcut();
if (maybeEat("&&")) {
p = new AndPointcut(p, parsePointcut());
}
return p;
}
private Pointcut parseAtomicPointcut() {
if (maybeEat("!")) {
int startPos = tokenSource.peek(-1).getStart();
Pointcut p = new NotPointcut(parseAtomicPointcut(), startPos);
return p;
}
if (maybeEat("(")) {
Pointcut p = parsePointcut();
eat(")");
return p;
}
if (maybeEat("@")) {
int startPos = tokenSource.peek().getStart();
Pointcut p = parseAnnotationPointcut();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext, startPos, endPos);
return p;
}
int startPos = tokenSource.peek().getStart();
Pointcut p = parseSinglePointcut();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext, startPos, endPos);
return p;
}
public Pointcut parseSinglePointcut() {
int start = tokenSource.getIndex();
IToken t = tokenSource.peek();
Pointcut p = t.maybeGetParsedPointcut();
if (p != null) {
tokenSource.next();
return p;
}
String kind = parseIdentifier();
// IToken possibleTypeVariableToken = tokenSource.peek();
// String[] typeVariables = maybeParseSimpleTypeVariableList();
if (kind.equals("execution") || kind.equals("call") ||
kind.equals("get") || kind.equals("set")) {
p = parseKindedPointcut(kind);
} else if (kind.equals("args")) {
p = parseArgsPointcut();
} else if (kind.equals("this")) {
p = parseThisOrTargetPointcut(kind);
} else if (kind.equals("target")) {
p = parseThisOrTargetPointcut(kind);
} else if (kind.equals("within")) {
p = parseWithinPointcut();
} else if (kind.equals("withincode")) {
p = parseWithinCodePointcut();
} else if (kind.equals("cflow")) {
p = parseCflowPointcut(false);
} else if (kind.equals("cflowbelow")) {
p = parseCflowPointcut(true);
} else if (kind.equals("adviceexecution")) {
eat("(");
eat(")");
p = new KindedPointcut(Shadow.AdviceExecution,
new SignaturePattern(Member.ADVICE, ModifiersPattern.ANY,
TypePattern.ANY, TypePattern.ANY, NamePattern.ANY,
TypePatternList.ANY,
ThrowsPattern.ANY,
AnnotationTypePattern.ANY));
} else if (kind.equals("handler")) {
eat("(");
TypePattern typePat = parseTypePattern(false);
eat(")");
p = new HandlerPointcut(typePat);
} else if (kind.equals("initialization")) {
eat("(");
SignaturePattern sig = parseConstructorSignaturePattern();
eat(")");
p = new KindedPointcut(Shadow.Initialization, sig);
} else if (kind.equals("staticinitialization")) {
eat("(");
TypePattern typePat = parseTypePattern(false);
eat(")");
p = new KindedPointcut(Shadow.StaticInitialization,
new SignaturePattern(Member.STATIC_INITIALIZATION, ModifiersPattern.ANY,
TypePattern.ANY, typePat, NamePattern.ANY, TypePatternList.EMPTY,
ThrowsPattern.ANY,AnnotationTypePattern.ANY));
} else if (kind.equals("preinitialization")) {
eat("(");
SignaturePattern sig = parseConstructorSignaturePattern();
eat(")");
p = new KindedPointcut(Shadow.PreInitialization, sig);
} else if (kind.equals("if")) {
// @style support allows if(), if(true), if(false)
eat("(");
if (maybeEatIdentifier("true")) {
eat(")");
p = new IfPointcut.IfTruePointcut();
} else if (maybeEatIdentifier("false")) {
eat(")");
p = new IfPointcut.IfFalsePointcut();
} else {
eat(")");
// TODO - Alex has some token stuff going on here to get a readable name in place of ""...
p = new IfPointcut("");
}
}
else {
tokenSource.setIndex(start);
p = parseReferencePointcut();
}
return p;
}
private void assertNoTypeVariables(String[] tvs, String errorMessage,IToken token) {
if ( tvs != null ) throw new ParserException(errorMessage,token);
}
public Pointcut parseAnnotationPointcut() {
int start = tokenSource.getIndex();
IToken t = tokenSource.peek();
String kind = parseIdentifier();
IToken possibleTypeVariableToken = tokenSource.peek();
String[] typeVariables = maybeParseSimpleTypeVariableList();
if (typeVariables != null) {
String message = "(";
assertNoTypeVariables(typeVariables, message, possibleTypeVariableToken);
}
tokenSource.setIndex(start);
if (kind.equals("annotation")) {
return parseAtAnnotationPointcut();
} else if (kind.equals("args")) {
return parseArgsAnnotationPointcut();
} else if (kind.equals("this") || kind.equals("target")) {
return parseThisOrTargetAnnotationPointcut();
} else if (kind.equals("within")) {
return parseWithinAnnotationPointcut();
} else if (kind.equals("withincode")) {
return parseWithinCodeAnnotationPointcut();
} throw new ParserException("pointcut name", t);
}
private Pointcut parseAtAnnotationPointcut() {
parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("@AnnotationName or parameter", tokenSource.peek());
}
ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new AnnotationPointcut(type);
}
private SignaturePattern parseConstructorSignaturePattern() {
SignaturePattern ret = parseMethodOrConstructorSignaturePattern();
if (ret.getKind() == Member.CONSTRUCTOR) return ret;
throw new ParserException("constructor pattern required, found method pattern",
ret);
}
private Pointcut parseWithinCodePointcut() {
//parseIdentifier();
eat("(");
SignaturePattern sig = parseMethodOrConstructorSignaturePattern();
eat(")");
return new WithincodePointcut(sig);
}
private Pointcut parseCflowPointcut(boolean isBelow) {
//parseIdentifier();
eat("(");
Pointcut entry = parsePointcut();
eat(")");
return new CflowPointcut(entry, isBelow, null);
}
/**
* Method parseWithinPointcut.
* @return Pointcut
*/
private Pointcut parseWithinPointcut() {
//parseIdentifier();
eat("(");
TypePattern type = parseTypePattern();
eat(")");
return new WithinPointcut(type);
}
/**
* Method parseThisOrTargetPointcut.
* @return Pointcut
*/
private Pointcut parseThisOrTargetPointcut(String kind) {
eat("(");
TypePattern type = parseTypePattern();
eat(")");
return new ThisOrTargetPointcut(kind.equals("this"), type);
}
private Pointcut parseThisOrTargetAnnotationPointcut() {
String kind = parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek());
}
ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new ThisOrTargetAnnotationPointcut(kind.equals("this"),type);
}
private Pointcut parseWithinAnnotationPointcut() {
String kind = parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek());
}
AnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new WithinAnnotationPointcut(type);
}
private Pointcut parseWithinCodeAnnotationPointcut() {
String kind = parseIdentifier();
eat("(");
if (maybeEat(")")) {
throw new ParserException("expecting @AnnotationName or parameter, but found ')'", tokenSource.peek());
}
ExactAnnotationTypePattern type = parseAnnotationNameOrVarTypePattern();
eat(")");
return new WithinCodeAnnotationPointcut(type);
}
/**
* Method parseArgsPointcut.
* @return Pointcut
*/
private Pointcut parseArgsPointcut() {
//parseIdentifier();
TypePatternList arguments = parseArgumentsPattern();
return new ArgsPointcut(arguments);
}
private Pointcut parseArgsAnnotationPointcut() {
parseIdentifier();
AnnotationPatternList arguments = parseArgumentsAnnotationPattern();
return new ArgsAnnotationPointcut(arguments);
}
private Pointcut parseReferencePointcut() {
TypePattern onType = parseTypePattern();
NamePattern name = tryToExtractName(onType);
if (name == null) {
throw new ParserException("name pattern", tokenSource.peek());
}
if (onType.toString().equals("")) {
onType = null;
}
TypePatternList arguments = parseArgumentsPattern();
return new ReferencePointcut(onType, name.maybeGetSimpleName(), arguments);
}
public List parseDottedIdentifier() {
List ret = new ArrayList();
ret.add(parseIdentifier());
while (maybeEat(".")) {
ret.add(parseIdentifier());
}
return ret;
}
private KindedPointcut parseKindedPointcut(String kind) {
eat("(");
SignaturePattern sig;
Shadow.Kind shadowKind = null;
if (kind.equals("execution")) {
sig = parseMethodOrConstructorSignaturePattern();
if (sig.getKind() == Member.METHOD) {
shadowKind = Shadow.MethodExecution;
} else if (sig.getKind() == Member.CONSTRUCTOR) {
shadowKind = Shadow.ConstructorExecution;
}
} else if (kind.equals("call")) {
sig = parseMethodOrConstructorSignaturePattern();
if (sig.getKind() == Member.METHOD) {
shadowKind = Shadow.MethodCall;
} else if (sig.getKind() == Member.CONSTRUCTOR) {
shadowKind = Shadow.ConstructorCall;
}
} else if (kind.equals("get")) {
sig = parseFieldSignaturePattern();
shadowKind = Shadow.FieldGet;
} else if (kind.equals("set")) {
sig = parseFieldSignaturePattern();
shadowKind = Shadow.FieldSet;
} else {
throw new ParserException("bad kind: " + kind, tokenSource.peek());
}
eat(")");
return new KindedPointcut(shadowKind, sig);
}
public TypePattern parseTypePattern() {
return parseTypePattern(false);
}
public TypePattern parseTypePattern(boolean insideTypeParameters) {
TypePattern p = parseAtomicTypePattern(insideTypeParameters);
if (maybeEat("&&")) {
p = new AndTypePattern(p, parseNotOrTypePattern(insideTypeParameters));
}
if (maybeEat("||")) {
p = new OrTypePattern(p, parseTypePattern(insideTypeParameters));
}
return p;
}
private TypePattern parseNotOrTypePattern(boolean insideTypeParameters) {
TypePattern p = parseAtomicTypePattern(insideTypeParameters);
if (maybeEat("&&")) {
p = new AndTypePattern(p, parseTypePattern(insideTypeParameters));
}
return p;
}
private TypePattern parseAtomicTypePattern(boolean insideTypeParameters) {
AnnotationTypePattern ap = maybeParseAnnotationPattern();
if (maybeEat("!")) {
//int startPos = tokenSource.peek(-1).getStart();
//??? we lose source location for true start of !type
TypePattern p = new NotTypePattern(parseAtomicTypePattern(insideTypeParameters));
p = setAnnotationPatternForTypePattern(p,ap);
return p;
}
if (maybeEat("(")) {
TypePattern p = parseTypePattern(insideTypeParameters);
p = setAnnotationPatternForTypePattern(p,ap);
eat(")");
boolean isVarArgs = maybeEat("...");
p.setIsVarArgs(isVarArgs);
return p;
}
int startPos = tokenSource.peek().getStart();
TypePattern p = parseSingleTypePattern(insideTypeParameters);
int endPos = tokenSource.peek(-1).getEnd();
p = setAnnotationPatternForTypePattern(p,ap);
p.setLocation(sourceContext, startPos, endPos);
return p;
}
private TypePattern setAnnotationPatternForTypePattern(TypePattern t, AnnotationTypePattern ap) {
TypePattern ret = t;
if (ap != AnnotationTypePattern.ANY) {
if (t == TypePattern.ANY) {
ret = new WildTypePattern(new NamePattern[] {NamePattern.ANY},false,0,false,null);
}
if (t.annotationPattern == AnnotationTypePattern.ANY) {
ret.setAnnotationTypePattern(ap);
} else {
ret.setAnnotationTypePattern(new AndAnnotationTypePattern(ap,t.annotationPattern)); //???
}
}
return ret;
}
public AnnotationTypePattern maybeParseAnnotationPattern() {
AnnotationTypePattern ret = AnnotationTypePattern.ANY;
AnnotationTypePattern nextPattern = null;
while ((nextPattern = maybeParseSingleAnnotationPattern()) != null) {
if (ret == AnnotationTypePattern.ANY) {
ret = nextPattern;
} else {
ret = new AndAnnotationTypePattern(ret,nextPattern);
}
}
return ret;
}
public AnnotationTypePattern maybeParseSingleAnnotationPattern() {
AnnotationTypePattern ret = null;
// LALR(2) - fix by making "!@" a single token
int startIndex = tokenSource.getIndex();
if (maybeEat("!")) {
if (maybeEat("@")) {
if (maybeEat("(")) {
TypePattern p = parseTypePattern();
ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p));
eat(")");
return ret;
} else {
TypePattern p = parseSingleTypePattern();
ret = new NotAnnotationTypePattern(new WildAnnotationTypePattern(p));
return ret;
}
} else {
tokenSource.setIndex(startIndex); // not for us!
return ret;
}
}
if (maybeEat("@")) {
if (maybeEat("(")) {
TypePattern p = parseTypePattern();
ret = new WildAnnotationTypePattern(p);
eat(")");
return ret;
} else {
TypePattern p = parseSingleTypePattern();
ret = new WildAnnotationTypePattern(p);
return ret;
}
} else {
tokenSource.setIndex(startIndex); // not for us!
return ret;
}
}
public TypePattern parseSingleTypePattern() {
return parseSingleTypePattern(false);
}
public TypePattern parseSingleTypePattern(boolean insideTypeParameters) {
if (insideTypeParameters && maybeEat("?")) return parseGenericsWildcardTypePattern();
List names = parseDottedNamePattern();
int dim = 0;
while (maybeEat("[")) {
eat("]");
dim++;
}
TypePatternList typeParameters = maybeParseTypeParameterList();
int endPos = tokenSource.peek(-1).getEnd();
boolean isVarArgs = maybeEat("...");
boolean includeSubtypes = maybeEat("+");
//??? what about the source location of any's????
if (names.size() == 1 && ((NamePattern)names.get(0)).isAny() &&
dim == 0 && !isVarArgs && typeParameters == null ) return TypePattern.ANY;
// Notice we increase the dimensions if varargs is set. this is to allow type matching to
// succeed later: The actual signature at runtime of a method declared varargs is an array type of
// the original declared type (so Integer... becomes Integer[] in the bytecode). So, here for the
// pattern 'Integer...' we create a WildTypePattern 'Integer[]' with varargs set. If this matches
// during shadow matching, we confirm that the varargs flags match up before calling it a successful
// match.
return new WildTypePattern(names, includeSubtypes, dim+(isVarArgs?1:0), endPos,isVarArgs,typeParameters);
}
public TypePattern parseGenericsWildcardTypePattern() {
List names = new ArrayList();
names.add(new NamePattern("?"));
TypePattern upperBound = null;
TypePattern[] additionalInterfaceBounds = new TypePattern[0];
TypePattern lowerBound = null;
if (maybeEatIdentifier("extends")) {
upperBound = parseTypePattern(false);
additionalInterfaceBounds = maybeParseAdditionalInterfaceBounds();
}
if (maybeEatIdentifier("super")) {
lowerBound = parseTypePattern(false);
}
int endPos = tokenSource.peek(-1).getEnd();
return new WildTypePattern(names,false,0,endPos,false,null,upperBound,additionalInterfaceBounds,lowerBound);
}
// private AnnotationTypePattern completeAnnotationPattern(AnnotationTypePattern p) {
// if (maybeEat("&&")) {
// return new AndAnnotationTypePattern(p,parseNotOrAnnotationPattern());
// }
// if (maybeEat("||")) {
// return new OrAnnotationTypePattern(p,parseAnnotationTypePattern());
// }
// return p;
// }
//
// protected AnnotationTypePattern parseAnnotationTypePattern() {
// AnnotationTypePattern ap = parseAtomicAnnotationPattern();
// if (maybeEat("&&")) {
// ap = new AndAnnotationTypePattern(ap, parseNotOrAnnotationPattern());
// }
//
// if (maybeEat("||")) {
// ap = new OrAnnotationTypePattern(ap, parseAnnotationTypePattern());
// }
// return ap;
// }
//
// private AnnotationTypePattern parseNotOrAnnotationPattern() {
// AnnotationTypePattern p = parseAtomicAnnotationPattern();
// if (maybeEat("&&")) {
// p = new AndAnnotationTypePattern(p,parseAnnotationTypePattern());
// }
// return p;
// }
protected ExactAnnotationTypePattern parseAnnotationNameOrVarTypePattern() {
ExactAnnotationTypePattern p = null;
int startPos = tokenSource.peek().getStart();
if (maybeEat("@")) {
throw new ParserException("@Foo form was deprecated in AspectJ 5 M2: annotation name or var ",tokenSource.peek(-1));
}
p = parseSimpleAnnotationName();
int endPos = tokenSource.peek(-1).getEnd();
p.setLocation(sourceContext,startPos,endPos);
return p;
}
/**
* @return
*/
private ExactAnnotationTypePattern parseSimpleAnnotationName() {
// the @ has already been eaten...
ExactAnnotationTypePattern p;
StringBuffer annotationName = new StringBuffer();
annotationName.append(parseIdentifier());
while (maybeEat(".")) {
annotationName.append('.');
annotationName.append(parseIdentifier());
}
UnresolvedType type = UnresolvedType.forName(annotationName.toString());
p = new ExactAnnotationTypePattern(type);
return p;
}
// private AnnotationTypePattern parseAtomicAnnotationPattern() {
// if (maybeEat("!")) {
// //int startPos = tokenSource.peek(-1).getStart();
// //??? we lose source location for true start of !type
// AnnotationTypePattern p = new NotAnnotationTypePattern(parseAtomicAnnotationPattern());
// return p;
// }
// if (maybeEat("(")) {
// AnnotationTypePattern p = parseAnnotationTypePattern();
// eat(")");
// return p;
// }
// int startPos = tokenSource.peek().getStart();
// eat("@");
// StringBuffer annotationName = new StringBuffer();
// annotationName.append(parseIdentifier());
// while (maybeEat(".")) {
// annotationName.append('.');
// annotationName.append(parseIdentifier());
// }
// UnresolvedType type = UnresolvedType.forName(annotationName.toString());
// AnnotationTypePattern p = new ExactAnnotationTypePattern(type);
// int endPos = tokenSource.peek(-1).getEnd();
// p.setLocation(sourceContext, startPos, endPos);
// return p;
// }
private boolean isAnnotationPattern(PatternNode p) {
return (p instanceof AnnotationTypePattern);
}
public List parseDottedNamePattern() {
List names = new ArrayList();
StringBuffer buf = new StringBuffer();
IToken previous = null;
boolean justProcessedEllipsis = false; // Remember if we just dealt with an ellipsis (PR61536)
boolean justProcessedDot = false;
boolean onADot = false;
while (true) {
IToken tok = null;
int startPos = tokenSource.peek().getStart();
String afterDot = null;
while (true) {
if (previous !=null && previous.getString().equals(".")) justProcessedDot = true;
tok = tokenSource.peek();
onADot = (tok.getString().equals("."));
if (previous != null) {
if (!isAdjacent(previous, tok)) break;
}
if (tok.getString() == "*" || (tok.isIdentifier() && tok.getString()!="...")) {
buf.append(tok.getString());
} else if (tok.getString()=="...") {
break;
} else if (tok.getLiteralKind() != null) {
//System.err.println("literal kind: " + tok.getString());
String s = tok.getString();
int dot = s.indexOf('.');
if (dot != -1) {
buf.append(s.substring(0, dot));
afterDot = s.substring(dot+1);
previous = tokenSource.next();
break;
}
buf.append(s); // ??? so-so
} else {
break;
}
previous = tokenSource.next();
//XXX need to handle floats and other fun stuff
}
int endPos = tokenSource.peek(-1).getEnd();
if (buf.length() == 0 && names.isEmpty()) {
throw new ParserException("name pattern", tok);
}
if (buf.length() == 0 && justProcessedEllipsis) {
throw new ParserException("name pattern cannot finish with ..", tok);
}
if (buf.length() == 0 && justProcessedDot && !onADot) {
throw new ParserException("name pattern cannot finish with .", tok);
}
if (buf.length() == 0) {
names.add(NamePattern.ELLIPSIS);
justProcessedEllipsis = true;
} else {
checkLegalName(buf.toString(), previous);
NamePattern ret = new NamePattern(buf.toString());
ret.setLocation(sourceContext, startPos, endPos);
names.add(ret);
justProcessedEllipsis = false;
}
if (afterDot == null) {
buf.setLength(0);
// no elipsis or dotted name part
if (!maybeEat(".")) break;
// go on
else previous = tokenSource.peek(-1);
} else {
buf.setLength(0);
buf.append(afterDot);
afterDot = null;
}
}
//System.err.println("parsed: " + names);
return names;
}
public NamePattern parseNamePattern() {
StringBuffer buf = new StringBuffer();
IToken previous = null;
IToken tok;
int startPos = tokenSource.peek().getStart();
while (true) {
tok = tokenSource.peek();
if (previous != null) {
if (!isAdjacent(previous, tok)) break;
}
if (tok.getString() == "*" || tok.isIdentifier()) {
buf.append(tok.getString());
} else if (tok.getLiteralKind() != null) {
//System.err.println("literal kind: " + tok.getString());
String s = tok.getString();
if (s.indexOf('.') != -1) break;
buf.append(s); // ??? so-so
} else {
break;
}
previous = tokenSource.next();
//XXX need to handle floats and other fun stuff
}
int endPos = tokenSource.peek(-1).getEnd();
if (buf.length() == 0) {
throw new ParserException("name pattern", tok);
}
checkLegalName(buf.toString(), previous);
NamePattern ret = new NamePattern(buf.toString());
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private void checkLegalName(String s, IToken tok) {
char ch = s.charAt(0);
if (!(ch == '*' || Character.isJavaIdentifierStart(ch))) {
throw new ParserException("illegal identifier start (" + ch + ")", tok);
}
for (int i=1, len=s.length(); i < len; i++) {
ch = s.charAt(i);
if (!(ch == '*' || Character.isJavaIdentifierPart(ch))) {
throw new ParserException("illegal identifier character (" + ch + ")", tok);
}
}
}
private boolean isAdjacent(IToken first, IToken second) {
return first.getEnd() == second.getStart()-1;
}
public ModifiersPattern parseModifiersPattern() {
int requiredFlags = 0;
int forbiddenFlags = 0;
int start;
while (true) {
start = tokenSource.getIndex();
boolean isForbidden = false;
isForbidden = maybeEat("!");
IToken t = tokenSource.next();
int flag = ModifiersPattern.getModifierFlag(t.getString());
if (flag == -1) break;
if (isForbidden) forbiddenFlags |= flag;
else requiredFlags |= flag;
}
tokenSource.setIndex(start);
if (requiredFlags == 0 && forbiddenFlags == 0) {
return ModifiersPattern.ANY;
} else {
return new ModifiersPattern(requiredFlags, forbiddenFlags);
}
}
public TypePatternList parseArgumentsPattern() {
List patterns = new ArrayList();
eat("(");
if (maybeEat(")")) {
return new TypePatternList();
}
do {
if (maybeEat(".")) {
eat(".");
patterns.add(TypePattern.ELLIPSIS);
} else {
patterns.add(parseTypePattern());
}
} while (maybeEat(","));
eat(")");
return new TypePatternList(patterns);
}
public AnnotationPatternList parseArgumentsAnnotationPattern() {
List patterns = new ArrayList();
eat("(");
if (maybeEat(")")) {
return new AnnotationPatternList();
}
do {
if (maybeEat(".")) {
eat(".");
patterns.add(AnnotationTypePattern.ELLIPSIS);
} else if (maybeEat("*")) {
patterns.add(AnnotationTypePattern.ANY);
} else {
patterns.add(parseAnnotationNameOrVarTypePattern());
}
} while (maybeEat(","));
eat(")");
return new AnnotationPatternList(patterns);
}
public ThrowsPattern parseOptionalThrowsPattern() {
IToken t = tokenSource.peek();
if (t.isIdentifier() && t.getString().equals("throws")) {
tokenSource.next();
List required = new ArrayList();
List forbidden = new ArrayList();
do {
boolean isForbidden = maybeEat("!");
//???might want an error for a second ! without a paren
TypePattern p = parseTypePattern();
if (isForbidden) forbidden.add(p);
else required.add(p);
} while (maybeEat(","));
return new ThrowsPattern(new TypePatternList(required), new TypePatternList(forbidden));
}
return ThrowsPattern.ANY;
}
public SignaturePattern parseMethodOrConstructorSignaturePattern() {
int startPos = tokenSource.peek().getStart();
AnnotationTypePattern annotationPattern = maybeParseAnnotationPattern();
ModifiersPattern modifiers = parseModifiersPattern();
TypePattern returnType = parseTypePattern(false);
TypePattern declaringType;
NamePattern name = null;
Member.Kind kind;
// here we can check for 'new'
if (maybeEatNew(returnType)) {
kind = Member.CONSTRUCTOR;
if (returnType.toString().length() == 0) {
declaringType = TypePattern.ANY;
} else {
declaringType = returnType;
}
returnType = TypePattern.ANY;
name = NamePattern.ANY;
} else {
kind = Member.METHOD;
IToken nameToken = tokenSource.peek();
declaringType = parseTypePattern(false);
if (maybeEat(".")) {
nameToken = tokenSource.peek();
name = parseNamePattern();
} else {
name = tryToExtractName(declaringType);
if (declaringType.toString().equals("")) {
declaringType = TypePattern.ANY;
}
}
if (name == null) {
throw new ParserException("name pattern", tokenSource.peek());
}
String simpleName = name.maybeGetSimpleName();
//XXX should add check for any Java keywords
if (simpleName != null && simpleName.equals("new")) {
throw new ParserException("method name (not constructor)",
nameToken);
}
}
TypePatternList parameterTypes = parseArgumentsPattern();
ThrowsPattern throwsPattern = parseOptionalThrowsPattern();
SignaturePattern ret = new SignaturePattern(kind, modifiers, returnType, declaringType, name, parameterTypes, throwsPattern, annotationPattern);
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private boolean maybeEatNew(TypePattern returnType) {
if (returnType instanceof WildTypePattern) {
WildTypePattern p = (WildTypePattern)returnType;
if (p.maybeExtractName("new")) return true;
}
int start = tokenSource.getIndex();
if (maybeEat(".")) {
String id = maybeEatIdentifier();
if (id != null && id.equals("new")) return true;
tokenSource.setIndex(start);
}
return false;
}
public SignaturePattern parseFieldSignaturePattern() {
int startPos = tokenSource.peek().getStart();
// TypePatternList followMe = TypePatternList.ANY;
AnnotationTypePattern annotationPattern = maybeParseAnnotationPattern();
ModifiersPattern modifiers = parseModifiersPattern();
TypePattern returnType = parseTypePattern();
TypePattern declaringType = parseTypePattern();
NamePattern name;
//System.err.println("parsed field: " + declaringType.toString());
if (maybeEat(".")) {
name = parseNamePattern();
} else {
name = tryToExtractName(declaringType);
if (declaringType.toString().equals("")) {
declaringType = TypePattern.ANY;
}
}
SignaturePattern ret = new SignaturePattern(Member.FIELD, modifiers, returnType,
declaringType, name, TypePatternList.ANY, ThrowsPattern.ANY,annotationPattern);
int endPos = tokenSource.peek(-1).getEnd();
ret.setLocation(sourceContext, startPos, endPos);
return ret;
}
private NamePattern tryToExtractName(TypePattern nextType) {
if (nextType == TypePattern.ANY) {
return NamePattern.ANY;
} else if (nextType instanceof WildTypePattern) {
WildTypePattern p = (WildTypePattern)nextType;
return p.extractName();
} else {
return null;
}
}
/**
* Parse type variable declarations for a generic method or at the start of a signature pointcut to identify
* type variable names in a generic type.
* @param includeParameterizedTypes
* @return
*/
public TypeVariablePatternList maybeParseTypeVariableList() {
if (!maybeEat("<")) return null;
List typeVars = new ArrayList();
TypeVariablePattern t = parseTypeVariable();
typeVars.add(t);
while (maybeEat(",")) {
TypeVariablePattern nextT = parseTypeVariable();
typeVars.add(nextT);
}
eat(">");
TypeVariablePattern[] tvs = new TypeVariablePattern[typeVars.size()];
typeVars.toArray(tvs);
return new TypeVariablePatternList(tvs);
}
// of the form execution<T,S,V> - allows identifiers only
public String[] maybeParseSimpleTypeVariableList() {
if (!maybeEat("<")) return null;
List typeVarNames = new ArrayList();
do {
typeVarNames.add(parseIdentifier());
} while (maybeEat(","));
eat(">","',' or '>'");
String[] tvs = new String[typeVarNames.size()];
typeVarNames.toArray(tvs);
return tvs;
}
public TypePatternList maybeParseTypeParameterList() {
if (!maybeEat("<")) return null;
List typePats = new ArrayList();
do {
TypePattern tp = parseTypePattern(true);
typePats.add(tp);
} while(maybeEat(","));
eat(">");
TypePattern[] tps = new TypePattern[typePats.size()];
typePats.toArray(tps);
return new TypePatternList(tps);
}
public TypeVariablePattern parseTypeVariable() {
TypePattern upperBound = null;
TypePattern[] additionalInterfaceBounds = null;
TypePattern lowerBound = null;
String typeVariableName = null;
if (typeVariableName == null) typeVariableName = parseIdentifier();
if (maybeEatIdentifier("extends")) {
upperBound = parseTypePattern();
additionalInterfaceBounds = maybeParseAdditionalInterfaceBounds();
} else if (maybeEatIdentifier("super")) {
lowerBound = parseTypePattern();
}
return new TypeVariablePattern(typeVariableName,upperBound,additionalInterfaceBounds,lowerBound);
}
private TypePattern[] maybeParseAdditionalInterfaceBounds() {
List boundsList = new ArrayList();
while (maybeEat("&")) {
TypePattern tp = parseTypePattern();
boundsList.add(tp);
}
if (boundsList.size() == 0) return null;
TypePattern[] ret = new TypePattern[boundsList.size()];
boundsList.toArray(ret);
return ret;
}
public String parsePossibleStringSequence(boolean shouldEnd) {
StringBuffer result = new StringBuffer();
IToken token = tokenSource.next();
if (token.getLiteralKind()==null) {
throw new ParserException("string",token);
}
while (token.getLiteralKind().equals("string")) {
result.append(token.getString());
boolean plus = maybeEat("+");
if (!plus) break;
token = tokenSource.next();
if (token.getLiteralKind()==null) {
throw new ParserException("string",token);
}
}
eatIdentifier(";");
IToken t = tokenSource.next();
if (shouldEnd && t!=IToken.EOF) {
throw new ParserException("<string>;",token);
}
return result.toString();
}
public String parseStringLiteral() {
IToken token = tokenSource.next();
String literalKind = token.getLiteralKind();
if (literalKind == "string") {
return token.getString();
}
throw new ParserException("string", token);
}
public String parseIdentifier() {
IToken token = tokenSource.next();
if (token.isIdentifier()) return token.getString();
throw new ParserException("identifier", token);
}
public void eatIdentifier(String expectedValue) {
IToken next = tokenSource.next();
if (!next.getString().equals(expectedValue)) {
throw new ParserException(expectedValue, next);
}
}
public boolean maybeEatIdentifier(String expectedValue) {
IToken next = tokenSource.peek();
if (next.getString().equals(expectedValue)) {
tokenSource.next();
return true;
} else {
return false;
}
}
public void eat(String expectedValue) {
eat(expectedValue,expectedValue);
}
private void eat(String expectedValue,String expectedMessage) {
IToken next = nextToken();
if (next.getString() != expectedValue) {
if (expectedValue.equals(">") && next.getString().startsWith(">")) {
// handle problem of >> and >>> being lexed as single tokens
pendingRightArrows = BasicToken.makeLiteral(next.getString().substring(1).intern(), "string", next.getStart()+1, next.getEnd());
return;
}
throw new ParserException(expectedMessage, next);
}
}
private IToken pendingRightArrows;
private IToken nextToken() {
if (pendingRightArrows != null) {
IToken ret = pendingRightArrows;
pendingRightArrows = null;
return ret;
} else {
return tokenSource.next();
}
}
public boolean maybeEat(String token) {
IToken next = tokenSource.peek();
if (next.getString() == token) {
tokenSource.next();
return true;
} else {
return false;
}
}
public String maybeEatIdentifier() {
IToken next = tokenSource.peek();
if (next.isIdentifier()) {
tokenSource.next();
return next.getString();
} else {
return null;
}
}
public boolean peek(String token) {
IToken next = tokenSource.peek();
return next.getString() == token;
}
public PatternParser(String data) {
this(BasicTokenSource.makeTokenSource(data,null));
}
public PatternParser(String data, ISourceContext context) {
this(BasicTokenSource.makeTokenSource(data,context));
}
}
|
106,461 |
Bug 106461 org.aspectj.weaver.patterns.WildTypePattern.maybeGetCleanName(WildTypePattern.java:500)
| null |
resolved fixed
|
5735e96
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-10T11:49:34Z | 2005-08-09T12:20:00Z |
weaver/src/org/aspectj/weaver/patterns/WildTypePattern.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FileUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.BoundedReferenceType;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.TypeFactory;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.UnresolvedTypeVariableReferenceType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
/**
* The PatternParser always creates WildTypePatterns for type patterns in pointcut
* expressions (apart from *, which is sometimes directly turned into TypePattern.ANY).
* resolveBindings() tries to work out what we've really got and turn it into a type
* pattern that we can use for matching. This will normally be either an ExactTypePattern
* or a WildTypePattern.
*
* Here's how the process pans out for various generic and parameterized patterns:
* (see GenericsWildTypePatternResolvingTestCase)
*
* Foo where Foo exists and is generic
* Parser creates WildTypePattern namePatterns={Foo}
* resolveBindings resolves Foo to RT(Foo - raw)
* return ExactTypePattern(LFoo;)
*
* Foo<String> where Foo exists and String meets the bounds
* Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{String}
* resolveBindings resolves typeParameters to ExactTypePattern(String)
* resolves Foo to RT(Foo)
* returns ExactTypePattern(PFoo<String>; - parameterized)
*
* Foo<Str*> where Foo exists and takes one bound
* Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{Str*}
* resolveBindings resolves typeParameters to WTP{Str*}
* resolves Foo to RT(Foo)
* returns WildTypePattern(name = Foo, typeParameters = WTP{Str*} isGeneric=false)
*
* Fo*<String>
* Parser creates WildTypePattern namePatterns = {Fo*}, typeParameters=WTP{String}
* resolveBindings resolves typeParameters to ETP{String}
* returns WildTypePattern(name = Fo*, typeParameters = ETP{String} isGeneric=false)
*
*
* Foo<?>
*
* Foo<? extends Number>
*
* Foo<? extends Number+>
*
* Foo<? super Number>
*
*/
public class WildTypePattern extends TypePattern {
private static final String GENERIC_WILDCARD_CHARACTER = "?";
private NamePattern[] namePatterns;
int ellipsisCount;
String[] importedPrefixes;
String[] knownMatches;
int dim;
// these next three are set if the type pattern is constrained by extends or super clauses, in which case the
// namePatterns must have length 1
// TODO AMC: read/write/resolve of these fields
TypePattern upperBound; // extends Foo
TypePattern[] additionalInterfaceBounds; // extends Foo & A,B,C
TypePattern lowerBound; // super Foo
// if we have type parameters, these fields indicate whether we should be a generic type pattern or a parameterized
// type pattern. We can only tell during resolve bindings.
private boolean isGeneric = true;
WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim, boolean isVarArgs, TypePatternList typeParams) {
super(includeSubtypes,isVarArgs,typeParams);
this.namePatterns = namePatterns;
this.dim = dim;
ellipsisCount = 0;
for (int i=0; i<namePatterns.length; i++) {
if (namePatterns[i] == NamePattern.ELLIPSIS) ellipsisCount++;
}
setLocation(namePatterns[0].getSourceContext(), namePatterns[0].getStart(), namePatterns[namePatterns.length-1].getEnd());
}
public WildTypePattern(List names, boolean includeSubtypes, int dim) {
this((NamePattern[])names.toArray(new NamePattern[names.size()]), includeSubtypes, dim,false,TypePatternList.EMPTY);
}
public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) {
this(names, includeSubtypes, dim);
this.end = endPos;
}
public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg) {
this(names, includeSubtypes, dim);
this.end = endPos;
this.isVarArgs = isVarArg;
}
public WildTypePattern(
List names,
boolean includeSubtypes,
int dim,
int endPos,
boolean isVarArg,
TypePatternList typeParams,
TypePattern upperBound,
TypePattern[] additionalInterfaceBounds,
TypePattern lowerBound) {
this((NamePattern[])names.toArray(new NamePattern[names.size()]),includeSubtypes,dim,isVarArg,typeParams);
this.end = endPos;
this.upperBound = upperBound;
this.lowerBound = lowerBound;
this.additionalInterfaceBounds = additionalInterfaceBounds;
}
public WildTypePattern(
List names,
boolean includeSubtypes,
int dim,
int endPos,
boolean isVarArg,
TypePatternList typeParams)
{
this((NamePattern[])names.toArray(new NamePattern[names.size()]),includeSubtypes,dim,isVarArg,typeParams);
this.end = endPos;
}
public NamePattern[] getNamePatterns() {
return namePatterns;
}
public TypePattern getUpperBound() { return upperBound; }
public TypePattern getLowerBound() { return lowerBound; }
public TypePattern[] getAdditionalIntefaceBounds() { return additionalInterfaceBounds; }
// called by parser after parsing a type pattern, must bump dim as well as setting flag
public void setIsVarArgs(boolean isVarArgs) {
this.isVarArgs = isVarArgs;
if (isVarArgs) this.dim += 1;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern)
*/
protected boolean couldEverMatchSameTypesAs(TypePattern other) {
if (super.couldEverMatchSameTypesAs(other)) return true;
// false is necessary but not sufficient
UnresolvedType otherType = other.getExactType();
if (otherType != ResolvedType.MISSING) {
if (namePatterns.length > 0) {
if (!namePatterns[0].matches(otherType.getName())) return false;
}
}
if (other instanceof WildTypePattern) {
WildTypePattern owtp = (WildTypePattern) other;
String mySimpleName = namePatterns[0].maybeGetSimpleName();
String yourSimpleName = owtp.namePatterns[0].maybeGetSimpleName();
if (mySimpleName != null && yourSimpleName != null) {
return (mySimpleName.startsWith(yourSimpleName) ||
yourSimpleName.startsWith(mySimpleName));
}
}
return true;
}
//XXX inefficient implementation
public static char[][] splitNames(String s) {
List ret = new ArrayList();
int startIndex = 0;
while (true) {
int breakIndex = s.indexOf('.', startIndex); // what about /
if (breakIndex == -1) breakIndex = s.indexOf('$', startIndex); // we treat $ like . here
if (breakIndex == -1) break;
char[] name = s.substring(startIndex, breakIndex).toCharArray();
ret.add(name);
startIndex = breakIndex+1;
}
ret.add(s.substring(startIndex).toCharArray());
return (char[][])ret.toArray(new char[ret.size()][]);
}
/**
* @see org.aspectj.weaver.TypePattern#matchesExactly(IType)
*/
protected boolean matchesExactly(ResolvedType type) {
return matchesExactly(type,type);
}
protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) {
String targetTypeName = type.getName();
//System.err.println("match: " + targetTypeName + ", " + knownMatches); //Arrays.asList(importedPrefixes));
// Ensure the annotation pattern is resolved
annotationPattern.resolve(type.getWorld());
return matchesExactlyByName(targetTypeName) &&
matchesParameters(type,STATIC) &&
matchesBounds(type,STATIC) &&
annotationPattern.matches(annotatedType).alwaysTrue();
}
// we've matched against the base (or raw) type, but if this type pattern specifies parameters or
// type variables we need to make sure we match against them too
private boolean matchesParameters(ResolvedType aType, MatchKind staticOrDynamic) {
if (!isGeneric && typeParameters.size() > 0) {
if(!aType.isParameterizedType()) return false;
// we have to match type parameters
return typeParameters.matches(aType.getResolvedTypeParameters(), staticOrDynamic).alwaysTrue();
}
return true;
}
// we've matched against the base (or raw) type, but if this type pattern specifies bounds because
// it is a ? extends or ? super deal then we have to match them too.
private boolean matchesBounds(ResolvedType aType, MatchKind staticOrDynamic) {
if (upperBound == null && aType.getUpperBound() != null) {
// for upper bound, null can also match against Object - but anything else and we're out.
if (!aType.getUpperBound().getName().equals(UnresolvedType.OBJECT.getName())) {
return false;
}
}
if (lowerBound == null && aType.getLowerBound() != null) return false;
if (upperBound != null) {
// match ? extends
if (aType.isGenericWildcard() && aType.isSuper()) return false;
if (aType.getUpperBound() == null) return false;
return upperBound.matches((ResolvedType)aType.getUpperBound(),staticOrDynamic).alwaysTrue();
}
if (lowerBound != null) {
// match ? super
if (!(aType.isGenericWildcard() && aType.isSuper())) return false;
return lowerBound.matches((ResolvedType)aType.getLowerBound(),staticOrDynamic).alwaysTrue();
}
return true;
}
/**
* Used in conjunction with checks on 'isStar()' to tell you if this pattern represents '*' or '*[]' which are
* different !
*/
public int getDimensions() {
return dim;
}
public boolean isArray() {
return dim > 1;
}
/**
* @param targetTypeName
* @return
*/
private boolean matchesExactlyByName(String targetTypeName) {
// we deal with parameter matching separately...
if (targetTypeName.indexOf('<') != -1) {
targetTypeName = targetTypeName.substring(0,targetTypeName.indexOf('<'));
}
// we deal with bounds matching separately too...
if (targetTypeName.startsWith(GENERIC_WILDCARD_CHARACTER)) {
targetTypeName = GENERIC_WILDCARD_CHARACTER;
}
//XXX hack
if (knownMatches == null && importedPrefixes == null) {
return innerMatchesExactly(targetTypeName);
}
if (isNamePatternStar()) {
// we match if the dimensions match
int numDimensionsInTargetType = 0;
if (dim > 0) {
int index;
while((index = targetTypeName.indexOf('[')) != -1) {
numDimensionsInTargetType++;
targetTypeName = targetTypeName.substring(index+1);
}
if (numDimensionsInTargetType == dim) {
return true;
} else {
return false;
}
}
}
// if our pattern is length 1, then known matches are exact matches
// if it's longer than that, then known matches are prefixes of a sort
if (namePatterns.length == 1) {
for (int i=0, len=knownMatches.length; i < len; i++) {
if (knownMatches[i].equals(targetTypeName)) return true;
}
} else {
for (int i=0, len=knownMatches.length; i < len; i++) {
String knownPrefix = knownMatches[i] + "$";
if (targetTypeName.startsWith(knownPrefix)) {
int pos = lastIndexOfDotOrDollar(knownMatches[i]);
if (innerMatchesExactly(targetTypeName.substring(pos+1))) {
return true;
}
}
}
}
// if any prefixes match, strip the prefix and check that the rest matches
// assumes that prefixes have a dot at the end
for (int i=0, len=importedPrefixes.length; i < len; i++) {
String prefix = importedPrefixes[i];
//System.err.println("prefix match? " + prefix + " to " + targetTypeName);
if (targetTypeName.startsWith(prefix)) {
if (innerMatchesExactly(targetTypeName.substring(prefix.length()))) {
return true;
}
}
}
return innerMatchesExactly(targetTypeName);
}
private int lastIndexOfDotOrDollar(String string) {
int dot = string.lastIndexOf('.');
int dollar = string.lastIndexOf('$');
return Math.max(dot, dollar);
}
private boolean innerMatchesExactly(String targetTypeName) {
//??? doing this everytime is not very efficient
char[][] names = splitNames(targetTypeName);
return innerMatchesExactly(names);
}
private boolean innerMatchesExactly(char[][] names) {
int namesLength = names.length;
int patternsLength = namePatterns.length;
int namesIndex = 0;
int patternsIndex = 0;
if (ellipsisCount == 0) {
if (namesLength != patternsLength) return false;
while (patternsIndex < patternsLength) {
if (!namePatterns[patternsIndex++].matches(names[namesIndex++])) {
return false;
}
}
return true;
} else if (ellipsisCount == 1) {
if (namesLength < patternsLength-1) return false;
while (patternsIndex < patternsLength) {
NamePattern p = namePatterns[patternsIndex++];
if (p == NamePattern.ELLIPSIS) {
namesIndex = namesLength - (patternsLength-patternsIndex);
} else {
if (!p.matches(names[namesIndex++])) {
return false;
}
}
}
return true;
} else {
// System.err.print("match(\"" + Arrays.asList(namePatterns) + "\", \"" + Arrays.asList(names) + "\") -> ");
boolean b = outOfStar(namePatterns, names, 0, 0, patternsLength - ellipsisCount, namesLength, ellipsisCount);
// System.err.println(b);
return b;
}
}
private static boolean outOfStar(final NamePattern[] pattern, final char[][] target,
int pi, int ti,
int pLeft, int tLeft,
final int starsLeft) {
if (pLeft > tLeft) return false;
while (true) {
// invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length)
if (tLeft == 0) return true;
if (pLeft == 0) {
return (starsLeft > 0);
}
if (pattern[pi] == NamePattern.ELLIPSIS) {
return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1);
}
if (! pattern[pi].matches(target[ti])) {
return false;
}
pi++; ti++; pLeft--; tLeft--;
}
}
private static boolean inStar(final NamePattern[] pattern, final char[][] target,
int pi, int ti,
final int pLeft, int tLeft,
int starsLeft) {
// invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern
// of course, we probably can't parse multiple ..'s in a row, but this keeps the algorithm
// exactly parallel with that in NamePattern
NamePattern patternChar = pattern[pi];
while (patternChar == NamePattern.ELLIPSIS) {
starsLeft--;
patternChar = pattern[++pi];
}
while (true) {
// invariant: if (tLeft > 0) then (ti < target.length)
if (pLeft > tLeft) return false;
if (patternChar.matches(target[ti])) {
if (outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft)) return true;
}
ti++; tLeft--;
}
}
/**
* @see org.aspectj.weaver.TypePattern#matchesInstanceof(IType)
*/
public FuzzyBoolean matchesInstanceof(ResolvedType type) {
//XXX hack to let unmatched types just silently remain so
if (maybeGetSimpleName() != null) return FuzzyBoolean.NO;
type.getWorld().getMessageHandler().handleMessage(
new Message("can't do instanceof matching on patterns with wildcards",
IMessage.ERROR, null, getSourceLocation()));
return FuzzyBoolean.NO;
}
public NamePattern extractName() {
//System.err.println("extract from : " + Arrays.asList(namePatterns));
int len = namePatterns.length;
NamePattern ret = namePatterns[len-1];
NamePattern[] newNames = new NamePattern[len-1];
System.arraycopy(namePatterns, 0, newNames, 0, len-1);
namePatterns = newNames;
//System.err.println(" left : " + Arrays.asList(namePatterns));
return ret;
}
/**
* Method maybeExtractName.
* @param string
* @return boolean
*/
public boolean maybeExtractName(String string) {
int len = namePatterns.length;
NamePattern ret = namePatterns[len-1];
String simple = ret.maybeGetSimpleName();
if (simple != null && simple.equals(string)) {
extractName();
return true;
}
return false;
}
/**
* If this type pattern has no '.' or '*' in it, then
* return a simple string
*
* otherwise, this will return null;
*/
public String maybeGetSimpleName() {
if (namePatterns.length == 1) {
return namePatterns[0].maybeGetSimpleName();
}
return null;
}
/**
* If this type pattern has no '*' or '..' in it
*/
public String maybeGetCleanName() {
if (namePatterns.length == 0) {
throw new RuntimeException("bad name: " + namePatterns);
}
//System.out.println("get clean: " + this);
StringBuffer buf = new StringBuffer();
for (int i=0, len=namePatterns.length; i < len; i++) {
NamePattern p = namePatterns[i];
String simpleName = p.maybeGetSimpleName();
if (simpleName == null) return null;
if (i > 0) buf.append(".");
buf.append(simpleName);
}
//System.out.println(buf);
return buf.toString();
}
/**
* Need to determine if I'm really a pattern or a reference to a formal
*
* We may wish to further optimize the case of pattern vs. non-pattern
*
* We will be replaced by what we return
*/
public TypePattern resolveBindings(IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType)
{
if (isNamePatternStar()) {
TypePattern anyPattern = maybeResolveToAnyPattern(scope, bindings, allowBinding, requireExactType);
if (anyPattern != null) return anyPattern;
}
TypePattern bindingTypePattern = maybeResolveToBindingTypePattern(scope, bindings, allowBinding, requireExactType);
if (bindingTypePattern != null) return bindingTypePattern;
annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding);
// resolve any type parameters
if (typeParameters!=null && typeParameters.size()>0) {
typeParameters.resolveBindings(scope,bindings,allowBinding,requireExactType);
// now we have to decide whether to create a "generic" type pattern or a "parameterized" type
// pattern
// start with the simple rule that if all parameters have resolved to a type variable based pattern
// then it is generic, otherwise it is parameterized
// if we have e.g. staticinitialization<T>(Foo<T,String>) then that's a parameterized type
isGeneric = true;
TypePattern[] tps = typeParameters.getTypePatterns();
for (int i = 0; i < tps.length; i++) {
if (!tps[i].getExactType().isTypeVariableReference()) {
isGeneric = false;
break;
}
}
}
// resolve any bounds
if (upperBound != null) upperBound = upperBound.resolveBindings(scope, bindings, allowBinding, requireExactType);
if (lowerBound != null) lowerBound = lowerBound.resolveBindings(scope, bindings, allowBinding, requireExactType);
// amc - additional interface bounds only needed if we support type vars again.
String fullyQualifiedName = maybeGetCleanName();
if (fullyQualifiedName != null) {
return resolveBindingsFromFullyQualifiedTypeName(fullyQualifiedName, scope, bindings, allowBinding, requireExactType);
} else {
if (requireExactType) {
scope.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED),
getSourceLocation()));
return NO;
}
importedPrefixes = scope.getImportedPrefixes();
knownMatches = preMatch(scope.getImportedNames());
return this; // pattern contains wildcards so can't be resolved to an ExactTypePattern...
//XXX need to implement behavior for Lint.invalidWildcardTypeName
}
}
private TypePattern maybeResolveToAnyPattern(IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType) {
// If there is an annotation specified we have to
// use a special variant of Any TypePattern called
// AnyWithAnnotation
if (annotationPattern == AnnotationTypePattern.ANY) {
if (dim == 0 && !isVarArgs && upperBound == null && lowerBound == null && (additionalInterfaceBounds == null || additionalInterfaceBounds.length==0)) { // pr72531
return TypePattern.ANY; //??? loses source location
}
} else {
annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding);
AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annotationPattern);
ret.setLocation(sourceContext,start,end);
return ret;
}
return null; // can't resolve to a simple "any" pattern
}
private TypePattern maybeResolveToBindingTypePattern(IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType) {
String simpleName = maybeGetSimpleName();
if (simpleName != null) {
FormalBinding formalBinding = scope.lookupFormal(simpleName);
if (formalBinding != null) {
if (bindings == null) {
scope.message(IMessage.ERROR, this, "negation doesn't allow binding");
return this;
}
if (!allowBinding) {
scope.message(IMessage.ERROR, this,
"name binding only allowed in target, this, and args pcds");
return this;
}
BindingTypePattern binding = new BindingTypePattern(formalBinding,isVarArgs);
binding.copyLocationFrom(this);
bindings.register(binding, scope);
return binding;
}
}
return null; // not possible to resolve to a binding type pattern
}
private TypePattern resolveBindingsFromFullyQualifiedTypeName(String fullyQualifiedName, IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType) {
String originalName = fullyQualifiedName;
ResolvedType resolvedTypeInTheWorld = null;
UnresolvedType type;
//System.out.println("resolve: " + cleanName);
//??? this loop has too many inefficiencies to count
resolvedTypeInTheWorld = lookupTypeInWorld(scope.getWorld(), fullyQualifiedName);
if (resolvedTypeInTheWorld.isGenericWildcard()) {
type = resolvedTypeInTheWorld;
} else {
type = lookupTypeInScope(scope, fullyQualifiedName, this);
}
if (type == ResolvedType.MISSING) {
return resolveBindingsForMissingType(resolvedTypeInTheWorld, originalName, scope, bindings, allowBinding, requireExactType);
} else {
return resolveBindingsForExactType(scope,type,fullyQualifiedName,requireExactType);
}
}
private UnresolvedType lookupTypeInScope(IScope scope, String typeName, IHasPosition location) {
UnresolvedType type = null;
while ((type = scope.lookupType(typeName, location)) == ResolvedType.MISSING) {
int lastDot = typeName.lastIndexOf('.');
if (lastDot == -1) break;
typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot+1);
}
return type;
}
private ResolvedType lookupTypeInWorld(World world, String typeName) {
ResolvedType ret = world.resolve(UnresolvedType.forName(typeName),true);
while (ret == ResolvedType.MISSING) {
int lastDot = typeName.lastIndexOf('.');
if (lastDot == -1) break;
typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot+1);
ret = world.resolve(UnresolvedType.forName(typeName),true);
}
return ret;
}
private TypePattern resolveBindingsForExactType(IScope scope, UnresolvedType aType, String fullyQualifiedName,boolean requireExactType) {
TypePattern ret = null;
if (aType.isTypeVariableReference()) {
// we have to set the bounds on it based on the bounds of this pattern
ret = resolveBindingsForTypeVariable(scope, (UnresolvedTypeVariableReferenceType) aType);
} else if (typeParameters.size()>0) {
ret = resolveParameterizedType(scope, aType, requireExactType);
} else if (upperBound != null || lowerBound != null) {
// this must be a generic wildcard with bounds
ret = resolveGenericWildcard(scope, aType);
} else {
if (dim != 0) aType = UnresolvedType.makeArray(aType, dim);
ret = new ExactTypePattern(aType,includeSubtypes,isVarArgs);
}
ret.setAnnotationTypePattern(annotationPattern);
ret.copyLocationFrom(this);
return ret;
}
private TypePattern resolveGenericWildcard(IScope scope, UnresolvedType aType) {
if (!aType.getSignature().equals(GENERIC_WILDCARD_CHARACTER)) throw new IllegalStateException("Can only have bounds for a generic wildcard");
boolean canBeExact = true;
if ((upperBound != null) && (upperBound.getExactType() == ResolvedType.MISSING)) canBeExact = false;
if ((lowerBound != null) && (lowerBound.getExactType() == ResolvedType.MISSING)) canBeExact = false;
if (canBeExact) {
ResolvedType type = null;
if (upperBound != null) {
if (upperBound.isIncludeSubtypes()) {
canBeExact = false;
} else {
ReferenceType upper = (ReferenceType) upperBound.getExactType().resolve(scope.getWorld());
type = new BoundedReferenceType(upper,true,scope.getWorld());
}
} else {
if (lowerBound.isIncludeSubtypes()) {
canBeExact = false;
} else {
ReferenceType lower = (ReferenceType) lowerBound.getExactType().resolve(scope.getWorld());
type = new BoundedReferenceType(lower,false,scope.getWorld());
}
}
if (canBeExact) {
// might have changed if we find out include subtypes is set on one of the bounds...
return new ExactTypePattern(type,includeSubtypes,isVarArgs);
}
}
// we weren't able to resolve to an exact type pattern...
// leave as wild type pattern
importedPrefixes = scope.getImportedPrefixes();
knownMatches = preMatch(scope.getImportedNames());
return this;
}
private TypePattern resolveParameterizedType(IScope scope, UnresolvedType aType, boolean requireExactType) {
if (!verifyTypeParameters(aType.resolve(scope.getWorld()),scope,requireExactType)) return TypePattern.NO; // messages already isued
// Only if the type is exact *and* the type parameters are exact should we create an
// ExactTypePattern for this WildTypePattern
if (typeParameters.areAllExactWithNoSubtypesAllowed()) {
TypePattern[] typePats = typeParameters.getTypePatterns();
UnresolvedType[] typeParameterTypes = new UnresolvedType[typePats.length];
for (int i = 0; i < typeParameterTypes.length; i++) {
typeParameterTypes[i] = ((ExactTypePattern)typePats[i]).getExactType();
}
ResolvedType type = TypeFactory.createParameterizedType(aType.resolve(scope.getWorld()), typeParameterTypes, scope.getWorld());
if (isGeneric) type = type.getGenericType();
// UnresolvedType tx = UnresolvedType.forParameterizedTypes(aType,typeParameterTypes);
// UnresolvedType type = scope.getWorld().resolve(tx,true);
if (dim != 0) type = ResolvedType.makeArray(type, dim);
return new ExactTypePattern(type,includeSubtypes,isVarArgs);
} else {
// AMC... just leave it as a wild type pattern then?
importedPrefixes = scope.getImportedPrefixes();
knownMatches = preMatch(scope.getImportedNames());
return this;
}
}
private TypePattern resolveBindingsForMissingType(ResolvedType typeFoundInWholeWorldSearch, String nameWeLookedFor, IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType) {
if (requireExactType) {
if (!allowBinding) {
scope.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE,nameWeLookedFor),
getSourceLocation()));
} else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) {
scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation());
}
return NO;
} else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) {
// Only put the lint warning out if we can't find it in the world
if (typeFoundInWholeWorldSearch == ResolvedType.MISSING) {
scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation());
}
}
importedPrefixes = scope.getImportedPrefixes();
knownMatches = preMatch(scope.getImportedNames());
return this;
}
/**
* We resolved the type to a type variable declared in the pointcut designator.
* Now we have to create either an exact type pattern or a wild type pattern for it,
* with upper and lower bounds set accordingly.
* XXX none of this stuff gets serialized yet
* @param scope
* @param tvrType
* @return
*/
private TypePattern resolveBindingsForTypeVariable(IScope scope, UnresolvedTypeVariableReferenceType tvrType) {
Bindings emptyBindings = new Bindings(0);
if (upperBound != null) {
upperBound = upperBound.resolveBindings(scope, emptyBindings, false, false);
}
if (lowerBound != null) {
lowerBound = lowerBound.resolveBindings(scope, emptyBindings, false, false);
}
if (additionalInterfaceBounds != null) {
TypePattern[] resolvedIfBounds = new TypePattern[additionalInterfaceBounds.length];
for (int i = 0; i < resolvedIfBounds.length; i++) {
resolvedIfBounds[i] = additionalInterfaceBounds[i].resolveBindings(scope, emptyBindings, false, false);
}
additionalInterfaceBounds = resolvedIfBounds;
}
if ( upperBound == null && lowerBound == null && additionalInterfaceBounds == null) {
// no bounds to worry about...
ResolvedType rType = tvrType.resolve(scope.getWorld());
if (dim != 0) rType = ResolvedType.makeArray(rType, dim);
return new ExactTypePattern(rType,includeSubtypes,isVarArgs);
} else {
// we have to set bounds on the TypeVariable held by tvrType before resolving it
boolean canCreateExactTypePattern = true;
if (upperBound != null && upperBound.getExactType() == ResolvedType.MISSING) canCreateExactTypePattern = false;
if (lowerBound != null && lowerBound.getExactType() == ResolvedType.MISSING) canCreateExactTypePattern = false;
if (additionalInterfaceBounds != null) {
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
if (additionalInterfaceBounds[i].getExactType() == ResolvedType.MISSING) canCreateExactTypePattern = false;
}
}
if (canCreateExactTypePattern) {
TypeVariable tv = tvrType.getTypeVariable();
if (upperBound != null) tv.setUpperBound(upperBound.getExactType());
if (lowerBound != null) tv.setLowerBound(lowerBound.getExactType());
if (additionalInterfaceBounds != null) {
UnresolvedType[] ifBounds = new UnresolvedType[additionalInterfaceBounds.length];
for (int i = 0; i < ifBounds.length; i++) {
ifBounds[i] = additionalInterfaceBounds[i].getExactType();
}
tv.setAdditionalInterfaceBounds(ifBounds);
}
ResolvedType rType = tvrType.resolve(scope.getWorld());
if (dim != 0) rType = ResolvedType.makeArray(rType, dim);
return new ExactTypePattern(rType,includeSubtypes,isVarArgs);
}
return this; // leave as wild type pattern then
}
}
/**
* When this method is called, we have resolved the base type to an exact type.
* We also have a set of type patterns for the parameters.
* Time to perform some basic checks:
* - can the base type be parameterized? (is it generic)
* - can the type parameter pattern list match the number of parameters on the base type
* - do all parameter patterns meet the bounds of the respective type variables
* If any of these checks fail, a warning message is issued and we return false.
* @return
*/
private boolean verifyTypeParameters(ResolvedType baseType,IScope scope, boolean requireExactType) {
ResolvedType genericType = baseType.getGenericType();
if (genericType == null) {
// issue message "does not match because baseType.getName() is not generic"
scope.message(MessageUtil.warn(
WeaverMessages.format(WeaverMessages.NOT_A_GENERIC_TYPE,baseType.getName()),
getSourceLocation()));
return false;
}
int minRequiredTypeParameters = typeParameters.size();
boolean foundEllipsis = false;
TypePattern[] typeParamPatterns = typeParameters.getTypePatterns();
for (int i = 0; i < typeParamPatterns.length; i++) {
if (typeParamPatterns[i] instanceof WildTypePattern) {
WildTypePattern wtp = (WildTypePattern) typeParamPatterns[i];
if (wtp.ellipsisCount > 0) {
foundEllipsis = true;
minRequiredTypeParameters--;
}
}
}
TypeVariable[] tvs = genericType.getTypeVariables();
if ((tvs.length < minRequiredTypeParameters) ||
(!foundEllipsis && minRequiredTypeParameters != tvs.length))
{
// issue message "does not match because wrong no of type params"
String msg = WeaverMessages.format(WeaverMessages.INCORRECT_NUMBER_OF_TYPE_ARGUMENTS,
genericType.getName(),new Integer(tvs.length));
if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation()));
else scope.message(MessageUtil.warn(msg,getSourceLocation()));
return false;
}
// now check that each typeParameter pattern, if exact, matches the bounds
// of the type variable.
if (typeParameters.areAllExactWithNoSubtypesAllowed()) {
for (int i = 0; i < tvs.length; i++) {
UnresolvedType ut = typeParamPatterns[i].getExactType();
if (!tvs[i].canBeBoundTo(ut.resolve(scope.getWorld()))) {
// issue message that type parameter does not meet specification
String parameterName = ut.getName();
if (ut.isTypeVariableReference()) parameterName = ((TypeVariableReference)ut).getTypeVariable().getDisplayName();
String msg =
WeaverMessages.format(
WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS,
parameterName,
new Integer(i+1),
tvs[i].getDisplayName(),
genericType.getName());
if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation()));
else scope.message(MessageUtil.warn(msg,getSourceLocation()));
return false;
}
}
}
return true;
}
public TypePattern resolveBindingsFromRTTI(boolean allowBinding, boolean requireExactType) {
if (isStar()) {
return TypePattern.ANY; //??? loses source location
}
String cleanName = maybeGetCleanName();
if (cleanName != null) {
Class clazz = null;
clazz = maybeGetPrimitiveClass(cleanName);
while (clazz == null) {
try {
clazz = Class.forName(cleanName);
} catch (ClassNotFoundException cnf) {
int lastDotIndex = cleanName.lastIndexOf('.');
if (lastDotIndex == -1) break;
cleanName = cleanName.substring(0, lastDotIndex) + '$' + cleanName.substring(lastDotIndex+1);
}
}
if (clazz == null) {
try {
clazz = Class.forName("java.lang." + cleanName);
} catch (ClassNotFoundException cnf) {
}
}
if (clazz == null) {
if (requireExactType) {
return NO;
}
} else {
UnresolvedType type = UnresolvedType.forName(clazz.getName());
if (dim != 0) type = UnresolvedType.makeArray(type,dim);
TypePattern ret = new ExactTypePattern(type, includeSubtypes,isVarArgs);
ret.copyLocationFrom(this);
return ret;
}
} else if (requireExactType) {
return NO;
}
importedPrefixes = SimpleScope.javaLangPrefixArray;
knownMatches = new String[0];
return this;
}
private Class maybeGetPrimitiveClass(String typeName) {
return (Class) ExactTypePattern.primitiveTypesMap.get(typeName);
}
public boolean isStar() {
boolean annPatternStar = annotationPattern == AnnotationTypePattern.ANY;
return (isNamePatternStar() && annPatternStar);
}
private boolean isNamePatternStar() {
return namePatterns.length == 1 && namePatterns[0].isAny();
}
/**
* returns those possible matches which I match exactly the last element of
*/
private String[] preMatch(String[] possibleMatches) {
//if (namePatterns.length != 1) return CollectionUtil.NO_STRINGS;
List ret = new ArrayList();
for (int i=0, len=possibleMatches.length; i < len; i++) {
char[][] names = splitNames(possibleMatches[i]); //??? not most efficient
if (namePatterns[0].matches(names[names.length-1])) {
ret.add(possibleMatches[i]);
}
}
return (String[])ret.toArray(new String[ret.size()]);
}
// public void postRead(ResolvedType enclosingType) {
// this.importedPrefixes = enclosingType.getImportedPrefixes();
// this.knownNames = prematch(enclosingType.getImportedNames());
// }
public String toString() {
StringBuffer buf = new StringBuffer();
if (annotationPattern != AnnotationTypePattern.ANY) {
buf.append('(');
buf.append(annotationPattern.toString());
buf.append(' ');
}
for (int i=0, len=namePatterns.length; i < len; i++) {
NamePattern name = namePatterns[i];
if (name == null) {
buf.append(".");
} else {
if (i > 0) buf.append(".");
buf.append(name.toString());
}
}
if (upperBound != null) {
buf.append(" extends ");
buf.append(upperBound.toString());
}
if (lowerBound != null) {
buf.append(" super ");
buf.append(lowerBound.toString());
}
if (typeParameters!=null && typeParameters.size()!=0) {
buf.append("<");
buf.append(typeParameters.toString());
buf.append(">");
}
if (includeSubtypes) buf.append('+');
if (isVarArgs) buf.append("...");
if (annotationPattern != AnnotationTypePattern.ANY) {
buf.append(')');
}
return buf.toString();
}
public boolean equals(Object other) {
if (!(other instanceof WildTypePattern)) return false;
WildTypePattern o = (WildTypePattern)other;
int len = o.namePatterns.length;
if (len != this.namePatterns.length) return false;
if (this.includeSubtypes != o.includeSubtypes) return false;
if (this.dim != o.dim) return false;
if (this.isVarArgs != o.isVarArgs) return false;
if (this.upperBound != null) {
if (o.upperBound == null) return false;
if (!this.upperBound.equals(o.upperBound)) return false;
} else {
if (o.upperBound != null) return false;
}
if (this.lowerBound != null) {
if (o.lowerBound == null) return false;
if (!this.lowerBound.equals(o.lowerBound)) return false;
} else {
if (o.lowerBound != null) return false;
}
if (!typeParameters.equals(o.typeParameters)) return false;
for (int i=0; i < len; i++) {
if (!o.namePatterns[i].equals(this.namePatterns[i])) return false;
}
return (o.annotationPattern.equals(this.annotationPattern));
}
public int hashCode() {
int result = 17;
for (int i = 0, len = namePatterns.length; i < len; i++) {
result = 37*result + namePatterns[i].hashCode();
}
result = 37*result + annotationPattern.hashCode();
if (upperBound != null) result = 37*result + upperBound.hashCode();
if (lowerBound != null) result = 37*result + lowerBound.hashCode();
return result;
}
public FuzzyBoolean matchesInstanceof(Class type) {
return FuzzyBoolean.NO;
}
public boolean matchesExactly(Class type) {
return matchesExactlyByName(type.getName());
}
private static final byte VERSION = 1; // rev on change
/**
* @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(TypePattern.WILD);
s.writeByte(VERSION);
s.writeShort(namePatterns.length);
for (int i = 0; i < namePatterns.length; i++) {
namePatterns[i].write(s);
}
s.writeBoolean(includeSubtypes);
s.writeInt(dim);
s.writeBoolean(isVarArgs);
typeParameters.write(s); // ! change from M2
//??? storing this information with every type pattern is wasteful of .class
// file size. Storing it on enclosing types would be more efficient
FileUtil.writeStringArray(knownMatches, s);
FileUtil.writeStringArray(importedPrefixes, s);
writeLocation(s);
annotationPattern.write(s);
// generics info, new in M3
s.writeBoolean(isGeneric);
s.writeBoolean(upperBound != null);
if (upperBound != null) upperBound.write(s);
s.writeBoolean(lowerBound != null);
if (lowerBound != null) lowerBound.write(s);
s.writeInt(additionalInterfaceBounds == null ? 0 : additionalInterfaceBounds.length);
if (additionalInterfaceBounds != null) {
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
additionalInterfaceBounds[i].write(s);
}
}
}
public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException {
if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) {
return readTypePattern150(s,context);
} else {
return readTypePatternOldStyle(s,context);
}
}
public static TypePattern readTypePattern150(VersionedDataInputStream s, ISourceContext context) throws IOException {
byte version = s.readByte();
if (version > VERSION) {
throw new BCException("WildTypePattern was written by a more recent version of AspectJ, cannot read");
}
int len = s.readShort();
NamePattern[] namePatterns = new NamePattern[len];
for (int i=0; i < len; i++) {
namePatterns[i] = NamePattern.read(s);
}
boolean includeSubtypes = s.readBoolean();
int dim = s.readInt();
boolean varArg = s.readBoolean();
TypePatternList typeParams = TypePatternList.read(s, context);
WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, varArg,typeParams);
ret.knownMatches = FileUtil.readStringArray(s);
ret.importedPrefixes = FileUtil.readStringArray(s);
ret.readLocation(context, s);
ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context));
// generics info, new in M3
ret.isGeneric = s.readBoolean();
if (s.readBoolean()) {
ret.upperBound = TypePattern.read(s,context);
}
if (s.readBoolean()) {
ret.lowerBound = TypePattern.read(s,context);
}
int numIfBounds = s.readInt();
if (numIfBounds > 0) {
ret.additionalInterfaceBounds = new TypePattern[numIfBounds];
for (int i = 0; i < numIfBounds; i++) {
ret.additionalInterfaceBounds[i] = TypePattern.read(s,context);
}
}
return ret;
}
public static TypePattern readTypePatternOldStyle(VersionedDataInputStream s, ISourceContext context) throws IOException {
int len = s.readShort();
NamePattern[] namePatterns = new NamePattern[len];
for (int i=0; i < len; i++) {
namePatterns[i] = NamePattern.read(s);
}
boolean includeSubtypes = s.readBoolean();
int dim = s.readInt();
WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, false,null);
ret.knownMatches = FileUtil.readStringArray(s);
ret.importedPrefixes = FileUtil.readStringArray(s);
ret.readLocation(context, s);
return ret;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
106,634 |
Bug 106634 regression: argument causes BcelGenericSignatureToTypeXConverter.java:203
|
the following reported a compile error using AspectJ Compiler DEVELOPMENT built on Monday Jun 20, 2005 at 08:14:57 GMT but now crashes using AspectJ Compiler DEVELOPMENT built on Wednesday Aug 10, 2005 at 13:12:53 GMT import java.util.Vector; // works if java.util.* is used public class Bug extends Vector { // works if Vector is not extended void test(DoesNotExist argument) {} // works without the argument } also, the bug only appears if the -1.5 flag is used.
|
resolved fixed
|
477c575
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-11T10:38:15Z | 2005-08-10T16:06:40Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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 testMissingNamePattern_pr106461() { runTest("missing name pattern"); }
// 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);
}
}
|
64,568 |
Bug 64568 Wildcarding in ITDs needs clearer compiler error message.
|
If a user attempts to define an ITD using a type pattern (illegal since AspectJ 1.1) they get back a compiler error message of the following form :- MyAspect.java:4 error Syntax error on token "*", around expected public String foo.bar.*.name; A clearer error message informing the user of their use of illegal syntax would help.
|
resolved fixed
|
5e9aca9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-19T12:43:13Z | 2004-05-28T16:00:00Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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 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 *)");
}
// 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);
}
}
|
91,114 |
Bug 91114 [jdt-parser] Parser error on System.out.printf("..." + (after-before) + "...")
|
Following code fragment: ***************************** class Foo { public void bar () { long before = 0; long after = 0; System.out.println("... " + (before - after) + " ..."); } } ***************************** leads to following parser error ***************************** [...].java:25 [error] Syntax error on token "-", invalid AssignmentOperator System.out.println("... " + (before - after) + " ..."); ***************************** Problems seems to vanish when I rename the before variable.
|
resolved fixed
|
169a488
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-19T13:50:20Z | 2005-04-12T12:46:40Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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 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 testNoBeforeReturningAdvice() {
runTest("before returning advice not allowed!");
}
// 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);
}
}
|
78,261 |
Bug 78261 field pattern with "void" type should be compile-time error
|
We really should barf early on get(void i) as opposed to just compiling through and treating it as something that'll never match. I rated this as minor since this is just an error message issue.
|
resolved fixed
|
2b23e91
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-19T14:47:59Z | 2004-11-10T07:00:00Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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 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!");
}
// 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);
}
}
|
86,057 |
Bug 86057 expect error when overriding final pointcuts
|
I get no compiler error when I "override"/redefine a final pointcut: ------------ public class Main { static void walk() {} static void run() {} public static void main(String[] args) { walk(); run(); } } abstract aspect AA { public final pointcut publicPointcut() : call(void walk()); before() : publicPointcut() { System.out.print("here: " + thisJoinPoint); } } aspect AA1 extends AA { // expecting error here b/c pointcut is final public pointcut publicPointcut() : call(void run()); } ------------ When run, it picks out run() rather than walk().
|
resolved fixed
|
86ce1f7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-19T16:51:30Z | 2005-02-21T21:06:40Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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 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");
}
// 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);
}
}
|
86,057 |
Bug 86057 expect error when overriding final pointcuts
|
I get no compiler error when I "override"/redefine a final pointcut: ------------ public class Main { static void walk() {} static void run() {} public static void main(String[] args) { walk(); run(); } } abstract aspect AA { public final pointcut publicPointcut() : call(void walk()); before() : publicPointcut() { System.out.print("here: " + thisJoinPoint); } } aspect AA1 extends AA { // expecting error here b/c pointcut is final public pointcut publicPointcut() : call(void run()); } ------------ When run, it picks out run() rather than walk().
|
resolved fixed
|
86ce1f7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-19T16:51:30Z | 2005-02-21T21:06:40Z |
weaver/src/org/aspectj/weaver/ResolvedType.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.PerClause;
public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement {
private static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0];
public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P";
private ResolvedType[] resolvedTypeParams;
protected World world;
protected ResolvedType(String signature, World world) {
super(signature);
this.world = world;
}
protected ResolvedType(String signature, String signatureErasure, World world) {
super(signature,signatureErasure);
this.world = world;
}
// ---- things that don't require a world
/**
* Returns an iterator through ResolvedType objects representing all the direct
* supertypes of this type. That is, through the superclass, if any, and
* all declared interfaces.
*/
public final Iterator getDirectSupertypes() {
Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces());
ResolvedType superclass = getSuperclass();
if (superclass == null) {
return ifacesIterator;
} else {
return Iterators.snoc(ifacesIterator, superclass);
}
}
public abstract ResolvedMember[] getDeclaredFields();
public abstract ResolvedMember[] getDeclaredMethods();
public abstract ResolvedType[] getDeclaredInterfaces();
public abstract ResolvedMember[] getDeclaredPointcuts();
/**
* Returns a ResolvedType object representing the superclass of this type, or null.
* If this represents a java.lang.Object, a primitive type, or void, this
* method returns null.
*/
public abstract ResolvedType getSuperclass();
/**
* Returns the modifiers for this type.
*
* See {@link java.lang.Class#getModifiers()} for a description
* of the weirdness of this methods on primitives and arrays.
*
* @param world the {@link World} in which the lookup is made.
* @return an int representing the modifiers for this type
* @see java.lang.reflect.Modifier
*/
public abstract int getModifiers();
public ResolvedType[] getAnnotationTypes() {
return EMPTY_RESOLVED_TYPE_ARRAY;
}
public final UnresolvedType getSuperclass(World world) {
return getSuperclass();
}
// This set contains pairs of types whose signatures are concatenated
// together, this means with a fast lookup we can tell if two types
// are equivalent.
static Set validBoxing = new HashSet();
static {
validBoxing.add("Ljava/lang/Byte;B");
validBoxing.add("Ljava/lang/Character;C");
validBoxing.add("Ljava/lang/Double;D");
validBoxing.add("Ljava/lang/Float;F");
validBoxing.add("Ljava/lang/Integer;I");
validBoxing.add("Ljava/lang/Long;J");
validBoxing.add("Ljava/lang/Short;S");
validBoxing.add("Ljava/lang/Boolean;Z");
validBoxing.add("BLjava/lang/Byte;");
validBoxing.add("CLjava/lang/Character;");
validBoxing.add("DLjava/lang/Double;");
validBoxing.add("FLjava/lang/Float;");
validBoxing.add("ILjava/lang/Integer;");
validBoxing.add("JLjava/lang/Long;");
validBoxing.add("SLjava/lang/Short;");
validBoxing.add("ZLjava/lang/Boolean;");
}
// utilities
public ResolvedType getResolvedComponentType() {
return null;
}
public World getWorld() {
return world;
}
// ---- things from object
public final boolean equals(Object other) {
if (other instanceof ResolvedType) {
return this == other;
} else {
return super.equals(other);
}
}
// ---- difficult things
/**
* returns an iterator through all of the fields of this type, in order
* for checking from JVM spec 2ed 5.4.3.2. This means that the order is
*
* <ul><li> fields from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
*
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getFields() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterators.Getter fieldGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedType)o).getDeclaredFields());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
fieldGetter);
}
/**
* returns an iterator through all of the methods of this type, in order
* for checking from JVM spec 2ed 5.4.3.3. This means that the order is
*
* <ul><li> methods from current class </li>
* <li> recur into superclass, all the way up, not touching interfaces </li>
* <li> recur into all superinterfaces, in some unspecified order </li>
* </ul>
*
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
* NOTE: Take a look at the javadoc on getMethodsWithoutIterator() to see if
* you are sensitive to a quirk in getMethods()
*/
public Iterator getMethods() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter ifaceGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
Iterators.array(((ResolvedType)o).getDeclaredInterfaces())
);
}
};
Iterators.Getter methodGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedType)o).getDeclaredMethods());
}
};
return
Iterators.mapOver(
Iterators.append(
new Iterator() {
ResolvedType curr = ResolvedType.this;
public boolean hasNext() {
return curr != null;
}
public Object next() {
ResolvedType ret = curr;
curr = curr.getSuperclass();
return ret;
}
public void remove() {
throw new UnsupportedOperationException();
}
},
Iterators.recur(this, ifaceGetter)),
methodGetter);
}
/**
* Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those declared
* on the superinterfaces. The getMethods() call above doesn't quite work the same as it will (through the iterator) return methods
* declared on *this* class twice, once at the start and once at the end - I couldn't debug that problem, so created this alternative.
*/
public List getMethodsWithoutIterator(boolean includeITDs) {
List methods = new ArrayList();
Set knowninterfaces = new HashSet();
addAndRecurse(knowninterfaces,methods,this,includeITDs);
return methods;
}
private void addAndRecurse(Set knowninterfaces,List collector, ResolvedType rtx, boolean includeITDs) {
collector.addAll(Arrays.asList(rtx.getDeclaredMethods())); // Add the methods declared on this type
// now add all the inter-typed members too
if (includeITDs && rtx.interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
ResolvedMember rm = tm.getSignature();
if (rm != null) { // new parent type munger can have null signature...
collector.add(tm.getSignature());
}
}
}
if (!rtx.equals(ResolvedType.OBJECT)) addAndRecurse(knowninterfaces,collector,rtx.getSuperclass(),includeITDs); // Recurse if we aren't at the top
ResolvedType[] interfaces = rtx.getDeclaredInterfaces(); // Go through the interfaces on the way back down
for (int i = 0; i < interfaces.length; i++) {
ResolvedType iface = interfaces[i];
if (!knowninterfaces.contains(iface)) { // Dont do interfaces more than once
knowninterfaces.add(iface);
addAndRecurse(knowninterfaces,collector,iface,includeITDs);
}
}
}
public ResolvedType[] getResolvedTypeParameters() {
if (resolvedTypeParams == null) {
resolvedTypeParams = world.resolve(typeParameters);
}
return resolvedTypeParams;
}
/**
* described in JVM spec 2ed 5.4.3.2
*/
public ResolvedMember lookupField(Member m) {
return lookupMember(m, getFields());
}
/**
* described in JVM spec 2ed 5.4.3.3.
* Doesnt check ITDs.
*/
public ResolvedMember lookupMethod(Member m) {
return lookupMember(m, getMethods());
}
public ResolvedMember lookupMethodInITDs(Member m) {
if (interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
if (matches(tm.getSignature(), m)) {
return tm.getSignature();
}
}
}
return null;
}
/** return null if not found */
private ResolvedMember lookupMember(Member m, Iterator i) {
while (i.hasNext()) {
ResolvedMember f = (ResolvedMember) i.next();
if (matches(f, m)) return f;
}
return null; //ResolvedMember.Missing;
//throw new BCException("can't find " + m);
}
/** return null if not found */
private ResolvedMember lookupMember(Member m, ResolvedMember[] a) {
for (int i = 0; i < a.length; i++) {
ResolvedMember f = a[i];
if (matches(f, m)) return f;
}
return null;
}
/**
* Looks for the first member in the hierarchy matching aMember. This method
* differs from lookupMember(Member) in that it takes into account parameters
* which are type variables - which clearly an unresolved Member cannot do since
* it does not know anything about type variables.
*/
public ResolvedMember lookupResolvedMember(ResolvedMember aMember) {
Iterator toSearch = null;
ResolvedMember found = null;
if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) {
toSearch = getMethodsWithoutIterator(true).iterator();
} else {
if (aMember.getKind() != Member.FIELD)
throw new IllegalStateException("I didn't know you would look for members of kind " + aMember.getKind());
toSearch = getFields();
}
while(toSearch.hasNext()) {
ResolvedMemberImpl candidate = (ResolvedMemberImpl) toSearch.next();
if (candidate.matches(aMember)) {
found = candidate;
break;
}
}
return found;
}
public static boolean matches(Member m1, Member m2) {
if (m1 == null) return m2 == null;
if (m2 == null) return false;
// Check the names
boolean equalNames = m1.getName().equals(m2.getName());
if (!equalNames) return false;
// Check the signatures
boolean equalSignatures = m1.getSignature().equals(m2.getSignature());
if (equalSignatures) return true;
// If they aren't the same, we need to allow for covariance ... where one sig might be ()LCar; and
// the subsig might be ()LFastCar; - where FastCar is a subclass of Car
boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature());
if (equalCovariantSignatures) return true;
return false;
}
public static boolean conflictingSignature(Member m1, Member m2) {
if (m1 == null || m2 == null) return false;
if (!m1.getName().equals(m2.getName())) { return false; }
if (m1.getKind() != m2.getKind()) { return false; }
if (m1.getKind() == Member.FIELD) {
return m1.getDeclaringType().equals(m2.getDeclaringType());
} else if (m1.getKind() == Member.POINTCUT) {
return true;
}
UnresolvedType[] p1 = m1.getParameterTypes();
UnresolvedType[] p2 = m2.getParameterTypes();
int n = p1.length;
if (n != p2.length) return false;
for (int i=0; i < n; i++) {
if (!p1[i].equals(p2[i])) return false;
}
return true;
}
/**
* returns an iterator through all of the pointcuts of this type, in order
* for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is
*
* <ul><li> pointcuts from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
*
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getPointcuts() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
// same order as fields
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterators.Getter pointcutGetter = new Iterators.Getter() {
public Iterator get(Object o) {
//System.err.println("getting for " + o);
return Iterators.array(((ResolvedType)o).getDeclaredPointcuts());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
pointcutGetter);
}
public ResolvedPointcutDefinition findPointcut(String name) {
//System.err.println("looking for pointcuts " + this);
for (Iterator i = getPointcuts(); i.hasNext(); ) {
ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next();
//System.err.println(f);
if (name.equals(f.getName())) {
return f;
}
}
return null; // should we throw an exception here?
}
// all about collecting CrosscuttingMembers
//??? collecting data-structure, shouldn't really be a field
public CrosscuttingMembers crosscuttingMembers;
public CrosscuttingMembers collectCrosscuttingMembers() {
crosscuttingMembers = new CrosscuttingMembers(this);
crosscuttingMembers.setPerClause(getPerClause());
crosscuttingMembers.addShadowMungers(collectShadowMungers());
crosscuttingMembers.addTypeMungers(getTypeMungers());
//FIXME AV - skip but needed ?? or ?? crosscuttingMembers.addLateTypeMungers(getLateTypeMungers());
crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers()));
crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses());
//System.err.println("collected cc members: " + this + ", " + collectDeclares());
return crosscuttingMembers;
}
public final Collection collectDeclares(boolean includeAdviceLike) {
if (! this.isAspect() ) return Collections.EMPTY_LIST;
ArrayList ret = new ArrayList();
//if (this.isAbstract()) {
// for (Iterator i = getDeclares().iterator(); i.hasNext();) {
// Declare dec = (Declare) i.next();
// if (!dec.isAdviceLike()) ret.add(dec);
// }
//
// if (!includeAdviceLike) return ret;
if (!this.isAbstract()) {
//ret.addAll(getDeclares());
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedType ty = (ResolvedType) typeIterator.next();
//System.out.println("super: " + ty + ", " + );
for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) {
Declare dec = (Declare) i.next();
if (dec.isAdviceLike()) {
if (includeAdviceLike) ret.add(dec);
} else {
ret.add(dec);
}
}
}
}
return ret;
}
private final Collection collectShadowMungers() {
if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST;
ArrayList acc = new ArrayList();
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedType ty = (ResolvedType) typeIterator.next();
acc.addAll(ty.getDeclaredShadowMungers());
}
return acc;
}
protected boolean doesNotExposeShadowMungers() {
return false;
}
public PerClause getPerClause() { return null; }
protected Collection getDeclares() {
return Collections.EMPTY_LIST;
}
protected Collection getTypeMungers() { return Collections.EMPTY_LIST; }
protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; }
// ---- useful things
public final boolean isInterface() {
return Modifier.isInterface(getModifiers());
}
public final boolean isAbstract() {
return Modifier.isAbstract(getModifiers());
}
public boolean isClass() {
return false;
}
public boolean isAspect() {
return false;
}
public boolean isAnnotationStyleAspect() {
return false;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isEnum() {
return false;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isAnnotation() {
return false;
}
/**
* Note: Only overridden by Name subtype
*/
public void addAnnotation(AnnotationX annotationX) {
throw new RuntimeException("ResolvedType.addAnnotation() should never be called");
}
/**
* Note: Only overridden by Name subtype
*/
public AnnotationX[] getAnnotations() {
throw new RuntimeException("ResolvedType.getAnnotations() should never be called");
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isAnnotationWithRuntimeRetention() {
return false;
}
public boolean isSynthetic() {
return signature.indexOf("$ajc") != -1;
}
public final boolean isFinal() {
return Modifier.isFinal(getModifiers());
}
protected Map /*Type variable name -> UnresolvedType*/ getMemberParameterizationMap() {
if (!isParameterizedType()) return Collections.EMPTY_MAP;
TypeVariable[] tvs = getGenericType().getTypeVariables();
Map parameterizationMap = new HashMap();
for (int i = 0; i < tvs.length; i++) {
parameterizationMap.put(tvs[i].getName(), typeParameters[i]);
}
return parameterizationMap;
}
public Collection getDeclaredAdvice() {
List l = new ArrayList();
ResolvedMember[] methods = getDeclaredMethods();
if (isParameterizedType()) methods = getGenericType().getDeclaredMethods();
Map typeVariableMap = getMemberParameterizationMap();
for (int i=0, len = methods.length; i < len; i++) {
ShadowMunger munger = methods[i].getAssociatedShadowMunger();
if (munger != null) {
if (this.isParameterizedType()) {
munger.setPointcut(munger.getPointcut().parameterizeWith(typeVariableMap));
}
l.add(munger);
}
}
return l;
}
public Collection getDeclaredShadowMungers() {
Collection c = getDeclaredAdvice();
return c;
}
// ---- only for testing!
public ResolvedMember[] getDeclaredJavaFields() {
return filterInJavaVisible(getDeclaredFields());
}
public ResolvedMember[] getDeclaredJavaMethods() {
return filterInJavaVisible(getDeclaredMethods());
}
public ShadowMunger[] getDeclaredShadowMungersArray() {
List l = (List) getDeclaredShadowMungers();
return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]);
}
private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) {
List l = new ArrayList();
for (int i=0, len = ms.length; i < len; i++) {
if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) {
l.add(ms[i]);
}
}
return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]);
}
public abstract ISourceContext getSourceContext();
// ---- fields
public static final ResolvedType[] NONE = new ResolvedType[0];
public static final Primitive BYTE = new Primitive("B", 1, 0);
public static final Primitive CHAR = new Primitive("C", 1, 1);
public static final Primitive DOUBLE = new Primitive("D", 2, 2);
public static final Primitive FLOAT = new Primitive("F", 1, 3);
public static final Primitive INT = new Primitive("I", 1, 4);
public static final Primitive LONG = new Primitive("J", 2, 5);
public static final Primitive SHORT = new Primitive("S", 1, 6);
public static final Primitive VOID = new Primitive("V", 0, 8);
public static final Primitive BOOLEAN = new Primitive("Z", 1, 7);
public static final Missing MISSING = new Missing();
// ---- types
public static ResolvedType makeArray(ResolvedType type, int dim) {
if (dim == 0) return type;
ResolvedType array = new Array("[" + type.getSignature(),type.getWorld(),type);
return makeArray(array,dim-1);
}
static class Array extends ResolvedType {
ResolvedType componentType;
Array(String s, World world, ResolvedType componentType) {
super(s, world);
this.componentType = componentType;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
// ??? should this return clone? Probably not...
// If it ever does, here is the code:
// ResolvedMember cloneMethod =
// new ResolvedMember(Member.METHOD,this,Modifier.PUBLIC,UnresolvedType.OBJECT,"clone",new UnresolvedType[]{});
// return new ResolvedMember[]{cloneMethod};
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return
new ResolvedType[] {
world.getCoreType(CLONEABLE),
world.getCoreType(SERIALIZABLE)
};
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final ResolvedType getSuperclass() {
return world.getCoreType(OBJECT);
}
public final boolean isAssignableFrom(ResolvedType o) {
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitiveType()) {
return o.equals(this);
} else {
return getComponentType().resolve(world).isAssignableFrom(o.getComponentType().resolve(world));
}
}
public final boolean isCoerceableFrom(ResolvedType o) {
if (o.equals(UnresolvedType.OBJECT) ||
o.equals(UnresolvedType.SERIALIZABLE) ||
o.equals(UnresolvedType.CLONEABLE)) {
return true;
}
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitiveType()) {
return o.equals(this);
} else {
return getComponentType().resolve(world).isCoerceableFrom(o.getComponentType().resolve(world));
}
}
public final int getModifiers() {
int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
return (componentType.getModifiers() & mask) | Modifier.FINAL;
}
public UnresolvedType getComponentType() {
return componentType;
}
public ResolvedType getResolvedComponentType() {
return componentType;
}
public ISourceContext getSourceContext() {
return getResolvedComponentType().getSourceContext();
}
}
static class Primitive extends ResolvedType {
private int size;
private int index;
Primitive(String signature, int size, int index) {
super(signature, null);
this.size = size;
this.index = index;
}
public final int getSize() {
return size;
}
public final int getModifiers() {
return Modifier.PUBLIC | Modifier.FINAL;
}
public final boolean isPrimitiveType() {
return true;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final boolean isAssignableFrom(ResolvedType other) {
if (!other.isPrimitiveType()) {
if (!world.isInJava5Mode()) return false;
return validBoxing.contains(this.getSignature()+other.getSignature());
}
return assignTable[((Primitive)other).index][index];
}
public final boolean isCoerceableFrom(ResolvedType other) {
if (this == other) return true;
if (! other.isPrimitiveType()) return false;
if (index > 6 || ((Primitive)other).index > 6) return false;
return true;
}
public ResolvedType resolve(World world) {
this.world = world;
return super.resolve(world);
}
public final boolean needsNoConversionFrom(ResolvedType other) {
if (! other.isPrimitiveType()) return false;
return noConvertTable[((Primitive)other).index][index];
}
private static final boolean[][] assignTable =
{// to: B C D F I J S V Z from
{ true , true , true , true , true , true , true , false, false }, // B
{ false, true , true , true , true , true , false, false, false }, // C
{ false, false, true , false, false, false, false, false, false }, // D
{ false, false, true , true , false, false, false, false, false }, // F
{ false, false, true , true , true , true , false, false, false }, // I
{ false, false, true , true , false, true , false, false, false }, // J
{ false, false, true , true , true , true , true , false, false }, // S
{ false, false, false, false, false, false, false, true , false }, // V
{ false, false, false, false, false, false, false, false, true }, // Z
};
private static final boolean[][] noConvertTable =
{// to: B C D F I J S V Z from
{ true , true , false, false, true , false, true , false, false }, // B
{ false, true , false, false, true , false, false, false, false }, // C
{ false, false, true , false, false, false, false, false, false }, // D
{ false, false, false, true , false, false, false, false, false }, // F
{ false, false, false, false, true , false, false, false, false }, // I
{ false, false, false, false, false, true , false, false, false }, // J
{ false, false, false, false, true , false, true , false, false }, // S
{ false, false, false, false, false, false, false, true , false }, // V
{ false, false, false, false, false, false, false, false, true }, // Z
};
// ----
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return ResolvedType.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedType getSuperclass() {
return null;
}
public ISourceContext getSourceContext() {
return null;
}
}
static class Missing extends ResolvedType {
Missing() {
super(MISSING_NAME, null);
}
// public final String toString() {
// return "<missing>";
// }
public final String getName() {
return MISSING_NAME;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return ResolvedType.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedType getSuperclass() {
return null;
}
public final int getModifiers() {
return 0;
}
public final boolean isAssignableFrom(ResolvedType other) {
return false;
}
public final boolean isCoerceableFrom(ResolvedType other) {
return false;
}
public boolean needsNoConversionFrom(ResolvedType other) {
return false;
}
public ISourceContext getSourceContext() {
return null;
}
}
/**
* Look up a member, takes into account any ITDs on this type.
* return null if not found */
public ResolvedMember lookupMemberNoSupers(Member member) {
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = lookupMember(member, getDeclaredFields());
} else {
// assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR
ret = lookupMember(member, getDeclaredMethods());
}
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;
}
protected List interTypeMungers = new ArrayList(0);
public List getInterTypeMungers() {
return interTypeMungers;
}
public List getInterTypeParentMungers() {
List l = new ArrayList();
for (Iterator iter = interTypeMungers.iterator(); iter.hasNext();) {
ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next();
if (element.getMunger() instanceof NewParentTypeMunger) l.add(element);
}
return l;
}
/**
* ??? This method is O(N*M) where N = number of methods and M is number of
* inter-type declarations in my super
*/
public List getInterTypeMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeMungers(ret);
return ret;
}
public List getInterTypeParentMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeParentMungers(ret);
return ret;
}
private void collectInterTypeParentMungers(List collector) {
for (Iterator iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedType superType = (ResolvedType) iter.next();
superType.collectInterTypeParentMungers(collector);
}
collector.addAll(getInterTypeParentMungers());
}
private void collectInterTypeMungers(List collector) {
for (Iterator iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedType superType = (ResolvedType) iter.next();
superType.collectInterTypeMungers(collector);
}
outer: for (Iterator iter1 = collector.iterator(); iter1.hasNext(); ) {
ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next();
if ( superMunger.getSignature() == null) continue;
if ( !superMunger.getSignature().isAbstract()) continue;
for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) {
ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next();
if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
if (!superMunger.getSignature().isPublic()) continue;
for (Iterator iter = getMethods(); iter.hasNext(); ) {
ResolvedMember method = (ResolvedMember)iter.next();
if (conflictingSignature(method, superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
}
collector.addAll(getInterTypeMungers());
}
/**
* Check:
* 1) That we don't have any abstract type mungers unless this type is abstract.
* 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794)
*/
public void checkInterTypeMungers() {
if (isAbstract()) return;
boolean itdProblem = false;
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next();
itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2
}
if (itdProblem) return; // If the rules above are broken, return right now
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next();
if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1
world.getMessageHandler().handleMessage(
new Message("must implement abstract inter-type declaration: " + munger.getSignature(),
"", IMessage.ERROR, getSourceLocation(), null,
new ISourceLocation[] { getMungerLocation(munger) }));
}
}
}
/**
* See PR70794. This method checks that if an abstract inter-type method declaration is made on
* an interface then it must also be public.
* This is a compiler limitation that could be made to work in the future (if someone
* provides a worthwhile usecase)
*
* @return indicates if the munger failed the check
*/
private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) {
if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) {
ResolvedMember itdMember = munger.getSignature();
ResolvedType onType = itdMember.getDeclaringType().resolve(world);
if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) {
world.getMessageHandler().handleMessage(
new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"",
Message.ERROR,getSourceLocation(),null,
new ISourceLocation[]{getMungerLocation(munger)})
);
return true;
}
}
return false;
}
/**
* Get a source location for the munger.
* Until intertype mungers remember where they came from, the source location
* for the munger itself is null. In these cases use the
* source location for the aspect containing the ITD.
*
*/
private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) {
ISourceLocation sloc = munger.getSourceLocation();
if (sloc == null) {
sloc = munger.getAspectType().getSourceLocation();
}
return sloc;
}
/**
* Returns a ResolvedType object representing the declaring type of this type, or
* null if this type does not represent a non-package-level-type.
*
* <strong>Warning</strong>: This is guaranteed to work for all member types.
* For anonymous/local types, the only guarantee is given in JLS 13.1, where
* it guarantees that if you call getDeclaringType() repeatedly, you will eventually
* get the top-level class, but it does not say anything about classes in between.
*
* @return the declaring UnresolvedType object, or null.
*/
public ResolvedType getDeclaringType() {
if (isArray()) return null;
String name = getName();
int lastDollar = name.lastIndexOf('$');
while (lastDollar != -1) {
ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true);
if (ret != ResolvedType.MISSING) return ret;
lastDollar = name.lastIndexOf('$', lastDollar-1);
}
return null;
}
public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) {
//System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType);
if (Modifier.isPublic(modifiers)) {
return true;
} else if (Modifier.isPrivate(modifiers)) {
return targetType.getOutermostType().equals(fromType.getOutermostType());
} else if (Modifier.isProtected(modifiers)) {
return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType);
} else { // package-visible
return samePackage(targetType, fromType);
}
}
public static boolean hasBridgeModifier(int modifiers) {
return (modifiers & Constants.ACC_BRIDGE)!=0;
}
private static boolean samePackage(
ResolvedType targetType,
ResolvedType fromType)
{
String p1 = targetType.getPackageName();
String p2 = fromType.getPackageName();
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
public void addInterTypeMunger(ConcreteTypeMunger munger) {
ResolvedMember sig = munger.getSignature();
if (sig == null || munger.getMunger() == null ||
munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess)
{
interTypeMungers.add(munger);
return;
}
//System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers);
if (sig.getKind() == Member.METHOD) {
if (!compareToExistingMembers(munger, getMethods())) return;
if (this.isInterface()) {
if (!compareToExistingMembers(munger,
Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return;
}
} else if (sig.getKind() == Member.FIELD) {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return;
} else {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return;
}
// now compare to existingMungers
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next();
if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) {
//System.err.println("match " + munger + " with " + existingMunger);
if (isVisible(munger.getSignature().getModifiers(),
munger.getAspectType(), existingMunger.getAspectType()))
{
//System.err.println(" is visible");
int c = compareMemberPrecedence(sig, existingMunger.getSignature());
if (c == 0) {
c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType());
}
//System.err.println(" compare: " + c);
if (c < 0) {
// the existing munger dominates the new munger
checkLegalOverride(munger.getSignature(), existingMunger.getSignature());
return;
} else if (c > 0) {
// the new munger dominates the existing one
checkLegalOverride(existingMunger.getSignature(), munger.getSignature());
i.remove();
break;
} else {
interTypeConflictError(munger, existingMunger);
interTypeConflictError(existingMunger, munger);
return;
}
}
}
}
//System.err.println("adding: " + munger + " to " + this);
interTypeMungers.add(munger);
}
//??? returning too soon
private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) {
ResolvedMember sig = munger.getSignature();
while (existingMembers.hasNext()) {
ResolvedMember existingMember = (ResolvedMember)existingMembers.next();
//System.err.println("Comparing munger: "+sig+" with member "+existingMember);
if (conflictingSignature(existingMember, munger.getSignature())) {
//System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger);
//System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation());
if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) {
int c = compareMemberPrecedence(sig, existingMember);
//System.err.println(" c: " + c);
if (c < 0) {
// existingMember dominates munger
checkLegalOverride(munger.getSignature(), existingMember);
return false;
} else if (c > 0) {
// munger dominates existingMember
checkLegalOverride(existingMember, munger.getSignature());
//interTypeMungers.add(munger);
//??? might need list of these overridden abstracts
continue;
} else {
//XXX dual errors possible if (this instanceof BcelObjectType) return false; //XXX ignores separate comp
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
*/
public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) {
//System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType());
if (!parent.getReturnType().equals(child.getReturnType())) {
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;
}
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);
} else if (child.isStatic() && !parent.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent),
child.getSourceLocation(),null);
}
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;
}
}
return null;
}
public void clearInterTypeMungers() {
if (isRawType()) getGenericType().clearInterTypeMungers();
interTypeMungers = new ArrayList();
}
public boolean isTopmostImplementor(ResolvedType interfaceType) {
if (isInterface()) return false;
if (!interfaceType.isAssignableFrom(this)) return false;
// check that I'm truly the topmost implementor
if (interfaceType.isAssignableFrom(this.getSuperclass())) {
return false;
}
return true;
}
public ResolvedType getTopmostImplementor(ResolvedType interfaceType) {
if (isInterface()) return null;
if (!interfaceType.isAssignableFrom(this)) return null;
// Check if my super class is an implementor?
ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType);
if (higherType!=null) return higherType;
return this;
}
private ResolvedType findHigher(ResolvedType other) {
if (this == other) return this;
for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) {
ResolvedType rtx = (ResolvedType)i.next();
boolean b = this.isAssignableFrom(rtx);
if (b) return rtx;
}
return null;
}
public List getExposedPointcuts() {
List ret = new ArrayList();
if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts());
for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) {
ResolvedType t = (ResolvedType)i.next();
addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false);
}
addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true);
for (Iterator i = ret.iterator(); i.hasNext(); ) {
ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next();
// System.err.println("looking at: " + inherited + " in " + this);
// System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract());
if (inherited.isAbstract()) {
if (!this.isAbstract()) {
getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()),
inherited.getSourceLocation(), this.getSourceLocation());
}
}
}
return ret;
}
private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) {
for (Iterator i = added.iterator(); i.hasNext();) {
ResolvedPointcutDefinition toAdd =
(ResolvedPointcutDefinition) i.next();
//System.err.println("adding: " + toAdd);
for (Iterator j = acc.iterator(); j.hasNext();) {
ResolvedPointcutDefinition existing =
(ResolvedPointcutDefinition) j.next();
if (existing == toAdd) continue;
if (!isVisible(existing.getModifiers(),
existing.getDeclaringType().resolve(getWorld()),
this)) {
continue;
}
if (conflictingSignature(existing, toAdd)) {
if (isOverriding) {
checkLegalOverride(existing, toAdd);
j.remove();
} else {
getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()),
existing.getSourceLocation(),
toAdd.getSourceLocation());
j.remove();
}
}
}
acc.add(toAdd);
}
}
public ISourceLocation getSourceLocation() { return null; }
public boolean isExposedToWeaver() { return false; }
public WeaverStateInfo getWeaverState() {
return null;
}
/**
* Overridden by ReferenceType to return a sensible answer for parameterized and raw types.
* @return
*/
public ResolvedType getGenericType() {
if (!(isParameterizedType() || isRawType()))
throw new BCException("The type "+getBaseName()+" is not parameterized or raw - it has no generic type");
return null;
}
public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) {
if (!(isGenericType() || isParameterizedType())) return this;
return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld());
}
/**
* Iff I am a parameterized type, and any of my parameters are type variable
* references, return a version with those type parameters replaced in accordance
* with the passed bindings.
*/
public UnresolvedType parameterize(Map typeBindings) {
if (!isParameterizedType()) throw new IllegalStateException("Can't parameterize a type that is not a parameterized type");
boolean workToDo = false;
for (int i = 0; i < typeParameters.length; i++) {
if (typeParameters[i].isTypeVariableReference()) {
workToDo = true;
}
}
if (!workToDo) {
return this;
} else {
UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length];
for (int i = 0; i < newTypeParams.length; i++) {
newTypeParams[i] = typeParameters[i];
if (newTypeParams[i].isTypeVariableReference()) {
TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i];
UnresolvedType binding = (UnresolvedType) typeBindings.get(tvrt.getTypeVariable().getName());
if (binding != null) newTypeParams[i] = binding;
}
}
return TypeFactory.createParameterizedType(getGenericType(), newTypeParams, getWorld());
}
}
public boolean hasParameterizedSuperType() {
getParameterizedSuperTypes();
return parameterizedSuperTypes.length > 0;
}
public boolean hasGenericSuperType() {
ResolvedType[] superTypes = getDeclaredInterfaces();
for (int i = 0; i < superTypes.length; i++) {
if (superTypes[i].isGenericType()) return true;
}
return false;
}
private ResolvedType[] parameterizedSuperTypes = null;
/**
* Similar to the above method, but accumulates the super types
* @return
*/
public ResolvedType[] getParameterizedSuperTypes() {
if (parameterizedSuperTypes != null) return parameterizedSuperTypes;
List accumulatedTypes = new ArrayList();
accumulateParameterizedSuperTypes(this,accumulatedTypes);
ResolvedType[] ret = new ResolvedType[accumulatedTypes.size()];
parameterizedSuperTypes = (ResolvedType[]) accumulatedTypes.toArray(ret);
return parameterizedSuperTypes;
}
private void accumulateParameterizedSuperTypes(ResolvedType forType, List parameterizedTypeList) {
if (forType.isParameterizedType()) {
parameterizedTypeList.add(forType);
}
if (forType.getSuperclass() != null) {
accumulateParameterizedSuperTypes(forType.getSuperclass(), parameterizedTypeList);
}
ResolvedType[] interfaces = forType.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
accumulateParameterizedSuperTypes(interfaces[i], parameterizedTypeList);
}
}
/**
* Types may have pointcuts just as they have methods and fields.
*/
public ResolvedPointcutDefinition findPointcut(String name, World world) {
throw new UnsupportedOperationException("Not yet implemenented");
}
/**
* Determines if variables of this type could be assigned values of another
* with lots of help.
* java.lang.Object is convertable from all types.
* A primitive type is convertable from X iff it's assignable from X.
* A reference type is convertable from X iff it's coerceable from X.
* In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y
* could be assignable to a variable of type X without loss of precision.
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other with possible conversion
*/
public final boolean isConvertableFrom(ResolvedType other) {
// // version from TypeX
// if (this.equals(OBJECT)) return true;
// if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other);
// return this.isCoerceableFrom(other);
//
// version from ResolvedTypeX
if (this.equals(OBJECT)) return true;
if (world.isInJava5Mode()) {
if (this.isPrimitiveType()^other.isPrimitiveType()) { // If one is primitive and the other isnt
if (validBoxing.contains(this.getSignature()+other.getSignature())) return true;
}
}
if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other);
return this.isCoerceableFrom(other);
}
/**
* Determines if the variables of this type could be assigned values
* of another type without casting. This still allows for assignment conversion
* as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER).
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other without casting
* @exception NullPointerException if other is null
*/
public abstract boolean isAssignableFrom(ResolvedType other);
/**
* Determines if values of another type could possibly be cast to
* this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion".
*
* <p> This method should be commutative, i.e., for all UnresolvedType a, b and all World w:
*
* <blockquote><pre>
* a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w)
* </pre></blockquote>
*
* @param other the other type
* @param world the {@link World} in which the possible coersion should be checked.
* @return true iff values of other could possibly be cast to this type.
* @exception NullPointerException if other is null.
*/
public abstract boolean isCoerceableFrom(ResolvedType other);
public boolean needsNoConversionFrom(ResolvedType o) {
return isAssignableFrom(o);
}
/**
* Implemented by ReferenceTypes
*/
public String getSignatureForAttribute() {
throw new RuntimeException("Cannot ask this type "+this+" for a generic sig attribute");
}
private FuzzyBoolean parameterizedWithAMemberTypeVariable = FuzzyBoolean.MAYBE;
/**
* return true if the parameterization of this type includes a member type variable. Member
* type variables occur in generic methods/ctors.
*/
public boolean isParameterizedWithAMemberTypeVariable() {
// MAYBE means we haven't worked it out yet...
if (parameterizedWithAMemberTypeVariable==FuzzyBoolean.MAYBE) {
// if there are no type parameters then we cant be...
if (typeParameters==null || typeParameters.length==0) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.NO;
return false;
}
for (int i = 0; i < typeParameters.length; i++) {
UnresolvedType aType = (ResolvedType)typeParameters[i];
if (aType.isTypeVariableReference() && ((TypeVariableReference)aType).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
if (aType.isParameterizedType()) {
boolean b = aType.isParameterizedWithAMemberTypeVariable();
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
}
if (aType.isGenericWildcard()) {
if (aType.isExtends()) {
boolean b = false;
UnresolvedType upperBound = aType.getUpperBound();
if (upperBound.isParameterizedType()) {
b = upperBound.isParameterizedWithAMemberTypeVariable();
} else if (upperBound.isTypeVariableReference() && ((TypeVariableReference)upperBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) {
b = true;
}
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
// FIXME asc need to check additional interface bounds
}
if (aType.isSuper()) {
boolean b = false;
UnresolvedType lowerBound = aType.getLowerBound();
if (lowerBound.isParameterizedType()) {
b = lowerBound.isParameterizedWithAMemberTypeVariable();
} else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference)lowerBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) {
b = true;
}
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
}
}
}
parameterizedWithAMemberTypeVariable=FuzzyBoolean.NO;
}
return parameterizedWithAMemberTypeVariable.alwaysTrue();
}
}
|
86,057 |
Bug 86057 expect error when overriding final pointcuts
|
I get no compiler error when I "override"/redefine a final pointcut: ------------ public class Main { static void walk() {} static void run() {} public static void main(String[] args) { walk(); run(); } } abstract aspect AA { public final pointcut publicPointcut() : call(void walk()); before() : publicPointcut() { System.out.print("here: " + thisJoinPoint); } } aspect AA1 extends AA { // expecting error here b/c pointcut is final public pointcut publicPointcut() : call(void run()); } ------------ When run, it picks out run() rather than walk().
|
resolved fixed
|
86ce1f7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-19T16:51:30Z | 2005-02-21T21:06:40Z |
weaver/src/org/aspectj/weaver/WeaverMessages.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.weaver;
import java.text.MessageFormat;
import java.util.ResourceBundle;
public class WeaverMessages {
private static ResourceBundle bundle = ResourceBundle.getBundle("org.aspectj.weaver.weaver-messages");
public static final String ARGS_IN_DECLARE = "argsInDeclare";
public static final String CFLOW_IN_DECLARE = "cflowInDeclare";
public static final String IF_IN_DECLARE = "ifInDeclare";
public static final String THIS_OR_TARGET_IN_DECLARE = "thisOrTargetInDeclare";
public static final String ABSTRACT_POINTCUT = "abstractPointcut";
public static final String POINCUT_NOT_CONCRETE = "abstractPointcutNotMadeConcrete";
public static final String CONFLICTING_INHERITED_POINTCUTS = "conflictingInheritedPointcuts";
public static final String CIRCULAR_POINTCUT = "circularPointcutDeclaration";
public static final String CANT_FIND_POINTCUT = "cantFindPointcut";
public static final String EXACT_TYPE_PATTERN_REQD = "exactTypePatternRequired";
public static final String CANT_BIND_TYPE = "cantBindType";
public static final String WILDCARD_NOT_ALLOWED = "wildcardTypePatternNotAllowed";
public static final String FIELDS_CANT_HAVE_VOID_TYPE = "fieldCantBeVoid";
public static final String DECP_OBJECT = "decpObject";
public static final String CANT_EXTEND_SELF="cantExtendSelf";
public static final String INTERFACE_CANT_EXTEND_CLASS="interfaceExtendClass";
public static final String DECP_HIERARCHY_ERROR = "decpHierarchy";
public static final String MULTIPLE_MATCHES_IN_PRECEDENCE = "multipleMatchesInPrecedence";
public static final String TWO_STARS_IN_PRECEDENCE = "circularityInPrecedenceStar";
public static final String CLASSES_IN_PRECEDENCE = "nonAspectTypesInPrecedence";
public static final String TWO_PATTERN_MATCHES_IN_PRECEDENCE = "circularityInPrecedenceTwo";
public static final String NOT_THROWABLE = "notThrowable";
public static final String ITD_CONS_ON_ASPECT = "itdConsOnAspect";
public static final String ITD_RETURN_TYPE_MISMATCH = "returnTypeMismatch";
public static final String ITD_PARAM_TYPE_MISMATCH = "paramTypeMismatch";
public static final String ITD_VISIBILITY_REDUCTION = "visibilityReduction";
public static final String ITD_DOESNT_THROW = "doesntThrow";
public static final String ITD_OVERRIDDEN_STATIC = "overriddenStatic";
public static final String ITD_OVERIDDING_STATIC = "overridingStatic";
public static final String ITD_CONFLICT = "itdConflict";
public static final String ITD_MEMBER_CONFLICT = "itdMemberConflict";
public static final String ITD_NON_EXPOSED_IMPLEMENTOR = "itdNonExposedImplementor";
public static final String ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE = "itdAbstractMustBePublicOnInterface";
public static final String NON_VOID_RETURN = "nonVoidReturn";
public static final String INCOMPATIBLE_RETURN_TYPE="incompatibleReturnType";
public static final String CANT_THROW_CHECKED = "cantThrowChecked";
public static final String CIRCULAR_DEPENDENCY = "circularDependency";
public static final String MISSING_PER_CLAUSE = "missingPerClause";
public static final String WRONG_PER_CLAUSE = "wrongPerClause";
public static final String ALREADY_WOVEN = "alreadyWoven";
public static final String REWEAVABLE_MODE = "reweavableMode";
public static final String PROCESSING_REWEAVABLE = "processingReweavable";
public static final String MISSING_REWEAVABLE_TYPE = "missingReweavableType";
public static final String VERIFIED_REWEAVABLE_TYPE = "verifiedReweavableType";
public static final String ASPECT_NEEDED = "aspectNeeded";
public static final String CANT_FIND_TYPE = "cantFindType";
public static final String CANT_FIND_CORE_TYPE = "cantFindCoreType";
public static final String CANT_FIND_TYPE_WITHINPCD = "cantFindTypeWithinpcd";
public static final String CANT_FIND_TYPE_DURING_AROUND_WEAVE = "cftDuringAroundWeave";
public static final String CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT = "cftDuringAroundWeavePreinit";
public static final String CANT_FIND_TYPE_EXCEPTION_TYPE = "cftExceptionType";
public static final String CANT_FIND_TYPE_ARG_TYPE = "cftArgType";
public static final String DECP_BINARY_LIMITATION = "decpBinaryLimitation";
public static final String OVERWRITE_JSR45 = "overwriteJSR45";
public static final String IF_IN_PERCLAUSE = "ifInPerClause";
public static final String IF_LEXICALLY_IN_CFLOW = "ifLexicallyInCflow";
public static final String ONLY_BEFORE_ON_HANDLER = "onlyBeforeOnHandler";
public static final String AROUND_ON_PREINIT = "aroundOnPreInit";
public static final String AROUND_ON_INIT = "aroundOnInit";
public static final String AROUND_ON_INTERFACE_STATICINIT = "aroundOnInterfaceStaticInit";
public static final String PROBLEM_GENERATING_METHOD = "problemGeneratingMethod";
public static final String CLASS_TOO_BIG = "classTooBig";
public static final String ZIPFILE_ENTRY_MISSING = "zipfileEntryMissing";
public static final String ZIPFILE_ENTRY_INVALID = "zipfileEntryInvalid";
public static final String DIRECTORY_ENTRY_MISSING = "directoryEntryMissing";
public static final String OUTJAR_IN_INPUT_PATH = "outjarInInputPath";
public static final String XLINT_LOAD_ERROR = "problemLoadingXLint";
public static final String XLINTDEFAULT_LOAD_ERROR = "unableToLoadXLintDefault";
public static final String XLINTDEFAULT_LOAD_PROBLEM = "errorLoadingXLintDefault";
public static final String XLINT_KEY_ERROR = "invalidXLintKey";
public static final String XLINT_VALUE_ERROR = "invalidXLintMessageKind";
public static final String UNBOUND_FORMAL = "unboundFormalInPC";
public static final String AMBIGUOUS_BINDING = "ambiguousBindingInPC";
public static final String AMBIGUOUS_BINDING_IN_OR = "ambiguousBindingInOrPC";
public static final String NEGATION_DOESNT_ALLOW_BINDING = "negationDoesntAllowBinding";
// Java5 messages
public static final String ITDC_ON_ENUM_NOT_ALLOWED = "itdcOnEnumNotAllowed";
public static final String ITDM_ON_ENUM_NOT_ALLOWED = "itdmOnEnumNotAllowed";
public static final String ITDF_ON_ENUM_NOT_ALLOWED = "itdfOnEnumNotAllowed";
public static final String CANT_DECP_ON_ENUM_TO_IMPL_INTERFACE = "cantDecpOnEnumToImplInterface";
public static final String CANT_DECP_ON_ENUM_TO_EXTEND_CLASS = "cantDecpOnEnumToExtendClass";
public static final String CANT_DECP_TO_MAKE_ENUM_SUPERTYPE = "cantDecpToMakeEnumSupertype";
public static final String ITDC_ON_ANNOTATION_NOT_ALLOWED = "itdcOnAnnotationNotAllowed";
public static final String ITDM_ON_ANNOTATION_NOT_ALLOWED = "itdmOnAnnotationNotAllowed";
public static final String ITDF_ON_ANNOTATION_NOT_ALLOWED = "itdfOnAnnotationNotAllowed";
public static final String CANT_DECP_ON_ANNOTATION_TO_IMPL_INTERFACE = "cantDecpOnAnnotationToImplInterface";
public static final String CANT_DECP_ON_ANNOTATION_TO_EXTEND_CLASS = "cantDecpOnAnnotationToExtendClass";
public static final String CANT_DECP_TO_MAKE_ANNOTATION_SUPERTYPE = "cantDecpToMakeAnnotationSupertype";
public static final String REFERENCE_TO_NON_ANNOTATION_TYPE = "referenceToNonAnnotationType";
public static final String BINDING_NON_RUNTIME_RETENTION_ANNOTATION = "bindingNonRuntimeRetentionAnnotation";
public static final String INCORRECT_TARGET_FOR_DECLARE_ANNOTATION = "incorrectTargetForDeclareAnnotation";
// Generics
public static final String CANT_DECP_MULTIPLE_PARAMETERIZATIONS="cantDecpMultipleParameterizations";
public static final String HANDLER_PCD_DOESNT_SUPPORT_PARAMETERS="noParameterizedTypePatternInHandler";
public static final String INCORRECT_NUMBER_OF_TYPE_ARGUMENTS = "incorrectNumberOfTypeArguments";
public static final String VIOLATES_TYPE_VARIABLE_BOUNDS = "violatesTypeVariableBounds";
public static final String NO_STATIC_INIT_JPS_FOR_PARAMETERIZED_TYPES = "noStaticInitJPsForParameterizedTypes";
public static final String NOT_A_GENERIC_TYPE="notAGenericType";
public static final String WITHIN_PCD_DOESNT_SUPPORT_PARAMETERS="noParameterizedTypePatternInWithin";
public static final String THIS_AND_TARGET_DONT_SUPPORT_PARAMETERS="noParameterizedTypesInThisAndTarget";
public static final String GET_AND_SET_DONT_SUPPORT_DEC_TYPE_PARAMETERS="noParameterizedTypesInGetAndSet";
public static final String NO_INIT_JPS_FOR_PARAMETERIZED_TYPES = "noInitJPsForParameterizedTypes";
public static final String NO_GENERIC_THROWABLES = "noGenericThrowables";
public static final String WITHINCODE_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES="noParameterizedDeclaringTypesWithinCode";
public static final String EXECUTION_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES="noParameterizedDeclaringTypesInExecution";
public static final String CALL_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES="noParameterizedDeclaringTypesInCall";
public static final String CANT_REFERENCE_POINTCUT_IN_RAW_TYPE="noRawTypePointcutReferences";
public static String format(String key) {
return bundle.getString(key);
}
public static String format(String key, Object insert) {
return MessageFormat.format(bundle.getString(key),new Object[] {insert});
}
public static String format(String key, Object insert1, Object insert2) {
return MessageFormat.format(bundle.getString(key),new Object[] {insert1,insert2});
}
public static String format(String key, Object insert1, Object insert2, Object insert3) {
return MessageFormat.format(bundle.getString(key),new Object[] {insert1, insert2, insert3});
}
public static String format(String key, Object insert1, Object insert2, Object insert3, Object insert4) {
return MessageFormat.format(bundle.getString(key),new Object[] {insert1, insert2, insert3, insert4});
}
}
|
104,529 |
Bug 104529 @SuppressWarnings( "unchecked" ) is not ignoring type safety checks
|
AJDT is ignoring the @SuppressWarnings( "unchecked" ) annotation. It is giving me a type safety warning when I don't specify the type when declaring a generic even though I have the @SuppressWarnings( "unchecked" ) annotation specified.
|
resolved fixed
|
7b32570
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-19T19:18:31Z | 2005-07-20T17: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 junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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 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");
}
// 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);
}
}
|
79,523 |
Bug 79523 BCException: illegal change to pointcut declaration: calls(<nothing>)
| null |
resolved fixed
|
93fdce1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-19T19:51:32Z | 2004-11-25T22:00:00Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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 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");
}
// 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);
}
}
|
79,523 |
Bug 79523 BCException: illegal change to pointcut declaration: calls(<nothing>)
| null |
resolved fixed
|
93fdce1
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-19T19:51:32Z | 2004-11-25T22:00:00Z |
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.Iterator;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.ast.Test;
/**
*/
//XXX needs check that arguments contains no WildTypePatterns
public class ReferencePointcut extends Pointcut {
public UnresolvedType onType;
public TypePattern onTypeSymbolic;
public String name;
public TypePatternList arguments;
/**
* if this is non-null then when the pointcut is concretized the result will be parameterized too.
*/
private Map typeVariableMap;
//public ResolvedPointcut binding;
public ReferencePointcut(TypePattern onTypeSymbolic, String name, TypePatternList arguments) {
this.onTypeSymbolic = onTypeSymbolic;
this.name = name;
this.arguments = arguments;
this.pointcutKind = REFERENCE;
}
public ReferencePointcut(UnresolvedType onType, String name, TypePatternList arguments) {
this.onType = onType;
this.name = name;
this.arguments = arguments;
this.pointcutKind = REFERENCE;
}
public Set couldMatchKinds() {
return Shadow.ALL_SHADOW_KINDS;
}
//??? do either of these match methods make any sense???
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
public FuzzyBoolean fastMatch(Class targetType) {
return FuzzyBoolean.MAYBE;
}
/**
* Do I really match this shadow?
*/
protected FuzzyBoolean matchInternal(Shadow shadow) {
return FuzzyBoolean.NO;
}
public String toString() {
StringBuffer buf = new StringBuffer();
if (onType != null) {
buf.append(onType);
buf.append(".");
// for (int i=0, len=fromType.length; i < len; i++) {
// buf.append(fromType[i]);
// buf.append(".");
// }
}
buf.append(name);
buf.append(arguments.toString());
return buf.toString();
}
public void write(DataOutputStream s) throws IOException {
//XXX ignores onType
s.writeByte(Pointcut.REFERENCE);
if (onType != null) {
s.writeBoolean(true);
onType.write(s);
} else {
s.writeBoolean(false);
}
s.writeUTF(name);
arguments.write(s);
writeLocation(s);
}
public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException {
UnresolvedType onType = null;
if (s.readBoolean()) {
onType = UnresolvedType.read(s);
}
ReferencePointcut ret = new ReferencePointcut(onType, s.readUTF(),
TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
if (onTypeSymbolic != null) {
onType = onTypeSymbolic.resolveExactType(scope, bindings);
// in this case we've already signalled an error
if (onType == ResolvedType.MISSING) return;
}
ResolvedType searchType;
if (onType != null) {
searchType = scope.getWorld().resolve(onType);
} else {
searchType = scope.getEnclosingType();
}
arguments.resolveBindings(scope, bindings, true, true);
//XXX ensure that arguments has no ..'s in it
// check that I refer to a real pointcut declaration and that I match
ResolvedPointcutDefinition pointcutDef = searchType.findPointcut(name);
// if we're not a static reference, then do a lookup of outers
if (pointcutDef == null && onType == null) {
while (true) {
UnresolvedType declaringType = searchType.getDeclaringType();
if (declaringType == null) break;
searchType = declaringType.resolve(scope.getWorld());
pointcutDef = searchType.findPointcut(name);
if (pointcutDef != null) {
// make this a static reference
onType = searchType;
break;
}
}
}
if (pointcutDef == null) {
scope.message(IMessage.ERROR, this, "can't find referenced pointcut " + name);
return;
}
// check visibility
if (!pointcutDef.isVisible(scope.getEnclosingType())) {
scope.message(IMessage.ERROR, this, "pointcut declaration " + pointcutDef + " is not accessible");
return;
}
if (Modifier.isAbstract(pointcutDef.getModifiers())) {
if (onType != null) {
scope.message(IMessage.ERROR, this,
"can't make static reference to abstract pointcut");
return;
} else if (!searchType.isAbstract()) {
scope.message(IMessage.ERROR, this,
"can't use abstract pointcut in concrete context");
return;
}
}
ResolvedType[] parameterTypes =
scope.getWorld().resolve(pointcutDef.getParameterTypes());
if (parameterTypes.length != arguments.size()) {
scope.message(IMessage.ERROR, this, "incompatible number of arguments to pointcut, expected " +
parameterTypes.length + " found " + arguments.size());
return;
}
for (int i=0,len=arguments.size(); i < len; i++) {
TypePattern p = arguments.get(i);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (p == TypePattern.NO) {
scope.message(IMessage.ERROR, this,
"bad parameter to pointcut reference");
return;
}
if (!p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(UnresolvedType.OBJECT))
{
scope.message(IMessage.ERROR, p, "incompatible type, expected " +
parameterTypes[i].getName() + " found " + p);
return;
}
}
if (onType != null) {
if (onType.isParameterizedType()) {
// build a type map mapping type variable names in the generic type to
// the type parameters presented
typeVariableMap = new HashMap();
ResolvedType underlyingGenericType = ((ResolvedType) onType).getGenericType();
TypeVariable[] tVars = underlyingGenericType.getTypeVariables();
ResolvedType[] typeParams = ((ResolvedType)onType).getResolvedTypeParameters();
for (int i = 0; i < tVars.length; i++) {
typeVariableMap.put(tVars[i].getName(),typeParams[i]);
}
} else if (onType.isGenericType()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_REFERENCE_POINTCUT_IN_RAW_TYPE),
getSourceLocation()));
}
}
}
public void resolveBindingsFromRTTI() {
throw new UnsupportedOperationException("Referenced pointcuts are not supported in runtime evaluation");
}
public void postRead(ResolvedType enclosingType) {
arguments.postRead(enclosingType);
}
protected Test findResidueInternal(Shadow shadow, ExposedState state) {
throw new RuntimeException("shouldn't happen");
}
//??? This is not thread safe, but this class is not designed for multi-threading
private boolean concretizing = false;
public Pointcut concretize1(ResolvedType searchStart, IntMap bindings) {
if (concretizing) {
//Thread.currentThread().dumpStack();
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.CIRCULAR_POINTCUT,this),
getSourceLocation()));
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
try {
concretizing = true;
ResolvedPointcutDefinition pointcutDec;
if (onType != null) {
searchStart = onType.resolve(searchStart.getWorld());
if (searchStart == ResolvedType.MISSING) {
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
}
pointcutDec = searchStart.findPointcut(name);
if (pointcutDec == null) {
searchStart.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_POINTCUT,name,searchStart.getName()),
getSourceLocation())
);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
if (pointcutDec.isAbstract()) {
//Thread.currentThread().dumpStack();
ShadowMunger enclosingAdvice = bindings.getEnclosingAdvice();
searchStart.getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ABSTRACT_POINTCUT,pointcutDec),
getSourceLocation(),
(null == enclosingAdvice) ? null : enclosingAdvice.getSourceLocation());
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
//System.err.println("start: " + searchStart);
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);
//we are allowed to bind to pointcuts which use subtypes as this is type safe
if (!p.matchesSubtypes(parameterTypes[i]) &&
!p.getExactType().equals(UnresolvedType.OBJECT))
{
throw new BCException("illegal change to pointcut declaration: " + this);
}
if (p instanceof BindingTypePattern) {
newBindings.put(i, ((BindingTypePattern)p).getFormalIndex());
}
}
if (searchStart.isParameterizedType()) {
// build a type map mapping type variable names in the generic type to
// the type parameters presented
typeVariableMap = new HashMap();
ResolvedType underlyingGenericType = searchStart.getGenericType();
TypeVariable[] tVars = underlyingGenericType.getTypeVariables();
ResolvedType[] typeParams = searchStart.getResolvedTypeParameters();
for (int i = 0; i < tVars.length; i++) {
typeVariableMap.put(tVars[i].getName(),typeParams[i]);
}
}
newBindings.copyContext(bindings);
newBindings.pushEnclosingDefinition(pointcutDec);
try {
Pointcut ret = pointcutDec.getPointcut();
if (typeVariableMap != null) ret = ret.parameterizeWith(typeVariableMap);
return ret.concretize(searchStart, 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);
}
}
|
82,989 |
Bug 82989 Compiler error due to a wrong exception check in try blocks
|
Compiler error on correct code when an aspect performs a method introdiction. The method introduction contains an invocation to a method from the class and such an invocation is inside an appropriate try block. The ajc compiler performs a wrong check on the exception types. To understand better, please see the attached example
|
resolved fixed
|
cc6e681
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-24T17:50:18Z | 2005-01-17T16:40:00Z |
tests/src/org/aspectj/systemtest/ajc150/Ajc150Tests.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc150;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.asm.AsmManager;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.util.LangUtil;
/**
* These are tests that will run on Java 1.4 and use the old harness format for test specification.
*/
public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc150Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
public void test_typeProcessingOrderWhenDeclareParents() {
runTest("Order of types passed to compiler determines weaving behavior");
}
public void test_aroundMethod() {
runTest("method called around in class");
}
public void test_aroundMethodAspect() {
runTest("method called around in aspect");
}
public void test_ambiguousBindingsDetection() {
runTest("Various kinds of ambiguous bindings");
}
public void test_ambiguousArgsDetection() {
runTest("ambiguous args");
}
public void testIncorrectExceptionTableWhenBreakInMethod_pr78021() {
runTest("Injecting exception into while loop with break statement causes catch block to be ignored");
}
public void testIncorrectExceptionTableWhenReturnInMethod_pr79554() {
runTest("Return in try-block disables catch-block if final-block is present");
}
public void testMissingDebugInfoForGeneratedMethods_pr82570() throws ClassNotFoundException {
runTest("Weaved code does not include debug lines");
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
Method[] meths = jc.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
if (f) System.err.println("Line number table for "+method.getName()+method.getSignature()+" = "+method.getLineNumberTable());
assertTrue("Didn't find a line number table for method "+method.getName()+method.getSignature(),
method.getLineNumberTable()!=null);
}
// This test would determine the info isn't there if you pass -g:none ...
// cR = ajc(baseDir,new String[]{"PR82570_1.java","-g:none"});
// assertTrue("Expected no compile problem:"+cR,!cR.hasErrorMessages());
// System.err.println(cR.getStandardError());
// jc = getClassFrom(ajc.getSandboxDirectory(),"PR82570_1");
// meths = jc.getMethods();
// for (int i = 0; i < meths.length; i++) {
// Method method = meths[i];
// assertTrue("Found a line number table for method "+method.getName(),
// method.getLineNumberTable()==null);
// }
}
public void testCanOverrideProtectedMethodsViaITDandDecp_pr83303() {
runTest("compiler error when mixing inheritance, overriding and polymorphism");
}
public void 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 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");
}
// 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);
}
}
|
82,989 |
Bug 82989 Compiler error due to a wrong exception check in try blocks
|
Compiler error on correct code when an aspect performs a method introdiction. The method introduction contains an invocation to a method from the class and such an invocation is inside an appropriate try block. The ajc compiler performs a wrong check on the exception types. To understand better, please see the attached example
|
resolved fixed
|
cc6e681
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-24T17:50:18Z | 2005-01-17T16:40:00Z |
tests/src/org/aspectj/systemtest/ajc150/GenericsTests.java
|
package org.aspectj.systemtest.ajc150;
import java.io.File;
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;
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?)
*
*
* strangeness:
*
* adding declare precedence into the itds/binaryweaving A2.aj, A3.aj causes a bizarre classfile inconsistent message
*/
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 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 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");}
// TODO FREAKYGENERICASPECTPROBLEM why does everything have to be in one source file?
// public void testGenericAspects5() {runTest("generic aspects - 5 (ajdk)");}
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 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");}
// next test commented out, error message is less than ideal - see
// comment in test program as to what should be expected
//public void testSophisticatedAspectsK() {runTest("uberaspects - K");}
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
// 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 testBinaryWeavingITDsA() {runTest("binary weaving ITDs - A");}
public void testBinaryWeavingITDsB() {runTest("binary weaving ITDs - B");}
public void testBinaryWeavingITDs1() {runTest("binary weaving ITDs - 1");}
// ?? Looks like reweavable files dont process their type mungers correctly.
// See AjLookupEnvironment.weaveInterTypeDeclarations(SourceTypeBinding,typeMungers,declareparents,...)
// it seems to process any it discovers from the weaver state info then not apply new ones (the ones
// passed in!)
// 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 testITDBridgeMethodsCovariance3() {runTest("bridging with covariance 1 itd binary weaving");}
// public void testITDBridgeMethods1Normal() {runTest("basic bridging with type vars - 1 - normal");}
// public void testITDBridgeMethods1Itd() {runTest("basic bridging with type vars - 1 - itd");}
// public void testITDBridgeMethods2() {runTest("basic bridging with type vars - 2");}
// public void testITDBridgeMethodsPr91381() {runTest("Abstract intertype method and covariant returns");}
public void testGenericITDsBridgeMethods1() {runTest("bridge methods -1");}
// public void testGenericITDsBridgeMethods1binary() {runTest("bridge methods -1binary");}
public void testGenericITDsBridgeMethods2() {runTest("bridge methods -2");}
// public void testGenericITDsBridgeMethods2binary() {runTest("bridge methods -2binary");}
public void testGenericITDsBridgeMethods3() {runTest("bridge methods -3");}
// public void testGenericITDsBridgeMethods3binary() {runTest("bridge methods -3binary");}
public void testGenericITDsBridgeMethodsPR91381() {runTest("abstract intertype methods and covariant returns");}
// ----------------------------------------------------------------------------------------
// generic declare parents tests
// ----------------------------------------------------------------------------------------
public void testPR96220_GenericDecp() {
runTest("generic decp - simple");
verifyClassSignature("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("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");
}
// --- helpers
// Check the signature attribute on a class is correct
private void verifyClassSignature(String classname,String sig) {
try {
ClassPath cp =
new ClassPath(ajc.getSandboxDirectory() + File.pathSeparator + System.getProperty("java.class.path"));
SyntheticRepository sRepos = SyntheticRepository.getInstance(cp);
JavaClass clazz = sRepos.loadClass(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;
}
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));
} catch (ClassNotFoundException e) {
fail("Couldn't find class "+classname+" in the sandbox directory.");
}
}
}
|
82,989 |
Bug 82989 Compiler error due to a wrong exception check in try blocks
|
Compiler error on correct code when an aspect performs a method introdiction. The method introduction contains an invocation to a method from the class and such an invocation is inside an appropriate try block. The ajc compiler performs a wrong check on the exception types. To understand better, please see the attached example
|
resolved fixed
|
cc6e681
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2005-08-24T17:50:18Z | 2005-01-17T16:40:00Z |
weaver/src/org/aspectj/weaver/AjcMemberMaker.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import java.lang.reflect.Modifier;
//import org.aspectj.weaver.ResolvedType.Name;
public class AjcMemberMaker {
private static final int PUBLIC_STATIC_FINAL =
Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL;
private static final int PRIVATE_STATIC =
Modifier.PRIVATE | Modifier.STATIC;
private static final int PUBLIC_STATIC =
Modifier.PUBLIC | Modifier.STATIC;
private static final int VISIBILITY =
Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
public static final UnresolvedType CFLOW_STACK_TYPE =
UnresolvedType.forName(NameMangler.CFLOW_STACK_TYPE);
public static final UnresolvedType AROUND_CLOSURE_TYPE =
UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure");
public static final UnresolvedType CONVERSIONS_TYPE =
UnresolvedType.forName("org.aspectj.runtime.internal.Conversions");
public static final UnresolvedType NO_ASPECT_BOUND_EXCEPTION =
UnresolvedType.forName("org.aspectj.lang.NoAspectBoundException");
public static ResolvedMember ajcPreClinitMethod(UnresolvedType declaringType) {
return new ResolvedMemberImpl(
Member.METHOD,
declaringType,
PRIVATE_STATIC,
NameMangler.AJC_PRE_CLINIT_NAME,
"()V");
}
public static ResolvedMember ajcPostClinitMethod(UnresolvedType declaringType) {
return new ResolvedMemberImpl(
Member.METHOD,
declaringType,
PRIVATE_STATIC,
NameMangler.AJC_POST_CLINIT_NAME,
"()V");
}
public static Member noAspectBoundExceptionInit() {
return new ResolvedMemberImpl(
Member.METHOD,
NO_ASPECT_BOUND_EXCEPTION,
Modifier.PUBLIC,
"<init>",
"()V");
}
public static Member noAspectBoundExceptionInit2() {
return new ResolvedMemberImpl(
Member.METHOD,
NO_ASPECT_BOUND_EXCEPTION,
Modifier.PUBLIC,
"<init>",
"(Ljava/lang/String;Ljava/lang/Throwable;)V");
}
public static Member noAspectBoundExceptionInitWithCause() {
return new ResolvedMemberImpl(
Member.METHOD,
NO_ASPECT_BOUND_EXCEPTION,
Modifier.PUBLIC,
"<init>",
"(Ljava/lang/String;Ljava/lang/Throwable;)V");
}
public static ResolvedMember perCflowPush(UnresolvedType declaringType) {
return new ResolvedMemberImpl(
Member.METHOD,
declaringType,
PUBLIC_STATIC,
NameMangler.PERCFLOW_PUSH_METHOD,
"()V");
}
public static ResolvedMember perCflowField(UnresolvedType declaringType) {
return new ResolvedMemberImpl(
Member.FIELD,
declaringType,
PUBLIC_STATIC_FINAL,
NameMangler.PERCFLOW_FIELD_NAME,
CFLOW_STACK_TYPE.getSignature());
}
public static ResolvedMember perSingletonField(UnresolvedType declaringType) {
return new ResolvedMemberImpl(
Member.FIELD,
declaringType,
PUBLIC_STATIC_FINAL,
NameMangler.PERSINGLETON_FIELD_NAME,
declaringType.getSignature());
}
public static ResolvedMember initFailureCauseField(UnresolvedType declaringType) {
return new ResolvedMemberImpl(
Member.FIELD,
declaringType,
PRIVATE_STATIC,
NameMangler.INITFAILURECAUSE_FIELD_NAME,
UnresolvedType.THROWABLE.getSignature());
}
public static ResolvedMember perObjectField(UnresolvedType declaringType, ResolvedType aspectType) {
int modifiers = Modifier.PRIVATE;
if (!UnresolvedType.SERIALIZABLE.resolve(aspectType.getWorld()).isAssignableFrom(aspectType)) {
modifiers |= Modifier.TRANSIENT;
}
return new ResolvedMemberImpl(
Member.FIELD,
declaringType,
modifiers,
aspectType,
NameMangler.perObjectInterfaceField(aspectType),
UnresolvedType.NONE);
}
// PTWIMPL ResolvedMember for aspect instance field, declared in matched type
public static ResolvedMember perTypeWithinField(UnresolvedType declaringType, ResolvedType aspectType) {
int modifiers = Modifier.PRIVATE | Modifier.STATIC;
if (!isSerializableAspect(aspectType)) {
modifiers |= Modifier.TRANSIENT;
}
return new ResolvedMemberImpl(Member.FIELD, declaringType, modifiers,
aspectType, NameMangler.perTypeWithinFieldForTarget(aspectType), UnresolvedType.NONE);
}
// PTWIMPL ResolvedMember for type instance field, declared in aspect
// (holds typename for which aspect instance exists)
public static ResolvedMember perTypeWithinWithinTypeField(UnresolvedType declaringType, ResolvedType aspectType) {
int modifiers = Modifier.PRIVATE;
if (!isSerializableAspect(aspectType)) {
modifiers |= Modifier.TRANSIENT;
}
return new ResolvedMemberImpl(Member.FIELD, declaringType, modifiers,
UnresolvedType.forSignature("Ljava/lang/String;"), NameMangler.PERTYPEWITHIN_WITHINTYPEFIELD, UnresolvedType.NONE);
}
private static boolean isSerializableAspect(ResolvedType aspectType) {
return UnresolvedType.SERIALIZABLE.resolve(aspectType.getWorld()).isAssignableFrom(aspectType);
}
public static ResolvedMember perObjectBind(UnresolvedType declaringType) {
return new ResolvedMemberImpl(
Member.METHOD,
declaringType,
PUBLIC_STATIC,
NameMangler.PEROBJECT_BIND_METHOD,
"(Ljava/lang/Object;)V");
}
// PTWIMPL ResolvedMember for getInstance() method, declared in aspect
public static ResolvedMember perTypeWithinGetInstance(UnresolvedType declaringType) {
// private static a.X ajc$getInstance(java.lang.Class)
ResolvedMemberImpl rm = new ResolvedMemberImpl(
Member.METHOD,
declaringType,
PRIVATE_STATIC,
declaringType, // return value
NameMangler.PERTYPEWITHIN_GETINSTANCE_METHOD,
new UnresolvedType[]{UnresolvedType.JAVA_LANG_CLASS}
);
return rm;
}
public static ResolvedMember perTypeWithinCreateAspectInstance(UnresolvedType declaringType) {
// public static a.X ajc$createAspectInstance(java.lang.String)
ResolvedMemberImpl rm = new ResolvedMemberImpl(
Member.METHOD,
declaringType,
PUBLIC_STATIC,
declaringType, // return value
NameMangler.PERTYPEWITHIN_CREATEASPECTINSTANCE_METHOD,
new UnresolvedType[]{UnresolvedType.forSignature("Ljava/lang/String;")},new UnresolvedType[]{}
);
return rm;
}
public static UnresolvedType perObjectInterfaceType(UnresolvedType aspectType) {
return UnresolvedType.forName(aspectType.getName()+"$ajcMightHaveAspect");
}
public static ResolvedMember perObjectInterfaceGet(UnresolvedType aspectType) {
return new ResolvedMemberImpl(
Member.METHOD,
perObjectInterfaceType(aspectType),
Modifier.PUBLIC | Modifier.ABSTRACT,
NameMangler.perObjectInterfaceGet(aspectType),
"()" + aspectType.getSignature());
}
public static ResolvedMember perObjectInterfaceSet(UnresolvedType aspectType) {
return new ResolvedMemberImpl(
Member.METHOD,
perObjectInterfaceType(aspectType),
Modifier.PUBLIC | Modifier.ABSTRACT,
NameMangler.perObjectInterfaceSet(aspectType),
"(" + aspectType.getSignature() + ")V");
}
// PTWIMPL ResolvedMember for localAspectOf() method, declared in matched type
public static ResolvedMember perTypeWithinLocalAspectOf(UnresolvedType shadowType,UnresolvedType aspectType) {
return new ResolvedMemberImpl(
Member.METHOD,
shadowType,//perTypeWithinInterfaceType(aspectType),
Modifier.PUBLIC | Modifier.STATIC,
NameMangler.perTypeWithinLocalAspectOf(aspectType),
"()" + aspectType.getSignature());
}
public static ResolvedMember perSingletonAspectOfMethod(UnresolvedType declaringType) {
return new ResolvedMemberImpl(Member.METHOD,
declaringType, PUBLIC_STATIC, "aspectOf",
"()" + declaringType.getSignature());
}
public static ResolvedMember perSingletonHasAspectMethod(UnresolvedType declaringType) {
return new ResolvedMemberImpl(Member.METHOD,
declaringType, PUBLIC_STATIC, "hasAspect",
"()Z");
};
public static ResolvedMember perCflowAspectOfMethod(UnresolvedType declaringType) {
return perSingletonAspectOfMethod(declaringType);
}
public static ResolvedMember perCflowHasAspectMethod(UnresolvedType declaringType) {
return perSingletonHasAspectMethod(declaringType);
};
public static ResolvedMember perObjectAspectOfMethod(UnresolvedType declaringType) {
return new ResolvedMemberImpl(Member.METHOD,
declaringType, PUBLIC_STATIC, "aspectOf",
"(Ljava/lang/Object;)" + declaringType.getSignature());
}
public static ResolvedMember perObjectHasAspectMethod(UnresolvedType declaringType) {
return new ResolvedMemberImpl(Member.METHOD,
declaringType, PUBLIC_STATIC, "hasAspect",
"(Ljava/lang/Object;)Z");
};
// PTWIMPL ResolvedMember for aspectOf(), declared in aspect
public static ResolvedMember perTypeWithinAspectOfMethod(UnresolvedType declaringType) {
return new ResolvedMemberImpl(Member.METHOD,
declaringType, PUBLIC_STATIC, "aspectOf",
"(Ljava/lang/Class;)" + declaringType.getSignature());
}
// PTWIMPL ResolvedMember for hasAspect(), declared in aspect
public static ResolvedMember perTypeWithinHasAspectMethod(UnresolvedType declaringType) {
return new ResolvedMemberImpl(Member.METHOD,
declaringType, PUBLIC_STATIC, "hasAspect",
"(Ljava/lang/Class;)Z");
};
// -- privileged accessors
public static ResolvedMember privilegedAccessMethodForMethod(UnresolvedType aspectType, ResolvedMember method) {
String sig = method.getDeclaredSignature();
return new ResolvedMemberImpl(Member.METHOD,
method.getDeclaringType(),
Modifier.PUBLIC | (method.isStatic() ? Modifier.STATIC : 0),
NameMangler.privilegedAccessMethodForMethod(method.getName(),
method.getDeclaringType(), aspectType),
sig);
//XXX needs thrown exceptions to be correct
}
public static ResolvedMember privilegedAccessMethodForFieldGet(UnresolvedType aspectType, Member field) {
String sig;
if (field.isStatic()) {
sig = "()" + field.getReturnType().getSignature();
} else {
sig = "(" + field.getDeclaringType().getSignature() + ")" + field.getReturnType().getSignature();
}
return new ResolvedMemberImpl(Member.METHOD,
field.getDeclaringType(),
PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0),
NameMangler.privilegedAccessMethodForFieldGet(field.getName(),
field.getDeclaringType(), aspectType),
sig);
}
public static ResolvedMember privilegedAccessMethodForFieldSet(UnresolvedType aspectType, Member field) {
String sig;
if (field.isStatic()) {
sig = "(" + field.getReturnType().getSignature() + ")V";
} else {
sig = "(" + field.getDeclaringType().getSignature() + field.getReturnType().getSignature() + ")V";
}
return new ResolvedMemberImpl(Member.METHOD,
field.getDeclaringType(),
PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0),
NameMangler.privilegedAccessMethodForFieldSet(field.getName(),
field.getDeclaringType(), aspectType),
sig);
}
// --- inline accessors
//??? can eclipse handle a transform this weird without putting synthetics into the mix
public static ResolvedMember superAccessMethod(UnresolvedType baseType, ResolvedMember method) {
return new ResolvedMemberImpl(Member.METHOD,
baseType,
Modifier.PUBLIC,
method.getReturnType(),
NameMangler.superDispatchMethod(baseType, method.getName()),
method.getParameterTypes(),
method.getExceptions());
}
public static ResolvedMember inlineAccessMethodForMethod(UnresolvedType aspectType, ResolvedMember method) {
UnresolvedType[] paramTypes = method.getParameterTypes();
if (!method.isStatic()) {
paramTypes = UnresolvedType.insert(method.getDeclaringType(), paramTypes);
}
return new ResolvedMemberImpl(Member.METHOD,
aspectType,
PUBLIC_STATIC, //??? what about privileged and super access
//???Modifier.PUBLIC | (method.isStatic() ? Modifier.STATIC : 0),
method.getReturnType(),
NameMangler.inlineAccessMethodForMethod(method.getName(),
method.getDeclaringType(), aspectType),
paramTypes, method.getExceptions());
}
public static ResolvedMember inlineAccessMethodForFieldGet(UnresolvedType aspectType, Member field) {
String sig;
if (field.isStatic()) {
sig = "()" + field.getReturnType().getSignature();
} else {
sig = "(" + field.getDeclaringType().getSignature() + ")" + field.getReturnType().getSignature();
}
return new ResolvedMemberImpl(Member.METHOD,
aspectType,
PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0),
NameMangler.inlineAccessMethodForFieldGet(field.getName(),
field.getDeclaringType(), aspectType),
sig);
}
public static ResolvedMember inlineAccessMethodForFieldSet(UnresolvedType aspectType, Member field) {
String sig;
if (field.isStatic()) {
sig = "(" + field.getReturnType().getSignature() + ")V";
} else {
sig = "(" + field.getDeclaringType().getSignature() + field.getReturnType().getSignature() + ")V";
}
return new ResolvedMemberImpl(Member.METHOD,
aspectType,
PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0),
NameMangler.inlineAccessMethodForFieldSet(field.getName(),
field.getDeclaringType(), aspectType),
sig);
}
// --- runtimeLibrary api stuff
public static Member cflowStackPeekInstance() {
return new MemberImpl(
Member.METHOD,
CFLOW_STACK_TYPE,
0,
"peekInstance",
"()Ljava/lang/Object;");
}
public static Member cflowStackPushInstance() {
return new MemberImpl(
Member.METHOD,
CFLOW_STACK_TYPE,
0,
"pushInstance",
"(Ljava/lang/Object;)V");
}
public static Member cflowStackIsValid() {
return new MemberImpl(
Member.METHOD,
CFLOW_STACK_TYPE,
0,
"isValid",
"()Z");
}
public static Member cflowStackInit() {
return new MemberImpl(
Member.CONSTRUCTOR,
CFLOW_STACK_TYPE,
0,
"<init>",
"()V");
}
public static Member aroundClosurePreInitializationField() {
return new MemberImpl(
Member.FIELD,
AROUND_CLOSURE_TYPE,
0,
"preInitializationState",
"[Ljava/lang/Object;");
}
public static Member aroundClosurePreInitializationGetter() {
return new MemberImpl(
Member.METHOD,
AROUND_CLOSURE_TYPE,
0,
"getPreInitializationState",
"()[Ljava/lang/Object;");
}
public static ResolvedMember preIntroducedConstructor(
UnresolvedType aspectType,
UnresolvedType targetType,
UnresolvedType[] paramTypes)
{
return new ResolvedMemberImpl(
Member.METHOD,
aspectType,
PUBLIC_STATIC_FINAL,
UnresolvedType.OBJECTARRAY,
NameMangler.preIntroducedConstructor(aspectType, targetType),
paramTypes);
}
public static ResolvedMember postIntroducedConstructor(
UnresolvedType aspectType,
UnresolvedType targetType,
UnresolvedType[] paramTypes)
{
return new ResolvedMemberImpl(
Member.METHOD,
aspectType,
PUBLIC_STATIC_FINAL,
ResolvedType.VOID,
NameMangler.postIntroducedConstructor(aspectType, targetType),
UnresolvedType.insert(targetType, paramTypes));
}
public static ResolvedMember interConstructor(ResolvedType targetType, ResolvedMember constructor, UnresolvedType aspectType) {
//
// ResolvedType targetType,
// UnresolvedType[] argTypes,
// int modifiers)
// {
ResolvedMember ret =
new ResolvedMemberImpl(
Member.CONSTRUCTOR,
targetType,
Modifier.PUBLIC,
ResolvedType.VOID,
"<init>",
constructor.getParameterTypes(),
constructor.getExceptions());
//System.out.println("ret: " + ret + " mods: " + Modifier.toString(modifiers));
if (Modifier.isPublic(constructor.getModifiers()))
return ret;
while (true) {
ret = addCookieTo(ret, aspectType);
if (targetType.lookupMemberNoSupers(ret) == null)
return ret;
}
}
public static ResolvedMember interFieldInitializer(ResolvedMember field, UnresolvedType aspectType) {
return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC,
NameMangler.interFieldInitializer(aspectType, field.getDeclaringType(), field.getName()),
field.isStatic() ? "()V" : "(" + field.getDeclaringType().getSignature() + ")V"
);
}
/**
* Makes public and non-final
*/
private static int makePublicNonFinal(int modifiers) {
return (modifiers & ~VISIBILITY & ~Modifier.FINAL) | Modifier.PUBLIC;
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static ResolvedMember interFieldSetDispatcher(ResolvedMember field, UnresolvedType aspectType) {
return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC,
ResolvedType.VOID,
NameMangler.interFieldSetDispatcher(aspectType, field.getDeclaringType(), field.getName()),
field.isStatic() ? new UnresolvedType[] {field.getReturnType()}
: new UnresolvedType[] {field.getDeclaringType(), field.getReturnType()}
);
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static ResolvedMember interFieldGetDispatcher(ResolvedMember field, UnresolvedType aspectType) {
return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC,
field.getReturnType(),
NameMangler.interFieldGetDispatcher(aspectType, field.getDeclaringType(), field.getName()),
field.isStatic() ? UnresolvedType.NONE : new UnresolvedType[] {field.getDeclaringType()},
UnresolvedType.NONE
);
}
// private static int makeFieldModifiers(int declaredModifiers) {
// int ret = Modifier.PUBLIC;
// if (Modifier.isTransient(declaredModifiers)) ret |= Modifier.TRANSIENT;
// if (Modifier.isVolatile(declaredModifiers)) ret |= Modifier.VOLATILE;
// return ret;
// }
/**
* This field goes on the class the field
* is declared onto
*/
public static ResolvedMember interFieldClassField(ResolvedMember field, UnresolvedType aspectType) {
return new ResolvedMemberImpl(Member.FIELD, field.getDeclaringType(),
makePublicNonFinal(field.getModifiers()),
field.getReturnType(),
NameMangler.interFieldClassField(field.getModifiers(), aspectType, field.getDeclaringType(), field.getName()),
UnresolvedType.NONE, UnresolvedType.NONE
);
}
/**
* This field goes on top-most implementers of the interface the field
* is declared onto
*/
public static ResolvedMember interFieldInterfaceField(ResolvedMember field, UnresolvedType onClass, UnresolvedType aspectType) {
return new ResolvedMemberImpl(Member.FIELD, onClass, makePublicNonFinal(field.getModifiers()),
field.getReturnType(),
NameMangler.interFieldInterfaceField(aspectType, field.getDeclaringType(), field.getName()),
UnresolvedType.NONE, UnresolvedType.NONE
);
}
/**
* This instance method goes on the interface the field is declared onto
* as well as its top-most implementors
*/
public static ResolvedMember interFieldInterfaceSetter(ResolvedMember field, ResolvedType onType, UnresolvedType aspectType) {
int modifiers = Modifier.PUBLIC;
if (onType.isInterface()) modifiers |= Modifier.ABSTRACT;
return new ResolvedMemberImpl(Member.METHOD, onType, modifiers,
ResolvedType.VOID,
NameMangler.interFieldInterfaceSetter(aspectType, field.getDeclaringType(), field.getName()),
new UnresolvedType[] {field.getReturnType()}, UnresolvedType.NONE
);
}
/**
* This instance method goes on the interface the field is declared onto
* as well as its top-most implementors
*/
public static ResolvedMember interFieldInterfaceGetter(ResolvedMember field, ResolvedType onType, UnresolvedType aspectType) {
int modifiers = Modifier.PUBLIC;
if (onType.isInterface()) modifiers |= Modifier.ABSTRACT;
return new ResolvedMemberImpl(Member.METHOD, onType, modifiers,
field.getReturnType(),
NameMangler.interFieldInterfaceGetter(aspectType, field.getDeclaringType(), field.getName()),
UnresolvedType.NONE, UnresolvedType.NONE
);
}
/**
* This method goes on the target type of the inter-type method. (and possibly the topmost-implementors,
* if the target type is an interface). The implementation will call the interMethodDispatch method on the
* aspect.
*/
public static ResolvedMember interMethod(ResolvedMember meth, UnresolvedType aspectType, boolean onInterface)
{
if (Modifier.isPublic(meth.getModifiers()) && !onInterface) return meth;
int modifiers = makePublicNonFinal(meth.getModifiers());
if (onInterface) modifiers |= Modifier.ABSTRACT;
return new ResolvedMemberImpl(Member.METHOD, meth.getDeclaringType(),
modifiers,
meth.getReturnType(),
NameMangler.interMethod(meth.getModifiers(), aspectType, meth.getDeclaringType(), meth.getName()),
meth.getParameterTypes(), meth.getExceptions());
}
/**
* This static method goes on the declaring aspect of the inter-type method. The implementation
* calls the interMethodBody() method on the aspect.
*/
public static ResolvedMember interMethodDispatcher(ResolvedMember meth, UnresolvedType aspectType)
{
UnresolvedType[] paramTypes = meth.getParameterTypes();
if (!meth.isStatic()) {
paramTypes = UnresolvedType.insert(meth.getDeclaringType(), paramTypes);
}
return new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC,
meth.getReturnType(),
NameMangler.interMethodDispatcher(aspectType, meth.getDeclaringType(), meth.getName()),
paramTypes, meth.getExceptions());
}
/**
* This method goes on the declaring aspect of the inter-type method.
* It contains the real body of the ITD method.
*/
public static ResolvedMember interMethodBody(ResolvedMember meth, UnresolvedType aspectType)
{
UnresolvedType[] paramTypes = meth.getParameterTypes();
if (!meth.isStatic()) {
paramTypes = UnresolvedType.insert(meth.getDeclaringType(), paramTypes);
}
int modifiers = PUBLIC_STATIC;
if (Modifier.isStrict(meth.getModifiers())) {
modifiers |= Modifier.STRICT;
}
return new ResolvedMemberImpl(Member.METHOD, aspectType, modifiers,
meth.getReturnType(),
NameMangler.interMethodBody(aspectType, meth.getDeclaringType(), meth.getName()),
paramTypes, meth.getExceptions());
}
private static ResolvedMember addCookieTo(ResolvedMember ret, UnresolvedType aspectType) {
UnresolvedType[] params = ret.getParameterTypes();
UnresolvedType[] freshParams = UnresolvedType.add(params, aspectType);
return new ResolvedMemberImpl(
ret.getKind(),
ret.getDeclaringType(),
ret.getModifiers(),
ret.getReturnType(),
ret.getName(),
freshParams, ret.getExceptions());
}
public static ResolvedMember toObjectConversionMethod(UnresolvedType fromType) {
if (fromType.isPrimitiveType()) {
String name = fromType.toString() + "Object";
return new ResolvedMemberImpl(
Member.METHOD,
CONVERSIONS_TYPE,
PUBLIC_STATIC,
UnresolvedType.OBJECT,
name,
new UnresolvedType[] { fromType }, UnresolvedType.NONE);
} else {
return null;
}
}
public static Member interfaceConstructor(ResolvedType resolvedTypeX) {
// AMC next two lines should not be needed when sig for generic type is changed
ResolvedType declaringType = resolvedTypeX;
if (declaringType.isRawType()) declaringType = declaringType.getGenericType();
return new ResolvedMemberImpl(
Member.CONSTRUCTOR,
declaringType,
Modifier.PUBLIC,
"<init>",
"()V");
}
//-- common types we use. Note: Java 5 dependand types are refered to as String
public final static UnresolvedType ASPECT_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.Aspect");
public final static UnresolvedType BEFORE_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.Before");
public final static UnresolvedType AROUND_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.Around");
public final static UnresolvedType AFTERRETURNING_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.AfterReturning");
public final static UnresolvedType AFTERTHROWING_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.AfterThrowing");
public final static UnresolvedType AFTER_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.After");
public final static UnresolvedType POINTCUT_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.Pointcut");
public final static UnresolvedType DECLAREERROR_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.DeclareError");
public final static UnresolvedType DECLAREWARNING_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.DeclareWarning");
public final static UnresolvedType DECLAREPRECEDENCE_ANNOTATION = UnresolvedType.forName("org.aspectj.lang.annotation.DeclarePrecedence");
public final static UnresolvedType TYPEX_JOINPOINT = UnresolvedType.forName(JoinPoint.class.getName().replace('/','.'));
public final static UnresolvedType TYPEX_PROCEEDINGJOINPOINT = UnresolvedType.forName(ProceedingJoinPoint.class.getName().replace('/','.'));
public final static UnresolvedType TYPEX_STATICJOINPOINT = UnresolvedType.forName(JoinPoint.StaticPart.class.getName().replace('/','.'));
public final static UnresolvedType TYPEX_ENCLOSINGSTATICJOINPOINT = UnresolvedType.forName(JoinPoint.EnclosingStaticPart.class.getName().replace('/','.'));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.