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
unknown | report_datetime
unknown | updated_file
stringlengths 2
187
| file_content
stringlengths 0
368k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
399,590 | Bug 399590 Bad generics signature generated | null | resolved fixed | 4af4b1e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-04T21:33:26Z" | "2013-01-31T08:13:20Z" | tests/bugs172/pr399590/Cage2.java | |
399,590 | Bug 399590 Bad generics signature generated | null | resolved fixed | 4af4b1e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-04T21:33:26Z" | "2013-01-31T08:13:20Z" | tests/bugs172/pr399590/five/Cage.java | |
399,590 | Bug 399590 Bad generics signature generated | null | resolved fixed | 4af4b1e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-04T21:33:26Z" | "2013-01-31T08:13:20Z" | tests/bugs172/pr399590/five/Cage2.java | |
399,590 | Bug 399590 Bad generics signature generated | null | resolved fixed | 4af4b1e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-04T21:33:26Z" | "2013-01-31T08:13:20Z" | tests/bugs172/pr399590/four/Cage.java | |
399,590 | Bug 399590 Bad generics signature generated | null | resolved fixed | 4af4b1e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-04T21:33:26Z" | "2013-01-31T08:13:20Z" | tests/bugs172/pr399590/four/Cage2.java | |
399,590 | Bug 399590 Bad generics signature generated | null | resolved fixed | 4af4b1e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-04T21:33:26Z" | "2013-01-31T08:13:20Z" | tests/bugs172/pr399590/three/Cage.java | |
399,590 | Bug 399590 Bad generics signature generated | null | resolved fixed | 4af4b1e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-04T21:33:26Z" | "2013-01-31T08:13:20Z" | tests/bugs172/pr399590/three/Cage2.java | |
399,590 | Bug 399590 Bad generics signature generated | null | resolved fixed | 4af4b1e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-04T21:33:26Z" | "2013-01-31T08:13:20Z" | tests/bugs172/pr399590/two/Cage.java | |
399,590 | Bug 399590 Bad generics signature generated | null | resolved fixed | 4af4b1e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-04T21:33:26Z" | "2013-01-31T08:13:20Z" | tests/bugs172/pr399590/two/Cage2.java | |
399,590 | Bug 399590 Bad generics signature generated | null | resolved fixed | 4af4b1e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-04T21:33:26Z" | "2013-01-31T08:13:20Z" | tests/src/org/aspectj/systemtest/ajc172/Ajc172Tests.java | /*******************************************************************************
* Copyright (c) 2012 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc172;
import java.io.File;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.testing.XMLBasedAjcTestCase;
/**
* @author Andy Clement
*/
public class Ajc172Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testIfPointcutNames_pr398246() throws Exception {
runTest("if pointcut names");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$andy", m.getName());
}
public void testIfPointcutNames_pr398246_2() throws Exception {
runTest("if pointcut names 2");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$fred", m.getName());
}
// fully qualified annotation name is used
public void testIfPointcutNames_pr398246_3() throws Exception {
runTest("if pointcut names 3");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$barney", m.getName());
}
// compiling a class later than the initial build - does it pick up the
// right if clause name?
public void testIfPointcutNames_pr398246_4() throws Exception {
runTest("if pointcut names 4");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$sid", m.getName());
}
// new style generated names
public void testIfPointcutNames_pr398246_5() throws Exception {
runTest("if pointcut names 5");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$ac0cb804", m.getName());
jc = getClassFrom(ajc.getSandboxDirectory(), "X2");
m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$ac0cb804", m.getName());
}
// new style generated names - multiple ifs in one pointcut
public void testIfPointcutNames_pr398246_6() throws Exception {
runTest("if pointcut names 6");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if",1);
assertEquals("ajc$if$aac93da8", m.getName());
m = getMethodStartsWith(jc, "ajc$if",2);
assertEquals("ajc$if$1$ae5e778a", m.getName());
}
// new style generated names - multiple ifs in one advice
public void testIfPointcutNames_pr398246_7() throws Exception {
runTest("if pointcut names 7");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if",1);
assertEquals("ajc$if$1$ac0607c", m.getName());
m = getMethodStartsWith(jc, "ajc$if",2);
assertEquals("ajc$if$1$1$4d4baf36", m.getName());
}
public void testOptionalAspects_pr398588() {
runTest("optional aspects");
}
public void testInconsistentClassFile_pr389750() {
runTest("inconsistent class file");
}
public void testInconsistentClassFile_pr389750_2() {
runTest("inconsistent class file 2");
}
public void testInconsistentClassFile_pr389750_3() {
runTest("inconsistent class file 3");
}
public void testInconsistentClassFile_pr389750_4() {
runTest("inconsistent class file 4");
}
public void testAnnotationValueError_pr389752_1() {
runTest("annotation value error 1");
}
public void testAnnotationValueError_pr389752_2() {
runTest("annotation value error 2");
}
// this needs some cleverness to fix... the annotation value is parsed as a
// string and then not checked
// to see if the user is accidentally supplying, for example, an enum value.
// Due to the use of strings, it
// is hard to check. The verification code might go here:
// WildAnnotationTypePattern, line 205 (the string case)
// public void testAnnotationValueError_pr389752_3() {
// runTest("annotation value error 3");
// }
// ---
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc172Tests.class);
}
@Override
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc172/ajc172.xml");
}
}
|
394,535 | Bug 394535 Java throws OutOfMemory in call to Class.getGenericSuperclass() on woven class | null | resolved fixed | 46f9079 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-05T18:45:03Z" | "2012-11-18T14:46:40Z" | org.aspectj.matcher/src/org/aspectj/weaver/TypeVariable.java | /* *******************************************************************
* Copyright (c) 2005-2010 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
* ******************************************************************/
package org.aspectj.weaver;
import java.io.IOException;
/**
* Represents a type variable with possible bounds.
*
* @author Adrian Colyer
* @author Andy Clement
*/
public class TypeVariable {
public static final TypeVariable[] NONE = new TypeVariable[0];
// the name of the type variable as recorded in the generic signature
private String name;
// index
private int rank;
// computed as required: either ==superclass or ==superInterfaces[0] or is OBJECT
private UnresolvedType firstbound;
// the upper bound of the type variable. From the extends clause, eg. T extends Number
private UnresolvedType superclass;
// any additional upper (interface) bounds. from the extends clause, e.g. T extends Number & Comparable
private UnresolvedType[] superInterfaces = UnresolvedType.NONE;
// It would be nice to push this field onto the TypeVariableDeclaringElement
// interface (a getKind()) but at the moment we don't always guarantee
// to set the declaring element (eclipse seems to utilise the knowledge of
// what declared the type variable, but we dont yet...)
public static final int UNKNOWN = -1;
public static final int METHOD = 1;
public static final int TYPE = 2;
// What kind of element declared this type variable?
private int declaringElementKind = UNKNOWN;
private TypeVariableDeclaringElement declaringElement;
// whether or not the bounds of this type variable have been resolved
public boolean isResolved = false;
// Is this type variable in the process of being resolved (allows for something self-referential like Enum)
private boolean beingResolved = false;
/**
* Constructor for an unbound type variable, eg. 'T'
*/
public TypeVariable(String name) {
this.name = name;
}
public TypeVariable(String name, UnresolvedType anUpperBound) {
this(name);
this.superclass = anUpperBound;
}
public TypeVariable(String name, UnresolvedType anUpperBound, UnresolvedType[] superInterfaces) {
this(name, anUpperBound);
this.superInterfaces = superInterfaces;
}
/**
* @return the first bound, either the superclass or if non is specified the first interface or if non are specified then OBJECT
*/
public UnresolvedType getFirstBound() {
if (firstbound != null) {
return firstbound;
}
if (superclass == null || superclass.getSignature().equals("Ljava/lang/Object;")) {
if (superInterfaces.length > 0) {
firstbound = superInterfaces[0];
} else {
firstbound = UnresolvedType.OBJECT;
}
} else {
firstbound = superclass;
}
return firstbound;
}
public UnresolvedType getUpperBound() {
return superclass;
}
public UnresolvedType[] getSuperInterfaces() {
return superInterfaces;
}
public String getName() {
return name;
}
/**
* resolve all the bounds of this type variable
*/
public TypeVariable resolve(World world) {
if (isResolved) {
return this;
}
if (beingResolved) {
return this;
}
beingResolved = true;
TypeVariable resolvedTVar = null;
if (declaringElement != null) {
// resolve by finding the real type var that we refer to...
if (declaringElementKind == TYPE) {
UnresolvedType declaring = (UnresolvedType) declaringElement;
ReferenceType rd = (ReferenceType) declaring.resolve(world);
TypeVariable[] tVars = rd.getTypeVariables();
for (int i = 0; i < tVars.length; i++) {
if (tVars[i].getName().equals(getName())) {
resolvedTVar = tVars[i];
break;
}
}
} else {
// look for type variable on method...
ResolvedMember declaring = (ResolvedMember) declaringElement;
TypeVariable[] tvrts = declaring.getTypeVariables();
for (int i = 0; i < tvrts.length; i++) {
if (tvrts[i].getName().equals(getName())) {
resolvedTVar = tvrts[i];
// if (tvrts[i].isTypeVariableReference()) {
// TypeVariableReferenceType tvrt = (TypeVariableReferenceType) tvrts[i].resolve(inSomeWorld);
// TypeVariable tv = tvrt.getTypeVariable();
// if (tv.getName().equals(getName())) resolvedTVar = tv;
// }
}
}
}
if (resolvedTVar == null) {
throw new IllegalStateException();
// well, this is bad... we didn't find the type variable on the member
// could be a separate compilation issue...
// should issue message, this is a workaround to get us going...
// resolvedTVar = this;
}
} else {
resolvedTVar = this;
}
superclass = resolvedTVar.superclass;
superInterfaces = resolvedTVar.superInterfaces;
if (superclass != null) {
ResolvedType rt = superclass.resolve(world);
// if (!superclass.isTypeVariableReference() && rt.isInterface()) {
// throw new IllegalStateException("Why is the type an interface? " + rt);
// }
superclass = rt;
}
firstbound = getFirstBound().resolve(world);
for (int i = 0; i < superInterfaces.length; i++) {
superInterfaces[i] = superInterfaces[i].resolve(world);
}
isResolved = true;
beingResolved = false;
return this;
}
/**
* answer true if the given type satisfies all of the bound constraints of this type variable. If type variable has not been
* resolved then throws IllegalStateException
*/
public boolean canBeBoundTo(ResolvedType candidate) {
if (!isResolved) {
throw new IllegalStateException("Can't answer binding questions prior to resolving");
}
// wildcard can accept any binding
if (candidate.isGenericWildcard()) {
return true;
}
// otherwise can be bound iff...
// candidate is a subtype of upperBound
if (superclass != null && !isASubtypeOf(superclass, candidate)) {
return false;
}
// candidate is a subtype of all superInterfaces
for (int i = 0; i < superInterfaces.length; i++) {
if (!isASubtypeOf(superInterfaces[i], candidate)) {
return false;
}
}
return true;
}
private boolean isASubtypeOf(UnresolvedType candidateSuperType, UnresolvedType candidateSubType) {
ResolvedType superType = (ResolvedType) candidateSuperType;
ResolvedType subType = (ResolvedType) candidateSubType;
return superType.isAssignableFrom(subType);
}
// only used when resolving
public void setUpperBound(UnresolvedType superclass) {
// if (isResolved) {
// throw new IllegalStateException("Why set this late?");
// }
this.firstbound = null;
this.superclass = superclass;
}
// only used when resolving
public void setAdditionalInterfaceBounds(UnresolvedType[] superInterfaces) {
// if (isResolved) {
// throw new IllegalStateException("Why set this late?");
// }
this.firstbound = null;
this.superInterfaces = superInterfaces;
}
public String toDebugString() {
return getDisplayName();
}
public String getDisplayName() {
StringBuffer ret = new StringBuffer();
ret.append(name);
if (!getFirstBound().getName().equals("java.lang.Object")) {
ret.append(" extends ");
ret.append(getFirstBound().getName());
if (superInterfaces != null) {
for (int i = 0; i < superInterfaces.length; i++) {
if (!getFirstBound().equals(superInterfaces[i])) {
ret.append(" & ");
ret.append(superInterfaces[i].getName());
}
}
}
}
return ret.toString();
}
@Override
public String toString() {
return "TypeVar " + getDisplayName();
}
/**
* Return complete signature, e.g. "T extends Number" would return "T:Ljava/lang/Number;" note: MAY INCLUDE P types if bounds
* are parameterized types
*/
public String getSignature() {
StringBuffer sb = new StringBuffer();
sb.append(name);
sb.append(":");
sb.append(superclass.getSignature());
if (superInterfaces.length != 0) {
sb.append(":");
for (int i = 0; i < superInterfaces.length; i++) {
UnresolvedType iBound = superInterfaces[i];
sb.append(iBound.getSignature());
}
}
return sb.toString();
}
/**
* @return signature for inclusion in an attribute, there must be no 'P' in it signatures
*/
public String getSignatureForAttribute() {
StringBuffer sb = new StringBuffer();
sb.append(name);
sb.append(":");
if (superInterfaces.length == 0) {
sb.append(((ResolvedType) superclass).getSignatureForAttribute());
}
if (superInterfaces.length != 0) {
sb.append(":");
for (int i = 0; i < superInterfaces.length; i++) {
ResolvedType iBound = (ResolvedType) superInterfaces[i];
sb.append(iBound.getSignatureForAttribute());
}
}
return sb.toString();
}
public void setRank(int rank) {
this.rank = rank;
}
public int getRank() {
return rank;
}
public void setDeclaringElement(TypeVariableDeclaringElement element) {
this.declaringElement = element;
if (element instanceof UnresolvedType) {
this.declaringElementKind = TYPE;
} else {
this.declaringElementKind = METHOD;
}
}
public TypeVariableDeclaringElement getDeclaringElement() {
return declaringElement;
}
public void setDeclaringElementKind(int kind) {
this.declaringElementKind = kind;
}
public int getDeclaringElementKind() {
// if (declaringElementKind==UNKNOWN) throw new RuntimeException("Dont know declarer of this tvar : "+this);
return declaringElementKind;
}
public void write(CompressingDataOutputStream s) throws IOException {
// name, upperbound, additionalInterfaceBounds, lowerbound
s.writeUTF(name);
superclass.write(s);
if (superInterfaces.length == 0) {
s.writeInt(0);
} else {
s.writeInt(superInterfaces.length);
for (int i = 0; i < superInterfaces.length; i++) {
UnresolvedType ibound = superInterfaces[i];
ibound.write(s);
}
}
}
public static TypeVariable read(VersionedDataInputStream s) throws IOException {
// if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) {
String name = s.readUTF();
UnresolvedType ubound = UnresolvedType.read(s);
int iboundcount = s.readInt();
UnresolvedType[] ibounds = UnresolvedType.NONE;
if (iboundcount > 0) {
ibounds = new UnresolvedType[iboundcount];
for (int i = 0; i < iboundcount; i++) {
ibounds[i] = UnresolvedType.read(s);
}
}
TypeVariable newVariable = new TypeVariable(name, ubound, ibounds);
return newVariable;
}
public String getGenericSignature() {
return "T" + name + ";";
}
public String getErasureSignature() {
return getFirstBound().getErasureSignature();
}
public UnresolvedType getSuperclass() {
return superclass;
}
public void setSuperclass(UnresolvedType superclass) {
this.firstbound = null;
this.superclass = superclass;
}
}
|
394,535 | Bug 394535 Java throws OutOfMemory in call to Class.getGenericSuperclass() on woven class | null | resolved fixed | 46f9079 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-05T18:45:03Z" | "2012-11-18T14:46:40Z" | tests/bugs172/pr394535/Bug.java | |
394,535 | Bug 394535 Java throws OutOfMemory in call to Class.getGenericSuperclass() on woven class | null | resolved fixed | 46f9079 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-05T18:45:03Z" | "2012-11-18T14:46:40Z" | tests/bugs172/pr394535/Bug2.java | |
394,535 | Bug 394535 Java throws OutOfMemory in call to Class.getGenericSuperclass() on woven class | null | resolved fixed | 46f9079 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-05T18:45:03Z" | "2012-11-18T14:46:40Z" | tests/src/org/aspectj/systemtest/ajc172/Ajc172Tests.java | /*******************************************************************************
* Copyright (c) 2012 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc172;
import java.io.File;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.testing.XMLBasedAjcTestCase;
/**
* @author Andy Clement
*/
public class Ajc172Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// extends
public void testPSignatures_pr399590() throws Exception {
runTest("p signatures 1");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Cage");
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal<+LCage<TT;>;>;>LBar;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal2<+LCage2<TT;>;>;>LBar2;Ljava/io/Serializable;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
}
// extends two classes
public void testPSignatures_pr399590_2() throws Exception {
runTest("p signatures 2");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Cage");
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal<+LCage<TT;LIntf;>;LIntf;>;Q:Ljava/lang/Object;>LBar;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal2<+LCage2<TT;LIntf2;>;LIntf2;>;Q:Ljava/lang/Object;>LBar2;Ljava/io/Serializable;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
}
// super
public void testPSignatures_pr399590_3() throws Exception {
runTest("p signatures 3");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Cage");
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal<-LXXX<TT;>;>;>LBar;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal2<-LXXX2<TT;>;>;>LBar2;Ljava/io/Serializable;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
}
// super
public void testPSignatures_pr399590_4() throws Exception {
runTest("p signatures 4");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Cage");
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal<-LXXX<TT;>;LYYY;>;>LBar;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal2<-LXXX2<TT;>;LYYY2;>;>LBar2;Ljava/io/Serializable;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
}
// unbound
public void testPSignatures_pr399590_5() throws Exception {
runTest("p signatures 5");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Cage");
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal<*>;>LBar;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal2<*>;>LBar2;Ljava/io/Serializable;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
}
public void testIfPointcutNames_pr398246() throws Exception {
runTest("if pointcut names");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$andy", m.getName());
}
public void testIfPointcutNames_pr398246_2() throws Exception {
runTest("if pointcut names 2");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$fred", m.getName());
}
// fully qualified annotation name is used
public void testIfPointcutNames_pr398246_3() throws Exception {
runTest("if pointcut names 3");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$barney", m.getName());
}
// compiling a class later than the initial build - does it pick up the
// right if clause name?
public void testIfPointcutNames_pr398246_4() throws Exception {
runTest("if pointcut names 4");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$sid", m.getName());
}
// new style generated names
public void testIfPointcutNames_pr398246_5() throws Exception {
runTest("if pointcut names 5");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$ac0cb804", m.getName());
jc = getClassFrom(ajc.getSandboxDirectory(), "X2");
m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$ac0cb804", m.getName());
}
// new style generated names - multiple ifs in one pointcut
public void testIfPointcutNames_pr398246_6() throws Exception {
runTest("if pointcut names 6");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if",1);
assertEquals("ajc$if$aac93da8", m.getName());
m = getMethodStartsWith(jc, "ajc$if",2);
assertEquals("ajc$if$1$ae5e778a", m.getName());
}
// new style generated names - multiple ifs in one advice
public void testIfPointcutNames_pr398246_7() throws Exception {
runTest("if pointcut names 7");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if",1);
assertEquals("ajc$if$1$ac0607c", m.getName());
m = getMethodStartsWith(jc, "ajc$if",2);
assertEquals("ajc$if$1$1$4d4baf36", m.getName());
}
public void testOptionalAspects_pr398588() {
runTest("optional aspects");
}
public void testInconsistentClassFile_pr389750() {
runTest("inconsistent class file");
}
public void testInconsistentClassFile_pr389750_2() {
runTest("inconsistent class file 2");
}
public void testInconsistentClassFile_pr389750_3() {
runTest("inconsistent class file 3");
}
public void testInconsistentClassFile_pr389750_4() {
runTest("inconsistent class file 4");
}
public void testAnnotationValueError_pr389752_1() {
runTest("annotation value error 1");
}
public void testAnnotationValueError_pr389752_2() {
runTest("annotation value error 2");
}
// this needs some cleverness to fix... the annotation value is parsed as a
// string and then not checked
// to see if the user is accidentally supplying, for example, an enum value.
// Due to the use of strings, it
// is hard to check. The verification code might go here:
// WildAnnotationTypePattern, line 205 (the string case)
// public void testAnnotationValueError_pr389752_3() {
// runTest("annotation value error 3");
// }
// ---
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc172Tests.class);
}
@Override
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc172/ajc172.xml");
}
}
|
391,384 | Bug 391384 WildAnnotationTypePattern.java:231 | OK, I get that this is not supported (and what I *want* here is matching on the existence of the supplied header *among* the headers in the String[]). A feature request might be in order, but a syntax for specifying how you want to match the array would be needed.... The bug that I'm reporting is that trying to *save* this program gets an error that pops up a dialog. This should just become another error marker. It might the compiler that has to change what it throws, but in the end it's the Eclipse IDE that ends up breaking from a user standpoint. (RequestMapping.headers() is of type String[]). public aspect Fail { pointcut testable(): execution(public * @RequestMapping(headers="x-test=test") com.example..*(..)); } java.lang.RuntimeException at org.aspectj.weaver.patterns.WildAnnotationTypePattern.resolveAnnotationValues(WildAnnotationTypePattern.java:231) at org.aspectj.weaver.patterns.WildAnnotationTypePattern.resolveBindings(WildAnnotationTypePattern.java:325) at org.aspectj.weaver.patterns.WildTypePattern.resolveBindings(WildTypePattern.java:657) at org.aspectj.weaver.patterns.SignaturePattern.resolveBindings(SignaturePattern.java:81) at org.a ... n(Worker.java:53) Compile error: RuntimeException thrown: Compiler limitation: annotation value support not implemented for type java.lang.String[] | resolved fixed | edb41e3 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-05T19:14:40Z" | "2012-10-09T05:20:00Z" | org.aspectj.matcher/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 Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.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 POINTCUT_NOT_VISIBLE = "pointcutNotVisible";
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 NO_NEWARRAY_JOINPOINTS_BY_DEFAULT = "noNewArrayJoinpointsByDefault";
public static final String UNSUPPORTED_POINTCUT_PRIMITIVE = "unsupportedPointcutPrimitive";
public static final String MISSING_TYPE_PREVENTS_MATCH = "missingTypePreventsMatch";
public static final String DECP_OBJECT = "decpObject";
public static final String CANT_EXTEND_SELF = "cantExtendSelf";
public static final String INTERFACE_CANT_EXTEND_CLASS = "interfaceExtendClass";
public static final String DECP_HIERARCHY_ERROR = "decpHierarchy";
public static final String MULTIPLE_MATCHES_IN_PRECEDENCE = "multipleMatchesInPrecedence";
public static final String TWO_STARS_IN_PRECEDENCE = "circularityInPrecedenceStar";
public static final String CLASSES_IN_PRECEDENCE = "nonAspectTypesInPrecedence";
public static final String TWO_PATTERN_MATCHES_IN_PRECEDENCE = "circularityInPrecedenceTwo";
public static final String NOT_THROWABLE = "notThrowable";
public static final String ITD_CONS_ON_ASPECT = "itdConsOnAspect";
public static final String ITD_RETURN_TYPE_MISMATCH = "returnTypeMismatch";
public static final String ITD_PARAM_TYPE_MISMATCH = "paramTypeMismatch";
public static final String ITD_VISIBILITY_REDUCTION = "visibilityReduction";
public static final String ITD_DOESNT_THROW = "doesntThrow";
public static final String ITD_OVERRIDDEN_STATIC = "overriddenStatic";
public static final String ITD_OVERIDDING_STATIC = "overridingStatic";
public static final String ITD_CONFLICT = "itdConflict";
public static final String ITD_MEMBER_CONFLICT = "itdMemberConflict";
public static final String ITD_NON_EXPOSED_IMPLEMENTOR = "itdNonExposedImplementor";
public static final String ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE = "itdAbstractMustBePublicOnInterface";
public static final String CANT_OVERRIDE_FINAL_MEMBER = "cantOverrideFinalMember";
public static final String NON_VOID_RETURN = "nonVoidReturn";
public static final String INCOMPATIBLE_RETURN_TYPE = "incompatibleReturnType";
public static final String CANT_THROW_CHECKED = "cantThrowChecked";
public static final String CIRCULAR_DEPENDENCY = "circularDependency";
public static final String MISSING_PER_CLAUSE = "missingPerClause";
public static final String WRONG_PER_CLAUSE = "wrongPerClause";
public static final String ALREADY_WOVEN = "alreadyWoven";
public static final String REWEAVABLE_MODE = "reweavableMode";
public static final String PROCESSING_REWEAVABLE = "processingReweavable";
public static final String MISSING_REWEAVABLE_TYPE = "missingReweavableType";
public static final String VERIFIED_REWEAVABLE_TYPE = "verifiedReweavableType";
public static final String ASPECT_NEEDED = "aspectNeeded";
public static final String REWEAVABLE_ASPECT_NOT_REGISTERED = "reweavableAspectNotRegistered";
public static final String CANT_FIND_TYPE = "cantFindType";
public static final String CANT_FIND_CORE_TYPE = "cantFindCoreType";
public static final String CANT_FIND_TYPE_WITHINPCD = "cantFindTypeWithinpcd";
public static final String CANT_FIND_TYPE_DURING_AROUND_WEAVE = "cftDuringAroundWeave";
public static final String CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT = "cftDuringAroundWeavePreinit";
public static final String CANT_FIND_TYPE_EXCEPTION_TYPE = "cftExceptionType";
public static final String CANT_FIND_TYPE_ARG_TYPE = "cftArgType";
public static final String CANT_FIND_PARENT_TYPE = "cantFindParentType";
public static final String CANT_FIND_PARENT_TYPE_NO_SUB = "cantFindParentTypeNoSub";
public static final String CANT_FIND_TYPE_FIELDS = "cantFindTypeFields";
public static final String CANT_FIND_TYPE_SUPERCLASS = "cantFindTypeSuperclass";
public static final String CANT_FIND_TYPE_INTERFACES = "cantFindTypeInterfaces";
public static final String CANT_FIND_TYPE_METHODS = "cantFindTypeMethods";
public static final String CANT_FIND_TYPE_POINTCUTS = "cantFindTypePointcuts";
public static final String CANT_FIND_TYPE_MODIFIERS = "cantFindTypeModifiers";
public static final String CANT_FIND_TYPE_ANNOTATION = "cantFindTypeAnnotation";
public static final String CANT_FIND_TYPE_ASSIGNABLE = "cantFindTypeAssignable";
public static final String CANT_FIND_TYPE_COERCEABLE = "cantFindTypeCoerceable";
public static final String CANT_FIND_TYPE_JOINPOINT = "cantFindTypeJoinPoint";
public static final String CANT_FIND_TYPE_INTERFACE_METHODS = "cantFindTypeInterfaceMethods";
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 NO_AROUND_ON_SYNCHRONIZATION = "noAroundOnSynchronization";
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";
public static final String NO_MATCH_BECAUSE_SOURCE_RETENTION = "noMatchBecauseSourceRetention";
// Annotation Value messages
public static final String INVALID_ANNOTATION_VALUE = "invalidAnnotationValue";
public static final String UNKNOWN_ANNOTATION_VALUE = "unknownAnnotationValue";
// < Java5 messages
public static final String ATANNOTATION_ONLY_SUPPORTED_AT_JAVA5_LEVEL = "atannotationNeedsJava5";
public static final String ATWITHIN_ONLY_SUPPORTED_AT_JAVA5_LEVEL = "atwithinNeedsJava5";
public static final String ATWITHINCODE_ONLY_SUPPORTED_AT_JAVA5_LEVEL = "atwithincodeNeedsJava5";
public static final String ATTHIS_ONLY_SUPPORTED_AT_JAVA5_LEVEL = "atthisNeedsJava5";
public static final String ATTARGET_ONLY_SUPPORTED_AT_JAVA5_LEVEL = "attargetNeedsJava5";
public static final String ATARGS_ONLY_SUPPORTED_AT_JAVA5_LEVEL = "atargsNeedsJava5";
public static final String DECLARE_ATTYPE_ONLY_SUPPORTED_AT_JAVA5_LEVEL = "declareAtTypeNeedsJava5";
public static final String DECLARE_ATMETHOD_ONLY_SUPPORTED_AT_JAVA5_LEVEL = "declareAtMethodNeedsJava5";
public static final String DECLARE_ATFIELD_ONLY_SUPPORTED_AT_JAVA5_LEVEL = "declareAtFieldNeedsJava5";
public static final String DECLARE_ATCONS_ONLY_SUPPORTED_AT_JAVA5_LEVEL = "declareAtConsNeedsJava5";
public static final String ANNOTATIONS_NEED_JAVA5 = "annotationsRequireJava5";
// Generics
public static final String CANT_DECP_MULTIPLE_PARAMETERIZATIONS = "cantDecpMultipleParameterizations";
public static final String HANDLER_PCD_DOESNT_SUPPORT_PARAMETERS = "noParameterizedTypePatternInHandler";
public static final String INCORRECT_NUMBER_OF_TYPE_ARGUMENTS = "incorrectNumberOfTypeArguments";
public static final String VIOLATES_TYPE_VARIABLE_BOUNDS = "violatesTypeVariableBounds";
public static final String NO_STATIC_INIT_JPS_FOR_PARAMETERIZED_TYPES = "noStaticInitJPsForParameterizedTypes";
public static final String NOT_A_GENERIC_TYPE = "notAGenericType";
public static final String WITHIN_PCD_DOESNT_SUPPORT_PARAMETERS = "noParameterizedTypePatternInWithin";
public static final String THIS_AND_TARGET_DONT_SUPPORT_PARAMETERS = "noParameterizedTypesInThisAndTarget";
public static final String GET_AND_SET_DONT_SUPPORT_DEC_TYPE_PARAMETERS = "noParameterizedTypesInGetAndSet";
public static final String NO_INIT_JPS_FOR_PARAMETERIZED_TYPES = "noInitJPsForParameterizedTypes";
public static final String NO_GENERIC_THROWABLES = "noGenericThrowables";
public static final String WITHINCODE_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES = "noParameterizedDeclaringTypesWithinCode";
public static final String EXECUTION_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES = "noParameterizedDeclaringTypesInExecution";
public static final String CALL_DOESNT_SUPPORT_PARAMETERIZED_DECLARING_TYPES = "noParameterizedDeclaringTypesInCall";
public static final String CANT_REFERENCE_POINTCUT_IN_RAW_TYPE = "noRawTypePointcutReferences";
public static final String HAS_MEMBER_NOT_ENABLED = "hasMemberNotEnabled";
// @AspectJ
public static final String RETURNING_FORMAL_NOT_DECLARED_IN_ADVICE = "returningFormalNotDeclaredInAdvice";
public static final String THROWN_FORMAL_NOT_DECLARED_IN_ADVICE = "thrownFormalNotDeclaredInAdvice";
public static String format(String key) {
return bundle.getString(key);
}
public static String format(String key, Object insert) {
return MessageFormat.format(bundle.getString(key), new Object[] { insert });
}
public static String format(String key, Object insert1, Object insert2) {
return MessageFormat.format(bundle.getString(key), new Object[] { insert1, insert2 });
}
public static String format(String key, Object insert1, Object insert2, Object insert3) {
return MessageFormat.format(bundle.getString(key), new Object[] { insert1, insert2, insert3 });
}
public static String format(String key, Object insert1, Object insert2, Object insert3, Object insert4) {
return MessageFormat.format(bundle.getString(key), new Object[] { insert1, insert2, insert3, insert4 });
}
}
|
391,384 | Bug 391384 WildAnnotationTypePattern.java:231 | OK, I get that this is not supported (and what I *want* here is matching on the existence of the supplied header *among* the headers in the String[]). A feature request might be in order, but a syntax for specifying how you want to match the array would be needed.... The bug that I'm reporting is that trying to *save* this program gets an error that pops up a dialog. This should just become another error marker. It might the compiler that has to change what it throws, but in the end it's the Eclipse IDE that ends up breaking from a user standpoint. (RequestMapping.headers() is of type String[]). public aspect Fail { pointcut testable(): execution(public * @RequestMapping(headers="x-test=test") com.example..*(..)); } java.lang.RuntimeException at org.aspectj.weaver.patterns.WildAnnotationTypePattern.resolveAnnotationValues(WildAnnotationTypePattern.java:231) at org.aspectj.weaver.patterns.WildAnnotationTypePattern.resolveBindings(WildAnnotationTypePattern.java:325) at org.aspectj.weaver.patterns.WildTypePattern.resolveBindings(WildTypePattern.java:657) at org.aspectj.weaver.patterns.SignaturePattern.resolveBindings(SignaturePattern.java:81) at org.a ... n(Worker.java:53) Compile error: RuntimeException thrown: Compiler limitation: annotation value support not implemented for type java.lang.String[] | resolved fixed | edb41e3 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-05T19:14:40Z" | "2012-10-09T05:20:00Z" | org.aspectj.matcher/src/org/aspectj/weaver/patterns/WildAnnotationTypePattern.java | /* *******************************************************************
* Copyright (c) 2004 IBM Corporation.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.IOException;
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.AjAttribute.WeaverVersionInfo;
import org.aspectj.weaver.AnnotatedElement;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.CompressingDataOutputStream;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
/**
* @author colyer
* @author Andy Clement
*/
public class WildAnnotationTypePattern extends AnnotationTypePattern {
private TypePattern typePattern;
private boolean resolved = false;
Map<String, String> annotationValues;
public WildAnnotationTypePattern(TypePattern typePattern) {
super();
this.typePattern = typePattern;
this.setLocation(typePattern.getSourceContext(), typePattern.start, typePattern.end);
}
public WildAnnotationTypePattern(TypePattern typePattern, Map<String, String> annotationValues) {
super();
this.typePattern = typePattern;
this.annotationValues = annotationValues;
// PVAL make the location be from start of type pattern to end of values
this.setLocation(typePattern.getSourceContext(), typePattern.start, typePattern.end);
}
public TypePattern getTypePattern() {
return typePattern;
}
/*
* (non-Javadoc)
*
* @see org.aspectj.weaver.patterns.AnnotationTypePattern#matches(org.aspectj.weaver.AnnotatedElement)
*/
@Override
public FuzzyBoolean matches(AnnotatedElement annotated) {
return matches(annotated, null);
}
/**
* Resolve any annotation values specified, checking they are all well formed (valid names, valid values)
*
* @param annotationType the annotation type for which the values have been specified
* @param scope the scope within which to resolve type references (eg. Color.GREEN)
*/
protected void resolveAnnotationValues(ResolvedType annotationType, IScope scope) {
if (annotationValues == null) {
return;
}
// Check any values specified are OK:
// - the value names are for valid annotation fields
// - the specified values are of the correct type
// - for enums, check the specified values can be resolved in the specified scope
Map<String,String> replacementValues = new HashMap<String,String>();
Set<String> keys = annotationValues.keySet();
ResolvedMember[] ms = annotationType.getDeclaredMethods();
for (String k: keys) {
String key = k;
// a trailing ! indicates the the user expressed key!=value rather than key=value as a match constraint
if (k.endsWith("!")) {
key = key.substring(0, k.length() - 1);
}
String v = annotationValues.get(k);
boolean validKey = false;
for (int i = 0; i < ms.length; i++) {
ResolvedMember resolvedMember = ms[i];
if (resolvedMember.getName().equals(key) && resolvedMember.isAbstract()) {
validKey = true;
ResolvedType t = resolvedMember.getReturnType().resolve(scope.getWorld());
if (t.isEnum()) {
// value must be an enum reference X.Y
int pos = v.lastIndexOf(".");
if (pos == -1) {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "enum"), getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
} else {
String typename = v.substring(0, pos);
ResolvedType rt = scope.lookupType(typename, this).resolve(scope.getWorld());
v = rt.getSignature() + v.substring(pos + 1); // from 'Color.RED' to 'Lp/Color;RED'
replacementValues.put(k, v);
break;
}
} else if (t.isPrimitiveType()) {
if (t.getSignature() == "I") {
try {
int value = Integer.parseInt(v);
replacementValues.put(k, Integer.toString(value));
break;
} catch (NumberFormatException nfe) {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "int"),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
}
} else if (t.getSignature() == "F") {
try {
float value = Float.parseFloat(v);
replacementValues.put(k, Float.toString(value));
break;
} catch (NumberFormatException nfe) {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "float"),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
}
} else if (t.getSignature() == "Z") {
if (v.equalsIgnoreCase("true") || v.equalsIgnoreCase("false")) {
// is it ok !
} else {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "boolean"),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
}
} else if (t.getSignature() == "S") {
try {
short value = Short.parseShort(v);
replacementValues.put(k, Short.toString(value));
break;
} catch (NumberFormatException nfe) {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "short"),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
}
} else if (t.getSignature() == "J") {
try {
replacementValues.put(k, Long.toString(Long.parseLong(v)));
break;
} catch (NumberFormatException nfe) {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "long"),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
}
} else if (t.getSignature() == "D") {
try {
replacementValues.put(k, Double.toString(Double.parseDouble(v)));
break;
} catch (NumberFormatException nfe) {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "double"),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
}
} else if (t.getSignature() == "B") {
try {
replacementValues.put(k, Byte.toString(Byte.parseByte(v)));
break;
} catch (NumberFormatException nfe) {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "byte"),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
}
} else if (t.getSignature() == "C") {
if (v.length() != 3) { // '?'
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.INVALID_ANNOTATION_VALUE, v, "char"),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
} else {
replacementValues.put(k, v.substring(1, 2));
break;
}
} else {
throw new RuntimeException("Not implemented for " + t);
}
} else if (t.equals(ResolvedType.JL_STRING)) {
// nothing to do, it will be OK
} else if (t.equals(ResolvedType.JL_CLASS)) {
String typename = v.substring(0, v.lastIndexOf('.')); // strip off '.class'
ResolvedType rt = scope.lookupType(typename, this).resolve(scope.getWorld());
if (rt.isMissing()) {
IMessage m = MessageUtil.error("Unable to resolve type '" + v + "' specified for value '" + k + "'",
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
}
replacementValues.put(k, rt.getSignature());
break;
} else {
if (t.isAnnotation()) {
if (v.indexOf("(") != -1) {
throw new RuntimeException(
"Compiler limitation: annotation values can only currently be marker annotations (no values): "
+ v);
}
String typename = v.substring(1);
ResolvedType rt = scope.lookupType(typename, this).resolve(scope.getWorld());
if (rt.isMissing()) {
IMessage m = MessageUtil.error(
"Unable to resolve type '" + v + "' specified for value '" + k + "'", getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
}
replacementValues.put(k, rt.getSignature());
break;
} else {
throw new RuntimeException("Compiler limitation: annotation value support not implemented for type "
+ t);
}
}
}
}
if (!validKey) {
IMessage m = MessageUtil.error(WeaverMessages.format(WeaverMessages.UNKNOWN_ANNOTATION_VALUE, annotationType, k),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
}
}
annotationValues.putAll(replacementValues);
}
@Override
public FuzzyBoolean matches(AnnotatedElement annotated, ResolvedType[] parameterAnnotations) {
if (!resolved) {
throw new IllegalStateException("Can't match on an unresolved annotation type pattern");
}
if (annotationValues != null && !typePattern.hasFailedResolution()) {
// PVAL improve this restriction, would allow '*(value=Color.RED)'
throw new IllegalStateException("Cannot use annotationvalues with a wild annotation pattern");
}
if (isForParameterAnnotationMatch()) {
if (parameterAnnotations != null && parameterAnnotations.length != 0) {
for (int i = 0; i < parameterAnnotations.length; i++) {
if (typePattern.matches(parameterAnnotations[i], TypePattern.STATIC).alwaysTrue()) {
return FuzzyBoolean.YES;
}
}
}
} else {
// matches if the type of any of the annotations on the AnnotatedElement is
// matched by the typePattern.
ResolvedType[] annTypes = annotated.getAnnotationTypes();
if (annTypes != null && annTypes.length != 0) {
for (int i = 0; i < annTypes.length; i++) {
if (typePattern.matches(annTypes[i], TypePattern.STATIC).alwaysTrue()) {
return FuzzyBoolean.YES;
}
}
}
}
return FuzzyBoolean.NO;
}
/*
* (non-Javadoc)
*
* @see org.aspectj.weaver.patterns.AnnotationTypePattern#resolve(org.aspectj.weaver.World)
*/
@Override
public void resolve(World world) {
if (!resolved) {
// attempt resolution - this helps with the Spring bug where they resolve() the pointcut in no scope (SPR-5307)
if (typePattern instanceof WildTypePattern && (annotationValues == null || annotationValues.isEmpty())) {
WildTypePattern wildTypePattern = (WildTypePattern) typePattern;
String fullyQualifiedName = wildTypePattern.maybeGetCleanName();
if (fullyQualifiedName != null && fullyQualifiedName.indexOf(".") != -1) {
ResolvedType resolvedType = world.resolve(UnresolvedType.forName(fullyQualifiedName));
if (resolvedType != null && !resolvedType.isMissing()) {
typePattern = new ExactTypePattern(resolvedType, false, false);
}
}
}
resolved = true;
}
}
/**
* This can modify in place, or return a new TypePattern if the type changes.
*/
@Override
public AnnotationTypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding) {
if (!scope.getWorld().isInJava5Mode()) {
scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ANNOTATIONS_NEED_JAVA5), getSourceLocation()));
return this;
}
if (resolved) {
return this;
}
this.typePattern = typePattern.resolveBindings(scope, bindings, false, false);
resolved = true;
if (typePattern instanceof ExactTypePattern) {
ExactTypePattern et = (ExactTypePattern) typePattern;
if (!et.getExactType().resolve(scope.getWorld()).isAnnotation()) {
IMessage m = MessageUtil.error(
WeaverMessages.format(WeaverMessages.REFERENCE_TO_NON_ANNOTATION_TYPE, et.getExactType().getName()),
getSourceLocation());
scope.getWorld().getMessageHandler().handleMessage(m);
resolved = false;
}
ResolvedType annotationType = et.getExactType().resolve(scope.getWorld());
resolveAnnotationValues(annotationType, scope);
ExactAnnotationTypePattern eatp = new ExactAnnotationTypePattern(annotationType, annotationValues);
eatp.copyLocationFrom(this);
if (isForParameterAnnotationMatch()) {
eatp.setForParameterAnnotationMatch();
}
return eatp;
} else {
return this;
}
}
@Override
public AnnotationTypePattern parameterizeWith(Map typeVariableMap, World w) {
WildAnnotationTypePattern ret = new WildAnnotationTypePattern(typePattern.parameterizeWith(typeVariableMap, w));
ret.copyLocationFrom(this);
ret.resolved = resolved;
return ret;
}
private static final byte VERSION = 1; // rev if ser. form changes
@Override
public void write(CompressingDataOutputStream s) throws IOException {
s.writeByte(AnnotationTypePattern.WILD);
s.writeByte(VERSION);
typePattern.write(s);
writeLocation(s);
s.writeBoolean(isForParameterAnnotationMatch());
// PVAL
if (annotationValues == null) {
s.writeInt(0);
} else {
s.writeInt(annotationValues.size());
Set<String> key = annotationValues.keySet();
for (Iterator<String> keys = key.iterator(); keys.hasNext();) {
String k = keys.next();
s.writeUTF(k);
s.writeUTF(annotationValues.get(k));
}
}
}
public static AnnotationTypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException {
WildAnnotationTypePattern ret;
byte version = s.readByte();
if (version > VERSION) {
throw new BCException("ExactAnnotationTypePattern was written by a newer version of AspectJ");
}
TypePattern t = TypePattern.read(s, context);
ret = new WildAnnotationTypePattern(t);
ret.readLocation(context, s);
if (s.getMajorVersion() >= WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ160) {
if (s.readBoolean()) {
ret.setForParameterAnnotationMatch();
}
}
if (s.getMajorVersion() >= WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ160M2) {
int annotationValueCount = s.readInt();
if (annotationValueCount > 0) {
Map<String, String> aValues = new HashMap<String, String>();
for (int i = 0; i < annotationValueCount; i++) {
String key = s.readUTF();
String val = s.readUTF();
aValues.put(key, val);
}
ret.annotationValues = aValues;
}
}
return ret;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof WildAnnotationTypePattern)) {
return false;
}
WildAnnotationTypePattern other = (WildAnnotationTypePattern) obj;
return other.typePattern.equals(typePattern)
&& this.isForParameterAnnotationMatch() == other.isForParameterAnnotationMatch()
&& (annotationValues == null ? other.annotationValues == null : annotationValues.equals(other.annotationValues));
}
@Override
public int hashCode() {
return (((17 + 37 * typePattern.hashCode()) * 37 + (isForParameterAnnotationMatch() ? 0 : 1)) * 37)
+ (annotationValues == null ? 0 : annotationValues.hashCode());
}
@Override
public String toString() {
return "@(" + typePattern.toString() + ")";
}
@Override
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
391,384 | Bug 391384 WildAnnotationTypePattern.java:231 | OK, I get that this is not supported (and what I *want* here is matching on the existence of the supplied header *among* the headers in the String[]). A feature request might be in order, but a syntax for specifying how you want to match the array would be needed.... The bug that I'm reporting is that trying to *save* this program gets an error that pops up a dialog. This should just become another error marker. It might the compiler that has to change what it throws, but in the end it's the Eclipse IDE that ends up breaking from a user standpoint. (RequestMapping.headers() is of type String[]). public aspect Fail { pointcut testable(): execution(public * @RequestMapping(headers="x-test=test") com.example..*(..)); } java.lang.RuntimeException at org.aspectj.weaver.patterns.WildAnnotationTypePattern.resolveAnnotationValues(WildAnnotationTypePattern.java:231) at org.aspectj.weaver.patterns.WildAnnotationTypePattern.resolveBindings(WildAnnotationTypePattern.java:325) at org.aspectj.weaver.patterns.WildTypePattern.resolveBindings(WildTypePattern.java:657) at org.aspectj.weaver.patterns.SignaturePattern.resolveBindings(SignaturePattern.java:81) at org.a ... n(Worker.java:53) Compile error: RuntimeException thrown: Compiler limitation: annotation value support not implemented for type java.lang.String[] | resolved fixed | edb41e3 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-05T19:14:40Z" | "2012-10-09T05:20:00Z" | tests/bugs172/pr391384/Code.java | |
391,384 | Bug 391384 WildAnnotationTypePattern.java:231 | OK, I get that this is not supported (and what I *want* here is matching on the existence of the supplied header *among* the headers in the String[]). A feature request might be in order, but a syntax for specifying how you want to match the array would be needed.... The bug that I'm reporting is that trying to *save* this program gets an error that pops up a dialog. This should just become another error marker. It might the compiler that has to change what it throws, but in the end it's the Eclipse IDE that ends up breaking from a user standpoint. (RequestMapping.headers() is of type String[]). public aspect Fail { pointcut testable(): execution(public * @RequestMapping(headers="x-test=test") com.example..*(..)); } java.lang.RuntimeException at org.aspectj.weaver.patterns.WildAnnotationTypePattern.resolveAnnotationValues(WildAnnotationTypePattern.java:231) at org.aspectj.weaver.patterns.WildAnnotationTypePattern.resolveBindings(WildAnnotationTypePattern.java:325) at org.aspectj.weaver.patterns.WildTypePattern.resolveBindings(WildTypePattern.java:657) at org.aspectj.weaver.patterns.SignaturePattern.resolveBindings(SignaturePattern.java:81) at org.a ... n(Worker.java:53) Compile error: RuntimeException thrown: Compiler limitation: annotation value support not implemented for type java.lang.String[] | resolved fixed | edb41e3 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-05T19:14:40Z" | "2012-10-09T05:20:00Z" | tests/src/org/aspectj/systemtest/ajc172/Ajc172Tests.java | /*******************************************************************************
* Copyright (c) 2012 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc172;
import java.io.File;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.testing.XMLBasedAjcTestCase;
/**
* @author Andy Clement
*/
public class Ajc172Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// if the test is failing because the classes won't run, remove the run blocks from the ajc172.xml entry and re-run to check signatures.
public void testSignatures_pr394535() throws Exception {
runTest("signatures");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Bug2$ClassA2"); // the working one
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T::LBug2$Interface12;:LBug2$Interface22;>Ljava/lang/Object;Ljava/io/Serializable;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Bug$ClassA");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T::LBug$Interface1;:LBug$Interface2;>Ljava/lang/Object;Ljava/io/Serializable;", sss);
}
// extends
public void testPSignatures_pr399590() throws Exception {
runTest("p signatures 1");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Cage");
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal<+LCage<TT;>;>;>LBar;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal2<+LCage2<TT;>;>;>LBar2;Ljava/io/Serializable;", sss);
}
// extends two classes
public void testPSignatures_pr399590_2() throws Exception {
runTest("p signatures 2");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Cage");
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal<+LCage<TT;LIntf;>;LIntf;>;Q:Ljava/lang/Object;>LBar;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal2<+LCage2<TT;LIntf2;>;LIntf2;>;Q:Ljava/lang/Object;>LBar2;Ljava/io/Serializable;", sss);
}
// super
public void testPSignatures_pr399590_3() throws Exception {
runTest("p signatures 3");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Cage");
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal<-LXXX<TT;>;>;>LBar;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal2<-LXXX2<TT;>;>;>LBar2;Ljava/io/Serializable;", sss);
}
// super
public void testPSignatures_pr399590_4() throws Exception {
runTest("p signatures 4");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Cage");
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal<-LXXX<TT;>;LYYY;>;>LBar;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal2<-LXXX2<TT;>;LYYY2;>;>LBar2;Ljava/io/Serializable;", sss);
}
// unbound
public void testPSignatures_pr399590_5() throws Exception {
runTest("p signatures 5");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Cage");
String sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal<*>;>LBar;", sss);
jc = getClassFrom(ajc.getSandboxDirectory(),"Cage2");
sss = jc.getSignatureAttribute().getSignature();
assertEquals("<T:LAnimal2<*>;>LBar2;Ljava/io/Serializable;", sss);
}
public void testIfPointcutNames_pr398246() throws Exception {
runTest("if pointcut names");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$andy", m.getName());
}
public void testIfPointcutNames_pr398246_2() throws Exception {
runTest("if pointcut names 2");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$fred", m.getName());
}
// fully qualified annotation name is used
public void testIfPointcutNames_pr398246_3() throws Exception {
runTest("if pointcut names 3");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$barney", m.getName());
}
// compiling a class later than the initial build - does it pick up the
// right if clause name?
public void testIfPointcutNames_pr398246_4() throws Exception {
runTest("if pointcut names 4");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$sid", m.getName());
}
// new style generated names
public void testIfPointcutNames_pr398246_5() throws Exception {
runTest("if pointcut names 5");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$ac0cb804", m.getName());
jc = getClassFrom(ajc.getSandboxDirectory(), "X2");
m = getMethodStartsWith(jc, "ajc$if");
assertEquals("ajc$if$ac0cb804", m.getName());
}
// new style generated names - multiple ifs in one pointcut
public void testIfPointcutNames_pr398246_6() throws Exception {
runTest("if pointcut names 6");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if",1);
assertEquals("ajc$if$aac93da8", m.getName());
m = getMethodStartsWith(jc, "ajc$if",2);
assertEquals("ajc$if$1$ae5e778a", m.getName());
}
// new style generated names - multiple ifs in one advice
public void testIfPointcutNames_pr398246_7() throws Exception {
runTest("if pointcut names 7");
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method m = getMethodStartsWith(jc, "ajc$if",1);
assertEquals("ajc$if$1$ac0607c", m.getName());
m = getMethodStartsWith(jc, "ajc$if",2);
assertEquals("ajc$if$1$1$4d4baf36", m.getName());
}
public void testOptionalAspects_pr398588() {
runTest("optional aspects");
}
public void testInconsistentClassFile_pr389750() {
runTest("inconsistent class file");
}
public void testInconsistentClassFile_pr389750_2() {
runTest("inconsistent class file 2");
}
public void testInconsistentClassFile_pr389750_3() {
runTest("inconsistent class file 3");
}
public void testInconsistentClassFile_pr389750_4() {
runTest("inconsistent class file 4");
}
public void testAnnotationValueError_pr389752_1() {
runTest("annotation value error 1");
}
public void testAnnotationValueError_pr389752_2() {
runTest("annotation value error 2");
}
// this needs some cleverness to fix... the annotation value is parsed as a
// string and then not checked
// to see if the user is accidentally supplying, for example, an enum value.
// Due to the use of strings, it
// is hard to check. The verification code might go here:
// WildAnnotationTypePattern, line 205 (the string case)
// public void testAnnotationValueError_pr389752_3() {
// runTest("annotation value error 3");
// }
// ---
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc172Tests.class);
}
@Override
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc172/ajc172.xml");
}
}
|
318,878 | Bug 318878 Pertarget aspect instantiation is not thread-safe | The way in which pertarget aspects compiled with ajc check if a given target already has an aspect is not thread safe. When two different threads trigger an advice on a target object for the first time at the same time, sometimes the aspect for that target gets created twice. The following code demonstrates the problem: The following pertarget aspect will add itself to a (synchronized) set in another class in it's constructor. aspect Pertarget pertarget(execution(void foo())) { public Pertarget() { Main.aspects.add(this); // Add this instance to the set in Main } before(): execution(void foo()) {} // Empty advice to trigger creation } This class creates 10000 target objects and has two separate threads call a method (that causes the aspect to be instantiated) on each object. The aspects add themselves to the "aspects" set and this set's size is printed when all threads have finished. import java.util.Collections; import java.util.IdentityHashMap; import java.util.Set; public class Main { public static Set aspects = Collections.synchronizedSet( Collections.newSetFromMap(new IdentityHashMap())); public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 10000; ++i) { final Main m = new Main(); // Create a new target for the aspect Runnable r = new Runnable() { public void run() { m.foo(); } // This will trigger the advice }; Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); t1.join(); t2.join(); } System.out.println(aspects.size()); // Should be 10000 } private void foo() {} } When compiled with ajc and run, the main method prints values over 10000 (something like 10030-10060 typically), which means that some target objects get multiple aspect instances. In my own application I sometimes also saw some threads accessing partially built aspect instances. This was quite rare however and I wasn't able to make a test case for it. The ajc version (the current stable) used was: AspectJ Compiler 1.6.8 (1.6.8 - Built: Friday Jan 8, 2010 at 21:53:37 GMT) - Eclipse Compiler 0.785_R33x, 3.3 The sun vm version was: Java(TM) SE Runtime Environment (build 1.6.0_20-b02) Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode) I investigated the source of this problem: the ajc compiler generates the following (decompiled) method into the aspect class: public static void ajc$perObjectBind(Object obj) { if((obj instanceof ajcMightHaveAspect) && ((ajcMightHaveAspect)obj).perObjectGet() == null) ((ajcMightHaveAspect)obj).perObjectSet(new Pertarget()); } , which obviously is not thread safe. | resolved fixed | be5a530 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-02-25T23:18:12Z" | "2010-07-05T11:40:00Z" | org.aspectj.matcher/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 Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.lang.reflect.Modifier;
//import org.aspectj.weaver.ResolvedType.Name;
/**
* The AjcMemberMaker is responsible for creating the representations of methods/fields/etc that are placed in both aspects and
* affected target types. It uses the NameMangler class to create the actual names that will be used.
*/
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 BRIDGE = 0x0040;
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
.forSignature("Lorg/aspectj/runtime/internal/AroundClosure;");
public static final UnresolvedType CONVERSIONS_TYPE = UnresolvedType.forSignature("Lorg/aspectj/runtime/internal/Conversions;");
public static final UnresolvedType NO_ASPECT_BOUND_EXCEPTION = UnresolvedType
.forSignature("Lorg/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.JL_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.JL_CLASS });
return rm;
}
// PTWIMPL ResolvedMember for getWithinTypeName() method
public static ResolvedMember perTypeWithinGetWithinTypeNameMethod(UnresolvedType declaringType, boolean inJava5Mode) {
// public String getWithinTypeName()
ResolvedMemberImpl rm = new ResolvedMemberImpl(Member.METHOD, declaringType, Modifier.PUBLIC, UnresolvedType.JL_STRING, // return
// value
NameMangler.PERTYPEWITHIN_GETWITHINTYPENAME_METHOD, UnresolvedType.NONE);
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, boolean inJava5Mode) {
UnresolvedType parameterType = null;
if (inJava5Mode) {
parameterType = UnresolvedType.forRawTypeName("java.lang.Class");
} else {
parameterType = UnresolvedType.forSignature("Ljava/lang/Class;");
}
return new ResolvedMemberImpl(Member.METHOD, declaringType, PUBLIC_STATIC, declaringType, "aspectOf",
new UnresolvedType[] { parameterType });
// return new ResolvedMemberImpl(Member.METHOD,
// declaringType, PUBLIC_STATIC, "aspectOf",
// "(Ljava/lang/Class;)" + declaringType.getSignature());
}
/*
* public static ResolvedMember perTypeWithinGetWithinTypeMethod(UnresolvedType declaringType, boolean inJava5Mode) {
* UnresolvedType returnType = null; if (inJava5Mode) { returnType = UnresolvedType.forRawTypeName("java.lang.Class"); } else {
* returnType = UnresolvedType.forSignature("Ljava/lang/Class;"); } return new
* ResolvedMemberImpl(Member.METHOD,declaringType,Modifier.PUBLIC,ResolvedType.JAVA_LANG_STRING,"getWithinType",new
* UnresolvedType[]{}); }
*/
// PTWIMPL ResolvedMember for hasAspect(), declared in aspect
public static ResolvedMember perTypeWithinHasAspectMethod(UnresolvedType declaringType, boolean inJava5Mode) {
UnresolvedType parameterType = null;
if (inJava5Mode) {
parameterType = UnresolvedType.forRawTypeName("java.lang.Class");
} else {
parameterType = UnresolvedType.forSignature("Ljava/lang/Class;");
}
return new ResolvedMemberImpl(Member.METHOD, declaringType, PUBLIC_STATIC, UnresolvedType.BOOLEAN, "hasAspect",
new UnresolvedType[] { parameterType });
// return new ResolvedMemberImpl(Member.METHOD,
// declaringType, PUBLIC_STATIC, "hasAspect",
// "(Ljava/lang/Class;)Z");
}
// -- privileged accessors
public static ResolvedMember privilegedAccessMethodForMethod(UnresolvedType aspectType, ResolvedMember method) {
return new ResolvedMemberImpl(Member.METHOD, method.getDeclaringType(), Modifier.PUBLIC
| (Modifier.isStatic(method.getModifiers()) ? Modifier.STATIC : 0), method.getReturnType(),
NameMangler.privilegedAccessMethodForMethod(method.getName(), method.getDeclaringType(), aspectType),
method.getParameterTypes(), method.getExceptions());
}
/**
* Return a resolvedmember representing the synthetic getter for the field. The old style (<1.6.9) is a heavyweight static
* method with a long name. The new style (1.6.9 and later) is short, and reusable across aspects.
*
* @param aspectType the aspect attempting the access
* @param field the field to be accessed
* @param shortSyntax is the old (long) or new (short) style format being used
* @return a resolvedmember representing the synthetic getter
*/
public static ResolvedMember privilegedAccessMethodForFieldGet(UnresolvedType aspectType, Member field, boolean shortSyntax) {
UnresolvedType fieldDeclaringType = field.getDeclaringType();
if (shortSyntax) {
UnresolvedType[] args = null;
if (Modifier.isStatic(field.getModifiers())) {
args = ResolvedType.NONE;
} else {
args = new UnresolvedType[] { fieldDeclaringType };
}
StringBuffer name = new StringBuffer("ajc$get$");
name.append(field.getName());
return new ResolvedMemberImpl(Member.METHOD, fieldDeclaringType, PUBLIC_STATIC, field.getReturnType(), name.toString(),
args);
} else {
String getterName = NameMangler.privilegedAccessMethodForFieldGet(field.getName(), fieldDeclaringType, aspectType);
String sig;
if (Modifier.isStatic(field.getModifiers())) {
sig = "()" + field.getReturnType().getSignature();
} else {
sig = "(" + fieldDeclaringType.getSignature() + ")" + field.getReturnType().getSignature();
}
return new ResolvedMemberImpl(Member.METHOD, fieldDeclaringType, PUBLIC_STATIC, getterName, sig);
}
}
/**
* Return a resolvedmember representing the synthetic setter for the field. The old style (<1.6.9) is a heavyweight static
* method with a long name. The new style (1.6.9 and later) is short, not always static, and reusable across aspects.
*
* @param aspectType the aspect attempting the access
* @param field the field to be accessed
* @param shortSyntax is the old or new style format being used
* @return a resolvedmember representing the synthetic setter
*/
public static ResolvedMember privilegedAccessMethodForFieldSet(UnresolvedType aspectType, Member field, boolean shortSyntax) {
UnresolvedType fieldDeclaringType = field.getDeclaringType();
if (shortSyntax) {
UnresolvedType[] args = null;
if (Modifier.isStatic(field.getModifiers())) {
args = new UnresolvedType[] { field.getType() };
} else {
args = new UnresolvedType[] { fieldDeclaringType, field.getType() };
}
StringBuffer name = new StringBuffer("ajc$set$");
name.append(field.getName());
return new ResolvedMemberImpl(Member.METHOD, fieldDeclaringType, PUBLIC_STATIC, UnresolvedType.VOID, name.toString(),
args);
} else {
String setterName = NameMangler.privilegedAccessMethodForFieldSet(field.getName(), fieldDeclaringType, aspectType);
String sig;
if (Modifier.isStatic(field.getModifiers())) {
sig = "(" + field.getReturnType().getSignature() + ")V";
} else {
sig = "(" + fieldDeclaringType.getSignature() + field.getReturnType().getSignature() + ")V";
}
return new ResolvedMemberImpl(Member.METHOD, fieldDeclaringType, PUBLIC_STATIC, setterName, sig);
}
}
// --- inline accessors
// ??? can eclipse handle a transform this weird without putting synthetics into the mix
public static ResolvedMember superAccessMethod(UnresolvedType baseType, ResolvedMember method) {
UnresolvedType[] paramTypes = method.getParameterTypes();
// if (!method.isStatic()) {
// paramTypes = UnresolvedType.insert(method.getDeclaringType(), paramTypes);
// }
return new ResolvedMemberImpl(Member.METHOD, baseType, Modifier.PUBLIC, method.getReturnType(),
NameMangler.superDispatchMethod(baseType, method.getName()), paramTypes, method.getExceptions());
}
public static ResolvedMember inlineAccessMethodForMethod(UnresolvedType aspectType, ResolvedMember method) {
UnresolvedType[] paramTypes = method.getParameterTypes();
if (!Modifier.isStatic(method.getModifiers())) {
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 (Modifier.isStatic(field.getModifiers())) {
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 (Modifier.isStatic(field.getModifiers())) {
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, UnresolvedType.VOID,
NameMangler.postIntroducedConstructor(aspectType, targetType), UnresolvedType.insert(targetType, paramTypes));
}
public static ResolvedMember itdAtDeclareParentsField(ResolvedType targetType, UnresolvedType itdType, UnresolvedType aspectType) {
return new ResolvedMemberImpl(Member.FIELD, targetType, Modifier.PRIVATE, itdType, NameMangler.itdAtDeclareParentsField(
aspectType, itdType), null);
}
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, UnresolvedType.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()), Modifier.isStatic(field.getModifiers()) ? "()V" : "("
+ field.getDeclaringType().getSignature() + ")V");
}
private static int makePublicNonFinal(int modifiers) {
return (modifiers & ~VISIBILITY & ~Modifier.FINAL) | Modifier.PUBLIC;
}
private static int makeNonFinal(int modifiers) {
return (modifiers & ~Modifier.FINAL);
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static ResolvedMember interFieldSetDispatcher(ResolvedMember field, UnresolvedType aspectType) {
ResolvedMember rm = new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC, UnresolvedType.VOID,
NameMangler.interFieldSetDispatcher(aspectType, field.getDeclaringType(), field.getName()), Modifier.isStatic(field
.getModifiers()) ? new UnresolvedType[] { field.getReturnType() } : new UnresolvedType[] {
field.getDeclaringType(), field.getReturnType() });
rm.setTypeVariables(field.getTypeVariables());
return rm;
}
/**
* This static method goes on the aspect that declares the inter-type field
*/
public static ResolvedMember interFieldGetDispatcher(ResolvedMember field, UnresolvedType aspectType) {
ResolvedMember rm = new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC, field.getReturnType(),
NameMangler.interFieldGetDispatcher(aspectType, field.getDeclaringType(), field.getName()), Modifier.isStatic(field
.getModifiers()) ? UnresolvedType.NONE : new UnresolvedType[] { field.getDeclaringType() },
UnresolvedType.NONE);
rm.setTypeVariables(field.getTypeVariables());
return rm;
}
// 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. Field names for ITDs onto interfaces are handled below.
*/
public static ResolvedMember interFieldClassField(ResolvedMember field, UnresolvedType aspectType, boolean newStyle) {
int modifiers = (newStyle ? makeNonFinal(field.getModifiers()) : makePublicNonFinal(field.getModifiers()));
String name = null;
if (newStyle) {
name = field.getName();
} else {
name = NameMangler.interFieldClassField(field.getModifiers(), aspectType, field.getDeclaringType(), field.getName());
}
return new ResolvedMemberImpl(Member.FIELD, field.getDeclaringType(), modifiers, field.getReturnType(), name,
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, boolean newStyle) {
String name = null;
if (newStyle) {
name = field.getName();
} else {
name = NameMangler.interFieldInterfaceField(aspectType, field.getDeclaringType(), field.getName());
}
return new ResolvedMemberImpl(Member.FIELD, onClass, makePublicNonFinal(field.getModifiers()), field.getReturnType(),
name, 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;
}
ResolvedMember rm = new ResolvedMemberImpl(Member.METHOD, onType, modifiers, UnresolvedType.VOID,
NameMangler.interFieldInterfaceSetter(aspectType, field.getDeclaringType(), field.getName()),
new UnresolvedType[] { field.getReturnType() }, UnresolvedType.NONE);
rm.setTypeVariables(field.getTypeVariables());
return rm;
}
/**
* 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;
}
ResolvedMember rm = new ResolvedMemberImpl(Member.METHOD, onType, modifiers, field.getReturnType(),
NameMangler.interFieldInterfaceGetter(aspectType, field.getDeclaringType(), field.getName()), UnresolvedType.NONE,
UnresolvedType.NONE);
rm.setTypeVariables(field.getTypeVariables());
return rm;
}
/**
* 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;
}
ResolvedMemberImpl rmi = new ResolvedMemberImpl(Member.METHOD, meth.getDeclaringType(), modifiers, meth.getReturnType(),
NameMangler.interMethod(meth.getModifiers(), aspectType, meth.getDeclaringType(), meth.getName()),
meth.getParameterTypes(), meth.getExceptions());
rmi.setParameterNames(meth.getParameterNames());
rmi.setTypeVariables(meth.getTypeVariables());
return rmi;
}
/**
* 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 interMethodBridger(ResolvedMember meth, UnresolvedType aspectType, boolean onInterface) {
// if (Modifier.isPublic(meth.getModifiers()) && !onInterface)
// return meth;
int modifiers = makePublicNonFinal(meth.getModifiers()) | BRIDGE;
if (onInterface) {
modifiers |= Modifier.ABSTRACT;
}
ResolvedMemberImpl rmi = new ResolvedMemberImpl(Member.METHOD, meth.getDeclaringType(), modifiers, meth.getReturnType(),
NameMangler.interMethod(meth.getModifiers(), aspectType, meth.getDeclaringType(), meth.getName()),
meth.getParameterTypes(), meth.getExceptions());
rmi.setTypeVariables(meth.getTypeVariables());
return rmi;
}
/**
* Sometimes the intertyped method requires a bridge method alongside it. For example if the method 'N SomeI<N>.m()' is put onto
* an interface 'interface I<N extends Number>' and then a concrete implementation is 'class C implements I<Float>' then the ITD
* on the interface will be 'Number m()', whereas the ITD on the 'topmostimplementor' will be 'Float m()'. A bridge method needs
* to be created in the topmostimplementor 'Number m()' that delegates to 'Float m()'
*/
public static ResolvedMember bridgerToInterMethod(ResolvedMember meth, UnresolvedType aspectType) {
int modifiers = makePublicNonFinal(meth.getModifiers());
ResolvedMemberImpl rmi = new ResolvedMemberImpl(Member.METHOD, aspectType, modifiers, meth.getReturnType(),
NameMangler.interMethod(meth.getModifiers(), aspectType, meth.getDeclaringType(), meth.getName()),
meth.getParameterTypes(), meth.getExceptions());
rmi.setTypeVariables(meth.getTypeVariables());
return rmi;
}
/**
* 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 (!Modifier.isStatic(meth.getModifiers())) {
paramTypes = UnresolvedType.insert(meth.getDeclaringType(), paramTypes);
}
ResolvedMemberImpl rmi = new ResolvedMemberImpl(Member.METHOD, aspectType, PUBLIC_STATIC, meth.getReturnType(),
NameMangler.interMethodDispatcher(aspectType, meth.getDeclaringType(), meth.getName()), paramTypes,
meth.getExceptions());
rmi.setParameterNames(meth.getParameterNames());
rmi.setTypeVariables(meth.getTypeVariables());
return rmi;
}
/**
* 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 (!Modifier.isStatic(meth.getModifiers())) {
paramTypes = UnresolvedType.insert(meth.getDeclaringType(), paramTypes);
}
int modifiers = PUBLIC_STATIC;
if (Modifier.isStrict(meth.getModifiers())) {
modifiers |= Modifier.STRICT;
}
ResolvedMemberImpl rmi = new ResolvedMemberImpl(Member.METHOD, aspectType, modifiers, meth.getReturnType(),
NameMangler.interMethodBody(aspectType, meth.getDeclaringType(), meth.getName()), paramTypes, meth.getExceptions());
rmi.setParameterNames(meth.getParameterNames());
rmi.setTypeVariables(meth.getTypeVariables());
return rmi;
}
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.forSignature("Lorg/aspectj/lang/annotation/Aspect;");
public final static UnresolvedType BEFORE_ANNOTATION = UnresolvedType.forSignature("Lorg/aspectj/lang/annotation/Before;");
public final static UnresolvedType AROUND_ANNOTATION = UnresolvedType.forSignature("Lorg/aspectj/lang/annotation/Around;");
public final static UnresolvedType AFTERRETURNING_ANNOTATION = UnresolvedType
.forSignature("Lorg/aspectj/lang/annotation/AfterReturning;");
public final static UnresolvedType AFTERTHROWING_ANNOTATION = UnresolvedType
.forSignature("Lorg/aspectj/lang/annotation/AfterThrowing;");
public final static UnresolvedType AFTER_ANNOTATION = UnresolvedType.forSignature("Lorg/aspectj/lang/annotation/After;");
public final static UnresolvedType POINTCUT_ANNOTATION = UnresolvedType.forSignature("Lorg/aspectj/lang/annotation/Pointcut;");
public final static UnresolvedType DECLAREERROR_ANNOTATION = UnresolvedType
.forSignature("Lorg/aspectj/lang/annotation/DeclareError;");
public final static UnresolvedType DECLAREWARNING_ANNOTATION = UnresolvedType
.forSignature("Lorg/aspectj/lang/annotation/DeclareWarning;");
public final static UnresolvedType DECLAREPRECEDENCE_ANNOTATION = UnresolvedType
.forSignature("Lorg/aspectj/lang/annotation/DeclarePrecedence;");
// public final static UnresolvedType DECLAREIMPLEMENTS_ANNOTATION =
// UnresolvedType.forSignature("Lorg/aspectj/lang/annotation/DeclareImplements;");
public final static UnresolvedType DECLAREPARENTS_ANNOTATION = UnresolvedType
.forSignature("Lorg/aspectj/lang/annotation/DeclareParents;");
public final static UnresolvedType DECLAREMIXIN_ANNOTATION = UnresolvedType
.forSignature("Lorg/aspectj/lang/annotation/DeclareMixin;");
public final static UnresolvedType TYPEX_JOINPOINT = UnresolvedType.forSignature("Lorg/aspectj/lang/JoinPoint;");
public final static UnresolvedType TYPEX_PROCEEDINGJOINPOINT = UnresolvedType
.forSignature("Lorg/aspectj/lang/ProceedingJoinPoint;");
public final static UnresolvedType TYPEX_STATICJOINPOINT = UnresolvedType
.forSignature("Lorg/aspectj/lang/JoinPoint$StaticPart;");
public final static UnresolvedType TYPEX_ENCLOSINGSTATICJOINPOINT = UnresolvedType
.forSignature("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;");
}
|
404,594 | Bug 404594 Assertion failed at ResolvedType.java:614 | null | resolved fixed | 4e34477 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-04-01T22:29:13Z" | "2013-03-28T19:46:40Z" | org.aspectj.matcher/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 Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur @AspectJ ITDs
* ******************************************************************/
package org.aspectj.weaver;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
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.AjAttribute.WeaverVersionInfo;
import org.aspectj.weaver.Iterators.Getter;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.PerClause;
public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement {
public static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0];
public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P";
// Set temporarily during a type pattern match call - this currently used to hold the
// annotations that may be attached to a type when it used as a parameter
public ResolvedType[] temporaryAnnotationTypes;
private ResolvedType[] resolvedTypeParams;
private String binaryPath;
protected World world;
private int bits;
private static int AnnotationBitsInitialized = 0x0001;
private static int AnnotationMarkedInherited = 0x0002;
private static int MungersAnalyzed = 0x0004;
private static int HasParentMunger = 0x0008;
private static int TypeHierarchyCompleteBit = 0x0010;
private static int GroovyObjectInitialized = 0x0020;
private static int IsGroovyObject = 0x0040;
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;
}
public int getSize() {
return 1;
}
/**
* 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<ResolvedType> getDirectSupertypes() {
Iterator<ResolvedType> interfacesIterator = Iterators.array(getDeclaredInterfaces());
ResolvedType superclass = getSuperclass();
if (superclass == null) {
return interfacesIterator;
} else {
return Iterators.snoc(interfacesIterator, superclass);
}
}
public abstract ResolvedMember[] getDeclaredFields();
public abstract ResolvedMember[] getDeclaredMethods();
public abstract ResolvedType[] getDeclaredInterfaces();
public abstract ResolvedMember[] getDeclaredPointcuts();
public boolean isCacheable() {
return true;
}
/**
* @return the superclass of this type, or null (if this represents a jlObject, primitive, or void)
*/
public abstract ResolvedType getSuperclass();
public abstract int getModifiers();
// return true if this resolved type couldn't be found (but we know it's name maybe)
public boolean isMissing() {
return false;
}
// FIXME asc I wonder if in some circumstances MissingWithKnownSignature
// should not be considered
// 'really' missing as some code can continue based solely on the signature
public static boolean isMissing(UnresolvedType unresolved) {
if (unresolved instanceof ResolvedType) {
ResolvedType resolved = (ResolvedType) unresolved;
return resolved.isMissing();
} else {
return (unresolved == MISSING);
}
}
public ResolvedType[] getAnnotationTypes() {
return EMPTY_RESOLVED_TYPE_ARRAY;
}
public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) {
return null;
}
// 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.
protected static Set<String> validBoxing = new HashSet<String>();
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
@Override
public boolean equals(Object other) {
if (other instanceof ResolvedType) {
return this == other;
} else {
return super.equals(other);
}
}
// ---- difficult things
/**
* returns an iterator through all of the fields of this type, in order for checking from JVM spec 2ed 5.4.3.2. This means that
* the order is
* <p/>
* <ul>
* <li>fields from current class</li>
* <li>recur into direct superinterfaces</li>
* <li>recur into superclass</li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral out into 2^n land.
*/
public Iterator<ResolvedMember> getFields() {
final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter();
Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() {
public Iterator<ResolvedType> get(ResolvedType o) {
return dupFilter.filter(o.getDirectSupertypes());
}
};
return Iterators.mapOver(Iterators.recur(this, typeGetter), FieldGetterInstance);
}
/**
* returns an iterator through all of the methods of this type, in order for checking from JVM spec 2ed 5.4.3.3. This means that
* the order is
* <p/>
* <ul>
* <li>methods from current class</li>
* <li>recur into superclass, all the way up, not touching interfaces</li>
* <li>recur into all superinterfaces, in some unspecified order (but those 'closest' to this type are first)</li>
* </ul>
* <p/>
*
* @param wantGenerics is true if the caller would like all generics information, otherwise those methods are collapsed to their
* erasure
*/
public Iterator<ResolvedMember> getMethods(boolean wantGenerics, boolean wantDeclaredParents) {
return Iterators.mapOver(getHierarchy(wantGenerics, wantDeclaredParents), MethodGetterInstance);
}
public Iterator<ResolvedMember> getMethodsIncludingIntertypeDeclarations(boolean wantGenerics, boolean wantDeclaredParents) {
return Iterators.mapOver(getHierarchy(wantGenerics, wantDeclaredParents), MethodGetterWithItdsInstance);
}
/**
* An Iterators.Getter that returns an iterator over all methods declared on some resolved type.
*/
private static class MethodGetter implements Iterators.Getter<ResolvedType, ResolvedMember> {
public Iterator<ResolvedMember> get(ResolvedType type) {
return Iterators.array(type.getDeclaredMethods());
}
}
/**
* An Iterators.Getter that returns an iterator over all pointcuts declared on some resolved type.
*/
private static class PointcutGetter implements Iterators.Getter<ResolvedType, ResolvedMember> {
public Iterator<ResolvedMember> get(ResolvedType o) {
return Iterators.array(o.getDeclaredPointcuts());
}
}
// OPTIMIZE could cache the result of discovering ITDs
// Getter that returns all declared methods for a type through an iterator - including intertype declarations
private static class MethodGetterIncludingItds implements Iterators.Getter<ResolvedType, ResolvedMember> {
public Iterator<ResolvedMember> get(ResolvedType type) {
ResolvedMember[] methods = type.getDeclaredMethods();
if (type.interTypeMungers != null) {
int additional = 0;
for (ConcreteTypeMunger typeTransformer : type.interTypeMungers) {
ResolvedMember rm = typeTransformer.getSignature();
// BUG won't this include fields? When we are looking for methods
if (rm != null) { // new parent type munger can have null signature
additional++;
}
}
if (additional > 0) {
ResolvedMember[] methods2 = new ResolvedMember[methods.length + additional];
System.arraycopy(methods, 0, methods2, 0, methods.length);
additional = methods.length;
for (ConcreteTypeMunger typeTransformer : type.interTypeMungers) {
ResolvedMember rm = typeTransformer.getSignature();
if (rm != null) { // new parent type munger can have null signature
methods2[additional++] = typeTransformer.getSignature();
}
}
methods = methods2;
}
}
return Iterators.array(methods);
}
}
/**
* An Iterators.Getter that returns an iterator over all fields declared on some resolved type.
*/
private static class FieldGetter implements Iterators.Getter<ResolvedType, ResolvedMember> {
public Iterator<ResolvedMember> get(ResolvedType type) {
return Iterators.array(type.getDeclaredFields());
}
}
private final static MethodGetter MethodGetterInstance = new MethodGetter();
private final static MethodGetterIncludingItds MethodGetterWithItdsInstance = new MethodGetterIncludingItds();
private final static PointcutGetter PointcutGetterInstance = new PointcutGetter();
private final static FieldGetter FieldGetterInstance = new FieldGetter();
/**
* Return an iterator over the types in this types hierarchy - starting with this type first, then all superclasses up to Object
* and then all interfaces (starting with those 'nearest' this type).
*
* @param wantGenerics true if the caller wants full generic information
* @param wantDeclaredParents true if the caller even wants those parents introduced via declare parents
* @return an iterator over all types in the hierarchy of this type
*/
public Iterator<ResolvedType> getHierarchy() {
return getHierarchy(false, false);
}
public Iterator<ResolvedType> getHierarchy(final boolean wantGenerics, final boolean wantDeclaredParents) {
final Iterators.Getter<ResolvedType, ResolvedType> interfaceGetter = new Iterators.Getter<ResolvedType, ResolvedType>() {
List<String> alreadySeen = new ArrayList<String>(); // Strings are signatures (ResolvedType.getSignature())
public Iterator<ResolvedType> get(ResolvedType type) {
ResolvedType[] interfaces = type.getDeclaredInterfaces();
// remove interfaces introduced by declare parents
// relatively expensive but hopefully uncommon
if (!wantDeclaredParents && type.hasNewParentMungers()) {
// Throw away interfaces from that array if they were decp'd onto here
List<Integer> forRemoval = new ArrayList<Integer>();
for (ConcreteTypeMunger munger : type.interTypeMungers) {
if (munger.getMunger() != null) {
ResolvedTypeMunger m = munger.getMunger();
if (m.getKind() == ResolvedTypeMunger.Parent) {
ResolvedType newType = ((NewParentTypeMunger) m).getNewParent();
if (!wantGenerics && newType.isParameterizedOrGenericType()) {
newType = newType.getRawType();
}
for (int ii = 0; ii < interfaces.length; ii++) {
ResolvedType iface = interfaces[ii];
if (!wantGenerics && iface.isParameterizedOrGenericType()) {
iface = iface.getRawType();
}
if (newType.getSignature().equals(iface.getSignature())) { // pr171953
forRemoval.add(ii);
}
}
}
}
}
// Found some to remove from those we are going to iterate over
if (forRemoval.size() > 0) {
ResolvedType[] interfaces2 = new ResolvedType[interfaces.length - forRemoval.size()];
int p = 0;
for (int ii = 0; ii < interfaces.length; ii++) {
if (!forRemoval.contains(ii)) {
interfaces2[p++] = interfaces[ii];
}
}
interfaces = interfaces2;
}
}
return new Iterators.ResolvedTypeArrayIterator(interfaces, alreadySeen, wantGenerics);
}
};
// If this type is an interface, there are only interfaces to walk
if (this.isInterface()) {
return new SuperInterfaceWalker(interfaceGetter, this);
} else {
SuperInterfaceWalker superInterfaceWalker = new SuperInterfaceWalker(interfaceGetter);
Iterator<ResolvedType> superClassesIterator = new SuperClassWalker(this, superInterfaceWalker, wantGenerics);
// append() will check if the second iterator is empty before appending - but the types which the superInterfaceWalker
// needs to visit are only accumulated whilst the superClassesIterator is in progress
return Iterators.append1(superClassesIterator, superInterfaceWalker);
}
}
/**
* 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. This is expensive - use the getMethods() method if you can!
*/
public List<ResolvedMember> getMethodsWithoutIterator(boolean includeITDs, boolean allowMissing, boolean genericsAware) {
List<ResolvedMember> methods = new ArrayList<ResolvedMember>();
Set<String> knowninterfaces = new HashSet<String>();
addAndRecurse(knowninterfaces, methods, this, includeITDs, allowMissing, genericsAware);
return methods;
}
/**
* Return a list of the types in the hierarchy of this type, starting with this type. The order in the list is the superclasses
* followed by the super interfaces.
*
* @param genericsAware should the list include parameterized/generic types (if not, they will be collapsed to raw)?
* @return list of resolvedtypes in this types hierarchy, including this type first
*/
public List<ResolvedType> getHierarchyWithoutIterator(boolean includeITDs, boolean allowMissing, boolean genericsAware) {
List<ResolvedType> types = new ArrayList<ResolvedType>();
Set<String> visited = new HashSet<String>();
recurseHierarchy(visited, types, this, includeITDs, allowMissing, genericsAware);
return types;
}
private void addAndRecurse(Set<String> knowninterfaces, List<ResolvedMember> collector, ResolvedType resolvedType,
boolean includeITDs, boolean allowMissing, boolean genericsAware) {
// Add the methods declared on this type
collector.addAll(Arrays.asList(resolvedType.getDeclaredMethods()));
// now add all the inter-typed members too
if (includeITDs && resolvedType.interTypeMungers != null) {
for (ConcreteTypeMunger typeTransformer : interTypeMungers) {
ResolvedMember rm = typeTransformer.getSignature();
if (rm != null) { // new parent type munger can have null signature
collector.add(typeTransformer.getSignature());
}
}
}
// BUG? interface type superclass is Object - is that correct?
if (!resolvedType.isInterface() && !resolvedType.equals(ResolvedType.OBJECT)) {
ResolvedType superType = resolvedType.getSuperclass();
if (superType != null && !superType.isMissing()) {
if (!genericsAware && superType.isParameterizedOrGenericType()) {
superType = superType.getRawType();
}
// Recurse if we are not at the top
addAndRecurse(knowninterfaces, collector, superType, includeITDs, allowMissing, genericsAware);
}
}
// Go through the interfaces on the way back down
ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
ResolvedType iface = interfaces[i];
if (!genericsAware && iface.isParameterizedOrGenericType()) {
iface = iface.getRawType();
}
// we need to know if it is an interface from Parent kind munger
// as those are used for @AJ ITD and we precisely want to skip those
boolean shouldSkip = false;
for (int j = 0; j < resolvedType.interTypeMungers.size(); j++) {
ConcreteTypeMunger munger = resolvedType.interTypeMungers.get(j);
if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent
&& ((NewParentTypeMunger) munger.getMunger()).getNewParent().equals(iface) // pr171953
) {
shouldSkip = true;
break;
}
}
// Do not do interfaces more than once
if (!shouldSkip && !knowninterfaces.contains(iface.getSignature())) {
knowninterfaces.add(iface.getSignature());
if (allowMissing && iface.isMissing()) {
if (iface instanceof MissingResolvedTypeWithKnownSignature) {
((MissingResolvedTypeWithKnownSignature) iface).raiseWarningOnMissingInterfaceWhilstFindingMethods();
}
} else {
addAndRecurse(knowninterfaces, collector, iface, includeITDs, allowMissing, genericsAware);
}
}
}
}
/**
* Recurse up a type hierarchy, first the superclasses then the super interfaces.
*/
private void recurseHierarchy(Set<String> knowninterfaces, List<ResolvedType> collector, ResolvedType resolvedType,
boolean includeITDs, boolean allowMissing, boolean genericsAware) {
collector.add(resolvedType);
if (!resolvedType.isInterface() && !resolvedType.equals(ResolvedType.OBJECT)) {
ResolvedType superType = resolvedType.getSuperclass();
if (superType != null && !superType.isMissing()) {
if (!genericsAware && (superType.isParameterizedType() || superType.isGenericType())) {
superType = superType.getRawType();
}
// Recurse if we are not at the top
recurseHierarchy(knowninterfaces, collector, superType, includeITDs, allowMissing, genericsAware);
}
}
// Go through the interfaces on the way back down
ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
ResolvedType iface = interfaces[i];
if (!genericsAware && (iface.isParameterizedType() || iface.isGenericType())) {
iface = iface.getRawType();
}
// we need to know if it is an interface from Parent kind munger
// as those are used for @AJ ITD and we precisely want to skip those
boolean shouldSkip = false;
for (int j = 0; j < resolvedType.interTypeMungers.size(); j++) {
ConcreteTypeMunger munger = resolvedType.interTypeMungers.get(j);
if (munger.getMunger() != null && munger.getMunger().getKind() == ResolvedTypeMunger.Parent
&& ((NewParentTypeMunger) munger.getMunger()).getNewParent().equals(iface) // pr171953
) {
shouldSkip = true;
break;
}
}
// Do not do interfaces more than once
if (!shouldSkip && !knowninterfaces.contains(iface.getSignature())) {
knowninterfaces.add(iface.getSignature());
if (allowMissing && iface.isMissing()) {
if (iface instanceof MissingResolvedTypeWithKnownSignature) {
((MissingResolvedTypeWithKnownSignature) iface).raiseWarningOnMissingInterfaceWhilstFindingMethods();
}
} else {
recurseHierarchy(knowninterfaces, collector, iface, includeITDs, allowMissing, genericsAware);
}
}
}
}
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 field) {
Iterator<ResolvedMember> i = getFields();
while (i.hasNext()) {
ResolvedMember resolvedMember = i.next();
if (matches(resolvedMember, field)) {
return resolvedMember;
}
if (resolvedMember.hasBackingGenericMember() && field.getName().equals(resolvedMember.getName())) {
// might be worth checking the member behind the parameterized member (see pr137496)
if (matches(resolvedMember.getBackingGenericMember(), field)) {
return resolvedMember;
}
}
}
return null;
}
/**
* described in JVM spec 2ed 5.4.3.3. Doesnt check ITDs.
*
* <p>
* Check the current type for the method. If it is not found, check the super class and any super interfaces. Taking care not to
* process interfaces multiple times.
*/
public ResolvedMember lookupMethod(Member m) {
List<ResolvedType> typesTolookat = new ArrayList<ResolvedType>();
typesTolookat.add(this);
int pos = 0;
while (pos < typesTolookat.size()) {
ResolvedType type = typesTolookat.get(pos++);
if (!type.isMissing()) {
ResolvedMember[] methods = type.getDeclaredMethods();
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
ResolvedMember method = methods[i];
if (matches(method, m)) {
return method;
}
// might be worth checking the method behind the parameterized method (137496)
if (method.hasBackingGenericMember() && m.getName().equals(method.getName())) {
if (matches(method.getBackingGenericMember(), m)) {
return method;
}
}
}
}
}
// Queue the superclass:
ResolvedType superclass = type.getSuperclass();
if (superclass != null) {
typesTolookat.add(superclass);
}
// Queue any interfaces not already checked:
ResolvedType[] superinterfaces = type.getDeclaredInterfaces();
if (superinterfaces != null) {
for (int i = 0; i < superinterfaces.length; i++) {
ResolvedType interf = superinterfaces[i];
if (!typesTolookat.contains(interf)) {
typesTolookat.add(interf);
}
}
}
}
return null;
}
/**
* @param member the member to lookup in intertype declarations affecting this type
* @return the real signature defined by any matching intertype declaration, otherwise null
*/
public ResolvedMember lookupMethodInITDs(Member member) {
for (ConcreteTypeMunger typeTransformer : interTypeMungers) {
if (matches(typeTransformer.getSignature(), member)) {
return typeTransformer.getSignature();
}
}
return null;
}
/**
* 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;
}
// Bug (1) Do callers expect ITDs to be involved in the lookup? or do they do their own walk over ITDs?
/**
* Looks for the first member in the hierarchy matching aMember. This method differs from lookupMember(Member) in that it takes
* into account parameters which are type variables - which clearly an unresolved Member cannot do since it does not know
* anything about type variables.
*/
public ResolvedMember lookupResolvedMember(ResolvedMember aMember, boolean allowMissing, boolean eraseGenerics) {
Iterator<ResolvedMember> toSearch = null;
ResolvedMember found = null;
if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) {
// toSearch = getMethodsWithoutIterator(true, allowMissing, !eraseGenerics).iterator();
toSearch = getMethodsIncludingIntertypeDeclarations(!eraseGenerics, true);
} else {
assert aMember.getKind() == Member.FIELD;
toSearch = getFields();
}
while (toSearch.hasNext()) {
ResolvedMember candidate = toSearch.next();
if (eraseGenerics) {
if (candidate.hasBackingGenericMember()) {
candidate = candidate.getBackingGenericMember();
}
}
// OPTIMIZE speed up matches? optimize order of checks
if (candidate.matches(aMember, eraseGenerics)) {
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) {
return conflictingSignature(m1,m2,true);
}
/**
* Do the two members conflict? Due to the change in 1.7.1, field itds on interfaces now act like 'default' fields - so types implementing
* those fields get the field if they don't have it already, otherwise they keep what they have. The conflict detection below had to be
* altered. Previously (<1.7.1) it is not a conflict if the declaring types are different. With v2itds it may still be a conflict if the
* declaring types are different.
*/
public static boolean conflictingSignature(Member m1, Member m2, boolean v2itds) {
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) {
if (v2itds) {
if (m1.getDeclaringType().equals(m2.getDeclaringType())) {
return true;
}
} else {
return m1.getDeclaringType().equals(m2.getDeclaringType());
}
} else if (m1.getKind() == Member.POINTCUT) {
return true;
}
UnresolvedType[] p1 = m1.getGenericParameterTypes();
UnresolvedType[] p2 = m2.getGenericParameterTypes();
if (p1 == null) {
p1 = m1.getParameterTypes();
}
if (p2 == null) {
p2 = m2.getParameterTypes();
}
int n = p1.length;
if (n != p2.length) {
return false;
}
for (int i = 0; i < n; i++) {
if (!p1[i].equals(p2[i])) {
return false;
}
}
return true;
}
/**
* returns an iterator through all of the pointcuts of this type, in order for checking from JVM spec 2ed 5.4.3.2 (as for
* fields). This means that the order is
* <p/>
* <ul>
* <li>pointcuts from current class</li>
* <li>recur into direct superinterfaces</li>
* <li>recur into superclass</li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral out into 2^n land.
*/
public Iterator<ResolvedMember> getPointcuts() {
final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter();
// same order as fields
Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() {
public Iterator<ResolvedType> get(ResolvedType o) {
return dupFilter.filter(o.getDirectSupertypes());
}
};
return Iterators.mapOver(Iterators.recur(this, typeGetter), PointcutGetterInstance);
}
public ResolvedPointcutDefinition findPointcut(String name) {
for (Iterator<ResolvedMember> i = getPointcuts(); i.hasNext();) {
ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next();
// the ResolvedPointcutDefinition can be null if there are other problems that prevented its resolution
if (f != null && name.equals(f.getName())) {
return f;
}
}
// pr120521
if (!getOutermostType().equals(this)) {
ResolvedType outerType = getOutermostType().resolve(world);
ResolvedPointcutDefinition rpd = outerType.findPointcut(name);
return rpd;
}
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(boolean shouldConcretizeIfNeeded) {
crosscuttingMembers = new CrosscuttingMembers(this, shouldConcretizeIfNeeded);
if (getPerClause() == null) {
return crosscuttingMembers;
}
crosscuttingMembers.setPerClause(getPerClause());
crosscuttingMembers.addShadowMungers(collectShadowMungers());
// GENERICITDFIX
// crosscuttingMembers.addTypeMungers(collectTypeMungers());
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 List<Declare> collectDeclares(boolean includeAdviceLike) {
if (!this.isAspect()) {
return Collections.emptyList();
}
List<Declare> ret = new ArrayList<Declare>();
// 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<ResolvedType> dupFilter = Iterators.dupFilter();
Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() {
public Iterator<ResolvedType> get(ResolvedType o) {
return dupFilter.filter((o).getDirectSupertypes());
}
};
Iterator<ResolvedType> typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedType ty = typeIterator.next();
// System.out.println("super: " + ty + ", " + );
for (Iterator<Declare> i = ty.getDeclares().iterator(); i.hasNext();) {
Declare dec = i.next();
if (dec.isAdviceLike()) {
if (includeAdviceLike) {
ret.add(dec);
}
} else {
ret.add(dec);
}
}
}
}
return ret;
}
private final List<ShadowMunger> collectShadowMungers() {
if (!this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) {
return Collections.emptyList();
}
List<ShadowMunger> acc = new ArrayList<ShadowMunger>();
final Iterators.Filter<ResolvedType> dupFilter = Iterators.dupFilter();
Iterators.Getter<ResolvedType, ResolvedType> typeGetter = new Iterators.Getter<ResolvedType, ResolvedType>() {
public Iterator<ResolvedType> get(ResolvedType o) {
return dupFilter.filter((o).getDirectSupertypes());
}
};
Iterator<ResolvedType> typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedType ty = typeIterator.next();
acc.addAll(ty.getDeclaredShadowMungers());
}
return acc;
}
public void addParent(ResolvedType newParent) {
// Nothing to do for anything except a ReferenceType
}
protected boolean doesNotExposeShadowMungers() {
return false;
}
public PerClause getPerClause() {
return null;
}
public Collection<Declare> getDeclares() {
return Collections.emptyList();
}
public Collection<ConcreteTypeMunger> getTypeMungers() {
return Collections.emptyList();
}
public Collection<ResolvedMember> getPrivilegedAccesses() {
return Collections.emptyList();
}
// ---- useful things
public final boolean isInterface() {
return Modifier.isInterface(getModifiers());
}
public final boolean isAbstract() {
return Modifier.isAbstract(getModifiers());
}
public boolean isClass() {
return false;
}
public boolean isAspect() {
return false;
}
public boolean isAnnotationStyleAspect() {
return false;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isEnum() {
return false;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isAnnotation() {
return false;
}
public boolean isAnonymous() {
return false;
}
public boolean isNested() {
return false;
}
public void addAnnotation(AnnotationAJ annotationX) {
throw new RuntimeException("ResolvedType.addAnnotation() should never be called");
}
public AnnotationAJ[] getAnnotations() {
throw new RuntimeException("ResolvedType.getAnnotations() should never be called");
}
/**
* Note: Only overridden by ReferenceType subtype
*/
public boolean canAnnotationTargetType() {
return false;
}
/**
* Note: Only overridden by ReferenceType subtype
*/
public AnnotationTargetKind[] getAnnotationTargetKinds() {
return null;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isAnnotationWithRuntimeRetention() {
return false;
}
public boolean isSynthetic() {
return signature.indexOf("$ajc") != -1;
}
public final boolean isFinal() {
return Modifier.isFinal(getModifiers());
}
protected Map<String, UnresolvedType> getMemberParameterizationMap() {
if (!isParameterizedType()) {
return Collections.emptyMap();
}
TypeVariable[] tvs = getGenericType().getTypeVariables();
Map<String, UnresolvedType> parameterizationMap = new HashMap<String, UnresolvedType>();
for (int i = 0; i < tvs.length; i++) {
parameterizationMap.put(tvs[i].getName(), typeParameters[i]);
}
return parameterizationMap;
}
public List<ShadowMunger> getDeclaredAdvice() {
List<ShadowMunger> l = new ArrayList<ShadowMunger>();
ResolvedMember[] methods = getDeclaredMethods();
if (isParameterizedType()) {
methods = getGenericType().getDeclaredMethods();
}
Map<String, UnresolvedType> typeVariableMap = getAjMemberParameterizationMap();
for (int i = 0, len = methods.length; i < len; i++) {
ShadowMunger munger = methods[i].getAssociatedShadowMunger();
if (munger != null) {
if (ajMembersNeedParameterization()) {
// munger.setPointcut(munger.getPointcut().parameterizeWith(
// typeVariableMap));
munger = munger.parameterizeWith(this, typeVariableMap);
if (munger instanceof Advice) {
Advice advice = (Advice) munger;
// update to use the parameterized signature...
UnresolvedType[] ptypes = methods[i].getGenericParameterTypes();
UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length];
for (int j = 0; j < ptypes.length; j++) {
if (ptypes[j] instanceof TypeVariableReferenceType) {
TypeVariableReferenceType tvrt = (TypeVariableReferenceType) ptypes[j];
if (typeVariableMap.containsKey(tvrt.getTypeVariable().getName())) {
newPTypes[j] = typeVariableMap.get(tvrt.getTypeVariable().getName());
} else {
newPTypes[j] = ptypes[j];
}
} else {
newPTypes[j] = ptypes[j];
}
}
advice.setBindingParameterTypes(newPTypes);
}
}
munger.setDeclaringType(this);
l.add(munger);
}
}
return l;
}
public List<ShadowMunger> getDeclaredShadowMungers() {
return getDeclaredAdvice();
}
// ---- only for testing!
public ResolvedMember[] getDeclaredJavaFields() {
return filterInJavaVisible(getDeclaredFields());
}
public ResolvedMember[] getDeclaredJavaMethods() {
return filterInJavaVisible(getDeclaredMethods());
}
private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) {
List<ResolvedMember> l = new ArrayList<ResolvedMember>();
for (int i = 0, len = ms.length; i < len; i++) {
if (!ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) {
l.add(ms[i]);
}
}
return l.toArray(new ResolvedMember[l.size()]);
}
public abstract ISourceContext getSourceContext();
// ---- fields
public static final ResolvedType[] NONE = new ResolvedType[0];
public static final ResolvedType[] EMPTY_ARRAY = NONE;
public static final Missing MISSING = new Missing();
// ---- types
public static ResolvedType makeArray(ResolvedType type, int dim) {
if (dim == 0) {
return type;
}
ResolvedType array = new ArrayReferenceType("[" + type.getSignature(), "[" + type.getErasureSignature(), type.getWorld(),
type);
return makeArray(array, dim - 1);
}
static class Primitive extends ResolvedType {
private final int size;
private final int index;
Primitive(String signature, int size, int index) {
super(signature, null);
this.size = size;
this.index = index;
this.typeKind = TypeKind.PRIMITIVE;
}
@Override
public final int getSize() {
return size;
}
@Override
public final int getModifiers() {
return Modifier.PUBLIC | Modifier.FINAL;
}
@Override
public final boolean isPrimitiveType() {
return true;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
@Override
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];
}
@Override
public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) {
return isAssignableFrom(other);
}
@Override
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;
}
@Override
public ResolvedType resolve(World world) {
if (this.world != world) {
throw new IllegalStateException();
}
this.world = world;
return super.resolve(world);
}
@Override
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
};
// ----
@Override
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
@Override
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
@Override
public final ResolvedType[] getDeclaredInterfaces() {
return ResolvedType.NONE;
}
@Override
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
@Override
public final ResolvedType getSuperclass() {
return null;
}
@Override
public ISourceContext getSourceContext() {
return null;
}
}
static class Missing extends ResolvedType {
Missing() {
super(MISSING_NAME, null);
}
// public final String toString() {
// return "<missing>";
// }
@Override
public final String getName() {
return MISSING_NAME;
}
@Override
public final boolean isMissing() {
return true;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
@Override
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
@Override
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
@Override
public final ResolvedType[] getDeclaredInterfaces() {
return ResolvedType.NONE;
}
@Override
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
@Override
public final ResolvedType getSuperclass() {
return null;
}
@Override
public final int getModifiers() {
return 0;
}
@Override
public final boolean isAssignableFrom(ResolvedType other) {
return false;
}
@Override
public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) {
return false;
}
@Override
public final boolean isCoerceableFrom(ResolvedType other) {
return false;
}
@Override
public boolean needsNoConversionFrom(ResolvedType other) {
return false;
}
@Override
public ISourceContext getSourceContext() {
return null;
}
}
/**
* Look up a member, takes into account any ITDs on this type. return null if not found
*/
public ResolvedMember lookupMemberNoSupers(Member member) {
ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member);
if (ret == null && interTypeMungers != null) {
for (ConcreteTypeMunger tm : interTypeMungers) {
if (matches(tm.getSignature(), member)) {
return tm.getSignature();
}
}
}
return ret;
}
public ResolvedMember lookupMemberWithSupersAndITDs(Member member) {
ResolvedMember ret = lookupMemberNoSupers(member);
if (ret != null) {
return ret;
}
ResolvedType supert = getSuperclass();
while (ret == null && supert != null) {
ret = supert.lookupMemberNoSupers(member);
if (ret == null) {
supert = supert.getSuperclass();
}
}
return ret;
}
/**
* as lookupMemberNoSupers, but does not include ITDs
*
* @param member
* @return
*/
public ResolvedMember lookupDirectlyDeclaredMemberNoSupers(Member member) {
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = lookupMember(member, getDeclaredFields());
} else {
// assert member.getKind() == Member.METHOD || member.getKind() ==
// Member.CONSTRUCTOR
ret = lookupMember(member, getDeclaredMethods());
}
return ret;
}
/**
* This lookup has specialized behaviour - a null result tells the EclipseTypeMunger that it should make a default
* implementation of a method on this type.
*
* @param member
* @return
*/
public ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member) {
return lookupMemberIncludingITDsOnInterfaces(member, this);
}
private ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member, ResolvedType onType) {
ResolvedMember ret = onType.lookupMemberNoSupers(member);
if (ret != null) {
return ret;
} else {
ResolvedType superType = onType.getSuperclass();
if (superType != null) {
ret = lookupMemberIncludingITDsOnInterfaces(member, superType);
}
if (ret == null) {
// try interfaces then, but only ITDs now...
ResolvedType[] superInterfaces = onType.getDeclaredInterfaces();
for (int i = 0; i < superInterfaces.length; i++) {
ret = superInterfaces[i].lookupMethodInITDs(member);
if (ret != null) {
return ret;
}
}
}
}
return ret;
}
protected List<ConcreteTypeMunger> interTypeMungers = new ArrayList<ConcreteTypeMunger>();
public List<ConcreteTypeMunger> getInterTypeMungers() {
return interTypeMungers;
}
public List<ConcreteTypeMunger> getInterTypeParentMungers() {
List<ConcreteTypeMunger> l = new ArrayList<ConcreteTypeMunger>();
for (ConcreteTypeMunger element : interTypeMungers) {
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<ConcreteTypeMunger> getInterTypeMungersIncludingSupers() {
ArrayList<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>();
collectInterTypeMungers(ret);
return ret;
}
public List<ConcreteTypeMunger> getInterTypeParentMungersIncludingSupers() {
ArrayList<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>();
collectInterTypeParentMungers(ret);
return ret;
}
private void collectInterTypeParentMungers(List<ConcreteTypeMunger> collector) {
for (Iterator<ResolvedType> iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedType superType = iter.next();
superType.collectInterTypeParentMungers(collector);
}
collector.addAll(getInterTypeParentMungers());
}
protected void collectInterTypeMungers(List<ConcreteTypeMunger> collector) {
for (Iterator<ResolvedType> iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedType superType = iter.next();
if (superType == null) {
throw new BCException("UnexpectedProblem: a supertype in the hierarchy for " + this.getName() + " is null");
}
superType.collectInterTypeMungers(collector);
}
outer: for (Iterator<ConcreteTypeMunger> iter1 = collector.iterator(); iter1.hasNext();) {
ConcreteTypeMunger superMunger = iter1.next();
if (superMunger.getSignature() == null) {
continue;
}
if (!superMunger.getSignature().isAbstract()) {
continue;
}
for (ConcreteTypeMunger myMunger : getInterTypeMungers()) {
if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
if (!superMunger.getSignature().isPublic()) {
continue;
}
for (Iterator<ResolvedMember> iter = getMethods(true, true); iter.hasNext();) {
ResolvedMember method = 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 (ConcreteTypeMunger munger : getInterTypeMungersIncludingSupers()) {
itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2
}
if (itdProblem) {
return; // If the rules above are broken, return right now
}
for (ConcreteTypeMunger munger : getInterTypeMungersIncludingSupers()) {
if (munger.getSignature() != null && munger.getSignature().isAbstract() && munger.getMunger().getKind()!=ResolvedTypeMunger.PrivilegedAccess) { // Rule 1
if (munger.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) {
// ignore for @AJ ITD as munger.getSignature() is the
// interface method hence abstract
} else {
world.getMessageHandler()
.handleMessage(
new Message("must implement abstract inter-type declaration: " + munger.getSignature(), "",
IMessage.ERROR, getSourceLocation(), null,
new ISourceLocation[] { getMungerLocation(munger) }));
}
}
}
}
/**
* See PR70794. This method checks that if an abstract inter-type method declaration is made on an interface then it must also
* be public. This is a compiler limitation that could be made to work in the future (if someone provides a worthwhile usecase)
*
* @return indicates if the munger failed the check
*/
private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) {
if (munger.getMunger() != null && (munger.getMunger() instanceof NewMethodTypeMunger)) {
ResolvedMember itdMember = munger.getSignature();
ResolvedType onType = itdMember.getDeclaringType().resolve(world);
if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) {
world.getMessageHandler().handleMessage(
new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,
munger.getSignature(), onType), "", Message.ERROR, getSourceLocation(), null,
new ISourceLocation[] { getMungerLocation(munger) }));
return true;
}
}
return false;
}
/**
* Get a source location for the munger. Until intertype mungers remember where they came from, the source location for the
* munger itself is null. In these cases use the source location for the aspect containing the ITD.
*/
private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) {
ISourceLocation sloc = munger.getSourceLocation();
if (sloc == null) {
sloc = munger.getAspectType().getSourceLocation();
}
return sloc;
}
/**
* Returns a ResolvedType object representing the declaring type of this type, or null if this type does not represent a
* non-package-level-type.
* <p/>
* <strong>Warning</strong>: This is guaranteed to work for all member types. For anonymous/local types, the only guarantee is
* given in JLS 13.1, where it guarantees that if you call getDeclaringType() repeatedly, you will eventually get the top-level
* class, but it does not say anything about classes in between.
*
* @return the declaring UnresolvedType object, or null.
*/
public ResolvedType getDeclaringType() {
if (isArray()) {
return null;
}
String name = getName();
int lastDollar = name.lastIndexOf('$');
while (lastDollar > 0) { // allow for classes starting '$' (pr120474)
ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true);
if (!ResolvedType.isMissing(ret)) {
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);
}
}
private static boolean samePackage(ResolvedType targetType, ResolvedType fromType) {
String p1 = targetType.getPackageName();
String p2 = fromType.getPackageName();
if (p1 == null) {
return p2 == null;
}
if (p2 == null) {
return false;
}
return p1.equals(p2);
}
/**
* Checks if the generic type for 'this' and the generic type for 'other' are the same - it can be passed raw or parameterized
* versions and will just compare the underlying generic type.
*/
private boolean genericTypeEquals(ResolvedType other) {
ResolvedType rt = other;
if (rt.isParameterizedType() || rt.isRawType()) {
rt.getGenericType();
}
if (((isParameterizedType() || isRawType()) && getGenericType().equals(rt)) || (this.equals(other))) {
return true;
}
return false;
}
/**
* Look up the actual occurence of a particular type in the hierarchy for 'this' type. The input is going to be a generic type,
* and the caller wants to know if it was used in its RAW or a PARAMETERIZED form in this hierarchy.
*
* returns null if it can't be found.
*/
public ResolvedType discoverActualOccurrenceOfTypeInHierarchy(ResolvedType lookingFor) {
if (!lookingFor.isGenericType()) {
throw new BCException("assertion failed: method should only be called with generic type, but " + lookingFor + " is "
+ lookingFor.typeKind);
}
if (this.equals(ResolvedType.OBJECT)) {
return null;
}
if (genericTypeEquals(lookingFor)) {
return this;
}
ResolvedType superT = getSuperclass();
if (superT.genericTypeEquals(lookingFor)) {
return superT;
}
ResolvedType[] superIs = getDeclaredInterfaces();
for (int i = 0; i < superIs.length; i++) {
ResolvedType superI = superIs[i];
if (superI.genericTypeEquals(lookingFor)) {
return superI;
}
ResolvedType checkTheSuperI = superI.discoverActualOccurrenceOfTypeInHierarchy(lookingFor);
if (checkTheSuperI != null) {
return checkTheSuperI;
}
}
return superT.discoverActualOccurrenceOfTypeInHierarchy(lookingFor);
}
/**
* Called for all type mungers but only does something if they share type variables with a generic type which they target. When
* this happens this routine will check for the target type in the target hierarchy and 'bind' any type parameters as
* appropriate. For example, for the ITD "List<T> I<T>.x" against a type like this: "class A implements I<String>" this routine
* will return a parameterized form of the ITD "List<String> I.x"
*/
public ConcreteTypeMunger fillInAnyTypeParameters(ConcreteTypeMunger munger) {
boolean debug = false;
ResolvedMember member = munger.getSignature();
if (munger.isTargetTypeParameterized()) {
if (debug) {
System.err.println("Processing attempted parameterization of " + munger + " targetting type " + this);
}
if (debug) {
System.err.println(" This type is " + this + " (" + typeKind + ")");
}
// need to tailor this munger instance for the particular target...
if (debug) {
System.err.println(" Signature that needs parameterizing: " + member);
}
// Retrieve the generic type
ResolvedType onTypeResolved = world.resolve(member.getDeclaringType());
ResolvedType onType = onTypeResolved.getGenericType();
if (onType == null) {
// The target is not generic
getWorld().getMessageHandler().handleMessage(
MessageUtil.error("The target type for the intertype declaration is not generic",
munger.getSourceLocation()));
return munger;
}
member.resolve(world); // Ensure all parts of the member are resolved
if (debug) {
System.err.println(" Actual target ontype: " + onType + " (" + onType.typeKind + ")");
}
// quickly find the targettype in the type hierarchy for this type
// (it will be either RAW or PARAMETERIZED)
ResolvedType actualTarget = discoverActualOccurrenceOfTypeInHierarchy(onType);
if (actualTarget == null) {
throw new BCException("assertion failed: asked " + this + " for occurrence of " + onType + " in its hierarchy??");
}
// only bind the tvars if its a parameterized type or the raw type
// (in which case they collapse to bounds) - don't do it
// for generic types ;)
if (!actualTarget.isGenericType()) {
if (debug) {
System.err.println("Occurrence in " + this + " is actually " + actualTarget + " (" + actualTarget.typeKind
+ ")");
// parameterize the signature
// ResolvedMember newOne =
// member.parameterizedWith(actualTarget.getTypeParameters(),
// onType,actualTarget.isParameterizedType());
}
}
// if (!actualTarget.isRawType())
munger = munger.parameterizedFor(actualTarget);
if (debug) {
System.err.println("New sig: " + munger.getSignature());
}
if (debug) {
System.err.println("=====================================");
}
}
return munger;
}
/**
* Add an intertype munger to this type. isDuringCompilation tells us if we should be checking for an error scenario where two
* ITD fields are trying to use the same name. When this happens during compilation one of them is altered to get mangled name
* but when it happens during weaving it is too late and we need to put out an error asking them to recompile.
*/
public void addInterTypeMunger(ConcreteTypeMunger munger, boolean isDuringCompilation) {
ResolvedMember sig = munger.getSignature();
bits = (bits & ~MungersAnalyzed); // clear the bit - as the mungers have changed
if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) {
interTypeMungers.add(munger);
return;
}
// ConcreteTypeMunger originalMunger = munger;
// we will use the 'parameterized' ITD for all the comparisons but we
// say the original
// one passed in actually matched as it will be added to the intertype
// member finder
// for the target type. It is possible we only want to do this if a
// generic type
// is discovered and the tvar is collapsed to a bound?
munger = fillInAnyTypeParameters(munger);
sig = munger.getSignature(); // possibly changed when type parms filled in
if (sig.getKind() == Member.METHOD) {
// OPTIMIZE can this be sped up?
if (clashesWithExistingMember(munger, getMethods(true, false))) { // ITDs checked below
return;
}
if (this.isInterface()) {
// OPTIMIZE this set of methods are always the same - must we keep creating them as a list?
if (clashesWithExistingMember(munger, Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) {
return;
}
}
} else if (sig.getKind() == Member.FIELD) {
if (clashesWithExistingMember(munger, Arrays.asList(getDeclaredFields()).iterator())) {
return;
}
// Cannot cope with two version '2' style mungers for the same field on the same type
// Must error and request the user recompile at least one aspect with the
// -Xset:itdStyle=1 option
if (!isDuringCompilation) {
ResolvedTypeMunger thisRealMunger = munger.getMunger();
if (thisRealMunger instanceof NewFieldTypeMunger) {
NewFieldTypeMunger newFieldTypeMunger = (NewFieldTypeMunger) thisRealMunger;
if (newFieldTypeMunger.version == NewFieldTypeMunger.VersionTwo) {
String thisRealMungerSignatureName = newFieldTypeMunger.getSignature().getName();
for (ConcreteTypeMunger typeMunger : interTypeMungers) {
if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
if (typeMunger.getSignature().getKind() == Member.FIELD) {
NewFieldTypeMunger existing = (NewFieldTypeMunger) typeMunger.getMunger();
if (existing.getSignature().getName().equals(thisRealMungerSignatureName)
&& existing.version == NewFieldTypeMunger.VersionTwo
// this check ensures no problem for a clash with an ITD on an interface
&& existing.getSignature().getDeclaringType()
.equals(newFieldTypeMunger.getSignature().getDeclaringType())) {
// report error on the aspect
StringBuffer sb = new StringBuffer();
sb.append("Cannot handle two aspects both attempting to use new style ITDs for the same named field ");
sb.append("on the same target type. Please recompile at least one aspect with '-Xset:itdVersion=1'.");
sb.append(" Aspects involved: " + munger.getAspectType().getName() + " and "
+ typeMunger.getAspectType().getName() + ".");
sb.append(" Field is named '" + existing.getSignature().getName() + "'");
getWorld().getMessageHandler().handleMessage(
new Message(sb.toString(), getSourceLocation(), true));
return;
}
}
}
}
}
}
}
} else {
if (clashesWithExistingMember(munger, Arrays.asList(getDeclaredMethods()).iterator())) {
return;
}
}
boolean needsAdding =true;
boolean needsToBeAddedEarlier =false;
// now compare to existingMungers
for (Iterator<ConcreteTypeMunger> i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger existingMunger = i.next();
boolean v2itds = munger.getSignature().getKind()== Member.FIELD && (munger.getMunger() instanceof NewFieldTypeMunger) && ((NewFieldTypeMunger)munger.getMunger()).version==NewFieldTypeMunger.VersionTwo;
if (conflictingSignature(existingMunger.getSignature(), munger.getSignature(),v2itds)) {
// 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(), 0x11, null);
needsAdding = false;
if (munger.getSignature().getKind()== Member.FIELD && munger.getSignature().getDeclaringType().resolve(world).isInterface() && ((NewFieldTypeMunger)munger.getMunger()).version==NewFieldTypeMunger.VersionTwo) {
// still need to add it
needsAdding=true;
}
break;
} else if (c > 0) {
// the new munger dominates the existing one
checkLegalOverride(existingMunger.getSignature(), munger.getSignature(), 0x11, null);
// i.remove();
if (existingMunger.getSignature().getKind()==Member.FIELD &&
existingMunger.getSignature().getDeclaringType().resolve(world).isInterface()
&& ((NewFieldTypeMunger)existingMunger.getMunger()).version==NewFieldTypeMunger.VersionTwo) {
needsToBeAddedEarlier=true;
} else {
i.remove();
}
break;
} else {
interTypeConflictError(munger, existingMunger);
interTypeConflictError(existingMunger, munger);
return;
}
}
}
}
// System.err.println("adding: " + munger + " to " + this);
// we are adding the parameterized form of the ITD to the list of
// mungers. Within it, the munger knows the original declared
// signature for the ITD so it can be retrieved.
if (needsAdding) {
if (!needsToBeAddedEarlier) {
interTypeMungers.add(munger);
} else {
interTypeMungers.add(0,munger);
}
}
}
/**
* Compare the type transformer with the existing members. A clash may not be an error (the ITD may be the 'default
* implementation') so returning false is not always a sign of an error.
*
* @return true if there is a clash
*/
private boolean clashesWithExistingMember(ConcreteTypeMunger typeTransformer, Iterator<ResolvedMember> existingMembers) {
ResolvedMember typeTransformerSignature = typeTransformer.getSignature();
// ResolvedType declaringAspectType = munger.getAspectType();
// if (declaringAspectType.isRawType()) declaringAspectType =
// declaringAspectType.getGenericType();
// if (declaringAspectType.isGenericType()) {
//
// ResolvedType genericOnType =
// getWorld().resolve(sig.getDeclaringType()).getGenericType();
// ConcreteTypeMunger ctm =
// munger.parameterizedFor(discoverActualOccurrenceOfTypeInHierarchy
// (genericOnType));
// sig = ctm.getSignature(); // possible sig change when type
// }
// if (munger.getMunger().hasTypeVariableAliases()) {
// ResolvedType genericOnType =
// getWorld().resolve(sig.getDeclaringType()).getGenericType();
// ConcreteTypeMunger ctm =
// munger.parameterizedFor(discoverActualOccurrenceOfTypeInHierarchy(
// genericOnType));
// sig = ctm.getSignature(); // possible sig change when type parameters
// filled in
// }
ResolvedTypeMunger rtm = typeTransformer.getMunger();
boolean v2itds = true;
if (rtm instanceof NewFieldTypeMunger && ((NewFieldTypeMunger)rtm).version==NewFieldTypeMunger.VersionOne) {
v2itds = false;
}
while (existingMembers.hasNext()) {
ResolvedMember existingMember = existingMembers.next();
// don't worry about clashing with bridge methods
if (existingMember.isBridgeMethod()) {
continue;
}
if (conflictingSignature(existingMember, typeTransformerSignature,v2itds)) {
// System.err.println("conflict: existingMember=" +
// existingMember + " typeMunger=" + munger);
// System.err.println(munger.getSourceLocation() + ", " +
// munger.getSignature() + ", " +
// munger.getSignature().getSourceLocation());
if (isVisible(existingMember.getModifiers(), this, typeTransformer.getAspectType())) {
int c = compareMemberPrecedence(typeTransformerSignature, existingMember);
// System.err.println(" c: " + c);
if (c < 0) {
ResolvedType typeTransformerTargetType = typeTransformerSignature.getDeclaringType().resolve(world);
if (typeTransformerTargetType.isInterface()) {
ResolvedType existingMemberType = existingMember.getDeclaringType().resolve(world);
if ((rtm instanceof NewMethodTypeMunger) && !typeTransformerTargetType.equals(existingMemberType)) {
// Might be pr404601. ITD is on an interface with a different visibility to the real member
if (Modifier.isPrivate(typeTransformerSignature.getModifiers()) &&
Modifier.isPublic(existingMember.getModifiers())) {
world.getMessageHandler().handleMessage(new Message("private intertype declaration '"+typeTransformerSignature.toString()+"' clashes with public member '"+existingMember.toString()+"'",existingMember.getSourceLocation(),true));
}
}
}
// existingMember dominates munger
checkLegalOverride(typeTransformerSignature, existingMember, 0x10, typeTransformer.getAspectType());
return true;
} else if (c > 0) {
// munger dominates existingMember
checkLegalOverride(existingMember, typeTransformerSignature, 0x01, typeTransformer.getAspectType());
// interTypeMungers.add(munger);
// ??? might need list of these overridden abstracts
continue;
} else {
// bridge methods can differ solely in return type.
// FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it
// could do with a rewrite !
boolean sameReturnTypes = (existingMember.getReturnType().equals(typeTransformerSignature.getReturnType()));
if (sameReturnTypes) {
// pr206732 - if the existingMember is due to a
// previous application of this same ITD (which can
// happen if this is a binary type being brought in
// from the aspectpath). The 'better' fix is
// to recognize it is from the aspectpath at a
// higher level and dont do this, but that is rather
// more work.
boolean isDuplicateOfPreviousITD = false;
ResolvedType declaringRt = existingMember.getDeclaringType().resolve(world);
WeaverStateInfo wsi = declaringRt.getWeaverState();
if (wsi != null) {
List<ConcreteTypeMunger> mungersAffectingThisType = wsi.getTypeMungers(declaringRt);
if (mungersAffectingThisType != null) {
for (Iterator<ConcreteTypeMunger> iterator = mungersAffectingThisType.iterator(); iterator
.hasNext() && !isDuplicateOfPreviousITD;) {
ConcreteTypeMunger ctMunger = iterator.next();
// relatively crude check - is the ITD
// for the same as the existingmember
// and does it come
// from the same aspect
if (ctMunger.getSignature().equals(existingMember)
&& ctMunger.aspectType.equals(typeTransformer.getAspectType())) {
isDuplicateOfPreviousITD = true;
}
}
}
}
if (!isDuplicateOfPreviousITD) {
// b275032 - this is OK if it is the default ctor and that default ctor was generated
// at compile time, otherwise we cannot overwrite it
if (!(typeTransformerSignature.getName().equals("<init>") && existingMember.isDefaultConstructor())) {
String aspectName = typeTransformer.getAspectType().getName();
ISourceLocation typeTransformerLocation = typeTransformer.getSourceLocation();
ISourceLocation existingMemberLocation = existingMember.getSourceLocation();
String msg = WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT, aspectName,
existingMember);
// this isn't quite right really... as I think the errors should only be recorded against
// what is currently being processed or they may get lost or reported twice
// report error on the aspect
getWorld().getMessageHandler().handleMessage(new Message(msg, typeTransformerLocation, true));
// report error on the affected type, if we can
if (existingMemberLocation != null) {
getWorld().getMessageHandler()
.handleMessage(new Message(msg, existingMemberLocation, true));
}
return true; // clash - so ignore this itd
}
}
}
}
} else if (isDuplicateMemberWithinTargetType(existingMember, this, typeTransformerSignature)) {
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT, typeTransformer
.getAspectType().getName(), existingMember), typeTransformer.getSourceLocation()));
return true;
}
}
}
return false;
}
// 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 (Modifier.isPrivate(itdMember.getModifiers())) {
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;
}
/**
* @param transformerPosition which parameter is the type transformer (0x10 for first, 0x01 for second, 0x11 for both, 0x00 for
* neither)
* @param aspectType the declaring type of aspect defining the *first* type transformer
* @return true if the override is legal note: calling showMessage with two locations issues TWO messages, not ONE message with
* an additional source location.
*/
public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child, int transformerPosition, ResolvedType aspectType) {
// System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType());
if (Modifier.isFinal(parent.getModifiers())) {
// If the ITD matching is occurring due to pulling in a BinaryTypeBinding then this check can incorrectly
// signal an error because the ITD transformer being examined here will exactly match the member it added
// during the first round of compilation. This situation can only occur if the ITD is on an interface whilst
// the class is the top most implementor. If the ITD is on the same type that received it during compilation,
// this method won't be called as the previous check for precedence level will return 0.
if (transformerPosition == 0x10 && aspectType != null) {
ResolvedType nonItdDeclaringType = child.getDeclaringType().resolve(world);
WeaverStateInfo wsi = nonItdDeclaringType.getWeaverState();
if (wsi != null) {
List<ConcreteTypeMunger> transformersOnThisType = wsi.getTypeMungers(nonItdDeclaringType);
if (transformersOnThisType != null) {
for (ConcreteTypeMunger transformer : transformersOnThisType) {
// relatively crude check - is the ITD for the same as the existingmember
// and does it come from the same aspect
if (transformer.aspectType.equals(aspectType)) {
if (parent.equalsApartFromDeclaringType(transformer.getSignature())) {
return true;
}
}
}
}
}
}
world.showMessage(Message.ERROR, WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER, parent),
child.getSourceLocation(), null);
return false;
}
boolean incompatibleReturnTypes = false;
// In 1.5 mode, allow for covariance on return type
if (world.isInJava5Mode() && parent.getKind() == Member.METHOD) {
// Look at the generic types when doing this comparison
ResolvedType rtParentReturnType = parent.resolve(world).getGenericReturnType().resolve(world);
ResolvedType rtChildReturnType = child.resolve(world).getGenericReturnType().resolve(world);
incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType);
// For debug, uncomment this bit and we'll repeat the check - stick
// a breakpoint on the call
// if (incompatibleReturnTypes) {
// incompatibleReturnTypes =
// !rtParentReturnType.isAssignableFrom(rtChildReturnType);
// }
} else {
ResolvedType rtParentReturnType = parent.resolve(world).getGenericReturnType().resolve(world);
ResolvedType rtChildReturnType = child.resolve(world).getGenericReturnType().resolve(world);
incompatibleReturnTypes = !rtParentReturnType.equals(rtChildReturnType);
}
if (incompatibleReturnTypes) {
world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH, parent, child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
if (parent.getKind() == Member.POINTCUT) {
UnresolvedType[] pTypes = parent.getParameterTypes();
UnresolvedType[] cTypes = child.getParameterTypes();
if (!Arrays.equals(pTypes, cTypes)) {
world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH, parent, child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
}
// System.err.println("check: " + child.getModifiers() +
// " more visible " + parent.getModifiers());
if (isMoreVisible(parent.getModifiers(), child.getModifiers())) {
world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION, parent, child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
// check declared exceptions
ResolvedType[] childExceptions = world.resolve(child.getExceptions());
ResolvedType[] parentExceptions = world.resolve(parent.getExceptions());
ResolvedType runtimeException = world.resolve("java.lang.RuntimeException");
ResolvedType error = world.resolve("java.lang.Error");
outer: for (int i = 0, leni = childExceptions.length; i < leni; i++) {
// System.err.println("checking: " + childExceptions[i]);
if (runtimeException.isAssignableFrom(childExceptions[i])) {
continue;
}
if (error.isAssignableFrom(childExceptions[i])) {
continue;
}
for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) {
if (parentExceptions[j].isAssignableFrom(childExceptions[i])) {
continue outer;
}
}
// this message is now better handled my MethodVerifier in JDT core.
// world.showMessage(IMessage.ERROR,
// WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,
// childExceptions[i].getName()),
// child.getSourceLocation(), null);
return false;
}
boolean parentStatic = Modifier.isStatic(parent.getModifiers());
boolean childStatic = Modifier.isStatic(child.getModifiers());
if (parentStatic && !childStatic) {
world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC, child, parent),
child.getSourceLocation(), null);
return false;
} else if (childStatic && !parentStatic) {
world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC, child, parent),
child.getSourceLocation(), null);
return false;
}
return true;
}
private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) {
// if (!m1.getReturnType().equals(m2.getReturnType())) return 0;
// need to allow for the special case of 'clone' - which is like
// abstract but is
// not marked abstract. The code below this next line seems to make
// assumptions
// about what will have gotten through the compiler based on the normal
// java rules. clone goes against these...
if (Modifier.isProtected(m2.getModifiers()) && m2.getName().charAt(0) == 'c') {
UnresolvedType declaring = m2.getDeclaringType();
if (declaring != null) {
if (declaring.getName().equals("java.lang.Object") && 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;
/*
* if (m1.getMunger().getKind() == ResolvedTypeMunger.Field && m2.getMunger().getKind() == ResolvedTypeMunger.Field) { // if
* *exactly* the same, it's ok return true; }
*/
// 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());
// return false;
}
public ResolvedMember lookupSyntheticMember(Member member) {
// ??? horribly inefficient
// for (Iterator i =
// System.err.println("lookup " + member + " in " + interTypeMungers);
for (ConcreteTypeMunger m : interTypeMungers) {
ResolvedMember ret = m.getMatchingSyntheticMember(member);
if (ret != null) {
// System.err.println(" found: " + ret);
return ret;
}
}
// Handling members for the new array join point
if (world.isJoinpointArrayConstructionEnabled() && this.isArray()) {
if (member.getKind() == Member.CONSTRUCTOR) {
ResolvedMemberImpl ret = new ResolvedMemberImpl(Member.CONSTRUCTOR, this, Modifier.PUBLIC, UnresolvedType.VOID,
"<init>", world.resolve(member.getParameterTypes()));
// Give the parameters names - they are going to be the dimensions uses to build the array (dim0 > dimN)
int count = ret.getParameterTypes().length;
String[] paramNames = new String[count];
for (int i = 0; i < count; i++) {
paramNames[i] = new StringBuffer("dim").append(i).toString();
}
ret.setParameterNames(paramNames);
return ret;
}
}
// if (this.getSuperclass() != ResolvedType.OBJECT &&
// this.getSuperclass() != null) {
// return getSuperclass().lookupSyntheticMember(member);
// }
return null;
}
static class SuperClassWalker implements Iterator<ResolvedType> {
private ResolvedType curr;
private SuperInterfaceWalker iwalker;
private boolean wantGenerics;
public SuperClassWalker(ResolvedType type, SuperInterfaceWalker iwalker, boolean genericsAware) {
this.curr = type;
this.iwalker = iwalker;
this.wantGenerics = genericsAware;
}
public boolean hasNext() {
return curr != null;
}
public ResolvedType next() {
ResolvedType ret = curr;
if (!wantGenerics && ret.isParameterizedOrGenericType()) {
ret = ret.getRawType();
}
iwalker.push(ret); // tell the interface walker about another class whose interfaces need visiting
curr = curr.getSuperclass();
return ret;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
static class SuperInterfaceWalker implements Iterator<ResolvedType> {
private Getter<ResolvedType, ResolvedType> ifaceGetter;
Iterator<ResolvedType> delegate = null;
public Queue<ResolvedType> toPersue = new LinkedList<ResolvedType>();
public Set<ResolvedType> visited = new HashSet<ResolvedType>();
SuperInterfaceWalker(Iterators.Getter<ResolvedType, ResolvedType> ifaceGetter) {
this.ifaceGetter = ifaceGetter;
}
SuperInterfaceWalker(Iterators.Getter<ResolvedType, ResolvedType> ifaceGetter, ResolvedType interfaceType) {
this.ifaceGetter = ifaceGetter;
this.delegate = Iterators.one(interfaceType);
}
public boolean hasNext() {
if (delegate == null || !delegate.hasNext()) {
// either we set it up or we have run out, is there anything else to look at?
if (toPersue.isEmpty()) {
return false;
}
do {
ResolvedType next = toPersue.remove();
visited.add(next);
delegate = ifaceGetter.get(next); // retrieve interfaces from a class or another interface
} while (!delegate.hasNext() && !toPersue.isEmpty());
}
return delegate.hasNext();
}
public void push(ResolvedType ret) {
toPersue.add(ret);
}
public ResolvedType next() {
ResolvedType next = delegate.next();
// BUG should check for generics and erase?
// if (!visited.contains(next)) {
// visited.add(next);
if (visited.add(next)) {
toPersue.add(next); // pushes on interfaces already visited?
}
return next;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
public void clearInterTypeMungers() {
if (isRawType()) {
ResolvedType genericType = getGenericType();
if (genericType.isRawType()) { // ERROR SITUATION: PR341926
// For some reason the raw type is pointing to another raw form (possibly itself)
System.err.println("DebugFor341926: Type " + this.getName() + " has an incorrect generic form");
} else {
genericType.clearInterTypeMungers();
}
}
// interTypeMungers.clear();
// BUG? Why can't this be clear() instead: 293620 c6
interTypeMungers = new ArrayList<ConcreteTypeMunger>();
}
public boolean isTopmostImplementor(ResolvedType interfaceType) {
boolean b = true;
if (isInterface()) {
b = false;
} else if (!interfaceType.isAssignableFrom(this, true)) {
b = false;
} else {
ResolvedType superclass = this.getSuperclass();
if (superclass.isMissing()) {
b = true; // we don't know anything about supertype, and it can't be exposed to weaver
} else if (interfaceType.isAssignableFrom(superclass, true)) { // check that I'm truly the topmost implementor
b = false;
}
}
// System.out.println("is " + getName() + " topmostimplementor of " + interfaceType + "? " + b);
return b;
}
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;
}
public List<ResolvedMember> getExposedPointcuts() {
List<ResolvedMember> ret = new ArrayList<ResolvedMember>();
if (getSuperclass() != null) {
ret.addAll(getSuperclass().getExposedPointcuts());
}
for (ResolvedType type : getDeclaredInterfaces()) {
addPointcutsResolvingConflicts(ret, Arrays.asList(type.getDeclaredPointcuts()), false);
}
addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true);
for (ResolvedMember member : ret) {
ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition) member;
if (inherited != null && 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<ResolvedMember> acc, List<ResolvedMember> added, boolean isOverriding) {
for (Iterator<ResolvedMember> i = added.iterator(); i.hasNext();) {
ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next();
for (Iterator<ResolvedMember> j = acc.iterator(); j.hasNext();) {
ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next();
if (toAdd == null || existing == null || existing == toAdd) {
continue;
}
UnresolvedType pointcutDeclaringTypeUT = existing.getDeclaringType();
if (pointcutDeclaringTypeUT != null) {
ResolvedType pointcutDeclaringType = pointcutDeclaringTypeUT.resolve(getWorld());
if (!isVisible(existing.getModifiers(), pointcutDeclaringType, this)) {
// if they intended to override it but it is not visible,
// give them a nicer message
if (existing.isAbstract() && conflictingSignature(existing, toAdd)) {
getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.POINTCUT_NOT_VISIBLE, existing.getDeclaringType()
.getName() + "." + existing.getName() + "()", this.getName()),
toAdd.getSourceLocation(), null);
j.remove();
}
continue;
}
}
if (conflictingSignature(existing, toAdd)) {
if (isOverriding) {
checkLegalOverride(existing, toAdd, 0x00, null);
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 ReferenceType getGenericType() {
// if (!(isParameterizedType() || isRawType()))
// throw new BCException("The type " + getBaseName() + " is not parameterized or raw - it has no generic type");
return null;
}
@Override
public ResolvedType getRawType() {
return super.getRawType().resolve(world);
}
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 (or nested parameterized types),
* return a version with those type parameters replaced in accordance with the passed bindings.
*/
@Override
public UnresolvedType parameterize(Map<String, UnresolvedType> typeBindings) {
if (!isParameterizedType()) {
// throw new IllegalStateException("Can't parameterize a type that is not a parameterized type");
return this;
}
boolean workToDo = false;
for (int i = 0; i < typeParameters.length; i++) {
if (typeParameters[i].isTypeVariableReference() || (typeParameters[i] instanceof BoundedReferenceType) || typeParameters[i].isParameterizedType()) {
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 = typeBindings.get(tvrt.getTypeVariable().getName());
if (binding != null) {
newTypeParams[i] = binding;
}
} else if (newTypeParams[i] instanceof BoundedReferenceType) {
BoundedReferenceType brType = (BoundedReferenceType) newTypeParams[i];
newTypeParams[i] = brType.parameterize(typeBindings);
// brType.parameterize(typeBindings)
} else if (newTypeParams[i].isParameterizedType()) {
newTypeParams[i] = newTypeParams[i].parameterize(typeBindings);
}
}
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);
// }
// }
/**
* @return true if assignable to java.lang.Exception
*/
public boolean isException() {
return (world.getCoreType(UnresolvedType.JL_EXCEPTION).isAssignableFrom(this));
}
/**
* @return true if it is an exception and it is a checked one, false otherwise.
*/
public boolean isCheckedException() {
if (!isException()) {
return false;
}
if (world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION).isAssignableFrom(this)) {
return false;
}
return true;
}
/**
* Determines if variables of this type could be assigned values of another with lots of help. java.lang.Object is convertable
* from all types. A primitive type is convertable from X iff it's assignable from X. A reference type is convertable from X iff
* it's coerceable from X. In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y could be
* assignable to a variable of type X without loss of precision.
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other with possible conversion
*/
public final boolean isConvertableFrom(ResolvedType other) {
// // version from TypeX
// if (this.equals(OBJECT)) return true;
// if (this.isPrimitiveType() || other.isPrimitiveType()) return
// this.isAssignableFrom(other);
// return this.isCoerceableFrom(other);
//
// version from ResolvedTypeX
if (this.equals(OBJECT)) {
return true;
}
if (world.isInJava5Mode()) {
if (this.isPrimitiveType() ^ other.isPrimitiveType()) { // If one is
// primitive
// and the
// other
// isnt
if (validBoxing.contains(this.getSignature() + other.getSignature())) {
return true;
}
}
}
if (this.isPrimitiveType() || other.isPrimitiveType()) {
return this.isAssignableFrom(other);
}
return this.isCoerceableFrom(other);
}
/**
* Determines if the variables of this type could be assigned values of another type without casting. This still allows for
* assignment conversion as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER).
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other without casting
* @throws NullPointerException if other is null
*/
public abstract boolean isAssignableFrom(ResolvedType other);
public abstract boolean isAssignableFrom(ResolvedType other, boolean allowMissing);
/**
* Determines if values of another type could possibly be cast to this type. The rules followed are from JLS 2ed 5.5,
* "Casting Conversion".
* <p/>
* <p>
* This method should be commutative, i.e., for all UnresolvedType a, b and all World w:
* <p/>
* <blockquote>
*
* <pre>
* a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w)
* </pre>
*
* </blockquote>
*
* @param other the other type
* @param world the {@link World} in which the possible coersion should be checked.
* @return true iff values of other could possibly be cast to this type.
* @throws NullPointerException if other is null.
*/
public abstract boolean isCoerceableFrom(ResolvedType other);
public boolean needsNoConversionFrom(ResolvedType o) {
return isAssignableFrom(o);
}
public String getSignatureForAttribute() {
return signature; // Assume if this is being called that it is for a
// simple type (eg. void, int, etc)
}
private FuzzyBoolean parameterizedWithTypeVariable = 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 isParameterizedWithTypeVariable() {
// MAYBE means we haven't worked it out yet...
if (parameterizedWithTypeVariable == FuzzyBoolean.MAYBE) {
// if there are no type parameters then we cant be...
if (typeParameters == null || typeParameters.length == 0) {
parameterizedWithTypeVariable = FuzzyBoolean.NO;
return false;
}
for (int i = 0; i < typeParameters.length; i++) {
ResolvedType aType = (ResolvedType) typeParameters[i];
if (aType.isTypeVariableReference()
// Changed according to the problems covered in bug 222648
// Don't care what kind of type variable - the fact that there
// is one
// at all means we can't risk caching it against we get confused
// later
// by another variation of the parameterization that just
// happens to
// use the same type variable name
// assume the worst - if its definetly not a type declared one,
// it could be anything
// && ((TypeVariableReference)aType).getTypeVariable().
// getDeclaringElementKind()!=TypeVariable.TYPE
) {
parameterizedWithTypeVariable = FuzzyBoolean.YES;
return true;
}
if (aType.isParameterizedType()) {
boolean b = aType.isParameterizedWithTypeVariable();
if (b) {
parameterizedWithTypeVariable = FuzzyBoolean.YES;
return true;
}
}
if (aType.isGenericWildcard()) {
BoundedReferenceType boundedRT = (BoundedReferenceType) aType;
if (boundedRT.isExtends()) {
boolean b = false;
UnresolvedType upperBound = boundedRT.getUpperBound();
if (upperBound.isParameterizedType()) {
b = ((ResolvedType) upperBound).isParameterizedWithTypeVariable();
} else if (upperBound.isTypeVariableReference()
&& ((TypeVariableReference) upperBound).getTypeVariable().getDeclaringElementKind() == TypeVariable.METHOD) {
b = true;
}
if (b) {
parameterizedWithTypeVariable = FuzzyBoolean.YES;
return true;
}
// FIXME asc need to check additional interface bounds
}
if (boundedRT.isSuper()) {
boolean b = false;
UnresolvedType lowerBound = boundedRT.getLowerBound();
if (lowerBound.isParameterizedType()) {
b = ((ResolvedType) lowerBound).isParameterizedWithTypeVariable();
} else if (lowerBound.isTypeVariableReference()
&& ((TypeVariableReference) lowerBound).getTypeVariable().getDeclaringElementKind() == TypeVariable.METHOD) {
b = true;
}
if (b) {
parameterizedWithTypeVariable = FuzzyBoolean.YES;
return true;
}
}
}
}
parameterizedWithTypeVariable = FuzzyBoolean.NO;
}
return parameterizedWithTypeVariable.alwaysTrue();
}
protected boolean ajMembersNeedParameterization() {
if (isParameterizedType()) {
return true;
}
ResolvedType superclass = getSuperclass();
if (superclass != null && !superclass.isMissing()) {
return superclass.ajMembersNeedParameterization();
}
return false;
}
protected Map<String, UnresolvedType> getAjMemberParameterizationMap() {
Map<String, UnresolvedType> myMap = getMemberParameterizationMap();
if (myMap.isEmpty()) {
// might extend a parameterized aspect that we also need to
// consider...
if (getSuperclass() != null) {
return getSuperclass().getAjMemberParameterizationMap();
}
}
return myMap;
}
public void setBinaryPath(String binaryPath) {
this.binaryPath = binaryPath;
}
/**
* Returns the path to the jar or class file from which this binary aspect came or null if not a binary aspect
*/
public String getBinaryPath() {
return binaryPath;
}
/**
* Undo any temporary modifications to the type (for example it may be holding annotations temporarily whilst some matching is
* occurring - These annotations will be added properly during weaving but sometimes for type completion they need to be held
* here for a while).
*/
public void ensureConsistent() {
// Nothing to do for anything except a ReferenceType
}
/**
* For an annotation type, this will return if it is marked with @Inherited
*/
public boolean isInheritedAnnotation() {
ensureAnnotationBitsInitialized();
return (bits & AnnotationMarkedInherited) != 0;
}
/*
* Setup the bitflags if they have not already been done.
*/
private void ensureAnnotationBitsInitialized() {
if ((bits & AnnotationBitsInitialized) == 0) {
bits |= AnnotationBitsInitialized;
// Is it marked @Inherited?
if (hasAnnotation(UnresolvedType.AT_INHERITED)) {
bits |= AnnotationMarkedInherited;
}
}
}
private boolean hasNewParentMungers() {
if ((bits & MungersAnalyzed) == 0) {
bits |= MungersAnalyzed;
for (ConcreteTypeMunger munger : interTypeMungers) {
ResolvedTypeMunger resolvedTypeMunger = munger.getMunger();
if (resolvedTypeMunger != null && resolvedTypeMunger.getKind() == ResolvedTypeMunger.Parent) {
bits |= HasParentMunger;
}
}
}
return (bits & HasParentMunger) != 0;
}
public void tagAsTypeHierarchyComplete() {
bits |= TypeHierarchyCompleteBit;
}
public boolean isTypeHierarchyComplete() {
return (bits & TypeHierarchyCompleteBit) != 0;
}
/**
* return the weaver version used to build this type - defaults to the most recent version unless discovered otherwise.
*
* @return the (major) version, {@link WeaverVersionInfo}
*/
public int getCompilerVersion() {
return WeaverVersionInfo.getCurrentWeaverMajorVersion();
}
public boolean isPrimitiveArray() {
return false;
}
public boolean isGroovyObject() {
if ((bits & GroovyObjectInitialized) == 0) {
ResolvedType[] intfaces = getDeclaredInterfaces();
boolean done = false;
// TODO do we need to walk more of these? (i.e. the interfaces interfaces and supertypes supertype). Check what groovy
// does in the case where a hierarchy is involved and there are types in between GroovyObject/GroovyObjectSupport and
// the type
if (intfaces != null) {
for (ResolvedType intface : intfaces) {
if (intface.getName().equals("groovy.lang.GroovyObject")) {
bits |= IsGroovyObject;
done = true;
break;
}
}
}
if (!done) {
// take a look at the supertype
if (getSuperclass().getName().equals("groovy.lang.GroovyObjectSupport")) {
bits |= IsGroovyObject;
}
}
bits |= GroovyObjectInitialized;
}
return (bits & IsGroovyObject) != 0;
}
}
|
404,600 | Bug 404600 Unhandled RuntimeException | I'm getting an unhandled RuntimeException from STS 3.2.0.RELEASE: java.lang.RuntimeException at org.aspectj.asm.AsmManager.sameType(AsmManager.java:897) at org.aspectj.asm.AsmManager.removeRelationshipsTargettingThisType(AsmManager.java:711) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1033) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.weaveQueuedEntries(AjPipeliningCompilerAdapter.java:514) at org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter.queueForWeavin ... ndation-domain/src\/main\/java<com.scispike.foundation.domain.trait.persistence*PersistableAspect.aj%com.scispike.foundation.domain.trait.persistence) Andy Clement, this can be reproduced in our private foundation repo's dev branch at commit d879446f2bfd83b51bf711d2931f4b28ce8c1901. After clicking ok on the exception dialog, there is an error marker on the package statement with text: Internal compiler error: java.lang.RuntimeException: Exception whilst walking up from target com.scispike.foundation.domain.trait.persistence kind=(package declaration) hid=(=foundation-domain/src\/main\/java<com.scispike.foundation.domain.trait.persistence*PersistableAspect.aj%com.scispike.foundation.domain.trait.persistence) at org.aspectj.asm.AsmManager.sameType(AsmManager.java:897) If I do a Project\Clean..., the exception is not reproduced and everything compiles ok. Next edit repros the exception. | resolved fixed | ff0859d | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-04-02T19:26:57Z" | "2013-03-29T04:06:40Z" | weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java | /* *******************************************************************
* Copyright (c) 2002-2010 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://www.eclipse.org/legal/epl-v10.html
* ******************************************************************/
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.Attributes.Name;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
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.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.AspectJElementHierarchy;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.util.FileUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute.WeaverVersionInfo;
import org.aspectj.weaver.AnnotationAJ;
import org.aspectj.weaver.AnnotationOnTypeMunger;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.CompressingDataOutputStream;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.CrosscuttingMembersSet;
import org.aspectj.weaver.CustomMungerFactory;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IUnwovenClassFile;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.model.AsmRelationshipProvider;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.BindingPattern;
import org.aspectj.weaver.patterns.BindingTypePattern;
import org.aspectj.weaver.patterns.ConcreteCflowPointcut;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.DeclareTypeErrorOrWarning;
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;
import org.aspectj.weaver.tools.Trace;
import org.aspectj.weaver.tools.TraceFactory;
/**
*
* @author PARC
* @author Andy Clement
* @author Alexandre Vasseur
*/
public class BcelWeaver {
public static final String CLOSURE_CLASS_PREFIX = "$Ajc";
public static final String SYNTHETIC_CLASS_POSTFIX = "$ajc";
private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWeaver.class);
private transient final BcelWorld world;
private final CrosscuttingMembersSet xcutSet;
private boolean inReweavableMode = false;
private transient List<UnwovenClassFile> addedClasses = new ArrayList<UnwovenClassFile>();
private transient List<String> deletedTypenames = new ArrayList<String>();
// These four are setup by prepareForWeave
private transient List<ShadowMunger> shadowMungerList = null;
private transient List<ConcreteTypeMunger> typeMungerList = null;
private transient List<ConcreteTypeMunger> lateTypeMungerList = null;
private transient List<DeclareParents> declareParentsList = null;
private Manifest manifest = null;
private boolean needToReweaveWorld = false;
private boolean isBatchWeave = true;
private ZipOutputStream zipOutputStream;
private CustomMungerFactory customMungerFactory;
public BcelWeaver(BcelWorld world) {
super();
if (trace.isTraceEnabled()) {
trace.enter("<init>", this, world);
}
this.world = world;
this.xcutSet = world.getCrosscuttingMembersSet();
if (trace.isTraceEnabled()) {
trace.exit("<init>");
}
}
/**
* Add the given aspect to the weaver. The type is resolved to support DOT for static inner classes as well as DOLLAR
*
* @param aspectName
* @return aspect
*/
public ResolvedType addLibraryAspect(String aspectName) {
if (trace.isTraceEnabled()) {
trace.enter("addLibraryAspect", this, aspectName);
}
// 1 - resolve as is
UnresolvedType unresolvedT = UnresolvedType.forName(aspectName);
unresolvedT.setNeedsModifiableDelegate(true);
ResolvedType type = world.resolve(unresolvedT, true);
if (type.isMissing()) {
// fallback on inner class lookup mechanism
String fixedName = aspectName;
int hasDot = fixedName.lastIndexOf('.');
while (hasDot > 0) {
// System.out.println("BcelWeaver.addLibraryAspect " +
// fixedName);
char[] fixedNameChars = fixedName.toCharArray();
fixedNameChars[hasDot] = '$';
fixedName = new String(fixedNameChars);
hasDot = fixedName.lastIndexOf('.');
UnresolvedType ut = UnresolvedType.forName(fixedName);
ut.setNeedsModifiableDelegate(true);
type = world.resolve(ut, true);
if (!type.isMissing()) {
break;
}
}
}
// System.out.println("type: " + type + " for " + aspectName);
if (type.isAspect()) {
// Bug 119657 ensure we use the unwoven aspect
WeaverStateInfo wsi = type.getWeaverState();
if (wsi != null && wsi.isReweavable()) {
BcelObjectType classType = getClassType(type.getName());
JavaClass wovenJavaClass = classType.getJavaClass();
byte[] bytes = wsi.getUnwovenClassFileData(wovenJavaClass.getBytes());
JavaClass unwovenJavaClass = Utility.makeJavaClass(wovenJavaClass.getFileName(), bytes);
world.storeClass(unwovenJavaClass);
classType.setJavaClass(unwovenJavaClass, true);
// classType.setJavaClass(Utility.makeJavaClass(classType.
// getJavaClass().getFileName(),
// wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes(
// ))));
}
// TODO AV - happens to reach that a lot of time: for each type
// flagged reweavable X for each aspect in the weaverstate
// => mainly for nothing for LTW - pbly for something in incremental
// build...
xcutSet.addOrReplaceAspect(type);
if (trace.isTraceEnabled()) {
trace.exit("addLibraryAspect", type);
}
if (type.getSuperclass().isAspect()) {
// If the supertype includes ITDs and the user has not included
// that aspect in the aop.xml, they will
// not get picked up, which can give unusual behaviour! See bug
// 223094
// This change causes us to pick up the super aspect regardless
// of what was said in the aop.xml - giving
// predictable behaviour. If the user also supplied it, there
// will be no problem other than the second
// addition overriding the first
addLibraryAspect(type.getSuperclass().getName());
}
return type;
} else {
// FIXME AV - better warning upon no such aspect from aop.xml
RuntimeException ex = new RuntimeException("Cannot register non aspect: " + type.getName() + " , " + aspectName);
if (trace.isTraceEnabled()) {
trace.exit("addLibraryAspect", ex);
}
throw ex;
}
}
/**
*
* @param inFile directory containing classes or zip/jar class archive
*/
public void addLibraryJarFile(File inFile) throws IOException {
List<ResolvedType> addedAspects = null;
if (inFile.isDirectory()) {
addedAspects = addAspectsFromDirectory(inFile);
} else {
addedAspects = addAspectsFromJarFile(inFile);
}
for (ResolvedType addedAspect : addedAspects) {
xcutSet.addOrReplaceAspect(addedAspect);
}
}
private List<ResolvedType> addAspectsFromJarFile(File inFile) throws FileNotFoundException, IOException {
ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); // ??? buffered
List<ResolvedType> addedAspects = new ArrayList<ResolvedType>();
try {
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.
int size = (int) entry.getSize();
ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName());
JavaClass jc = parser.parse();
inStream.closeEntry();
ResolvedType type = world.addSourceObjectType(jc, false).getResolvedTypeX();
type.setBinaryPath(inFile.getAbsolutePath());
if (type.isAspect()) {
addedAspects.add(type);
} else {
world.demote(type);
}
}
} finally {
inStream.close();
}
return addedAspects;
}
/**
* Look for .class files that represent aspects in the supplied directory - return the list of accumulated aspects.
*
* @param directory the directory in which to look for Aspect .class files
* @return the list of discovered aspects
* @throws FileNotFoundException
* @throws IOException
*/
private List<ResolvedType> addAspectsFromDirectory(File directory) throws FileNotFoundException, IOException {
List<ResolvedType> addedAspects = new ArrayList<ResolvedType>();
File[] classFiles = FileUtil.listFiles(directory, new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(".class");
}
});
for (File classFile : classFiles) {
FileInputStream fis = new FileInputStream(classFile);
byte[] classBytes = FileUtil.readAsByteArray(fis);
ResolvedType aspectType = isAspect(classBytes, classFile.getAbsolutePath(), directory);
if (aspectType != null) {
addedAspects.add(aspectType);
}
fis.close();
}
return addedAspects;
}
/**
* Determine if the supplied bytes represent an aspect, if they do then create a ResolvedType instance for the aspect and return
* it, otherwise return null
*
* @param classbytes the classbytes that might represent an aspect
* @param name the name of the class
* @param directory directory which contained the class file
* @return a ResolvedType if the classbytes represent an aspect, otherwise null
*/
private ResolvedType isAspect(byte[] classbytes, String name, File dir) throws IOException {
ClassParser parser = new ClassParser(new ByteArrayInputStream(classbytes), name);
JavaClass jc = parser.parse();
ResolvedType type = world.addSourceObjectType(jc, false).getResolvedTypeX();
String typeName = type.getName().replace('.', File.separatorChar);
int end = name.lastIndexOf(typeName + ".class");
String binaryPath = null;
// if end is -1 then something weird happened, the class file is not in
// the correct place, something like
// bin/A.class when the declaration for A specifies it is in a package.
if (end == -1) {
binaryPath = dir.getAbsolutePath();
} else {
binaryPath = name.substring(0, end - 1);
}
type.setBinaryPath(binaryPath);
if (type.isAspect()) {
return type;
} else {
// immediately demote the type we just added since it will have
// have been stuffed into the permanent map (assumed to be
// an aspect)
world.demote(type);
return null;
}
}
// // The ANT copy task should be used to copy resources across.
// private final static boolean
// CopyResourcesFromInpathDirectoriesToOutput=false;
/**
* Add any .class files in the directory to the outdir. Anything other than .class files in the directory (or its
* subdirectories) are considered resources and are also copied.
*
*/
public List<UnwovenClassFile> addDirectoryContents(File inFile, File outDir) throws IOException {
List<UnwovenClassFile> addedClassFiles = new ArrayList<UnwovenClassFile>();
// 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<UnwovenClassFile> addJarFile(File inFile, File outDir, boolean canBeDirectory) {
// System.err.println("? addJarFile(" + inFile + ", " + outDir + ")");
List<UnwovenClassFile> addedClassFiles = new ArrayList<UnwovenClassFile>();
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);
try {
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")) {
ReferenceType type = this.addClassFile(classFile, false);
StringBuffer sb = new StringBuffer();
sb.append(inFile.getAbsolutePath());
sb.append("!");
sb.append(entry.getName());
type.setBinaryPath(sb.toString());
addedClassFiles.add(classFile);
}
// else if (!entry.isDirectory()) {
//
// /* bug-44190 Copy meta-data */
// addResource(filename,classFile);
// }
inStream.close();
}
} finally {
inJar.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 boolean needToReweaveWorld() {
return needToReweaveWorld;
}
/**
* Should be addOrReplace
*/
public ReferenceType addClassFile(UnwovenClassFile classFile, boolean fromInpath) {
addedClasses.add(classFile);
ReferenceType type = world.addSourceObjectType(classFile.getJavaClass(), false).getResolvedTypeX();
if (fromInpath) {
type.setBinaryPath(classFile.getFilename());
}
return type;
}
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);
StringBuffer sb = new StringBuffer();
sb.append(inPathDir.getAbsolutePath());
sb.append("!");
sb.append(filename);
ReferenceType type = this.addClassFile(ucf, false);
type.setBinaryPath(sb.toString());
}
fis.close();
return ucf;
}
public void deleteClassFile(String typename) {
deletedTypenames.add(typename);
world.deleteSourceObjectType(UnresolvedType.forName(typename));
}
// ---- weave preparation
public void setIsBatchWeave(boolean b) {
isBatchWeave = b;
}
public void prepareForWeave() {
if (trace.isTraceEnabled()) {
trace.enter("prepareForWeave", this);
}
needToReweaveWorld = xcutSet.hasChangedSinceLastReset();
// update mungers
for (Iterator<UnwovenClassFile> i = addedClasses.iterator(); i.hasNext();) {
UnwovenClassFile jc = i.next();
String name = jc.getClassName();
ResolvedType type = world.resolve(name);
if (type.isAspect() && !world.isOverWeaving()) {
needToReweaveWorld |= xcutSet.addOrReplaceAspect(type);
}
}
for (Iterator<String> i = deletedTypenames.iterator(); i.hasNext();) {
String name = i.next();
if (xcutSet.deleteAspect(UnresolvedType.forName(name))) {
needToReweaveWorld = true;
}
}
shadowMungerList = xcutSet.getShadowMungers();
// world.debug("shadow mungers=" + shadowMungerList);
rewritePointcuts(shadowMungerList);
// Sometimes an error occurs during rewriting pointcuts (for example, if
// ambiguous bindings
// are detected) - we ought to fail the prepare when this happens
// because continuing with
// inconsistent pointcuts could lead to problems
typeMungerList = xcutSet.getTypeMungers();
lateTypeMungerList = xcutSet.getLateTypeMungers();
declareParentsList = xcutSet.getDeclareParents();
addCustomMungers();
// 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<ShadowMunger>() {
public int compare(ShadowMunger sm1, ShadowMunger sm2) {
if (sm1.getSourceLocation() == null) {
return (sm2.getSourceLocation() == null ? 0 : 1);
}
if (sm2.getSourceLocation() == null) {
return -1;
}
return (sm2.getSourceLocation().getOffset() - sm1.getSourceLocation().getOffset());
}
});
if (inReweavableMode) {
world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.REWEAVABLE_MODE), null, null);
}
if (trace.isTraceEnabled()) {
trace.exit("prepareForWeave");
}
}
private void addCustomMungers() {
if (customMungerFactory != null) {
for (Iterator<UnwovenClassFile> i = addedClasses.iterator(); i.hasNext();) {
UnwovenClassFile jc = i.next();
String name = jc.getClassName();
ResolvedType type = world.resolve(name);
if (type.isAspect()) {
Collection<ShadowMunger> shadowMungers = customMungerFactory.createCustomShadowMungers(type);
if (shadowMungers != null) {
shadowMungerList.addAll(shadowMungers);
}
Collection<ConcreteTypeMunger> typeMungers = customMungerFactory.createCustomTypeMungers(type);
if (typeMungers != null) {
typeMungerList.addAll(typeMungers);
}
}
}
}
}
public void setCustomMungerFactory(CustomMungerFactory factory) {
customMungerFactory = factory;
}
/*
* 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 (ShadowMunger munger : shadowMungers) {
Pointcut p = munger.getPointcut();
Pointcut newP = rewriter.rewrite(p);
// validateBindings now whilst we still have around the pointcut
// that resembles what the user actually wrote in their program
// text.
if (munger instanceof Advice) {
Advice advice = (Advice) munger;
if (advice.getSignature() != null) {
final int numFormals;
final String names[];
// If the advice is being concretized in a @AJ aspect *and*
// the advice was declared in
// an @AJ aspect (it could have been inherited from a code
// style aspect) then
// evaluate the alternative set of formals. pr125699
if ((advice.getConcreteAspect().isAnnotationStyleAspect() && advice.getDeclaringAspect() != null && advice
.getDeclaringAspect().resolve(world).isAnnotationStyleAspect())
|| advice.isAnnotationStyle()) {
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);
}
}
}
}
newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames;
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<Pointcut, Pointcut>();
for (ShadowMunger munger: shadowMungers) {
Pointcut p = munger.getPointcut();
Pointcut newP = shareEntriesFromMap(p, pcMap);
newP.m_ignoreUnboundBindingForNames = p.m_ignoreUnboundBindingForNames;
munger.setPointcut(newP);
}
}
private Pointcut shareEntriesFromMap(Pointcut p, Map<Pointcut, Pointcut> 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 pcMap.get(p); // same instance (identity)
} else {
pcMap.put(p, p);
return p;
}
}
}
// userPointcut is the pointcut that the user wrote in the program text.
// dnfPointcut is the same pointcut rewritten in DNF
// numFormals is the number of formal parameters in the pointcut
// if numFormals > 0 then every branch of a disjunction must bind each
// formal once and only once.
// in addition, the left and right branches of a disjunction must hold on
// join point kinds in
// common.
private void validateBindings(Pointcut dnfPointcut, Pointcut userPointcut, int numFormals, String[] names) {
if (numFormals == 0) {
return; // nothing to check
}
if (dnfPointcut.couldMatchKinds() == Shadow.NO_SHADOW_KINDS_BITS) {
return; // cant have problems if you dont match!
}
if (dnfPointcut instanceof OrPointcut) {
OrPointcut orBasedDNFPointcut = (OrPointcut) dnfPointcut;
Pointcut[] leftBindings = new Pointcut[numFormals];
Pointcut[] rightBindings = new Pointcut[numFormals];
validateOrBranch(orBasedDNFPointcut, userPointcut, numFormals, names, leftBindings, rightBindings);
} else {
Pointcut[] bindings = new Pointcut[numFormals];
validateSingleBranch(dnfPointcut, userPointcut, numFormals, names, bindings);
}
}
private void validateOrBranch(OrPointcut pc, Pointcut userPointcut, int numFormals, String[] names, Pointcut[] leftBindings,
Pointcut[] rightBindings) {
Pointcut left = pc.getLeft();
Pointcut right = pc.getRight();
if (left instanceof OrPointcut) {
Pointcut[] newRightBindings = new Pointcut[numFormals];
validateOrBranch((OrPointcut) left, userPointcut, numFormals, names, leftBindings, newRightBindings);
} else {
if (left.couldMatchKinds() != Shadow.NO_SHADOW_KINDS_BITS) {
validateSingleBranch(left, userPointcut, numFormals, names, leftBindings);
}
}
if (right instanceof OrPointcut) {
Pointcut[] newLeftBindings = new Pointcut[numFormals];
validateOrBranch((OrPointcut) right, userPointcut, numFormals, names, newLeftBindings, rightBindings);
} else {
if (right.couldMatchKinds() != Shadow.NO_SHADOW_KINDS_BITS) {
validateSingleBranch(right, userPointcut, numFormals, names, rightBindings);
}
}
int kindsInCommon = left.couldMatchKinds() & right.couldMatchKinds();
if (kindsInCommon != Shadow.NO_SHADOW_KINDS_BITS && couldEverMatchSameJoinPoints(left, right)) {
// we know that every branch binds every formal, so there is no
// ambiguity
// if each branch binds it in exactly the same way...
List<String> ambiguousNames = new ArrayList<String>();
for (int i = 0; i < numFormals; i++) {
if (leftBindings[i] == null) {
if (rightBindings[i] != null) {
ambiguousNames.add(names[i]);
}
} else 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/* BindingPattern */baps = ((NameBindingPointcut) pc).getBindingAnnotationTypePatterns();
for (Iterator iter = baps.iterator(); iter.hasNext();) {
BindingPattern bap = (BindingPattern) iter.next();
int index = bap.getFormalIndex();
bindings[index] = pc;
if (foundFormals[index]) {
raiseAmbiguousBindingError(names[index], userPointcut);
} else {
foundFormals[index] = true;
}
}
} else if (pc instanceof ConcreteCflowPointcut) {
ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc;
int[] slots = cfp.getUsedFormalSlots();
for (int i = 0; i < slots.length; i++) {
bindings[slots[i]] = cfp;
if (foundFormals[slots[i]]) {
raiseAmbiguousBindingError(names[slots[i]], userPointcut);
} else {
foundFormals[slots[i]] = true;
}
}
}
}
// By returning false from this method, we are allowing binding of the same
// variable on either side of an or.
// Be conservative :- have to consider overriding, varargs, autoboxing,
// the effects of itds (on within for example), interfaces, the fact that
// join points can have multiple signatures and so on.
private boolean couldEverMatchSameJoinPoints(Pointcut left, Pointcut right) {
if (left instanceof OrPointcut) {
OrPointcut leftOrPointcut = (OrPointcut) left;
if (couldEverMatchSameJoinPoints(leftOrPointcut.getLeft(), right)) {
return true;
}
if (couldEverMatchSameJoinPoints(leftOrPointcut.getRight(), right)) {
return true;
}
return false;
}
if (right instanceof OrPointcut) {
OrPointcut rightOrPointcut = (OrPointcut) right;
if (couldEverMatchSameJoinPoints(left, rightOrPointcut.getLeft())) {
return true;
}
if (couldEverMatchSameJoinPoints(left, rightOrPointcut.getRight())) {
return true;
}
return false;
}
// look for withins
WithinPointcut leftWithin = (WithinPointcut) findFirstPointcutIn(left, WithinPointcut.class);
WithinPointcut rightWithin = (WithinPointcut) findFirstPointcutIn(right, WithinPointcut.class);
if ((leftWithin != null) && (rightWithin != null)) {
if (!leftWithin.couldEverMatchSameJoinPointsAs(rightWithin)) {
return false;
}
}
// look for kinded
KindedPointcut leftKind = (KindedPointcut) findFirstPointcutIn(left, KindedPointcut.class);
KindedPointcut rightKind = (KindedPointcut) findFirstPointcutIn(right, KindedPointcut.class);
if ((leftKind != null) && (rightKind != null)) {
if (!leftKind.couldEverMatchSameJoinPointsAs(rightKind)) {
return false;
}
}
return true;
}
private Pointcut findFirstPointcutIn(Pointcut toSearch, Class toLookFor) {
if (toSearch instanceof NotPointcut) {
return null;
}
if (toLookFor.isInstance(toSearch)) {
return toSearch;
}
if (toSearch instanceof AndPointcut) {
AndPointcut apc = (AndPointcut) toSearch;
Pointcut left = findFirstPointcutIn(apc.getLeft(), toLookFor);
if (left != null) {
return left;
}
return findFirstPointcutIn(apc.getRight(), toLookFor);
}
return null;
}
/**
* @param userPointcut
*/
private void raiseNegationBindingError(Pointcut userPointcut) {
world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.NEGATION_DOESNT_ALLOW_BINDING), userPointcut
.getSourceContext().makeSourceLocation(userPointcut), null);
}
/**
* @param name
* @param userPointcut
*/
private void raiseAmbiguousBindingError(String name, Pointcut userPointcut) {
world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.AMBIGUOUS_BINDING, name), userPointcut
.getSourceContext().makeSourceLocation(userPointcut), null);
}
/**
* @param userPointcut
*/
private void raiseAmbiguityInDisjunctionError(Pointcut userPointcut, List<String> 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.getSourceLocation(), null);
}
public void addManifest(Manifest newManifest) {
// System.out.println("? addManifest() newManifest=" + newManifest);
if (manifest == null) {
manifest = newManifest;
}
}
public Manifest getManifest(boolean shouldCreate) {
if (manifest == null && shouldCreate) {
String WEAVER_MANIFEST_VERSION = "1.0";
Attributes.Name CREATED_BY = new Name("Created-By");
String WEAVER_CREATED_BY = "AspectJ Compiler";
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
// FOR TESTING
public Collection<String> weave(File file) throws IOException {
OutputStream os = FileUtil.makeOutputStream(file);
this.zipOutputStream = new ZipOutputStream(os);
prepareForWeave();
Collection<String> c = weave(new IClassFileProvider() {
public boolean isApplyAtAspectJMungersOnly() {
return false;
}
public Iterator<UnwovenClassFile> getClassFileIterator() {
return addedClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(IUnwovenClassFile result) {
try {
writeZipEntry(result.getFilename(), result.getBytes());
} 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;
}
private Set<IProgramElement> candidatesForRemoval = null;
// variation of "weave" that sources class files from an external source.
public Collection<String> weave(IClassFileProvider input) throws IOException {
if (trace.isTraceEnabled()) {
trace.enter("weave", this, input);
}
ContextToken weaveToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING, "");
Collection<String> wovenClassNames = new ArrayList<String>();
IWeaveRequestor requestor = input.getRequestor();
if (world.getModel() != null && world.isMinimalModel()) {
candidatesForRemoval = new HashSet<IProgramElement>();
}
if (world.getModel() != null && !isBatchWeave) {
AsmManager manager = world.getModelAsAsmManager();
for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
UnwovenClassFile classFile = i.next();
// remove all relationships where this file being woven is
// the target of the relationship
manager.removeRelationshipsTargettingThisType(classFile.getClassName());
}
}
// Go through the types and ensure any 'damaged' during compile time are
// repaired prior to weaving
for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
UnwovenClassFile classFile = i.next();
String className = classFile.getClassName();
ResolvedType theType = world.resolve(className);
if (theType != null) {
theType.ensureConsistent();
}
}
// special case for AtAspectJMungerOnly - see #113587
if (input.isApplyAtAspectJMungersOnly()) {
ContextToken atAspectJMungersOnly = CompilationAndWeavingContext.enteringPhase(
CompilationAndWeavingContext.PROCESSING_ATASPECTJTYPE_MUNGERS_ONLY, "");
requestor.weavingAspects();
// ContextToken aspectToken =
CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
UnwovenClassFile classFile = i.next();
String className = classFile.getClassName();
ResolvedType theType = world.resolve(className);
if (theType.isAnnotationStyleAspect()) {
BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
if (classType == null) {
throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
}
LazyClassGen clazz = classType.getLazyClassGen();
BcelPerClauseAspectAdder selfMunger = new BcelPerClauseAspectAdder(theType, theType.getPerClause().getKind());
selfMunger.forceMunge(clazz, true);
classType.finishedWith();
UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
for (int news = 0; news < newClasses.length; news++) {
requestor.acceptResult(newClasses[news]);
}
wovenClassNames.add(classFile.getClassName());
}
}
requestor.weaveCompleted();
CompilationAndWeavingContext.leavingPhase(atAspectJMungersOnly);
return wovenClassNames;
}
requestor.processingReweavableState();
ContextToken reweaveToken = CompilationAndWeavingContext.enteringPhase(
CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, "");
prepareToProcessReweavableState();
// clear all state from files we'll be reweaving
for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
UnwovenClassFile classFile = i.next();
String className = classFile.getClassName();
BcelObjectType classType = getClassType(className);
// null return from getClassType() means the delegate is an eclipse
// source type - so
// there *cant* be any reweavable state... (he bravely claimed...)
if (classType != null) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(
CompilationAndWeavingContext.PROCESSING_REWEAVABLE_STATE, className);
processReweavableStateIfPresent(className, classType);
CompilationAndWeavingContext.leavingPhase(tok);
}
}
CompilationAndWeavingContext.leavingPhase(reweaveToken);
ContextToken typeMungingToken = CompilationAndWeavingContext.enteringPhase(
CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS, "");
requestor.addingTypeMungers();
// We process type mungers in two groups, first mungers that change the
// type
// hierarchy, then 'normal' ITD type mungers.
// Process the types in a predictable order (rather than the order
// encountered).
// For class A, the order is superclasses of A then superinterfaces of A
// (and this mechanism is applied recursively)
List<String> typesToProcess = new ArrayList<String>();
for (Iterator<UnwovenClassFile> iter = input.getClassFileIterator(); iter.hasNext();) {
UnwovenClassFile clf = iter.next();
typesToProcess.add(clf.getClassName());
}
while (typesToProcess.size() > 0) {
weaveParentsFor(typesToProcess, typesToProcess.get(0), null);
}
for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
UnwovenClassFile classFile = i.next();
String className = classFile.getClassName();
addNormalTypeMungers(className);
}
CompilationAndWeavingContext.leavingPhase(typeMungingToken);
requestor.weavingAspects();
ContextToken aspectToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_ASPECTS, "");
// first weave into aspects
for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
UnwovenClassFile classFile = i.next();
String className = classFile.getClassName();
ResolvedType theType = world.resolve(className);
if (theType.isAspect()) {
BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
if (classType == null) {
// Sometimes.. if the Bcel Delegate couldn't be found then a
// problem occurred at compile time - on
// a previous compiler run. In this case I assert the
// delegate will still be an EclipseSourceType
// and we can ignore the problem here (the original compile
// error will be reported again from
// the eclipse source type) - pr113531
ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate();
if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) {
continue;
}
throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
}
weaveAndNotify(classFile, classType, requestor);
wovenClassNames.add(className);
}
}
CompilationAndWeavingContext.leavingPhase(aspectToken);
requestor.weavingClasses();
ContextToken classToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_CLASSES, "");
// then weave into non-aspects
for (Iterator<UnwovenClassFile> i = input.getClassFileIterator(); i.hasNext();) {
UnwovenClassFile classFile = i.next();
String className = classFile.getClassName();
ResolvedType theType = world.resolve(className);
if (!theType.isAspect()) {
BcelObjectType classType = BcelWorld.getBcelObjectType(theType);
if (classType == null) {
// bug 119882 - see above comment for bug 113531
ReferenceTypeDelegate theDelegate = ((ReferenceType) theType).getDelegate();
// TODO urgh - put a method on the interface to check this,
// string compare is hideous
if (theDelegate.getClass().getName().endsWith("EclipseSourceType")) {
continue;
}
throw new BCException("Can't find bcel delegate for " + className + " type=" + theType.getClass());
}
weaveAndNotify(classFile, classType, requestor);
wovenClassNames.add(className);
}
}
CompilationAndWeavingContext.leavingPhase(classToken);
addedClasses.clear();
deletedTypenames.clear();
requestor.weaveCompleted();
CompilationAndWeavingContext.leavingPhase(weaveToken);
if (trace.isTraceEnabled()) {
trace.exit("weave", wovenClassNames);
}
if (world.getModel() != null && world.isMinimalModel()) {
candidatesForRemoval.clear();
}
return wovenClassNames;
}
public void allWeavingComplete() {
warnOnUnmatchedAdvice();
}
/**
* In 1.5 mode and with XLint:adviceDidNotMatch enabled, put out messages for any mungers that did not match anything.
*/
private void warnOnUnmatchedAdvice() {
class AdviceLocation {
private final int lineNo;
private final UnresolvedType inAspect;
public AdviceLocation(BcelAdvice advice) {
this.lineNo = advice.getSourceLocation().getLine();
this.inAspect = advice.getDeclaringAspect();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AdviceLocation)) {
return false;
}
AdviceLocation other = (AdviceLocation) obj;
if (this.lineNo != other.lineNo) {
return false;
}
if (!this.inAspect.equals(other.inAspect)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return 37 + 17 * lineNo + 17 * inAspect.hashCode();
}
}
// FIXME asc Should be factored out into Xlint code and done
// automatically for all xlint messages, ideally.
// if a piece of advice hasn't matched anywhere and we are in -1.5 mode,
// put out a warning
if (world.isInJava5Mode() && world.getLint().adviceDidNotMatch.isEnabled()) {
List l = world.getCrosscuttingMembersSet().getShadowMungers();
Set<AdviceLocation> alreadyWarnedLocations = new HashSet<AdviceLocation>();
for (Iterator iter = l.iterator(); iter.hasNext();) {
ShadowMunger element = (ShadowMunger) iter.next();
// This will stop us incorrectly reporting deow checkers:
if (element instanceof BcelAdvice) {
BcelAdvice ba = (BcelAdvice) element;
if (ba.getKind() == AdviceKind.CflowEntry || ba.getKind() == AdviceKind.CflowBelowEntry) {
continue;
}
if (!ba.hasMatchedSomething()) {
// Because we implement some features of AJ itself by
// creating our own kind of mungers, you sometimes
// find that ba.getSignature() is not a BcelMethod - for
// example it might be a cflow entry munger.
if (ba.getSignature() != null) {
// check we haven't already warned on this advice and line
// (cflow creates multiple mungers for the same advice)
AdviceLocation loc = new AdviceLocation(ba);
if (alreadyWarnedLocations.contains(loc)) {
continue;
} else {
alreadyWarnedLocations.add(loc);
}
if (!(ba.getSignature() instanceof BcelMethod)
|| !Utility.isSuppressing(ba.getSignature(), "adviceDidNotMatch")) {
world.getLint().adviceDidNotMatch.signal(ba.getDeclaringAspect().toString(), new SourceLocation(
element.getSourceLocation().getSourceFile(), element.getSourceLocation().getLine()));
}
}
}
}
}
}
}
/**
* '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<String> typesForWeaving, String typeToWeave, ResolvedType resolvedTypeToWeave) {
if (resolvedTypeToWeave == null) {
// resolve it if the caller could not pass in the resolved type
resolvedTypeToWeave = world.resolve(typeToWeave);
}
ResolvedType superclassType = resolvedTypeToWeave.getSuperclass();
String superclassTypename = (superclassType == null ? null : superclassType.getName());
// PR336654 added the 'typesForWeaving.contains(superclassTypename)' clause.
// Without it we can delete all type mungers on the parents and yet we only
// add back in the declare parents related ones, not the regular ITDs.
if (superclassType != null && !superclassType.isTypeHierarchyComplete() && superclassType.isExposedToWeaver()
&& typesForWeaving.contains(superclassTypename)) {
weaveParentsFor(typesForWeaving, superclassTypename, superclassType);
}
ResolvedType[] interfaceTypes = resolvedTypeToWeave.getDeclaredInterfaces();
for (ResolvedType resolvedSuperInterface : interfaceTypes) {
if (!resolvedSuperInterface.isTypeHierarchyComplete()) {
String interfaceTypename = resolvedSuperInterface.getName();
if (resolvedSuperInterface.isExposedToWeaver()) { // typesForWeaving.contains(interfaceTypename)) {
weaveParentsFor(typesForWeaving, interfaceTypename, resolvedSuperInterface);
}
}
}
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,
resolvedTypeToWeave.getName());
weaveParentTypeMungers(resolvedTypeToWeave);
CompilationAndWeavingContext.leavingPhase(tok);
typesForWeaving.remove(typeToWeave);
resolvedTypeToWeave.tagAsTypeHierarchyComplete();
}
public void prepareToProcessReweavableState() {
}
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();
// System.out.println(">> processReweavableStateIfPresent " + className + " wsi=" + wsi);
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<String> aspectsPreviouslyInWorld = wsi.getAspectsAffectingType();
// keep track of them just to ensure unique missing aspect error
// reporting
Set<String> alreadyConfirmedReweavableState = new HashSet<String>();
for (String requiredTypeSignature : aspectsPreviouslyInWorld) {
// for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) {
// String requiredTypeName = (String) iter.next();
if (!alreadyConfirmedReweavableState.contains(requiredTypeSignature)) {
ResolvedType rtx = world.resolve(UnresolvedType.forSignature(requiredTypeSignature), true);
boolean exists = !rtx.isMissing();
if (!exists) {
world.getLint().missingAspectForReweaving.signal(new String[] { rtx.getName(), className },
classType.getSourceLocation(), null);
// world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.MISSING_REWEAVABLE_TYPE,
// requiredTypeName, className), classType.getSourceLocation(), null);
} else {
if (world.isOverWeaving()) {
// System.out.println(">> Removing " + requiredTypeName + " from weaving process: "
// + xcutSet.deleteAspect(rtx));
} else {
// weaved in aspect that are not declared in aop.xml
// trigger an error for now
// may cause headhache for LTW and packaged lib
// without aop.xml in
// see #104218
if (!xcutSet.containsAspect(rtx)) {
world.showMessage(IMessage.ERROR, WeaverMessages.format(
WeaverMessages.REWEAVABLE_ASPECT_NOT_REGISTERED, rtx.getName(), className), null, null);
} else if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
world.showMessage(IMessage.INFO, WeaverMessages.format(WeaverMessages.VERIFIED_REWEAVABLE_TYPE,
rtx.getName(), rtx.getSourceLocation().getSourceFile()), null, null);
}
}
alreadyConfirmedReweavableState.add(requiredTypeSignature);
}
}
}
// old:
// classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass
// ().getFileName(), wsi.getUnwovenClassFileData()));
// new: reweavable default with clever diff
if (!world.isOverWeaving()) {
byte[] bytes = wsi.getUnwovenClassFileData(classType.getJavaClass().getBytes());
WeaverVersionInfo wvi = classType.getWeaverVersionAttribute();
JavaClass newJavaClass = Utility.makeJavaClass(classType.getJavaClass().getFileName(), bytes);
classType.setJavaClass(newJavaClass, true);
classType.getResolvedTypeX().ensureConsistent();
}
// } else {
// classType.resetState();
}
}
private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType, IWeaveRequestor requestor) throws IOException {
trace.enter("weaveAndNotify", this, new Object[] { classFile, classType, requestor });
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_TYPE, classType
.getResolvedTypeX().getName());
LazyClassGen clazz = weaveWithoutDump(classFile, classType);
classType.finishedWith();
// clazz is null if the classfile was unchanged by weaving...
if (clazz != null) {
UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
// OPTIMIZE can we avoid using the string name at all in
// UnwovenClassFile instances?
// Copy the char[] across as it means the
// WeaverAdapter.removeFromMap() can be fast!
if (newClasses[0].getClassName().equals(classFile.getClassName())) {
newClasses[0].setClassNameAsChars(classFile.getClassNameAsChars());
}
for (int i = 0; i < newClasses.length; i++) {
requestor.acceptResult(newClasses[i]);
}
} else {
requestor.acceptResult(classFile);
}
classType.weavingCompleted();
CompilationAndWeavingContext.leavingPhase(tok);
trace.exit("weaveAndNotify");
}
/**
* helper method - will return NULL if the underlying delegate is an EclipseSourceType and not a BcelObjectType
*/
public BcelObjectType getClassType(String forClass) {
return BcelWorld.getBcelObjectType(world.resolve(forClass));
}
public void addParentTypeMungers(String typeName) {
weaveParentTypeMungers(world.resolve(typeName));
}
public void addNormalTypeMungers(String typeName) {
weaveNormalTypeMungers(world.resolve(typeName));
}
public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) {
List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
ret[0] = new UnwovenClassFile(clazz.getFileName(), clazz.getClassName(), clazz.getJavaClassBytesIncludingReweavable(world));
int index = 1;
for (Iterator<UnwovenClassFile.ChildClass> iter = childClasses.iterator(); iter.hasNext();) {
UnwovenClassFile.ChildClass element = iter.next();
UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
ret[index++] = childClass;
}
return ret;
}
/**
* Weaves new parents and annotations onto a type ("declare parents" and "declare @type")
*
* Algorithm: 1. First pass, do parents then do annotations. During this pass record: - any parent mungers that don't match but
* have a non-wild annotation type pattern - any annotation mungers that don't match 2. Multiple subsequent passes which go over
* the munger lists constructed in the first pass, repeatedly applying them until nothing changes. FIXME asc confirm that
* algorithm is optimal ??
*/
public void weaveParentTypeMungers(ResolvedType onType) {
if (onType.isRawType()) {
onType = onType.getGenericType();
}
onType.clearInterTypeMungers();
List<DeclareParents> decpToRepeat = new ArrayList<DeclareParents>();
boolean aParentChangeOccurred = false;
boolean anAnnotationChangeOccurred = false;
// First pass - apply all decp mungers
for (DeclareParents decp : declareParentsList) {
boolean typeChanged = applyDeclareParents(decp, onType);
if (typeChanged) {
aParentChangeOccurred = true;
} else {
decpToRepeat.add(decp);
}
}
// Still first pass - apply all dec @type mungers
for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) {
boolean typeChanged = applyDeclareAtType(decA, onType, true);
if (typeChanged) {
anAnnotationChangeOccurred = true;
}
}
while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
anAnnotationChangeOccurred = aParentChangeOccurred = false;
List<DeclareParents> decpToRepeatNextTime = new ArrayList<DeclareParents>();
for (Iterator<DeclareParents> iter = decpToRepeat.iterator(); iter.hasNext();) {
DeclareParents decp = iter.next();
boolean typeChanged = applyDeclareParents(decp, onType);
if (typeChanged) {
aParentChangeOccurred = true;
} else {
decpToRepeatNextTime.add(decp);
}
}
for (DeclareAnnotation decA : xcutSet.getDeclareAnnotationOnTypes()) {
boolean typeChanged = applyDeclareAtType(decA, onType, false);
if (typeChanged) {
anAnnotationChangeOccurred = true;
}
}
decpToRepeat = decpToRepeatNextTime;
}
}
/**
* Apply a declare @type - return true if we change the type
*/
private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) {
boolean didSomething = false;
if (decA.matches(onType)) {
AnnotationAJ theAnnotation = decA.getAnnotation();
// can be null for broken code!
if (theAnnotation == null) {
return false;
}
if (onType.hasAnnotation(theAnnotation.getType())) {
// Could put out a lint here for an already annotated type ...
// if (reportProblems) {
// world.getLint().elementAlreadyAnnotated.signal(
// new
// String[]{onType.toString(),decA.getAnnotationTypeX().toString
// ()},
// onType.getSourceLocation(),new
// ISourceLocation[]{decA.getSourceLocation()});
// }
return false;
}
AnnotationAJ annoX = decA.getAnnotation();
// check the annotation is suitable for the target
boolean problemReported = verifyTargetIsOK(decA, onType, annoX, reportProblems);
if (!problemReported) {
AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(), decA.getSourceLocation(),
onType.getSourceLocation(), false);
// TAG: WeavingMessage
if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
getWorld().getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(
WeaveMessage.WEAVEMESSAGE_ANNOTATES,
new String[] { onType.toString(), Utility.beautifyLocation(onType.getSourceLocation()),
decA.getAnnotationString(), "type", decA.getAspect().toString(),
Utility.beautifyLocation(decA.getSourceLocation()) }));
}
didSomething = true;
ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
newAnnotationTM.setSourceLocation(decA.getSourceLocation());
onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(world)), false);
decA.copyAnnotationTo(onType);
}
}
return didSomething;
}
/**
* Checks for an @target() on the annotation and if found ensures it allows the annotation to be attached to the target type
* that matched.
*/
private boolean verifyTargetIsOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ 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.getTypeName(), annoX.getValidTargets()),
decA.getSourceLocation()));
} else {
if (world.getLint().invalidTargetForAnnotation.isEnabled()) {
world.getLint().invalidTargetForAnnotation.signal(new String[] { onType.getName(), annoX.getTypeName(),
annoX.getValidTargets() }, decA.getSourceLocation(),
new ISourceLocation[] { onType.getSourceLocation() });
}
}
}
problemReported = true;
}
}
return problemReported;
}
/**
* Apply a single declare parents - return true if we change the type
*/
private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) {
boolean didSomething = false;
List<ResolvedType> newParents = p.findMatchingNewParents(onType, true);
if (!newParents.isEmpty()) {
didSomething = true;
BcelWorld.getBcelObjectType(onType);
// System.err.println("need to do declare parents for: " + onType);
for (ResolvedType newParent : newParents) {
// 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);
onType.addParent(newParent);
NewParentTypeMunger newParentMunger = new NewParentTypeMunger(newParent, p.getDeclaringType());
if (p.isMixin()) {
newParentMunger.setIsMixin(true);
}
newParentMunger.setSourceLocation(p.getSourceLocation());
onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)), false);
}
}
return didSomething;
}
public void weaveNormalTypeMungers(ResolvedType onType) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_TYPE_MUNGERS,
onType.getName());
if (onType.isRawType() || onType.isParameterizedType()) {
onType = onType.getGenericType();
}
for (ConcreteTypeMunger m : typeMungerList) {
if (!m.isLateMunger() && m.matches(onType)) {
onType.addInterTypeMunger(m, false);
}
}
CompilationAndWeavingContext.leavingPhase(tok);
}
// exposed for ClassLoader dynamic weaving
public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
return weave(classFile, classType, false);
}
// FOR TESTING
LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
LazyClassGen ret = weave(classFile, classType, true);
return ret;
}
private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
try {
if (classType.isSynthetic()) { // Don't touch synthetic classes
if (dump) {
dumpUnchanged(classFile);
}
return null;
}
ReferenceType resolvedClassType = classType.getResolvedTypeX();
if (world.isXmlConfigured() && world.getXmlConfiguration().excludesType(resolvedClassType)) {
if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
world.getMessageHandler().handleMessage(
MessageUtil.info("Type '" + resolvedClassType.getName()
+ "' not woven due to exclusion via XML weaver exclude section"));
}
if (dump) {
dumpUnchanged(classFile);
}
return null;
}
List<ShadowMunger> shadowMungers = fastMatch(shadowMungerList, resolvedClassType);
List<ConcreteTypeMunger> typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
resolvedClassType.checkInterTypeMungers();
// Decide if we need to do actual weaving for this class
boolean mightNeedToWeave = shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()
|| world.getDeclareAnnotationOnMethods().size() > 0 || world.getDeclareAnnotationOnFields().size() > 0;
// May need bridge methods if on 1.5 and something in our hierarchy is
// affected by ITDs
boolean mightNeedBridgeMethods = world.isInJava5Mode() && !classType.isInterface()
&& resolvedClassType.getInterTypeMungersIncludingSupers().size() > 0;
LazyClassGen clazz = null;
if (mightNeedToWeave || mightNeedBridgeMethods) {
clazz = classType.getLazyClassGen();
// System.err.println("got lazy gen: " + clazz + ", " +
// clazz.getWeaverState());
try {
boolean isChanged = false;
if (mightNeedToWeave) {
isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers, lateTypeMungerList,
inReweavableMode);
}
checkDeclareTypeErrorOrWarning(world, classType);
if (mightNeedBridgeMethods) {
isChanged = BcelClassWeaver.calculateAnyRequiredBridgeMethods(world, clazz) || isChanged;
}
if (isChanged) {
if (dump) {
dump(classFile, clazz);
}
return clazz;
}
} catch (RuntimeException re) {
String classDebugInfo = null;
try {
classDebugInfo = clazz.toLongString();
} catch (Throwable e) {
new RuntimeException("Crashed whilst crashing with this exception: " + e, e).printStackTrace();
// recover from crash whilst producing debug string
classDebugInfo = clazz.getClassName();
}
String messageText = "trouble in: \n" + classDebugInfo;
getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null));
} catch (Error re) {
String classDebugInfo = null;
try {
classDebugInfo = clazz.toLongString();
} catch (OutOfMemoryError oome) {
System.err.println("Ran out of memory creating debug info for an error");
re.printStackTrace(System.err);
// recover from crash whilst producing debug string
classDebugInfo = clazz.getClassName();
} catch (Throwable e) {
// recover from crash whilst producing debug string
classDebugInfo = clazz.getClassName();
}
String messageText = "trouble in: \n" + classDebugInfo;
getWorld().getMessageHandler().handleMessage(new Message(messageText, IMessage.ABORT, re, null));
}
} else {
checkDeclareTypeErrorOrWarning(world, classType);
}
// this is very odd return behavior trying to keep everyone happy
// can we remove it from the model now? we know it contains no relationship endpoints...
AsmManager model = world.getModelAsAsmManager();
if (world.isMinimalModel() && model != null && !classType.isAspect()) {
AspectJElementHierarchy hierarchy = (AspectJElementHierarchy) model.getHierarchy();
String pkgname = classType.getResolvedTypeX().getPackageName();
String tname = classType.getResolvedTypeX().getSimpleBaseName();
IProgramElement typeElement = hierarchy.findElementForType(pkgname, tname);
if (typeElement != null && hasInnerType(typeElement)) {
// Cannot remove it right now (has inner type), schedule it
// for possible deletion later if all inner types are
// removed
candidatesForRemoval.add(typeElement);
}
if (typeElement != null && !hasInnerType(typeElement)) {
IProgramElement parent = typeElement.getParent();
// parent may have children: PACKAGE DECL, IMPORT-REFERENCE, TYPE_DECL
if (parent != null) {
// if it was the only type we should probably remove
// the others too.
parent.removeChild(typeElement);
if (parent.getKind().isSourceFile()) {
removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeElement, parent);
} else {
hierarchy.forget(null, typeElement);
// At this point, the child has been removed. We
// should now check if the parent is in our
// 'candidatesForRemoval' set. If it is then that
// means we were going to remove it but it had a
// child. Now we can check if it still has a child -
// if it doesn't it can also be removed!
walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent);
}
}
}
}
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;
}
} finally {
world.demote();
}
}
private void walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(AspectJElementHierarchy hierarchy, String tname,
IProgramElement typeThatHasChildRemoved) {
// typeThatHasChildRemoved might be a source file, type or a method/ctor
// - for a method/ctor find the type/sourcefile
while (typeThatHasChildRemoved != null
&& !(typeThatHasChildRemoved.getKind().isType() || typeThatHasChildRemoved.getKind().isSourceFile())) {
// this will take us 'up' through methods that contain anonymous
// inner classes
typeThatHasChildRemoved = typeThatHasChildRemoved.getParent();
}
// now typeThatHasChildRemoved points to the type or sourcefile that has
// had something removed
if (candidatesForRemoval.contains(typeThatHasChildRemoved) && !hasInnerType(typeThatHasChildRemoved)) {
// now we can get rid of it
IProgramElement parent = typeThatHasChildRemoved.getParent();
if (parent != null) {
parent.removeChild(typeThatHasChildRemoved);
candidatesForRemoval.remove(typeThatHasChildRemoved);
if (parent.getKind().isSourceFile()) {
removeSourceFileIfNoMoreTypeDeclarationsInside(hierarchy, typeThatHasChildRemoved, parent);
// System.out.println("Removed on second pass: " +
// typeThatHasChildRemoved.getName());
} else {
// System.out.println("On later pass, parent of type " +
// typeThatHasChildRemoved.getName()
// + " was found not to be a sourcefile, recursing up...");
walkUpRemovingEmptyTypesAndPossiblyEmptySourceFile(hierarchy, tname, parent);
}
}
}
}
private void removeSourceFileIfNoMoreTypeDeclarationsInside(AspectJElementHierarchy hierarchy, IProgramElement typeElement,
IProgramElement sourceFileNode) {
IProgramElement compilationUnit = sourceFileNode;
boolean anyOtherTypeDeclarations = false;
for (IProgramElement child : compilationUnit.getChildren()) {
IProgramElement.Kind k = child.getKind();
if (k.isType()) {
anyOtherTypeDeclarations = true;
break;
}
}
// If the compilation unit node contained no
// other types, there is no need to keep it
if (!anyOtherTypeDeclarations) {
IProgramElement cuParent = compilationUnit.getParent();
if (cuParent != null) {
compilationUnit.setParent(null);
cuParent.removeChild(compilationUnit);
}
// need to update some caches and structures too?
hierarchy.forget(sourceFileNode, typeElement);
} else {
hierarchy.forget(null, typeElement);
}
}
// ---- writing
// TODO could be smarter - really only matters if inner type has been woven, but there is a chance we haven't woven it *yet*
private boolean hasInnerType(IProgramElement typeNode) {
for (IProgramElement child : typeNode.getChildren()) {
IProgramElement.Kind kind = child.getKind();
if (kind.isType()) {
return true;
}
// if (kind == IProgramElement.Kind.ASPECT) {
// return true;
// }
if (kind.isType() || kind == IProgramElement.Kind.METHOD || kind == IProgramElement.Kind.CONSTRUCTOR) {
boolean b = hasInnerType(child);
if (b) {
return b;
}
}
}
return false;
}
private void checkDeclareTypeErrorOrWarning(BcelWorld world2, BcelObjectType classType) {
List<DeclareTypeErrorOrWarning> dteows = world.getDeclareTypeEows();
for (DeclareTypeErrorOrWarning dteow : dteows) {
if (dteow.getTypePattern().matchesStatically(classType.getResolvedTypeX())) {
if (dteow.isError()) {
world.getMessageHandler().handleMessage(
MessageUtil.error(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation()));
} else {
world.getMessageHandler().handleMessage(
MessageUtil.warn(dteow.getMessage(), classType.getResolvedTypeX().getSourceLocation()));
}
}
}
}
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());
List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
if (!childClasses.isEmpty()) {
for (Iterator<UnwovenClassFile.ChildClass> i = childClasses.iterator(); i.hasNext();) {
UnwovenClassFile.ChildClass c = 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();
}
/**
* Perform a fast match of the specified list of shadowmungers against the specified type. A subset of those that might match is
* returned.
*
* @param list list of all shadow mungers that might match
* @param type the target type
* @return a list of shadow mungers that might match with those that cannot (according to fast match rules) removed
*/
private List<ShadowMunger> fastMatch(List<ShadowMunger> list, ResolvedType type) {
if (list == null) {
return Collections.emptyList();
}
boolean isOverweaving = world.isOverWeaving();
WeaverStateInfo typeWeaverState = (isOverweaving ? type.getWeaverState() : null);
// 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, world);
List<ShadowMunger> result = new ArrayList<ShadowMunger>();
if (world.areInfoMessagesEnabled() && world.isTimingEnabled()) {
for (ShadowMunger munger : list) {
if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate
ResolvedType declaringAspect = munger.getDeclaringType();
if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) {
continue;
}
}
Pointcut pointcut = munger.getPointcut();
long starttime = System.nanoTime();
FuzzyBoolean fb = pointcut.fastMatch(info);
long endtime = System.nanoTime();
world.recordFastMatch(pointcut, endtime - starttime);
if (fb.maybeTrue()) {
result.add(munger);
}
}
} else {
for (ShadowMunger munger : list) {
if (typeWeaverState != null) { // will only be null if overweaving is ON and there is weaverstate
ResolvedType declaringAspect = munger.getConcreteAspect();// getDeclaringType();
if (typeWeaverState.isAspectAlreadyApplied(declaringAspect)) {
continue;
}
}
Pointcut pointcut = munger.getPointcut();
FuzzyBoolean fb = pointcut.fastMatch(info);
if (fb.maybeTrue()) {
result.add(munger);
}
}
}
return result;
}
public void setReweavableMode(boolean xNotReweavable) {
inReweavableMode = !xNotReweavable;
WeaverStateInfo.setReweavableModeDefaults(!xNotReweavable, false, true);
}
public boolean isReweavable() {
return inReweavableMode;
}
public World getWorld() {
return world;
}
public void tidyUp() {
if (trace.isTraceEnabled()) {
trace.enter("tidyUp", this);
}
shadowMungerList = null; // setup by prepareForWeave
typeMungerList = null; // setup by prepareForWeave
lateTypeMungerList = null; // setup by prepareForWeave
declareParentsList = null; // setup by prepareForWeave
if (trace.isTraceEnabled()) {
trace.exit("tidyUp");
}
}
public void write(CompressingDataOutputStream dos) throws IOException {
xcutSet.write(dos);
}
// only called for testing
public void setShadowMungers(List<ShadowMunger> shadowMungers) {
shadowMungerList = shadowMungers;
}
}
|
408,721 | Bug 408721 java.util.ConcurrentModificationException when multiple threads enter the weaver | I am using AspectJ 1.7.1. Occasionally I see the following exception, which I believe is related to multiple threads initializing some internal state. java.util.ConcurrentModificationException: null at java.util.ArrayList$Itr.checkForComodification(Unknown Source) ~[na:1.7.0_11] at java.util.ArrayList$Itr.next(Unknown Source) ~[na:1.7.0_11] at org.aspectj.weaver.ReferenceType.findDerivativeType(ReferenceType.java:1122) ~[aspectjweaver.jar:1.7.1] at org.aspectj.weaver.TypeFactory.createParameterizedType(TypeFactory.java:44) ~[aspectjweaver.jar:1.7.1] at org.aspectj.weaver.ResolvedType.parameterize(ResolvedType.java:2479) ~[aspectjweaver.jar:1.7.1] at org.aspectj.weaver.ReferenceType.getDeclaredInterfaces(ReferenceType.java:673) ~[aspectjweaver.jar:1.7.1] at org.aspectj.weaver.ResolvedType.getDirectSupertypes(ResolvedType.java:82) ~[aspectjweaver.jar:1.7.1] at org.aspectj.weaver.patterns.TypePattern.matchesSubtypes(TypePattern.java:178) ~[aspectjweaver.jar:1.7.1] at org.aspectj.weaver.patterns.ExactTypePattern.matchesSubtypes(ExactTypePattern.java:74) ~[aspectjweaver.jar:1.7.1] at org.aspectj.weaver.patterns.TypePattern.matchesStatically(TypePattern.java:130) ~[aspectjweaver.jar:1.7.1] at org.aspectj.weaver.patterns.KindedPointcut.fastMatch(KindedPointcut.java:130) ~[aspectjweaver.jar:1.7.1] at org.aspectj.weaver.internal.tools.PointcutExpressionImpl.couldMatchJoinPointsInType(PointcutExpressionImpl.java:84) ~[aspectjweaver.jar:1.7.1] at org.springframework.aop.aspectj.AspectJExpressionPointcut.matches(AspectJExpressionPointcut.java:250) ~[spring-aop.jar:3.2.1.RELEASE] at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:208) ~[spring-aop.jar:3.2.1.RELEASE] at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:262) ~[spring-aop.jar:3.2.1.RELEASE] at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:294) ~[spring-aop.jar:3.2.1.RELEASE] at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:118) ~[spring-aop.jar:3.2.1.RELEASE] | resolved fixed | 3f6e166 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-06-26T22:08:06Z" | "2013-05-22T16:26:40Z" | org.aspectj.matcher/src/org/aspectj/weaver/ReferenceType.java | /* *******************************************************************
* Copyright (c) 2002 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* Andy Clement - June 2005 - separated out from ResolvedType
* ******************************************************************/
package org.aspectj.weaver;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.World.TypeMap;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.PerClause;
/**
* A reference type represents some 'real' type, not a primitive, not an array - but a real type, for example java.util.List. Each
* ReferenceType has a delegate that is the underlying artifact - either an eclipse artifact or a bcel artifact. If the type
* represents a raw type (i.e. there is a generic form) then the genericType field is set to point to the generic type. If it is for
* a parameterized type then the generic type is also set to point to the generic form.
*/
public class ReferenceType extends ResolvedType {
public static final ReferenceType[] EMPTY_ARRAY = new ReferenceType[0];
/**
* For generic types, this list holds references to all the derived raw and parameterized versions. We need this so that if the
* generic delegate is swapped during incremental compilation, the delegate of the derivatives is swapped also.
*/
private final List<WeakReference<ReferenceType>> derivativeTypes = new ArrayList<WeakReference<ReferenceType>>();
/**
* For parameterized types (or the raw type) - this field points to the actual reference type from which they are derived.
*/
ReferenceType genericType = null;
ReferenceType rawType = null; // generic types have a pointer back to their raw variant (prevents GC of the raw from the typemap!)
ReferenceTypeDelegate delegate = null;
int startPos = 0;
int endPos = 0;
// cached values for members
ResolvedMember[] parameterizedMethods = null;
ResolvedMember[] parameterizedFields = null;
ResolvedMember[] parameterizedPointcuts = null;
WeakReference<ResolvedType[]> parameterizedInterfaces = new WeakReference<ResolvedType[]>(null);
Collection<Declare> parameterizedDeclares = null;
// Collection parameterizedTypeMungers = null;
// During matching it can be necessary to temporary mark types as annotated. For example
// a declare @type may trigger a separate declare parents to match, and so the annotation
// is temporarily held against the referencetype, the annotation will be properly
// added to the class during weaving.
private ResolvedType[] annotationTypes = null;
private AnnotationAJ[] annotations = null;
// Similarly these are temporary replacements and additions for the superclass and
// superinterfaces
private ResolvedType newSuperclass;
private ResolvedType[] newInterfaces;
public ReferenceType(String signature, World world) {
super(signature, world);
}
public ReferenceType(String signature, String signatureErasure, World world) {
super(signature, signatureErasure, world);
}
public static ReferenceType fromTypeX(UnresolvedType tx, World world) {
ReferenceType rt = new ReferenceType(tx.getErasureSignature(), world);
rt.typeKind = tx.typeKind;
return rt;
}
/**
* Constructor used when creating a parameterized type.
*/
public ReferenceType(ResolvedType theGenericType, ResolvedType[] theParameters, World aWorld) {
super(makeParameterizedSignature(theGenericType, theParameters), theGenericType.signatureErasure, aWorld);
ReferenceType genericReferenceType = (ReferenceType) theGenericType;
this.typeParameters = theParameters;
this.genericType = genericReferenceType;
this.typeKind = TypeKind.PARAMETERIZED;
this.delegate = genericReferenceType.getDelegate();
genericReferenceType.addDependentType(this);
}
synchronized void addDependentType(ReferenceType dependent) {
// checkDuplicates(dependent);
this.derivativeTypes.add(new WeakReference<ReferenceType>(dependent));
}
public void checkDuplicates(ReferenceType newRt) {
List<WeakReference<ReferenceType>> forRemoval = new ArrayList<WeakReference<ReferenceType>>();
for (WeakReference<ReferenceType> derivativeTypeReference: derivativeTypes) {
ReferenceType derivativeType = derivativeTypeReference.get();
if (derivativeType==null) {
forRemoval.add(derivativeTypeReference);
} else {
if (derivativeType.getTypekind()!=newRt.getTypekind()) {
continue; // cannot be this one
}
if (equal2(newRt.getTypeParameters(),derivativeType.getTypeParameters())) {
if (TypeMap.useExpendableMap) {
throw new IllegalStateException();
}
}
}
}
derivativeTypes.removeAll(forRemoval);
}
private boolean equal2(UnresolvedType[] typeParameters, UnresolvedType[] resolvedParameters) {
if (typeParameters.length!=resolvedParameters.length) {
return false;
}
int len = typeParameters.length;
for (int p=0;p<len;p++) {
if (!typeParameters[p].equals(resolvedParameters[p])) {
return false;
}
}
return true;
}
@Override
public String getSignatureForAttribute() {
if (genericType == null || typeParameters == null) {
return getSignature();
}
return makeDeclaredSignature(genericType, typeParameters);
}
/**
* Create a reference type for a generic type
*/
public ReferenceType(UnresolvedType genericType, World world) {
super(genericType.getSignature(), world);
typeKind = TypeKind.GENERIC;
this.typeVariables=genericType.typeVariables;
}
@Override
public boolean isClass() {
return getDelegate().isClass();
}
@Override
public int getCompilerVersion() {
return getDelegate().getCompilerVersion();
}
@Override
public boolean isGenericType() {
return !isParameterizedType() && !isRawType() && getDelegate().isGeneric();
}
public String getGenericSignature() {
String sig = getDelegate().getDeclaredGenericSignature();
return (sig == null) ? "" : sig;
}
@Override
public AnnotationAJ[] getAnnotations() {
return getDelegate().getAnnotations();
}
@Override
public void addAnnotation(AnnotationAJ annotationX) {
if (annotations == null) {
annotations = new AnnotationAJ[]{annotationX};
} else {
AnnotationAJ[] newAnnotations = new AnnotationAJ[annotations.length + 1];
System.arraycopy(annotations, 0, newAnnotations, 1, annotations.length);
newAnnotations[0] = annotationX;
annotations = newAnnotations;
}
addAnnotationType(annotationX.getType());
}
public boolean hasAnnotation(UnresolvedType ofType) {
boolean onDelegate = getDelegate().hasAnnotation(ofType);
if (onDelegate) {
return true;
}
if (annotationTypes != null) {
for (int i = 0; i < annotationTypes.length; i++) {
if (annotationTypes[i].equals(ofType)) {
return true;
}
}
}
return false;
}
private void addAnnotationType(ResolvedType ofType) {
if (annotationTypes == null) {
annotationTypes = new ResolvedType[1];
annotationTypes[0] = ofType;
} else {
ResolvedType[] newAnnotationTypes = new ResolvedType[annotationTypes.length + 1];
System.arraycopy(annotationTypes, 0, newAnnotationTypes, 1, annotationTypes.length);
newAnnotationTypes[0] = ofType;
annotationTypes = newAnnotationTypes;
}
}
@Override
public ResolvedType[] getAnnotationTypes() {
if (getDelegate() == null) {
throw new BCException("Unexpected null delegate for type " + this.getName());
}
if (annotationTypes == null) {
// there are no extras:
return getDelegate().getAnnotationTypes();
} else {
ResolvedType[] delegateAnnotationTypes = getDelegate().getAnnotationTypes();
ResolvedType[] result = new ResolvedType[annotationTypes.length + delegateAnnotationTypes.length];
System.arraycopy(delegateAnnotationTypes, 0, result, 0, delegateAnnotationTypes.length);
System.arraycopy(annotationTypes, 0, result, delegateAnnotationTypes.length, annotationTypes.length);
return result;
}
}
@Override
public String getNameAsIdentifier() {
return getRawName().replace('.', '_');
}
@Override
public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) {
AnnotationAJ[] axs = getDelegate().getAnnotations();
if (axs != null) {
for (int i = 0; i < axs.length; i++) {
if (axs[i].getTypeSignature().equals(ofType.getSignature())) {
return axs[i];
}
}
}
if (annotations != null) {
String searchSig = ofType.getSignature();
for (int i = 0; i < annotations.length; i++) {
if (annotations[i].getTypeSignature().equals(searchSig)) {
return annotations[i];
}
}
}
return null;
}
@Override
public boolean isAspect() {
return getDelegate().isAspect();
}
@Override
public boolean isAnnotationStyleAspect() {
return getDelegate().isAnnotationStyleAspect();
}
@Override
public boolean isEnum() {
return getDelegate().isEnum();
}
@Override
public boolean isAnnotation() {
return getDelegate().isAnnotation();
}
@Override
public boolean isAnonymous() {
return getDelegate().isAnonymous();
}
@Override
public boolean isNested() {
return getDelegate().isNested();
}
public ResolvedType getOuterClass() {
return getDelegate().getOuterClass();
}
public String getRetentionPolicy() {
return getDelegate().getRetentionPolicy();
}
@Override
public boolean isAnnotationWithRuntimeRetention() {
return getDelegate().isAnnotationWithRuntimeRetention();
}
@Override
public boolean canAnnotationTargetType() {
return getDelegate().canAnnotationTargetType();
}
@Override
public AnnotationTargetKind[] getAnnotationTargetKinds() {
return getDelegate().getAnnotationTargetKinds();
}
// true iff the statement "this = (ThisType) other" would compile
@Override
public boolean isCoerceableFrom(ResolvedType o) {
ResolvedType other = o.resolve(world);
if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) {
return true;
}
if (this.isParameterizedType() && other.isParameterizedType()) {
return isCoerceableFromParameterizedType(other);
}
if (this.isParameterizedType() && other.isRawType()) {
return ((ReferenceType) this.getRawType()).isCoerceableFrom(other.getGenericType());
}
if (this.isRawType() && other.isParameterizedType()) {
return this.getGenericType().isCoerceableFrom((other.getRawType()));
}
if (!this.isInterface() && !other.isInterface()) {
return false;
}
if (this.isFinal() || other.isFinal()) {
return false;
}
// ??? needs to be Methods, not just declared methods? JLS 5.5 unclear
ResolvedMember[] a = getDeclaredMethods();
ResolvedMember[] b = other.getDeclaredMethods(); // ??? is this cast
// always safe
for (int ai = 0, alen = a.length; ai < alen; ai++) {
for (int bi = 0, blen = b.length; bi < blen; bi++) {
if (!b[bi].isCompatibleWith(a[ai])) {
return false;
}
}
}
return true;
}
private final boolean isCoerceableFromParameterizedType(ResolvedType other) {
if (!other.isParameterizedType()) {
return false;
}
ResolvedType myRawType = getRawType();
ResolvedType theirRawType = other.getRawType();
if (myRawType == theirRawType || myRawType.isCoerceableFrom(theirRawType)) {
if (getTypeParameters().length == other.getTypeParameters().length) {
// there's a chance it can be done
ResolvedType[] myTypeParameters = getResolvedTypeParameters();
ResolvedType[] theirTypeParameters = other.getResolvedTypeParameters();
for (int i = 0; i < myTypeParameters.length; i++) {
if (myTypeParameters[i] != theirTypeParameters[i]) {
// thin ice now... but List<String> may still be
// coerceable from e.g. List<T>
if (myTypeParameters[i].isGenericWildcard()) {
BoundedReferenceType wildcard = (BoundedReferenceType) myTypeParameters[i];
if (!wildcard.canBeCoercedTo(theirTypeParameters[i])) {
return false;
}
} else if (myTypeParameters[i].isTypeVariableReference()) {
TypeVariableReferenceType tvrt = (TypeVariableReferenceType) myTypeParameters[i];
TypeVariable tv = tvrt.getTypeVariable();
tv.resolve(world);
if (!tv.canBeBoundTo(theirTypeParameters[i])) {
return false;
}
} else if (theirTypeParameters[i].isTypeVariableReference()) {
TypeVariableReferenceType tvrt = (TypeVariableReferenceType) theirTypeParameters[i];
TypeVariable tv = tvrt.getTypeVariable();
tv.resolve(world);
if (!tv.canBeBoundTo(myTypeParameters[i])) {
return false;
}
} else if (theirTypeParameters[i].isGenericWildcard()) {
BoundedReferenceType wildcard = (BoundedReferenceType) theirTypeParameters[i];
if (!wildcard.canBeCoercedTo(myTypeParameters[i])) {
return false;
}
} else {
return false;
}
}
}
return true;
}
// } else {
// // we do this walk for situations like the following:
// // Base<T>, Sub<S,T> extends Base<S>
// // is Sub<Y,Z> coerceable from Base<X> ???
// for (Iterator i = getDirectSupertypes(); i.hasNext();) {
// ReferenceType parent = (ReferenceType) i.next();
// if (parent.isCoerceableFromParameterizedType(other))
// return true;
// }
}
return false;
}
@Override
public boolean isAssignableFrom(ResolvedType other) {
return isAssignableFrom(other, false);
}
// TODO rewrite this method - it is a terrible mess
// true iff the statement "this = other" would compile.
@Override
public boolean isAssignableFrom(ResolvedType other, boolean allowMissing) {
if (other.isPrimitiveType()) {
if (!world.isInJava5Mode()) {
return false;
}
if (ResolvedType.validBoxing.contains(this.getSignature() + other.getSignature())) {
return true;
}
}
if (this == other) {
return true;
}
if (this.getSignature().equals("Ljava/lang/Object;")) {
return true;
}
if (!isTypeVariableReference() && other.getSignature().equals("Ljava/lang/Object;")) {
return false;
}
boolean thisRaw = this.isRawType();
if (thisRaw && other.isParameterizedOrGenericType()) {
return isAssignableFrom(other.getRawType());
}
boolean thisGeneric = this.isGenericType();
if (thisGeneric && other.isParameterizedOrRawType()) {
return isAssignableFrom(other.getGenericType());
}
if (this.isParameterizedType()) {
// look at wildcards...
if (((ReferenceType) this.getRawType()).isAssignableFrom(other)) {
boolean wildcardsAllTheWay = true;
ResolvedType[] myParameters = this.getResolvedTypeParameters();
for (int i = 0; i < myParameters.length; i++) {
if (!myParameters[i].isGenericWildcard()) {
wildcardsAllTheWay = false;
} else {
BoundedReferenceType boundedRT = (BoundedReferenceType) myParameters[i];
if (boundedRT.isExtends() || boundedRT.isSuper()) {
wildcardsAllTheWay = false;
}
}
}
if (wildcardsAllTheWay && !other.isParameterizedType()) {
return true;
}
// we have to match by parameters one at a time
ResolvedType[] theirParameters = other.getResolvedTypeParameters();
boolean parametersAssignable = true;
if (myParameters.length == theirParameters.length) {
for (int i = 0; i < myParameters.length && parametersAssignable; i++) {
if (myParameters[i] == theirParameters[i]) {
continue;
}
// dont do this: pr253109
// if (myParameters[i].isAssignableFrom(theirParameters[i], allowMissing)) {
// continue;
// }
ResolvedType mp = myParameters[i];
ResolvedType tp = theirParameters[i];
if (mp.isParameterizedType() && tp.isParameterizedType()) {
if (mp.getGenericType().equals(tp.getGenericType())) {
UnresolvedType[] mtps = mp.getTypeParameters();
UnresolvedType[] ttps = tp.getTypeParameters();
for (int ii = 0; ii < mtps.length; ii++) {
if (mtps[ii].isTypeVariableReference() && ttps[ii].isTypeVariableReference()) {
TypeVariable mtv = ((TypeVariableReferenceType) mtps[ii]).getTypeVariable();
boolean b = mtv.canBeBoundTo((ResolvedType) ttps[ii]);
if (!b) {// TODO incomplete testing here I think
parametersAssignable = false;
break;
}
} else {
parametersAssignable = false;
break;
}
}
continue;
} else {
parametersAssignable = false;
break;
}
}
if (myParameters[i].isTypeVariableReference() && theirParameters[i].isTypeVariableReference()) {
TypeVariable myTV = ((TypeVariableReferenceType) myParameters[i]).getTypeVariable();
// TypeVariable theirTV = ((TypeVariableReferenceType) theirParameters[i]).getTypeVariable();
boolean b = myTV.canBeBoundTo(theirParameters[i]);
if (!b) {// TODO incomplete testing here I think
parametersAssignable = false;
break;
} else {
continue;
}
}
if (!myParameters[i].isGenericWildcard()) {
parametersAssignable = false;
break;
} else {
BoundedReferenceType wildcardType = (BoundedReferenceType) myParameters[i];
if (!wildcardType.alwaysMatches(theirParameters[i])) {
parametersAssignable = false;
break;
}
}
}
} else {
parametersAssignable = false;
}
if (parametersAssignable) {
return true;
}
}
}
// eg this=T other=Ljava/lang/Object;
if (isTypeVariableReference() && !other.isTypeVariableReference()) {
TypeVariable aVar = ((TypeVariableReference) this).getTypeVariable();
return aVar.resolve(world).canBeBoundTo(other);
}
if (other.isTypeVariableReference()) {
TypeVariableReferenceType otherType = (TypeVariableReferenceType) other;
if (this instanceof TypeVariableReference) {
return ((TypeVariableReference) this).getTypeVariable().resolve(world)
.canBeBoundTo(otherType.getTypeVariable().getFirstBound().resolve(world));// pr171952
// return
// ((TypeVariableReference)this).getTypeVariable()==otherType
// .getTypeVariable();
} else {
// FIXME asc should this say canBeBoundTo??
return this.isAssignableFrom(otherType.getTypeVariable().getFirstBound().resolve(world));
}
}
if (allowMissing && other.isMissing()) {
return false;
}
ResolvedType[] interfaces = other.getDeclaredInterfaces();
for (ResolvedType intface : interfaces) {
boolean b;
if (thisRaw && intface.isParameterizedOrGenericType()) {
b = this.isAssignableFrom(intface.getRawType(), allowMissing);
} else {
b = this.isAssignableFrom(intface, allowMissing);
}
if (b) {
return true;
}
}
ResolvedType superclass = other.getSuperclass();
if (superclass != null) {
boolean b;
if (thisRaw && superclass.isParameterizedOrGenericType()) {
b = this.isAssignableFrom(superclass.getRawType(), allowMissing);
} else {
b = this.isAssignableFrom(superclass, allowMissing);
}
if (b) {
return true;
}
}
return false;
}
@Override
public ISourceContext getSourceContext() {
return getDelegate().getSourceContext();
}
@Override
public ISourceLocation getSourceLocation() {
ISourceContext isc = getDelegate().getSourceContext();
return isc.makeSourceLocation(new Position(startPos, endPos));
}
@Override
public boolean isExposedToWeaver() {
return (getDelegate() == null) || delegate.isExposedToWeaver();
}
@Override
public WeaverStateInfo getWeaverState() {
return getDelegate().getWeaverState();
}
@Override
public ResolvedMember[] getDeclaredFields() {
if (parameterizedFields != null) {
return parameterizedFields;
}
if (isParameterizedType() || isRawType()) {
ResolvedMember[] delegateFields = getDelegate().getDeclaredFields();
parameterizedFields = new ResolvedMember[delegateFields.length];
for (int i = 0; i < delegateFields.length; i++) {
parameterizedFields[i] = delegateFields[i].parameterizedWith(getTypesForMemberParameterization(), this,
isParameterizedType());
}
return parameterizedFields;
} else {
return getDelegate().getDeclaredFields();
}
}
/**
* Find out from the generic signature the true signature of any interfaces I implement. If I am parameterized, these may then
* need to be parameterized before returning.
*/
@Override
public ResolvedType[] getDeclaredInterfaces() {
ResolvedType[] interfaces = parameterizedInterfaces.get();
if (interfaces != null) {
return interfaces;
}
ResolvedType[] delegateInterfaces = getDelegate().getDeclaredInterfaces();
if (isRawType()) {
if (newInterfaces != null) {// debug 375777
throw new IllegalStateException(
"The raw type should never be accumulating new interfaces, they should be on the generic type. Type is "
+ this.getName());
}
ResolvedType[] newInterfacesFromGenericType = genericType.newInterfaces;
if (newInterfacesFromGenericType != null) {
ResolvedType[] extraInterfaces = new ResolvedType[delegateInterfaces.length + newInterfacesFromGenericType.length];
System.arraycopy(delegateInterfaces, 0, extraInterfaces, 0, delegateInterfaces.length);
System.arraycopy(newInterfacesFromGenericType, 0, extraInterfaces, delegateInterfaces.length,
newInterfacesFromGenericType.length);
delegateInterfaces = extraInterfaces;
}
} else if (newInterfaces != null) {
// OPTIMIZE does this part of the method trigger often?
ResolvedType[] extraInterfaces = new ResolvedType[delegateInterfaces.length + newInterfaces.length];
System.arraycopy(delegateInterfaces, 0, extraInterfaces, 0, delegateInterfaces.length);
System.arraycopy(newInterfaces, 0, extraInterfaces, delegateInterfaces.length, newInterfaces.length);
delegateInterfaces = extraInterfaces;
}
if (isParameterizedType()) {
// UnresolvedType[] paramTypes =
// getTypesForMemberParameterization();
interfaces = new ResolvedType[delegateInterfaces.length];
for (int i = 0; i < delegateInterfaces.length; i++) {
// We may have to sub/super set the set of parametertypes if the
// implemented interface
// needs more or less than this type does. (pr124803/pr125080)
if (delegateInterfaces[i].isParameterizedType()) {
interfaces[i] = delegateInterfaces[i].parameterize(getMemberParameterizationMap()).resolve(world);
} else {
interfaces[i] = delegateInterfaces[i];
}
}
parameterizedInterfaces = new WeakReference<ResolvedType[]>(interfaces);
return interfaces;
} else if (isRawType()) {
UnresolvedType[] paramTypes = getTypesForMemberParameterization();
interfaces = new ResolvedType[delegateInterfaces.length];
for (int i = 0, max = interfaces.length; i < max; i++) {
interfaces[i] = delegateInterfaces[i];
if (interfaces[i].isGenericType()) {
// a generic supertype of a raw type is replaced by its raw
// equivalent
interfaces[i] = interfaces[i].getRawType().resolve(getWorld());
} else if (interfaces[i].isParameterizedType()) {
// a parameterized supertype collapses any type vars to
// their upper bounds
UnresolvedType[] toUseForParameterization = determineThoseTypesToUse(interfaces[i], paramTypes);
interfaces[i] = interfaces[i].parameterizedWith(toUseForParameterization);
}
}
parameterizedInterfaces = new WeakReference<ResolvedType[]>(interfaces);
return interfaces;
}
if (getDelegate().isCacheable()) {
parameterizedInterfaces = new WeakReference<ResolvedType[]>(delegateInterfaces);
}
return delegateInterfaces;
}
/**
* It is possible this type has multiple type variables but the interface we are about to parameterize only uses a subset - this
* method determines the subset to use by looking at the type variable names used. For example: <code>
* class Foo<T extends String,E extends Number> implements SuperInterface<T> {}
* </code> where <code>
* interface SuperInterface<Z> {}
* </code> In that example, a use of the 'Foo' raw type should know that it implements the SuperInterface<String>.
*/
private UnresolvedType[] determineThoseTypesToUse(ResolvedType parameterizedInterface, UnresolvedType[] paramTypes) {
// What are the type parameters for the supertype?
UnresolvedType[] tParms = parameterizedInterface.getTypeParameters();
UnresolvedType[] retVal = new UnresolvedType[tParms.length];
// Go through the supertypes type parameters, if any of them is a type
// variable, use the
// real type variable on the declaring type.
// it is possibly overkill to look up the type variable - ideally the
// entry in the type parameter list for the
// interface should be the a ref to the type variable in the current
// type ... but I'm not 100% confident right now.
for (int i = 0; i < tParms.length; i++) {
UnresolvedType tParm = tParms[i];
if (tParm.isTypeVariableReference()) {
TypeVariableReference tvrt = (TypeVariableReference) tParm;
TypeVariable tv = tvrt.getTypeVariable();
int rank = getRank(tv.getName());
// -1 probably means it is a reference to a type variable on the
// outer generic type (see pr129566)
if (rank != -1) {
retVal[i] = paramTypes[rank];
} else {
retVal[i] = tParms[i];
}
} else {
retVal[i] = tParms[i];
}
}
return retVal;
}
/**
* Returns the position within the set of type variables for this type for the specified type variable name. Returns -1 if there
* is no type variable with the specified name.
*/
private int getRank(String tvname) {
TypeVariable[] thisTypesTVars = getGenericType().getTypeVariables();
for (int i = 0; i < thisTypesTVars.length; i++) {
TypeVariable tv = thisTypesTVars[i];
if (tv.getName().equals(tvname)) {
return i;
}
}
return -1;
}
@Override
public ResolvedMember[] getDeclaredMethods() {
if (parameterizedMethods != null) {
return parameterizedMethods;
}
if (isParameterizedType() || isRawType()) {
ResolvedMember[] delegateMethods = getDelegate().getDeclaredMethods();
UnresolvedType[] parameters = getTypesForMemberParameterization();
parameterizedMethods = new ResolvedMember[delegateMethods.length];
for (int i = 0; i < delegateMethods.length; i++) {
parameterizedMethods[i] = delegateMethods[i].parameterizedWith(parameters, this, isParameterizedType());
}
return parameterizedMethods;
} else {
return getDelegate().getDeclaredMethods();
}
}
@Override
public ResolvedMember[] getDeclaredPointcuts() {
if (parameterizedPointcuts != null) {
return parameterizedPointcuts;
}
if (isParameterizedType()) {
ResolvedMember[] delegatePointcuts = getDelegate().getDeclaredPointcuts();
parameterizedPointcuts = new ResolvedMember[delegatePointcuts.length];
for (int i = 0; i < delegatePointcuts.length; i++) {
parameterizedPointcuts[i] = delegatePointcuts[i].parameterizedWith(getTypesForMemberParameterization(), this,
isParameterizedType());
}
return parameterizedPointcuts;
} else {
return getDelegate().getDeclaredPointcuts();
}
}
private UnresolvedType[] getTypesForMemberParameterization() {
UnresolvedType[] parameters = null;
if (isParameterizedType()) {
parameters = getTypeParameters();
} else if (isRawType()) {
// raw type, use upper bounds of type variables on generic type
TypeVariable[] tvs = getGenericType().getTypeVariables();
parameters = new UnresolvedType[tvs.length];
for (int i = 0; i < tvs.length; i++) {
parameters[i] = tvs[i].getFirstBound();
}
}
return parameters;
}
@Override
public TypeVariable[] getTypeVariables() {
if (typeVariables == null) {
typeVariables = getDelegate().getTypeVariables();
for (int i = 0; i < this.typeVariables.length; i++) {
typeVariables[i].resolve(world);
}
}
return typeVariables;
}
@Override
public PerClause getPerClause() {
PerClause pclause = getDelegate().getPerClause();
if (pclause != null && isParameterizedType()) { // could cache the result here...
Map<String, UnresolvedType> parameterizationMap = getAjMemberParameterizationMap();
pclause = (PerClause) pclause.parameterizeWith(parameterizationMap, world);
}
return pclause;
}
@Override
public Collection<Declare> getDeclares() {
if (parameterizedDeclares != null) {
return parameterizedDeclares;
}
Collection<Declare> declares = null;
if (ajMembersNeedParameterization()) {
Collection<Declare> genericDeclares = getDelegate().getDeclares();
parameterizedDeclares = new ArrayList<Declare>();
Map<String, UnresolvedType> parameterizationMap = getAjMemberParameterizationMap();
for (Declare declareStatement : genericDeclares) {
parameterizedDeclares.add(declareStatement.parameterizeWith(parameterizationMap, world));
}
declares = parameterizedDeclares;
} else {
declares = getDelegate().getDeclares();
}
for (Declare d : declares) {
d.setDeclaringType(this);
}
return declares;
}
@Override
public Collection<ConcreteTypeMunger> getTypeMungers() {
return getDelegate().getTypeMungers();
}
@Override
public Collection<ResolvedMember> getPrivilegedAccesses() {
return getDelegate().getPrivilegedAccesses();
}
@Override
public int getModifiers() {
return getDelegate().getModifiers();
}
WeakReference<ResolvedType> superclassReference = new WeakReference<ResolvedType>(null);
@Override
public ResolvedType getSuperclass() {
ResolvedType ret = null;// superclassReference.get();
// if (ret != null) {
// return ret;
// }
if (newSuperclass != null) {
if (this.isParameterizedType() && newSuperclass.isParameterizedType()) {
return newSuperclass.parameterize(getMemberParameterizationMap()).resolve(getWorld());
}
if (getDelegate().isCacheable()) {
superclassReference = new WeakReference<ResolvedType>(ret);
}
return newSuperclass;
}
try {
world.setTypeVariableLookupScope(this);
ret = getDelegate().getSuperclass();
} finally {
world.setTypeVariableLookupScope(null);
}
if (this.isParameterizedType() && ret.isParameterizedType()) {
ret = ret.parameterize(getMemberParameterizationMap()).resolve(getWorld());
}
if (getDelegate().isCacheable()) {
superclassReference = new WeakReference<ResolvedType>(ret);
}
return ret;
}
public ReferenceTypeDelegate getDelegate() {
return delegate;
}
public void setDelegate(ReferenceTypeDelegate delegate) {
// Don't copy from BcelObjectType to EclipseSourceType - the context may
// be tidied (result null'd) after previous weaving
if (this.delegate != null && this.delegate.copySourceContext()
&& this.delegate.getSourceContext() != SourceContextImpl.UNKNOWN_SOURCE_CONTEXT) {
((AbstractReferenceTypeDelegate) delegate).setSourceContext(this.delegate.getSourceContext());
}
this.delegate = delegate;
List<WeakReference<ReferenceType>> forRemoval = new ArrayList<WeakReference<ReferenceType>>();
for (WeakReference<ReferenceType> derivativeRef : derivativeTypes) {
ReferenceType derivative = derivativeRef.get();
if (derivative!=null) {
derivative.setDelegate(delegate);
} else {
forRemoval.add(derivativeRef);
}
}
derivativeTypes.removeAll(forRemoval);
// If we are raw, we have a generic type - we should ensure it uses the
// same delegate
if (isRawType() && getGenericType() != null) {
ReferenceType genType = (ReferenceType) getGenericType();
if (genType.getDelegate() != delegate) { // avoids circular updates
genType.setDelegate(delegate);
}
}
clearParameterizationCaches();
ensureConsistent();
}
private void clearParameterizationCaches() {
parameterizedFields = null;
parameterizedInterfaces.clear();
parameterizedMethods = null;
parameterizedPointcuts = null;
superclassReference = new WeakReference<ResolvedType>(null);
}
public int getEndPos() {
return endPos;
}
public int getStartPos() {
return startPos;
}
public void setEndPos(int endPos) {
this.endPos = endPos;
}
public void setStartPos(int startPos) {
this.startPos = startPos;
}
@Override
public boolean doesNotExposeShadowMungers() {
return getDelegate().doesNotExposeShadowMungers();
}
public String getDeclaredGenericSignature() {
return getDelegate().getDeclaredGenericSignature();
}
public void setGenericType(ReferenceType rt) {
genericType = rt;
// Should we 'promote' this reference type from simple to raw?
// makes sense if someone is specifying that it has a generic form
if (typeKind == TypeKind.SIMPLE) {
typeKind = TypeKind.RAW;
signatureErasure = signature;
if (newInterfaces != null) { // debug 375777
throw new IllegalStateException(
"Simple type promoted to raw, but simple type had new interfaces/superclass. Type is "
+ this.getName());
}
}
if (typeKind == TypeKind.RAW) {
genericType.addDependentType(this);
}
if (isRawType()) {
genericType.rawType = this;
}
if (this.isRawType() && rt.isRawType()) {
new RuntimeException("PR341926 diagnostics: Incorrect setup for a generic type, raw type should not point to raw: "
+ this.getName()).printStackTrace();
}
}
public void demoteToSimpleType() {
genericType = null;
typeKind = TypeKind.SIMPLE;
signatureErasure = null;
}
@Override
public ReferenceType getGenericType() {
if (isGenericType()) {
return this;
}
return genericType;
}
/**
* a parameterized signature starts with a "P" in place of the "L", see the comment on signatures in UnresolvedType.
*
* @param aGenericType
* @param someParameters
* @return
*/
private static String makeParameterizedSignature(ResolvedType aGenericType, ResolvedType[] someParameters) {
String rawSignature = aGenericType.getErasureSignature();
StringBuffer ret = new StringBuffer();
ret.append(PARAMETERIZED_TYPE_IDENTIFIER);
ret.append(rawSignature.substring(1, rawSignature.length() - 1));
ret.append("<");
for (int i = 0; i < someParameters.length; i++) {
ret.append(someParameters[i].getSignature());
}
ret.append(">;");
return ret.toString();
}
private static String makeDeclaredSignature(ResolvedType aGenericType, UnresolvedType[] someParameters) {
StringBuffer ret = new StringBuffer();
String rawSig = aGenericType.getErasureSignature();
ret.append(rawSig.substring(0, rawSig.length() - 1));
ret.append("<");
for (int i = 0; i < someParameters.length; i++) {
if (someParameters[i] instanceof ReferenceType) {
ret.append(((ReferenceType)someParameters[i]).getSignatureForAttribute());
} else if (someParameters[i] instanceof Primitive) {
ret.append(((Primitive)someParameters[i]).getSignatureForAttribute());
} else {
throw new IllegalStateException("DebugFor325731: expected a ReferenceType or Primitive but was " + someParameters[i]
+ " of type " + someParameters[i].getClass().getName());
}
}
ret.append(">;");
return ret.toString();
}
@Override
public void ensureConsistent() {
annotations = null;
annotationTypes = null;
newSuperclass = null;
newInterfaces = null;
typeVariables = null;
parameterizedInterfaces.clear();
superclassReference = new WeakReference<ResolvedType>(null);
if (getDelegate() != null) {
delegate.ensureConsistent();
}
}
@Override
public void addParent(ResolvedType newParent) {
if (this.isRawType()) {
throw new IllegalStateException(
"The raw type should never be accumulating new interfaces, they should be on the generic type. Type is "
+ this.getName());
}
if (newParent.isClass()) {
newSuperclass = newParent;
superclassReference = new WeakReference<ResolvedType>(null);
} else {
if (newInterfaces == null) {
newInterfaces = new ResolvedType[1];
newInterfaces[0] = newParent;
} else {
ResolvedType[] existing = getDelegate().getDeclaredInterfaces();
if (existing != null) {
for (int i = 0; i < existing.length; i++) {
if (existing[i].equals(newParent)) {
return; // already has this interface
}
}
}
ResolvedType[] newNewInterfaces = new ResolvedType[newInterfaces.length + 1];
System.arraycopy(newInterfaces, 0, newNewInterfaces, 1, newInterfaces.length);
newNewInterfaces[0] = newParent;
newInterfaces = newNewInterfaces;
}
if (this.isGenericType()) {
for (WeakReference<ReferenceType> derivativeTypeRef : derivativeTypes) {
ReferenceType derivativeType = derivativeTypeRef.get();
if (derivativeType!=null) {
derivativeType.parameterizedInterfaces.clear();
}
}
}
parameterizedInterfaces.clear();
}
}
private boolean equal(UnresolvedType[] typeParameters, ResolvedType[] resolvedParameters) {
if (typeParameters.length!=resolvedParameters.length) {
return false;
}
int len = typeParameters.length;
for (int p=0;p<len;p++) {
if (!typeParameters[p].equals(resolvedParameters[p])) {
return false;
}
}
return true;
}
/**
* Look for a derivative type with the specified type parameters. This can avoid creating an
* unnecessary new (duplicate) with the same information in it. This method also cleans up
* any reference entries that have been null'd by a GC.
*
* @param typeParameters the type parameters to use when searching for the derivative type.
* @return an existing derivative type or null if there isn't one
*/
public ReferenceType findDerivativeType(ResolvedType[] typeParameters) {
List<WeakReference<ReferenceType>> forRemoval = new ArrayList<WeakReference<ReferenceType>>();
for (WeakReference<ReferenceType> derivativeTypeRef: derivativeTypes) {
ReferenceType derivativeType = derivativeTypeRef.get();
if (derivativeType==null) {
forRemoval.add(derivativeTypeRef);
} else {
if (derivativeType.isRawType()) {
continue;
}
if (equal(derivativeType.typeParameters,typeParameters)) {
return derivativeType; // this escape route wont remove the empty refs
}
}
}
derivativeTypes.removeAll(forRemoval);
return null;
}
public boolean hasNewInterfaces() {
return newInterfaces!=null;
}
} |
407,017 | Bug 407017 Stack trace being printed, but want to mute it | In org.aspectj.ajdt.internal.core.builder.AjState.getDelegate(ReferenceType), there is a call to printStackTrace(). On the AJDT build server, this exception is being printed and causing some noise. Can you replace that call with a call to the IMessageHandler for the build? | resolved fixed | e6cb508 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-06-28T23:30:34Z" | "2013-05-01T20:26:40Z" | org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java | /* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* Andy Clement overhauled
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.ajdt.internal.compiler.CompilationResultDestinationManager;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.ajdt.internal.core.builder.AjBuildConfig.BinarySourceFile;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.asm.AsmManager;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
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.compiler.env.IBinaryAnnotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryField;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryMethod;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryNestedType;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
import org.aspectj.org.eclipse.jdt.internal.core.builder.ReferenceCollection;
import org.aspectj.org.eclipse.jdt.internal.core.builder.StringSet;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.CompressingDataOutputStream;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.TypeDelegateResolver;
import org.aspectj.weaver.bcel.UnwovenClassFile;
/**
* Maintains state needed for incremental compilation
*/
public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateResolver {
// SECRETAPI configures whether we use state instead of lastModTime - see pr245566
public static boolean CHECK_STATE_FIRST = true;
// SECRETAPI static so beware of multi-threading bugs...
public static IStateListener stateListener = null;
public static boolean FORCE_INCREMENTAL_DURING_TESTING = false;
static int PATHID_CLASSPATH = 0;
static int PATHID_ASPECTPATH = 1;
static int PATHID_INPATH = 2;
private static int CLASS_FILE_NO_CHANGES = 0;
private static int CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD = 1;
private static int CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD = 2;
private static final char[][] EMPTY_CHAR_ARRAY = new char[0][];
// now follows non static, but transient state - no need to write out, doesn't need reinitializing
// State recreated for each build:
/**
* When looking at changes on the classpath, this set accumulates files in our state instance that affected by those changes.
* Then if we can do an incremental build - these must be compiled.
*/
private final Set<File> affectedFiles = new HashSet<File>();
// these are references created on a particular compile run - when looping round in
// addAffectedSourceFiles(), if some have been created then we look at which source files
// touch upon those and get them recompiled.
private StringSet qualifiedStrings = new StringSet(3);
private StringSet simpleStrings = new StringSet(3);
private Set<File> addedFiles;
private Set<File> deletedFiles;
private Set<BinarySourceFile> addedBinaryFiles;
private Set<BinarySourceFile> deletedBinaryFiles;
// For a particular build run, this set records the changes to classesFromName
public final Set<String> deltaAddedClasses = new HashSet<String>();
// now follows non static, but transient state - no need to write out, DOES need reinitializing when read AjState instance
// reloaded
private final AjBuildManager buildManager;
private INameEnvironment nameEnvironment;
// now follows normal state that must be written out
private boolean couldBeSubsequentIncrementalBuild = false;
private boolean batchBuildRequiredThisTime = false;
private AjBuildConfig buildConfig;
private long lastSuccessfulFullBuildTime = -1;
private final Hashtable<String, Long> structuralChangesSinceLastFullBuild = new Hashtable<String, Long>();
private long lastSuccessfulBuildTime = -1;
private long currentBuildTime = -1;
private AsmManager structureModel;
/**
* For a given source file, records the ClassFiles (which contain a fully qualified name and a file name) that were created when
* the source file was compiled. Populated in noteResult and used in addDependentsOf(File)
*/
private final Map<File, List<ClassFile>> fullyQualifiedTypeNamesResultingFromCompilationUnit = new HashMap<File, List<ClassFile>>();
/**
* Source files defining aspects Populated in noteResult and used in processDeletedFiles
*/
private final Set<File> sourceFilesDefiningAspects = new HashSet<File>();
/**
* Populated in noteResult to record the set of types that should be recompiled if the given file is modified or deleted.
* Referred to during addAffectedSourceFiles when calculating incremental compilation set.
*/
private final Map<File, ReferenceCollection> references = new HashMap<File, ReferenceCollection>();
/**
* Holds UnwovenClassFiles (byte[]s) originating from the given file source. This could be a jar file, a directory, or an
* individual .class file. This is an *expensive* map. It is cleared immediately following a batch build, and the cheaper
* inputClassFilesBySource map is kept for processing of any subsequent incremental builds.
*
* Populated during AjBuildManager.initBcelWorld().
*
* Passed into AjCompiler adapter as the set of binary input files to reweave if the weaver determines a full weave is required.
*
* Cleared during initBcelWorld prior to repopulation.
*
* Used when a file is deleted during incremental compilation to delete all of the class files in the output directory that
* resulted from the weaving of File.
*
* Used during getBinaryFilesToCompile when compiling incrementally to determine which files should be recompiled if a given
* input file has changed.
*
*/
private Map<String, List<UnwovenClassFile>> binarySourceFiles = new HashMap<String, List<UnwovenClassFile>>();
/**
* Initially a duplicate of the information held in binarySourceFiles, with the key difference that the values are ClassFiles
* (type name, File) not UnwovenClassFiles (which also have all the byte code in them). After a batch build, binarySourceFiles
* is cleared, leaving just this much lighter weight map to use in processing subsequent incremental builds.
*/
private final Map<String, List<ClassFile>> inputClassFilesBySource = new HashMap<String, List<ClassFile>>();
/**
* A list of the .class files created by this state that contain aspects.
*/
private final List<String> aspectClassFiles = new ArrayList<String>();
/**
* Holds structure information on types as they were at the end of the last build. It would be nice to get rid of this too, but
* can't see an easy way to do that right now.
*/
private final Map<String, CompactTypeStructureRepresentation> resolvedTypeStructuresFromLastBuild = new HashMap<String, CompactTypeStructureRepresentation>();
/**
* Populated in noteResult to record the set of UnwovenClassFiles (intermediate results) that originated from compilation of the
* class with the given fully-qualified name.
*
* Used in removeAllResultsOfLastBuild to remove .class files from output directory.
*
* Passed into StatefulNameEnvironment during incremental compilation to support findType lookups.
*/
private final Map<String, File> classesFromName = new HashMap<String, File>();
/**
* Populated by AjBuildManager to record the aspects with the file name in which they're contained. This is later used when
* writing the outxml file in AjBuildManager. Need to record the file name because want to write an outxml file for each of the
* output directories and in order to ask the OutputLocationManager for the output location for a given aspect we need the file
* in which it is contained.
*/
private Map<String, char[]> aspectsFromFileNames;
private Set<File> compiledSourceFiles = new HashSet<File>();
private final Map<String, File> resources = new HashMap<String, File>();
SoftHashMap/* <baseDir,SoftHashMap<theFile,className>> */fileToClassNameMap = new SoftHashMap();
private BcelWeaver weaver;
private BcelWorld world;
// --- below here is unsorted state
// ---
public AjState(AjBuildManager buildManager) {
this.buildManager = buildManager;
}
public void setCouldBeSubsequentIncrementalBuild(boolean yesThereCould) {
this.couldBeSubsequentIncrementalBuild = yesThereCould;
}
void successfulCompile(AjBuildConfig config, boolean wasFullBuild) {
buildConfig = config;
lastSuccessfulBuildTime = currentBuildTime;
if (stateListener != null) {
stateListener.buildSuccessful(wasFullBuild);
}
if (wasFullBuild) {
lastSuccessfulFullBuildTime = currentBuildTime;
}
}
/**
* Returns false if a batch build is needed.
*/
public boolean prepareForNextBuild(AjBuildConfig newBuildConfig) {
currentBuildTime = System.currentTimeMillis();
if (!maybeIncremental()) {
if (listenerDefined()) {
getListener().recordDecision(
"Preparing for build: not going to be incremental because either not in AJDT or incremental deactivated");
}
return false;
}
if (this.batchBuildRequiredThisTime) {
this.batchBuildRequiredThisTime = false;
if (listenerDefined()) {
getListener().recordDecision(
"Preparing for build: not going to be incremental this time because batch build explicitly forced");
}
return false;
}
if (lastSuccessfulBuildTime == -1 || buildConfig == null) {
structuralChangesSinceLastFullBuild.clear();
if (listenerDefined()) {
getListener().recordDecision(
"Preparing for build: not going to be incremental because no successful previous full build");
}
return false;
}
// we don't support incremental with an outjar yet
if (newBuildConfig.getOutputJar() != null) {
structuralChangesSinceLastFullBuild.clear();
if (listenerDefined()) {
getListener().recordDecision("Preparing for build: not going to be incremental because outjar being used");
}
return false;
}
affectedFiles.clear();
// 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();
if (stateListener != null) {
stateListener.pathChangeDetected();
}
structuralChangesSinceLastFullBuild.clear();
if (listenerDefined()) {
getListener()
.recordDecision(
"Preparing for build: not going to be incremental because path change detected (one of classpath/aspectpath/inpath/injars)");
}
return false;
}
if (simpleStrings.elementSize > 20) {
simpleStrings = new StringSet(3);
} else {
simpleStrings.clear();
}
if (qualifiedStrings.elementSize > 20) {
qualifiedStrings = new StringSet(3);
} else {
qualifiedStrings.clear();
}
if ((newBuildConfig.getChanged() & PROJECTSOURCEFILES_CHANGED) == 0) {
addedFiles = Collections.emptySet();
deletedFiles = Collections.emptySet();
} else {
Set<File> oldFiles = new HashSet<File>(buildConfig.getFiles());
Set<File> newFiles = new HashSet<File>(newBuildConfig.getFiles());
addedFiles = new HashSet<File>(newFiles);
addedFiles.removeAll(oldFiles);
deletedFiles = new HashSet<File>(oldFiles);
deletedFiles.removeAll(newFiles);
}
Set<BinarySourceFile> oldBinaryFiles = new HashSet<BinarySourceFile>(buildConfig.getBinaryFiles());
Set<BinarySourceFile> newBinaryFiles = new HashSet<BinarySourceFile>(newBuildConfig.getBinaryFiles());
addedBinaryFiles = new HashSet<BinarySourceFile>(newBinaryFiles);
addedBinaryFiles.removeAll(oldBinaryFiles);
deletedBinaryFiles = new HashSet<BinarySourceFile>(oldBinaryFiles);
deletedBinaryFiles.removeAll(newBinaryFiles);
boolean couldStillBeIncremental = processDeletedFiles(deletedFiles);
if (!couldStillBeIncremental) {
if (listenerDefined()) {
getListener().recordDecision("Preparing for build: not going to be incremental because an aspect was deleted");
}
return false;
}
if (listenerDefined()) {
getListener().recordDecision("Preparing for build: planning to be an incremental build");
}
return true;
}
/**
* Checks if any of the files in the set passed in contains an aspect declaration. If one is found then we start the process of
* batch building, i.e. we remove all the results of the last build, call any registered listener to tell them whats happened
* and return false.
*
* @return false if we discovered an aspect declaration
*/
private boolean processDeletedFiles(Set<File> deletedFiles) {
for (File deletedFile : deletedFiles) {
if (this.sourceFilesDefiningAspects.contains(deletedFile)) {
removeAllResultsOfLastBuild();
if (stateListener != null) {
stateListener.detectedAspectDeleted(deletedFile);
}
return false;
}
List<ClassFile> classes = fullyQualifiedTypeNamesResultingFromCompilationUnit.get(deletedFile);
if (classes != null) {
for (ClassFile cf : classes) {
resolvedTypeStructuresFromLastBuild.remove(cf.fullyQualifiedTypeName);
}
}
}
return true;
}
private Collection<File> getModifiedFiles() {
return getModifiedFiles(lastSuccessfulBuildTime);
}
Collection<File> getModifiedFiles(long lastBuildTime) {
Set<File> ret = new HashSet<File>();
// Check if the build configuration knows what files have changed...
List<File> modifiedFiles = buildConfig.getModifiedFiles();
if (modifiedFiles == null) {
// do not know, so need to go looking
// not our job to account for new and deleted files
for (Iterator<File> i = buildConfig.getFiles().iterator(); i.hasNext();) {
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);
}
}
} else {
ret.addAll(modifiedFiles);
}
ret.addAll(affectedFiles);
return ret;
}
private Collection<BinarySourceFile> getModifiedBinaryFiles() {
return getModifiedBinaryFiles(lastSuccessfulBuildTime);
}
Collection<BinarySourceFile> getModifiedBinaryFiles(long lastBuildTime) {
List<BinarySourceFile> ret = new ArrayList<BinarySourceFile>();
// not our job to account for new and deleted files
for (Iterator<BinarySourceFile> i = buildConfig.getBinaryFiles().iterator(); i.hasNext();) {
AjBuildConfig.BinarySourceFile bsfile = 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 void recordDecision(String decision) {
getListener().recordDecision(decision);
}
/**
* Analyse .class files in the directory specified, if they have changed since the last successful build then see if we can
* determine which source files in our project depend on the change. If we can then we can still do an incremental build, if we
* can't then we have to do a full build.
*
*/
private int classFileChangedInDirSinceLastBuildRequiringFullBuild(File dir, int pathid) {
if (!dir.isDirectory()) {
if (listenerDefined()) {
recordDecision("ClassFileChangeChecking: not a directory so forcing full build: '" + dir.getPath() + "'");
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
}
// Are we managing that output directory?
AjState state = IncrementalStateManager.findStateManagingOutputLocation(dir);
if (listenerDefined()) {
if (state != null) {
recordDecision("ClassFileChangeChecking: found state instance managing output location : " + dir);
} else {
recordDecision("ClassFileChangeChecking: failed to find a state instance managing output location : " + dir);
}
}
// pr268827 - this guard will cause us to exit quickly if the state says there really is
// nothing of interest. This will not catch the case where a user modifies the .class files outside of
// eclipse because the state will not be aware of it. But that seems an unlikely scenario and
// we are paying a heavy price to check it
if (state != null && !state.hasAnyStructuralChangesSince(lastSuccessfulBuildTime)) {
if (listenerDefined()) {
getListener().recordDecision("ClassFileChangeChecking: no reported changes in that state");
}
return CLASS_FILE_NO_CHANGES;
}
if (state == null) {
// This may be because the directory is the output path of a Java project upon which we depend
// we need to call back into AJDT to ask about that projects state.
CompilationResultDestinationManager crdm = buildConfig.getCompilationResultDestinationManager();
if (crdm != null) {
int i = crdm.discoverChangesSince(dir, lastSuccessfulBuildTime);
// 0 = dontknow if it has changed
// 1 = definetly not changed at all
// further numbers can determine more granular changes
if (i == 1) {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: queried JDT and '" + dir
+ "' is apparently unchanged so not performing timestamp check");
}
return CLASS_FILE_NO_CHANGES;
}
}
}
List<File> classFiles = FileUtil.listClassFiles(dir);
for (Iterator<File> iterator = classFiles.iterator(); iterator.hasNext();) {
File classFile = iterator.next();
if (CHECK_STATE_FIRST && state != null) {
// Next section reworked based on bug 270033:
// if it is an aspect we may or may not be in trouble depending on whether (a) we depend on it (b) it is on the
// classpath or the aspectpath
if (state.isAspect(classFile)) {
boolean hasStructuralChanges = state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime);
if (hasStructuralChanges || isTypeWeReferTo(classFile)) {
if (hasStructuralChanges) {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: aspect found that has structurally changed : " + classFile);
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
} else {
// must be 'isTypeWeReferTo()'
if (pathid == PATHID_CLASSPATH) {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: aspect found that this project refers to : " + classFile
+ " but only referred to via classpath");
}
} else {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: aspect found that this project refers to : " + classFile
+ " from either inpath/aspectpath, switching to full build");
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
}
}
} else {
// it is an aspect but we don't refer to it:
// - for CLASSPATH I think this is OK, we can continue and try an
// incremental build
// - for ASPECTPATH we don't know what else might be touched in this project
// and must rebuild
if (pathid == PATHID_CLASSPATH) {
if (listenerDefined()) {
getListener()
.recordDecision(
"ClassFileChangeChecking: found aspect on classpath but this project doesn't reference it, continuing to try for incremental build : "
+ classFile);
}
} else {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: found aspect on aspectpath/inpath - can't determine if this project is affected, must full build: "
+ classFile);
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
}
}
}
if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime)) {
if (listenerDefined()) {
getListener().recordDecision("ClassFileChangeChecking: structural change detected in : " + classFile);
}
isTypeWeReferTo(classFile);
}
} else {
long modTime = classFile.lastModified();
if ((modTime + 1000) >= lastSuccessfulBuildTime) {
// so the class on disk has changed since the last successful build for this state object
// BUG? we stop on the first change that leads us to an incremental build, surely we need to continue and look
// at all files incase another change means we need to incremental a bit more stuff?
// To work out if it is a real change we should ask any state
// object managing the output location whether the file has
// structurally changed or not
if (state != null) {
if (state.isAspect(classFile)) {
if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime) || isTypeWeReferTo(classFile)) {
// further improvements possible
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: aspect found that has structurally changed or that this project depends upon : "
+ classFile);
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
} else {
// it is an aspect but we don't refer to it:
// - for CLASSPATH I think this is OK, we can continue and try an
// incremental build
// - for ASPECTPATH we don't know what else might be touched in this project
// and must rebuild
if (pathid == PATHID_CLASSPATH) {
if (listenerDefined()) {
getListener()
.recordDecision(
"ClassFileChangeChecking: found aspect on classpath but this project doesn't reference it, continuing to try for incremental build : "
+ classFile);
}
} else {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: found aspect on aspectpath/inpath - can't determine if this project is affected, must full build: "
+ classFile);
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
}
}
}
if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime)) {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: structural change detected in : " + classFile);
}
isTypeWeReferTo(classFile);
} else {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: change detected in " + classFile + " but it is not structural");
}
}
} else {
// No state object to ask, so it only matters if we know which type depends on this file
if (isTypeWeReferTo(classFile)) {
return CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD;
} else {
return CLASS_FILE_NO_CHANGES;
}
}
}
}
}
return CLASS_FILE_NO_CHANGES;
}
private boolean isAspect(File file) {
return aspectClassFiles.contains(file.getAbsolutePath());
}
@SuppressWarnings("rawtypes")
public static class SoftHashMap extends AbstractMap {
private final Map map;
private final ReferenceQueue rq = new ReferenceQueue();
public SoftHashMap(Map map) {
this.map = map;
}
public SoftHashMap() {
this(new HashMap());
}
public SoftHashMap(Map map, boolean b) {
this(map);
}
class SoftReferenceKnownKey extends SoftReference {
private final Object key;
@SuppressWarnings("unchecked")
SoftReferenceKnownKey(Object k, Object v) {
super(v, rq);
this.key = k;
}
}
private void processQueue() {
SoftReferenceKnownKey sv = null;
while ((sv = (SoftReferenceKnownKey) rq.poll()) != null) {
map.remove(sv.key);
}
}
public Object get(Object key) {
SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.get(key);
if (value == null) {
return null;
}
if (value.get() == null) {
// it got GC'd
map.remove(value.key);
return null;
} else {
return value.get();
}
}
public Object put(Object k, Object v) {
processQueue();
return map.put(k, new SoftReferenceKnownKey(k, v));
}
public Set entrySet() {
return map.entrySet();
}
public void clear() {
processQueue();
map.clear();
}
public int size() {
processQueue();
return map.size();
}
public Object remove(Object k) {
processQueue();
SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.remove(k);
if (value == null) {
return null;
}
if (value.get() != null) {
return value.get();
}
return null;
}
}
/**
* If a class file has changed in a path on our classpath, it may not be for a type that any of our source files care about.
* This method checks if any of our source files have a dependency on the class in question and if not, we don't consider it an
* interesting change.
*/
private boolean isTypeWeReferTo(File file) {
String fpath = file.getAbsolutePath();
int finalSeparator = fpath.lastIndexOf(File.separator);
String baseDir = fpath.substring(0, finalSeparator);
String theFile = fpath.substring(finalSeparator + 1);
SoftHashMap classNames = (SoftHashMap) fileToClassNameMap.get(baseDir);
if (classNames == null) {
classNames = new SoftHashMap();
fileToClassNameMap.put(baseDir, classNames);
}
char[] className = (char[]) classNames.get(theFile);
if (className == null) {
// if (listenerDefined())
// getListener().recordDecision("Cache miss, looking up classname for : " + fpath);
ClassFileReader cfr;
try {
cfr = ClassFileReader.read(file);
} catch (ClassFormatException e) {
return true;
} catch (IOException e) {
return true;
}
className = cfr.getName();
classNames.put(theFile, className);
// } else {
// if (listenerDefined())
// getListener().recordDecision("Cache hit, looking up classname for : " + fpath);
}
char[][][] qualifiedNames = null;
char[][] simpleNames = null;
if (CharOperation.indexOf('/', className) != -1) {
qualifiedNames = new char[1][][];
qualifiedNames[0] = CharOperation.splitOn('/', className);
qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedNames);
} else {
simpleNames = new char[1][];
simpleNames[0] = className;
simpleNames = ReferenceCollection.internSimpleNames(simpleNames, true);
}
int newlyAffectedFiles = 0;
for (Iterator<Map.Entry<File, ReferenceCollection>> i = references.entrySet().iterator(); i.hasNext();) {
Map.Entry<File, ReferenceCollection> entry = i.next();
ReferenceCollection refs = entry.getValue();
if (refs != null && refs.includes(qualifiedNames, simpleNames)) {
if (listenerDefined()) {
getListener().recordDecision(
toString() + ": type " + new String(className) + " is depended upon by '" + entry.getKey() + "'");
}
newlyAffectedFiles++;
// possibly the beginnings of addressing the second point in 270033 comment 3
// List/*ClassFile*/ cfs = (List)this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(entry.getKey());
affectedFiles.add(entry.getKey());
}
}
if (newlyAffectedFiles > 0) {
return true;
}
if (listenerDefined()) {
getListener().recordDecision(toString() + ": type " + new String(className) + " is not depended upon by this state");
}
return false;
}
// /**
// * For a given class file, determine which source file it came from. This will only succeed if the class file is from a source
// * file within this project.
// */
// private File getSourceFileForClassFile(File classfile) {
// Set sourceFiles = fullyQualifiedTypeNamesResultingFromCompilationUnit.keySet();
// for (Iterator sourceFileIterator = sourceFiles.iterator(); sourceFileIterator.hasNext();) {
// File sourceFile = (File) sourceFileIterator.next();
// List/* ClassFile */classesFromSourceFile = (List/* ClassFile */) fullyQualifiedTypeNamesResultingFromCompilationUnit
// .get(sourceFile);
// for (int i = 0; i < classesFromSourceFile.size(); i++) {
// if (((ClassFile) classesFromSourceFile.get(i)).locationOnDisk.equals(classfile))
// return sourceFile;
// }
// }
// return null;
// }
public String toString() {
StringBuffer sb = new StringBuffer();
// null config means failed build i think as it is only set on successful full build?
sb.append("AjState(").append((buildConfig == null ? "NULLCONFIG" : buildConfig.getConfigFile().toString())).append(")");
return sb.toString();
}
/**
* Determine if a file has changed since a given time, using the local information recorded in the structural changes data
* structure.
*
* @param file the file we are wondering about
* @param lastSuccessfulBuildTime the last build time for the state asking the question
*/
private boolean hasStructuralChangedSince(File file, long lastSuccessfulBuildTime) {
// long lastModTime = file.lastModified();
Long l = structuralChangesSinceLastFullBuild.get(file.getAbsolutePath());
long strucModTime = -1;
if (l != null) {
strucModTime = l.longValue();
} else {
strucModTime = this.lastSuccessfulFullBuildTime;
}
// we now have:
// 'strucModTime'-> the last time the class was structurally changed
return (strucModTime > lastSuccessfulBuildTime);
}
/**
* Determine if anything has changed since a given time.
*/
private boolean hasAnyStructuralChangesSince(long lastSuccessfulBuildTime) {
Set<Map.Entry<String, Long>> entries = structuralChangesSinceLastFullBuild.entrySet();
for (Iterator<Map.Entry<String, Long>> iterator = entries.iterator(); iterator.hasNext();) {
Map.Entry<String, Long> entry = iterator.next();
Long l = entry.getValue();
if (l != null) {
long lvalue = l.longValue();
if (lvalue > lastSuccessfulBuildTime) {
if (listenerDefined()) {
getListener().recordDecision(
"Seems this has changed " + entry.getKey() + "modtime=" + lvalue + " lsbt="
+ this.lastSuccessfulFullBuildTime + " incoming check value=" + lastSuccessfulBuildTime);
}
return true;
}
}
}
return (this.lastSuccessfulFullBuildTime > lastSuccessfulBuildTime);
}
/**
* Determine if something has changed on the classpath/inpath/aspectpath and a full build is required rather than an incremental
* one.
*
* @param previousConfig the previous configuration used
* @param newConfig the new configuration being used
* @return true if full build required
*/
private boolean pathChange(AjBuildConfig previousConfig, AjBuildConfig newConfig) {
int changes = newConfig.getChanged();
if ((changes & (CLASSPATH_CHANGED | ASPECTPATH_CHANGED | INPATH_CHANGED | OUTPUTDESTINATIONS_CHANGED | INJARS_CHANGED)) != 0) {
List<File> oldOutputLocs = getOutputLocations(previousConfig);
Set<String> alreadyAnalysedPaths = new HashSet<String>();
List<String> oldClasspath = previousConfig.getClasspath();
List<String> newClasspath = newConfig.getClasspath();
if (stateListener != null) {
stateListener.aboutToCompareClasspaths(oldClasspath, newClasspath);
}
if (classpathChangedAndNeedsFullBuild(oldClasspath, newClasspath, true, oldOutputLocs, alreadyAnalysedPaths)) {
return true;
}
List<File> oldAspectpath = previousConfig.getAspectpath();
List<File> newAspectpath = newConfig.getAspectpath();
if (changedAndNeedsFullBuild(oldAspectpath, newAspectpath, true, oldOutputLocs, alreadyAnalysedPaths, PATHID_ASPECTPATH)) {
return true;
}
List<File> oldInPath = previousConfig.getInpath();
List<File> newInPath = newConfig.getInpath();
if (changedAndNeedsFullBuild(oldInPath, newInPath, false, oldOutputLocs, alreadyAnalysedPaths, PATHID_INPATH)) {
return true;
}
List<File> oldInJars = previousConfig.getInJars();
List<File> newInJars = newConfig.getInJars();
if (changedAndNeedsFullBuild(oldInJars, newInJars, false, oldOutputLocs, alreadyAnalysedPaths, PATHID_INPATH)) {
return true;
}
} else if (newConfig.getClasspathElementsWithModifiedContents() != null) {
// Although the classpath entries themselves are the same as before, the contents of one of the
// directories on the classpath has changed - rather than go digging around to find it, let's ask
// the compiler configuration. This will allow for projects with long classpaths where classpaths
// are also capturing project dependencies - when a project we depend on is rebuilt, we can just check
// it as a standalone element on our classpath rather than going through them all
List<String> modifiedCpElements = newConfig.getClasspathElementsWithModifiedContents();
for (Iterator<String> iterator = modifiedCpElements.iterator(); iterator.hasNext();) {
File cpElement = new File(iterator.next());
if (cpElement.exists() && !cpElement.isDirectory()) {
if (cpElement.lastModified() > lastSuccessfulBuildTime) {
return true;
}
} else {
int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(cpElement, PATHID_CLASSPATH);
if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) {
return true;
}
}
}
}
return false;
}
/**
* Return a list of the output locations - this includes any 'default' output location and then any known by a registered
* CompilationResultDestinationManager.
*
* @param config the build configuration for which the output locations should be determined
* @return a list of file objects
*/
private List<File> getOutputLocations(AjBuildConfig config) {
List<File> outputLocs = new ArrayList<File>();
// Is there a default location?
if (config.getOutputDir() != null) {
try {
outputLocs.add(config.getOutputDir().getCanonicalFile());
} catch (IOException e) {
}
}
if (config.getCompilationResultDestinationManager() != null) {
List<File> dirs = config.getCompilationResultDestinationManager().getAllOutputLocations();
for (Iterator<File> iterator = dirs.iterator(); iterator.hasNext();) {
File f = iterator.next();
try {
File cf = f.getCanonicalFile();
if (!outputLocs.contains(cf)) {
outputLocs.add(cf);
}
} catch (IOException e) {
}
}
}
return outputLocs;
}
private File getOutputLocationFor(AjBuildConfig config, File aResourceFile) {
if (config.getCompilationResultDestinationManager() != null) {
File outputLoc = config.getCompilationResultDestinationManager().getOutputLocationForResource(aResourceFile);
if (outputLoc != null) {
return outputLoc;
}
}
// Is there a default location?
if (config.getOutputDir() != null) {
return config.getOutputDir();
}
return null;
}
/**
* Check the old and new paths, if they vary by length or individual elements then that is considered a change. Or if the last
* modified time of a path entry has changed (or last modified time of a classfile in that path entry has changed) then return
* true. The outputlocations are supplied so they can be 'ignored' in the comparison.
*
* @param oldPath
* @param newPath
* @param checkClassFiles whether to examine individual class files within directories
* @param outputLocs the output locations that should be ignored if they occur on the paths being compared
* @return true if a change is detected that requires a full build
*/
private boolean changedAndNeedsFullBuild(List oldPath, List newPath, boolean checkClassFiles, List<File> outputLocs,
Set<String> alreadyAnalysedPaths, int pathid) {
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 (checkClassFiles && f.exists() && f.isDirectory()) {
// We should use here a list/set of directories we know have or have not changed - some kind of
// List<File> buildConfig.getClasspathEntriesWithChangedContents()
// and then only proceed to look inside directories if it is one of these, ignoring others -
// that should save a massive amount of processing for incremental builds in a multi project scenario
boolean foundMatch = false;
for (Iterator<File> iterator = outputLocs.iterator(); !foundMatch && iterator.hasNext();) {
File dir = iterator.next();
if (f.equals(dir)) {
foundMatch = true;
}
}
if (!foundMatch) {
if (!alreadyAnalysedPaths.contains(f.getAbsolutePath())) { // Do not check paths more than once
alreadyAnalysedPaths.add(f.getAbsolutePath());
int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(f, pathid);
if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) {
return true;
}
}
}
}
}
return false;
}
/**
* Check the old and new paths, if they vary by length or individual elements then that is considered a change. Or if the last
* modified time of a path entry has changed (or last modified time of a classfile in that path entry has changed) then return
* true. The outputlocations are supplied so they can be 'ignored' in the comparison.
*
* @param oldPath
* @param newPath
* @param checkClassFiles whether to examine individual class files within directories
* @param outputLocs the output locations that should be ignored if they occur on the paths being compared
* @return true if a change is detected that requires a full build
*/
private boolean classpathChangedAndNeedsFullBuild(List<String> oldPath, List<String> newPath, boolean checkClassFiles,
List<File> outputLocs, Set<String> alreadyAnalysedPaths) {
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;
}
File f = new File(oldPath.get(i));
if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) {
return true;
}
if (checkClassFiles && f.exists() && f.isDirectory()) {
// We should use here a list/set of directories we know have or have not changed - some kind of
// List<File> buildConfig.getClasspathEntriesWithChangedContents()
// and then only proceed to look inside directories if it is one of these, ignoring others -
// that should save a massive amount of processing for incremental builds in a multi project scenario
boolean foundMatch = false;
for (Iterator<File> iterator = outputLocs.iterator(); !foundMatch && iterator.hasNext();) {
File dir = iterator.next();
if (f.equals(dir)) {
foundMatch = true;
}
}
if (!foundMatch) {
if (!alreadyAnalysedPaths.contains(f.getAbsolutePath())) { // Do not check paths more than once
alreadyAnalysedPaths.add(f.getAbsolutePath());
int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(f, PATHID_CLASSPATH);
if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) {
return true;
}
}
}
}
}
return false;
}
public Set<File> getFilesToCompile(boolean firstPass) {
Set<File> thisTime = new HashSet<File>();
if (firstPass) {
compiledSourceFiles = new HashSet<File>();
Collection<File> 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);
// }
if (addedFiles != null) {
for (Iterator<File> fIter = addedFiles.iterator(); fIter.hasNext();) {
File o = fIter.next();
// TODO isn't it a set?? why do this
if (!thisTime.contains(o)) {
thisTime.add(o);
}
}
// thisTime.addAll(addedFiles);
}
deleteClassFiles();
// Do not delete resources on incremental build, AJDT will handle
// copying updates to the output folder. AspectJ only does a copy
// of them on full build (see copyResourcesToDestination() call
// in AjBuildManager)
// deleteResources();
addAffectedSourceFiles(thisTime, thisTime);
} else {
addAffectedSourceFiles(thisTime, compiledSourceFiles);
}
compiledSourceFiles = thisTime;
return thisTime;
}
private boolean maybeIncremental() {
return (FORCE_INCREMENTAL_DURING_TESTING || this.couldBeSubsequentIncrementalBuild);
}
public Map<String, List<UnwovenClassFile>> getBinaryFilesToCompile(boolean firstTime) {
if (lastSuccessfulBuildTime == -1 || buildConfig == null || !maybeIncremental()) {
return binarySourceFiles;
}
// else incremental...
Map<String, List<UnwovenClassFile>> toWeave = new HashMap<String, List<UnwovenClassFile>>();
if (firstTime) {
List<BinarySourceFile> addedOrModified = new ArrayList<BinarySourceFile>();
addedOrModified.addAll(addedBinaryFiles);
addedOrModified.addAll(getModifiedBinaryFiles());
for (Iterator<BinarySourceFile> iter = addedOrModified.iterator(); iter.hasNext();) {
AjBuildConfig.BinarySourceFile bsf = iter.next();
UnwovenClassFile ucf = createUnwovenClassFile(bsf);
if (ucf == null) {
continue;
}
List<UnwovenClassFile> ucfs = new ArrayList<UnwovenClassFile>();
ucfs.add(ucf);
recordTypeChanged(ucf.getClassName());
binarySourceFiles.put(bsf.binSrc.getPath(), ucfs);
List<ClassFile> cfs = new ArrayList<ClassFile>(1);
cfs.add(getClassFileFor(ucf));
this.inputClassFilesBySource.put(bsf.binSrc.getPath(), cfs);
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<List<ClassFile>> iter = this.inputClassFilesBySource.values().iterator(); iter.hasNext();) {
List<ClassFile> cfs = iter.next();
for (ClassFile cf : cfs) {
cf.deleteFromFileSystem(buildConfig);
}
}
for (Iterator<File> iterator = classesFromName.values().iterator(); iterator.hasNext();) {
File f = iterator.next();
new ClassFile("", f).deleteFromFileSystem(buildConfig);
}
Set<Map.Entry<String, File>> resourceEntries = resources.entrySet();
for (Iterator<Map.Entry<String, File>> iter = resourceEntries.iterator(); iter.hasNext();) {
Map.Entry<String, File> resourcePair = iter.next();
File sourcePath = resourcePair.getValue();
File outputLoc = getOutputLocationFor(buildConfig, sourcePath);
if (outputLoc != null) {
outputLoc = new File(outputLoc, resourcePair.getKey());
if (!outputLoc.getPath().equals(sourcePath.getPath()) && outputLoc.exists()) {
outputLoc.delete();
if (buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileRemove(outputLoc.getPath(),
CompilationResultDestinationManager.FILETYPE_RESOURCE);
}
}
}
}
}
private void deleteClassFiles() {
if (deletedFiles == null) {
return;
}
for (File deletedFile : deletedFiles) {
addDependentsOf(deletedFile);
List<ClassFile> cfs = this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(deletedFile);
this.fullyQualifiedTypeNamesResultingFromCompilationUnit.remove(deletedFile);
if (cfs != null) {
for (ClassFile cf : cfs) {
deleteClassFile(cf);
}
}
}
}
private void deleteBinaryClassFiles() {
// range of bsf is ucfs, domain is files (.class and jars) in inpath/jars
for (BinarySourceFile deletedFile : deletedBinaryFiles) {
List<ClassFile> cfs = this.inputClassFilesBySource.get(deletedFile.binSrc.getPath());
for (Iterator<ClassFile> iterator = cfs.iterator(); iterator.hasNext();) {
deleteClassFile(iterator.next());
}
this.inputClassFilesBySource.remove(deletedFile.binSrc.getPath());
}
}
// 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();
// List outputDirs = getOutputLocations(buildConfig);
// for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
// File dir = (File) iterator.next();
// File f = new File(dir, victim);
// if (f.exists()) {
// f.delete();
// }
// resources.remove(victim);
// }
// }
// }
// private void maybeDeleteResource(String resName, List oldResources) {
// if (resources.contains(resName)) {
// oldResources.remove(resName);
// List outputDirs = getOutputLocations(buildConfig);
// for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
// File dir = (File) iterator.next();
// File source = new File(dir, resName);
// if (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 = null;
// try {
// filename = files[i].getCanonicalPath().substring(dir.getCanonicalPath().length() + 1);
// } catch (IOException e) {
// // we are in trouble if this happens...
// IMessage msg = new Message("call to getCanonicalPath() failed for file " + files[i] + " with: " + e.getMessage(),
// new SourceLocation(files[i], 0), false);
// buildManager.handler.handleMessage(msg);
// filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1);
// }
//
// maybeDeleteResource(filename, oldResources);
// }
// }
private void deleteClassFile(ClassFile cf) {
classesFromName.remove(cf.fullyQualifiedTypeName);
weaver.deleteClassFile(cf.fullyQualifiedTypeName);
cf.deleteFromFileSystem(buildConfig);
}
private UnwovenClassFile createUnwovenClassFile(AjBuildConfig.BinarySourceFile bsf) {
UnwovenClassFile ucf = null;
try {
File outputDir = buildConfig.getOutputDir();
if (buildConfig.getCompilationResultDestinationManager() != null) {
// createUnwovenClassFile is called only for classes that are on the inpath,
// all inpath classes are put in the defaultOutputLocation, therefore,
// this is the output dir
outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation();
}
ucf = weaver.addClassFile(bsf.binSrc, bsf.fromInPathDirectory, outputDir);
} 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) {
if (!maybeIncremental()) {
return;
}
File sourceFile = new File(result.fileName());
CompilationResult cr = result.result();
references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences,cr.rootReferences));
UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles();
for (int i = 0; i < unwovenClassFiles.length; i++) {
File lastTimeRound = classesFromName.get(unwovenClassFiles[i].getClassName());
recordClassFile(unwovenClassFiles[i], lastTimeRound);
String name = unwovenClassFiles[i].getClassName();
if (lastTimeRound == null) {
deltaAddedClasses.add(name);
}
classesFromName.put(name, new File(unwovenClassFiles[i].getFilename()));
}
// need to do this before types are deleted from the World...
recordWhetherCompilationUnitDefinedAspect(sourceFile, cr);
deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles);
recordFQNsResultingFromCompilationUnit(sourceFile, result);
}
public void noteNewResult(CompilationResult cr) {
// if (!maybeIncremental()) {
// return;
// }
//
// // File sourceFile = new File(result.fileName());
// // CompilationResult cr = result.result();
// if (new String(cr.getFileName()).indexOf("C") != -1) {
// cr.references.put(new String(cr.getFileName()),
// new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences));
// int stop = 1;
// }
// references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences));
//
// UnwovenClassFile[] unwovenClassFiles = cr.unwovenClassFiles();
// for (int i = 0; i < unwovenClassFiles.length; i++) {
// File lastTimeRound = (File) classesFromName.get(unwovenClassFiles[i].getClassName());
// recordClassFile(unwovenClassFiles[i], lastTimeRound);
// classesFromName.put(unwovenClassFiles[i].getClassName(), new File(unwovenClassFiles[i].getFilename()));
// }
// need to do this before types are deleted from the World...
// recordWhetherCompilationUnitDefinedAspect(sourceFile, cr);
// deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles);
//
// recordFQNsResultingFromCompilationUnit(sourceFile, result);
}
/**
* @param sourceFile
* @param unwovenClassFiles
*/
private void deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(File sourceFile,
UnwovenClassFile[] unwovenClassFiles) {
List<ClassFile> classFiles = this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile);
if (classFiles != null) {
for (int i = 0; i < unwovenClassFiles.length; i++) {
// deleting also deletes types from the weaver... don't do this if they are
// still present this time around...
removeFromClassFilesIfPresent(unwovenClassFiles[i].getClassName(), classFiles);
}
for (ClassFile cf : classFiles) {
recordTypeChanged(cf.fullyQualifiedTypeName);
resolvedTypeStructuresFromLastBuild.remove(cf.fullyQualifiedTypeName);
// }
// for (ClassFile cf : classFiles) {
deleteClassFile(cf);
}
}
}
private void removeFromClassFilesIfPresent(String className, List<ClassFile> classFiles) {
ClassFile victim = null;
for (ClassFile cf : classFiles) {
if (cf.fullyQualifiedTypeName.equals(className)) {
victim = cf;
break;
}
}
if (victim != null) {
classFiles.remove(victim);
}
}
/**
* Record the fully-qualified names of the types that were declared in the given source file.
*
* @param sourceFile, the compilation unit
* @param icr, the CompilationResult from compiling it
*/
private void recordFQNsResultingFromCompilationUnit(File sourceFile, InterimCompilationResult icr) {
List<ClassFile> classFiles = new ArrayList<ClassFile>();
UnwovenClassFile[] types = icr.unwovenClassFiles();
for (int i = 0; i < types.length; i++) {
classFiles.add(new ClassFile(types[i].getClassName(), new File(types[i].getFilename())));
}
this.fullyQualifiedTypeNamesResultingFromCompilationUnit.put(sourceFile, classFiles);
}
/**
* If this compilation unit defined an aspect, we need to know in case it is modified in a future increment.
*
* @param sourceFile
* @param cr
*/
private void recordWhetherCompilationUnitDefinedAspect(File sourceFile, CompilationResult cr) {
this.sourceFilesDefiningAspects.remove(sourceFile);
if (cr != null) {
Map compiledTypes = cr.compiledTypes;
if (compiledTypes != null) {
for (Iterator<char[]> iterator = compiledTypes.keySet().iterator(); iterator.hasNext();) {
char[] className = iterator.next();
String typeName = new String(className).replace('/', '.');
if (typeName.indexOf(BcelWeaver.SYNTHETIC_CLASS_POSTFIX) == -1) {
ResolvedType rt = world.resolve(typeName);
if (rt.isMissing()) {
// This can happen in a case where another problem has occurred that prevented it being
// correctly added to the world. Eg. pr148285. Duplicate types
// throw new IllegalStateException("Type '" + rt.getSignature() + "' not found in world!");
} else if (rt.isAspect()) {
this.sourceFilesDefiningAspects.add(sourceFile);
break;
}
}
}
}
}
}
// 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, File lastTime) {
if (simpleStrings == null) {
// batch build
// record resolved type for structural comparisons in future increments
// this records a second reference to a structure already held in memory
// by the world.
ResolvedType rType = world.resolve(thisTime.getClassName());
if (!rType.isMissing()) {
try {
ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null);
boolean isAspect = false;
if (rType instanceof ReferenceType && ((ReferenceType) rType).getDelegate() != null) {
isAspect = ((ReferenceType) rType).isAspect();
}
this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(), new CompactTypeStructureRepresentation(
reader, isAspect));
} catch (ClassFormatException cfe) {
throw new BCException("Unexpected problem processing class", cfe);
}
}
return;
}
CompactTypeStructureRepresentation existingStructure = this.resolvedTypeStructuresFromLastBuild
.get(thisTime.getClassName());
ResolvedType newResolvedType = world.resolve(thisTime.getClassName());
if (!newResolvedType.isMissing()) {
try {
ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null);
boolean isAspect = false;
if (newResolvedType instanceof ReferenceType && ((ReferenceType) newResolvedType).getDelegate() != null) {
isAspect = ((ReferenceType) newResolvedType).isAspect();
}
this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(), new CompactTypeStructureRepresentation(
reader, isAspect));
} catch (ClassFormatException cfe) {
try {
String s = System.getProperty("aspectj.debug377096","false");
if (s.equalsIgnoreCase("true")) {
String location = System.getProperty("java.io.tmpdir","/tmp");
String name = thisTime.getClassName();
File f = File.createTempFile(location+File.separator+name, ".class");
StringBuilder debug = new StringBuilder();
debug.append("Debug377096: Dumping class called "+name+" to "+f.getName()+" size:"+thisTime.getBytes().length);
DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
dos.write(thisTime.getBytes());
dos.close();
throw new BCException(debug.toString(), cfe);
}
} catch (Exception e) {
e.printStackTrace();
}
throw new BCException("Unexpected problem processing class", cfe);
}
}
if (lastTime == null) {
recordTypeChanged(thisTime.getClassName());
return;
}
if (newResolvedType.isMissing()) {
return;
}
world.ensureAdvancedConfigurationProcessed();
byte[] newBytes = thisTime.getBytes();
try {
ClassFileReader reader = new ClassFileReader(newBytes, lastTime.getAbsolutePath().toCharArray());
// ignore local types since they're only visible inside a single method
if (!(reader.isLocal() || reader.isAnonymous())) {
if (hasStructuralChanges(reader, existingStructure)) {
if (world.forDEBUG_structuralChangesCode) {
System.err.println("Detected a structural change in " + thisTime.getFilename());
}
structuralChangesSinceLastFullBuild.put(thisTime.getFilename(), new Long(currentBuildTime));
recordTypeChanged(new String(reader.getName()).replace('/', '.'));
}
}
} catch (ClassFormatException e) {
recordTypeChanged(thisTime.getClassName());
}
}
/**
* Compare the class structure of the new intermediate (unwoven) class with the existingResolvedType of the same class that we
* have in the world, looking for any structural differences (and ignoring aj members resulting from weaving....)
*
* Some notes from Andy... lot of problems here, which I've eventually resolved by building the compactstructure based on a
* classfilereader, rather than on a ResolvedType. There are accessors for inner types and funky fields that the compiler
* creates to support the language - for non-static inner types it also mangles ctors to be prefixed with an instance of the
* surrounding type.
*
* @param reader
* @param existingType
* @return
*/
private boolean hasStructuralChanges(ClassFileReader reader, CompactTypeStructureRepresentation existingType) {
if (existingType == null) {
return true;
}
// modifiers
if (!modifiersEqual(reader.getModifiers(), existingType.modifiers)) {
return true;
}
// generic signature
if (!CharOperation.equals(reader.getGenericSignature(), existingType.genericSignature)) {
return true;
}
// superclass name
if (!CharOperation.equals(reader.getSuperclassName(), existingType.superclassName)) {
return true;
}
// have annotations changed on the type?
IBinaryAnnotation[] newAnnos = reader.getAnnotations();
if (newAnnos == null || newAnnos.length == 0) {
if (existingType.annotations != null && existingType.annotations.length != 0) {
return true;
}
} else {
IBinaryAnnotation[] existingAnnos = existingType.annotations;
if (existingAnnos == null || existingAnnos.length != newAnnos.length) {
return true;
}
// Does not allow for an order switch
// Does not cope with a change in values set on the annotation (hard to create a testcase where this is a problem tho)
for (int i = 0; i < newAnnos.length; i++) {
if (!CharOperation.equals(newAnnos[i].getTypeName(), existingAnnos[i].getTypeName())) {
return true;
}
}
}
// interfaces
char[][] existingIfs = existingType.interfaces;
char[][] newIfsAsChars = reader.getInterfaceNames();
if (newIfsAsChars == null) {
newIfsAsChars = EMPTY_CHAR_ARRAY;
} // damn I'm lazy...
if (existingIfs == null) {
existingIfs = EMPTY_CHAR_ARRAY;
}
if (existingIfs.length != newIfsAsChars.length) {
return true;
}
new_interface_loop: for (int i = 0; i < newIfsAsChars.length; i++) {
for (int j = 0; j < existingIfs.length; j++) {
if (CharOperation.equals(existingIfs[j], newIfsAsChars[i])) {
continue new_interface_loop;
}
}
return true;
}
// fields
// CompactMemberStructureRepresentation[] existingFields = existingType.fields;
IBinaryField[] newFields = reader.getFields();
if (newFields == null) {
newFields = CompactTypeStructureRepresentation.NoField;
}
// all redundant for now ... could be an optimization at some point...
// remove any ajc$XXX fields from those we compare with
// the existing fields - bug 129163
// List nonGenFields = new ArrayList();
// for (int i = 0; i < newFields.length; i++) {
// IBinaryField field = newFields[i];
// //if (!CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,field.getName())) { // this would skip ajc$ fields
// //if ((field.getModifiers()&0x1000)==0) // 0x1000 => synthetic - this will skip synthetic fields (eg. this$0)
// nonGenFields.add(field);
// //}
// }
IBinaryField[] existingFs = existingType.binFields;
if (newFields.length != existingFs.length) {
return true;
}
new_field_loop: for (int i = 0; i < newFields.length; i++) {
IBinaryField field = newFields[i];
char[] fieldName = field.getName();
for (int j = 0; j < existingFs.length; j++) {
if (CharOperation.equals(existingFs[j].getName(), fieldName)) {
IBinaryField existing = existingFs[j];
if (!modifiersEqual(field.getModifiers(), existing.getModifiers())) {
return true;
}
if (!CharOperation.equals(existing.getTypeName(), field.getTypeName())) {
return true;
}
char[] existingGSig = existing.getGenericSignature();
char[] fieldGSig = field.getGenericSignature();
if ((existingGSig == null && fieldGSig != null) || (existingGSig != null && fieldGSig == null)) {
return true;
}
if (existingGSig != null) {
if (!CharOperation.equals(existingGSig, fieldGSig)) {
return true;
}
}
continue new_field_loop;
}
}
return true;
}
// methods
// CompactMemberStructureRepresentation[] existingMethods = existingType.methods;
IBinaryMethod[] newMethods = reader.getMethods();
if (newMethods == null) {
newMethods = CompactTypeStructureRepresentation.NoMethod;
}
// all redundant for now ... could be an optimization at some point...
// Ctors in a non-static inner type have an 'extra parameter' of the enclosing type.
// If skippableDescriptorPrefix gets set here then it is set to the descriptor portion
// for this 'extra parameter'. For an inner class of pkg.Foo the skippable descriptor
// prefix will be '(Lpkg/Foo;' - so later when comparing <init> methods we know what to
// compare.
// IF THIS CODE NEEDS TO GET MORE COMPLICATED, I THINK ITS WORTH RIPPING IT ALL OUT AND
// CREATING THE STRUCTURAL CHANGES OBJECT BASED ON CLASSREADER OUTPUT RATHER THAN
// THE RESOLVEDTYPE - THEN THERE WOULD BE NO NEED TO TREAT SOME METHODS IN A PECULIAR
// WAY.
// char[] skippableDescriptorPrefix = null;
// char[] enclosingTypeName = reader.getEnclosingTypeName();
// boolean isStaticType = Modifier.isStatic(reader.getModifiers());
// if (!isStaticType && enclosingTypeName!=null) {
// StringBuffer sb = new StringBuffer();
// sb.append("(L").append(new String(enclosingTypeName)).append(";");
// skippableDescriptorPrefix = sb.toString().toCharArray();
// }
//
//
// // remove the aspectOf, hasAspect, clinit and ajc$XXX methods
// // from those we compare with the existing methods - bug 129163
// List nonGenMethods = new ArrayList();
// for (int i = 0; i < newMethods.length; i++) {
// IBinaryMethod method = newMethods[i];
// // if ((method.getModifiers() & 0x1000)!=0) continue; // 0x1000 => synthetic - will cause us to skip access$0 - is this
// always safe?
// char[] methodName = method.getSelector();
// // if (!CharOperation.equals(methodName,NameMangler.METHOD_ASPECTOF) &&
// // !CharOperation.equals(methodName,NameMangler.METHOD_HASASPECT) &&
// // !CharOperation.equals(methodName,NameMangler.STATIC_INITIALIZER) &&
// // !CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,methodName) &&
// // !CharOperation.prefixEquals(NameMangler.CLINIT,methodName)) {
// nonGenMethods.add(method);
// // }
// }
IBinaryMethod[] existingMs = existingType.binMethods;
if (newMethods.length != existingMs.length) {
return true;
}
new_method_loop: for (int i = 0; i < newMethods.length; i++) {
IBinaryMethod method = newMethods[i];
char[] methodName = method.getSelector();
for (int j = 0; j < existingMs.length; j++) {
if (CharOperation.equals(existingMs[j].getSelector(), methodName)) {
// candidate match
if (!CharOperation.equals(method.getMethodDescriptor(), existingMs[j].getMethodDescriptor())) {
// ok, the descriptors don't match, but is this a funky ctor on a non-static inner
// type?
// boolean mightBeOK =
// skippableDescriptorPrefix!=null && // set for inner types
// CharOperation.equals(methodName,NameMangler.INIT) && // ctor
// CharOperation.prefixEquals(skippableDescriptorPrefix,method.getMethodDescriptor()); // checking for
// prefix on the descriptor
// if (mightBeOK) {
// // OK, so the descriptor starts something like '(Lpkg/Foo;' - we now may need to look at the rest of the
// // descriptor if it takes >1 parameter.
// // eg. could be (Lpkg/C;Ljava/lang/String;) where the skippablePrefix is (Lpkg/C;
// char [] md = method.getMethodDescriptor();
// char[] remainder = CharOperation.subarray(md, skippableDescriptorPrefix.length, md.length);
// if (CharOperation.equals(remainder,BRACKET_V)) continue new_method_loop; // no other parameters to worry
// about
// char[] comparableSig = CharOperation.subarray(existingMethods[j].signature, 1,
// existingMethods[j].signature.length);
// boolean match = CharOperation.equals(comparableSig, remainder);
// if (match) continue new_method_loop;
// }
continue; // might be overloading
} else {
// matching sigs
IBinaryMethod existing = existingMs[j];
if (!modifiersEqual(method.getModifiers(), existing.getModifiers())) {
return true;
}
if (exceptionClausesDiffer(existing, method)) {
return true;
}
char[] existingGSig = existing.getGenericSignature();
char[] methodGSig = method.getGenericSignature();
if ((existingGSig == null && methodGSig != null) || (existingGSig != null && methodGSig == null)) {
return true;
}
if (existingGSig != null) {
if (!CharOperation.equals(existingGSig, methodGSig)) {
return true;
}
}
continue new_method_loop;
}
}
}
return true; // (no match found)
}
// check for differences in inner types
// TODO could make order insensitive
IBinaryNestedType[] binaryNestedTypes = reader.getMemberTypes();
IBinaryNestedType[] existingBinaryNestedTypes = existingType.getMemberTypes();
if ((binaryNestedTypes == null && existingBinaryNestedTypes != null)
|| (binaryNestedTypes != null && existingBinaryNestedTypes == null)) {
return true;
}
if (binaryNestedTypes != null) {
int bnLength = binaryNestedTypes.length;
if (existingBinaryNestedTypes.length != bnLength) {
return true;
}
for (int m = 0; m < bnLength; m++) {
IBinaryNestedType bnt = binaryNestedTypes[m];
IBinaryNestedType existingBnt = existingBinaryNestedTypes[m];
if (!CharOperation.equals(bnt.getName(), existingBnt.getName())) {
return true;
}
}
}
return false;
}
/**
* For two methods, discover if there has been a change in the exception types specified.
*
* @return true if the exception types have changed
*/
private boolean exceptionClausesDiffer(IBinaryMethod lastMethod, IBinaryMethod newMethod) {
char[][] previousExceptionTypeNames = lastMethod.getExceptionTypeNames();
char[][] newExceptionTypeNames = newMethod.getExceptionTypeNames();
int pLength = previousExceptionTypeNames.length;
int nLength = newExceptionTypeNames.length;
if (pLength != nLength) {
return true;
}
if (pLength == 0) {
return false;
}
// TODO could be insensitive to an order change
for (int i = 0; i < pLength; i++) {
if (!CharOperation.equals(previousExceptionTypeNames[i], newExceptionTypeNames[i])) {
return true;
}
}
return false;
}
private boolean modifiersEqual(int eclipseModifiers, int resolvedTypeModifiers) {
resolvedTypeModifiers = resolvedTypeModifiers & ExtraCompilerModifiers.AccJustFlag;
eclipseModifiers = eclipseModifiers & ExtraCompilerModifiers.AccJustFlag;
// if ((eclipseModifiers & CompilerModifiers.AccSuper) != 0) {
// eclipseModifiers -= CompilerModifiers.AccSuper;
// }
return (eclipseModifiers == resolvedTypeModifiers);
}
// 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;
// }
private String stringifySet(Set<?> l) {
StringBuffer sb = new StringBuffer();
sb.append("{");
for (Iterator<?> iter = l.iterator(); iter.hasNext();) {
Object el = iter.next();
sb.append(el);
if (iter.hasNext()) {
sb.append(",");
}
}
sb.append("}");
return sb.toString();
}
protected void addAffectedSourceFiles(Set<File> addTo, Set<File> lastTimeSources) {
if (qualifiedStrings.elementSize == 0 && simpleStrings.elementSize == 0) {
return;
}
if (listenerDefined()) {
getListener().recordDecision(
"Examining whether any other files now need compilation based on just compiling: '"
+ stringifySet(lastTimeSources) + "'");
}
// the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X'
char[][][] qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedStrings);
// if a well known qualified name was found then we can skip over these
if (qualifiedNames.length < qualifiedStrings.elementSize) {
qualifiedNames = null;
}
char[][] simpleNames = ReferenceCollection.internSimpleNames(simpleStrings);
// if a well known name was found then we can skip over these
if (simpleNames.length < simpleStrings.elementSize) {
simpleNames = null;
}
// System.err.println("simple: " + simpleStrings);
// System.err.println("qualif: " + qualifiedStrings);
for (Iterator<Map.Entry<File, ReferenceCollection>> i = references.entrySet().iterator(); i.hasNext();) {
Map.Entry<File, ReferenceCollection> entry = i.next();
ReferenceCollection refs = entry.getValue();
if (refs != null && refs.includes(qualifiedNames, simpleNames)) {
File file = entry.getKey();
if (file.exists()) {
if (!lastTimeSources.contains(file)) { // ??? O(n**2)
if (listenerDefined()) {
getListener().recordDecision("Need to recompile '" + file.getName().toString() + "'");
}
addTo.add(file);
}
}
}
}
// add in the things we compiled previously - I know that seems crap but otherwise we may pull woven
// stuff off disk (since we no longer have UnwovenClassFile objects) in order to satisfy references
// in the new files we are about to compile (see pr133532)
if (addTo.size() > 0) {
addTo.addAll(lastTimeSources);
}
// // XXX Promote addTo to a Set - then we don't need this rubbish? but does it need to be ordered?
// if (addTo.size()>0) {
// for (Iterator iter = lastTimeSources.iterator(); iter.hasNext();) {
// Object element = (Object) iter.next();
// if (!addTo.contains(element)) addTo.add(element);
// }
// }
qualifiedStrings.clear();
simpleStrings.clear();
}
/**
* Record that a particular type has been touched during a compilation run. Information is used to ensure any types depending
* upon this one are also recompiled.
*
* @param typename (possibly qualified) type name
*/
protected void recordTypeChanged(String typename) {
int lastDot = typename.lastIndexOf('.');
String typeName;
if (lastDot != -1) {
String packageName = typename.substring(0, lastDot).replace('.', '/');
qualifiedStrings.add(packageName);
typeName = typename.substring(lastDot + 1);
} else {
qualifiedStrings.add("");
typeName = typename;
}
int memberIndex = typeName.indexOf('$');
if (memberIndex > 0) {
typeName = typeName.substring(0, memberIndex);
}
simpleStrings.add(typeName);
}
/**
* Record some additional dependencies between types. When any of the types specified in fullyQualifiedTypeNames changes, we
* need to recompile the file named in the CompilationResult. This method patches that information into the existing data
* structures.
*/
public boolean recordDependencies(File file, String[] typeNameDependencies) {
try {
File sourceFile = new File(new String(file.getCanonicalPath()));
ReferenceCollection existingCollection = references.get(sourceFile);
if (existingCollection != null) {
existingCollection.addDependencies(typeNameDependencies);
return true;
} else {
ReferenceCollection rc = new ReferenceCollection(null, null, null);
rc.addDependencies(typeNameDependencies);
references.put(sourceFile, rc);
return true;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return false;
}
protected void addDependentsOf(File sourceFile) {
List<ClassFile> cfs = this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile);
if (cfs != null) {
for (ClassFile cf : cfs) {
recordTypeChanged(cf.fullyQualifiedTypeName);
}
}
}
public void setStructureModel(AsmManager structureModel) {
this.structureModel = structureModel;
}
public AsmManager getStructureModel() {
return structureModel;
}
public void setWeaver(BcelWeaver bw) {
weaver = bw;
}
public BcelWeaver getWeaver() {
return weaver;
}
public void setWorld(BcelWorld bw) {
world = bw;
world.addTypeDelegateResolver(this);
}
public BcelWorld getBcelWorld() {
return world;
}
//
// public void setRelationshipMap(IRelationshipMap irm) {
// relmap = irm;
// }
//
// public IRelationshipMap getRelationshipMap() {
// return relmap;
// }
public int getNumberOfStructuralChangesSinceLastFullBuild() {
return structuralChangesSinceLastFullBuild.size();
}
/** Returns last time we did a full or incremental build. */
public long getLastBuildTime() {
return lastSuccessfulBuildTime;
}
/** Returns last time we did a full build */
public long getLastFullBuildTime() {
return lastSuccessfulFullBuildTime;
}
/**
* @return Returns the buildConfig.
*/
public AjBuildConfig getBuildConfig() {
return this.buildConfig;
}
public void clearBinarySourceFiles() {
this.binarySourceFiles = new HashMap<String, List<UnwovenClassFile>>();
}
public void recordBinarySource(String fromPathName, List<UnwovenClassFile> unwovenClassFiles) {
this.binarySourceFiles.put(fromPathName, unwovenClassFiles);
if (this.maybeIncremental()) {
List<ClassFile> simpleClassFiles = new LinkedList<ClassFile>();
for (UnwovenClassFile ucf : unwovenClassFiles) {
ClassFile cf = getClassFileFor(ucf);
simpleClassFiles.add(cf);
}
this.inputClassFilesBySource.put(fromPathName, simpleClassFiles);
}
}
/**
* @param ucf
* @return
*/
private ClassFile getClassFileFor(UnwovenClassFile ucf) {
return new ClassFile(ucf.getClassName(), new File(ucf.getFilename()));
}
public Map<String, List<UnwovenClassFile>> getBinarySourceMap() {
return this.binarySourceFiles;
}
public Map<String, File> getClassNameToFileMap() {
return this.classesFromName;
}
public boolean hasResource(String resourceName) {
return this.resources.keySet().contains(resourceName);
}
public void recordResource(String resourceName, File resourceSourceLocation) {
this.resources.put(resourceName, resourceSourceLocation);
}
/**
* @return Returns the addedFiles.
*/
public Set<File> getAddedFiles() {
return this.addedFiles;
}
/**
* @return Returns the deletedFiles.
*/
public Set<File> getDeletedFiles() {
return this.deletedFiles;
}
public void forceBatchBuildNextTimeAround() {
this.batchBuildRequiredThisTime = true;
}
public boolean requiresFullBatchBuild() {
return this.batchBuildRequiredThisTime;
}
private static class ClassFile {
public String fullyQualifiedTypeName;
public File locationOnDisk;
public ClassFile(String fqn, File location) {
this.fullyQualifiedTypeName = fqn;
this.locationOnDisk = location;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append("ClassFile(type=").append(fullyQualifiedTypeName).append(",location=").append(locationOnDisk).append(")");
return s.toString();
}
public void deleteFromFileSystem(AjBuildConfig buildConfig) {
String namePrefix = locationOnDisk.getName();
namePrefix = namePrefix.substring(0, namePrefix.lastIndexOf('.'));
final String targetPrefix = namePrefix + BcelWeaver.CLOSURE_CLASS_PREFIX;
File dir = locationOnDisk.getParentFile();
if (dir != null) {
File[] weaverGenerated = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(targetPrefix);
}
});
if (weaverGenerated != null) {
for (int i = 0; i < weaverGenerated.length; i++) {
weaverGenerated[i].delete();
if (buildConfig != null && buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileRemove(weaverGenerated[i].getPath(),
CompilationResultDestinationManager.FILETYPE_CLASS);
}
}
}
}
locationOnDisk.delete();
if (buildConfig != null && buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileRemove(locationOnDisk.getPath(),
CompilationResultDestinationManager.FILETYPE_CLASS);
}
}
}
public void wipeAllKnowledge() {
buildManager.state = null;
// buildManager.setStructureModel(null);
}
public Map<String, char[]> getAspectNamesToFileNameMap() {
return aspectsFromFileNames;
}
public void initializeAspectNamesToFileNameMap() {
this.aspectsFromFileNames = new HashMap<String, char[]>();
}
// Will allow us to record decisions made during incremental processing, hopefully aid in debugging
public boolean listenerDefined() {
return stateListener != null;
}
public IStateListener getListener() {
return stateListener;
}
public IBinaryType checkPreviousBuild(String name) {
return resolvedTypeStructuresFromLastBuild.get(name);
}
public AjBuildManager getAjBuildManager() {
return buildManager;
}
public INameEnvironment getNameEnvironment() {
return this.nameEnvironment;
}
public void setNameEnvironment(INameEnvironment nameEnvironment) {
this.nameEnvironment = nameEnvironment;
}
/**
* Record an aspect that came in on the aspect path. When a .class file changes on the aspect path we can then recognize it as
* an aspect and know to do more than just a tiny incremental build. <br>
* TODO but this doesn't allow for a new aspect created on the aspectpath?
*
* @param aspectFile path to the file, eg. c:/temp/foo/Fred.class
*/
public void recordAspectClassFile(String aspectFile) {
aspectClassFiles.add(aspectFile);
}
public void write(CompressingDataOutputStream dos) throws IOException {
// weaver
weaver.write(dos);
// world
// model
// local state
}
/**
* See if we can create a delegate from a CompactTypeStructure - TODO better comment
*/
public ReferenceTypeDelegate getDelegate(ReferenceType referenceType) {
File f = classesFromName.get(referenceType.getName());
if (f == null) {
return null; // not heard of it
}
try {
ClassParser parser = new ClassParser(f.toString());
return world.buildBcelDelegate(referenceType, parser.parse(), true, false);
} catch (IOException e) {
System.err.println("Failed to recover " + referenceType);
e.printStackTrace();
}
return null;
}
}
|
413,378 | Bug 413378 A constructor added by ITD cannot invoke the method of its super class | AspectJ Development Tools 2.2.0.e37x-RELEASE-20120704-0900 It seems *super.someMethod()* can not be correctly resolved in the constructor added by ITD It can be compiled with no problem, but* at runtime, exception is raised.* The class which I'll add a new constructor to: public class Child extends Parent{ public String mParent = "John"; public Child(String parent) { this.mParent = parent; } public String getParent() { return this.mParent; } } As we can see, *Child * extends *Parent* class Parent has a method getAge() public class Parent { private String mName = "John"; private int mAge = 50; public int getAge(){ return mAge; } } If I add a new constructor for the *Child * in my aspect. public aspect MyTest { public Child.new(String parent, int age) { this(parent); System.out.println("Get Age:" + super.getAge()); System.out.println("Child Name:" + this.mParent); } } The above aspect code will trigger an exception. Exception in thread "main" java.lang.NoSuchMethodError: com.test.Child.ajc$superDispatch$com_test_Child$getAge()I at MyTest.ajc$postInterConstructor$MyTest$com_test_Child(MyTest.aj:13) at com.test.Child.<init>(Child.java:1) at MainProgram.main(MainProgram.java:14) Is this a limitation of AspectJ? Is this the only way to resolve this issue? I also attach the src & compiled binary files | resolved fixed | 302c14e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-22T21:50:14Z" | "2013-07-20T06:00:00Z" | tests/bugs174/pr413378/Code.java | |
413,378 | Bug 413378 A constructor added by ITD cannot invoke the method of its super class | AspectJ Development Tools 2.2.0.e37x-RELEASE-20120704-0900 It seems *super.someMethod()* can not be correctly resolved in the constructor added by ITD It can be compiled with no problem, but* at runtime, exception is raised.* The class which I'll add a new constructor to: public class Child extends Parent{ public String mParent = "John"; public Child(String parent) { this.mParent = parent; } public String getParent() { return this.mParent; } } As we can see, *Child * extends *Parent* class Parent has a method getAge() public class Parent { private String mName = "John"; private int mAge = 50; public int getAge(){ return mAge; } } If I add a new constructor for the *Child * in my aspect. public aspect MyTest { public Child.new(String parent, int age) { this(parent); System.out.println("Get Age:" + super.getAge()); System.out.println("Child Name:" + this.mParent); } } The above aspect code will trigger an exception. Exception in thread "main" java.lang.NoSuchMethodError: com.test.Child.ajc$superDispatch$com_test_Child$getAge()I at MyTest.ajc$postInterConstructor$MyTest$com_test_Child(MyTest.aj:13) at com.test.Child.<init>(Child.java:1) at MainProgram.main(MainProgram.java:14) Is this a limitation of AspectJ? Is this the only way to resolve this issue? I also attach the src & compiled binary files | resolved fixed | 302c14e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-22T21:50:14Z" | "2013-07-20T06:00:00Z" | tests/src/org/aspectj/systemtest/AllTests17.java | /*
* Created on 19-01-2005
*/
package org.aspectj.systemtest;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.aspectj.systemtest.ajc170.AllTestsAspectJ170;
import org.aspectj.systemtest.ajc171.AllTestsAspectJ171;
import org.aspectj.systemtest.ajc172.AllTestsAspectJ172;
import org.aspectj.systemtest.ajc173.AllTestsAspectJ173;
public class AllTests17 {
public static Test suite() {
TestSuite suite = new TestSuite("AspectJ System Test Suite - 1.7");
// $JUnit-BEGIN$
suite.addTest(AllTestsAspectJ173.suite());
suite.addTest(AllTestsAspectJ172.suite());
suite.addTest(AllTestsAspectJ171.suite());
suite.addTest(AllTestsAspectJ170.suite());
suite.addTest(AllTests16.suite());
suite.addTest(AllTests15.suite());
// $JUnit-END$
return suite;
}
}
|
413,378 | Bug 413378 A constructor added by ITD cannot invoke the method of its super class | AspectJ Development Tools 2.2.0.e37x-RELEASE-20120704-0900 It seems *super.someMethod()* can not be correctly resolved in the constructor added by ITD It can be compiled with no problem, but* at runtime, exception is raised.* The class which I'll add a new constructor to: public class Child extends Parent{ public String mParent = "John"; public Child(String parent) { this.mParent = parent; } public String getParent() { return this.mParent; } } As we can see, *Child * extends *Parent* class Parent has a method getAge() public class Parent { private String mName = "John"; private int mAge = 50; public int getAge(){ return mAge; } } If I add a new constructor for the *Child * in my aspect. public aspect MyTest { public Child.new(String parent, int age) { this(parent); System.out.println("Get Age:" + super.getAge()); System.out.println("Child Name:" + this.mParent); } } The above aspect code will trigger an exception. Exception in thread "main" java.lang.NoSuchMethodError: com.test.Child.ajc$superDispatch$com_test_Child$getAge()I at MyTest.ajc$postInterConstructor$MyTest$com_test_Child(MyTest.aj:13) at com.test.Child.<init>(Child.java:1) at MainProgram.main(MainProgram.java:14) Is this a limitation of AspectJ? Is this the only way to resolve this issue? I also attach the src & compiled binary files | resolved fixed | 302c14e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-22T21:50:14Z" | "2013-07-20T06:00:00Z" | tests/src/org/aspectj/systemtest/ajc174/Ajc174Tests.java | |
413,378 | Bug 413378 A constructor added by ITD cannot invoke the method of its super class | AspectJ Development Tools 2.2.0.e37x-RELEASE-20120704-0900 It seems *super.someMethod()* can not be correctly resolved in the constructor added by ITD It can be compiled with no problem, but* at runtime, exception is raised.* The class which I'll add a new constructor to: public class Child extends Parent{ public String mParent = "John"; public Child(String parent) { this.mParent = parent; } public String getParent() { return this.mParent; } } As we can see, *Child * extends *Parent* class Parent has a method getAge() public class Parent { private String mName = "John"; private int mAge = 50; public int getAge(){ return mAge; } } If I add a new constructor for the *Child * in my aspect. public aspect MyTest { public Child.new(String parent, int age) { this(parent); System.out.println("Get Age:" + super.getAge()); System.out.println("Child Name:" + this.mParent); } } The above aspect code will trigger an exception. Exception in thread "main" java.lang.NoSuchMethodError: com.test.Child.ajc$superDispatch$com_test_Child$getAge()I at MyTest.ajc$postInterConstructor$MyTest$com_test_Child(MyTest.aj:13) at com.test.Child.<init>(Child.java:1) at MainProgram.main(MainProgram.java:14) Is this a limitation of AspectJ? Is this the only way to resolve this issue? I also attach the src & compiled binary files | resolved fixed | 302c14e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-22T21:50:14Z" | "2013-07-20T06:00:00Z" | tests/src/org/aspectj/systemtest/ajc174/AllTestsAspectJ174.java | |
413,378 | Bug 413378 A constructor added by ITD cannot invoke the method of its super class | AspectJ Development Tools 2.2.0.e37x-RELEASE-20120704-0900 It seems *super.someMethod()* can not be correctly resolved in the constructor added by ITD It can be compiled with no problem, but* at runtime, exception is raised.* The class which I'll add a new constructor to: public class Child extends Parent{ public String mParent = "John"; public Child(String parent) { this.mParent = parent; } public String getParent() { return this.mParent; } } As we can see, *Child * extends *Parent* class Parent has a method getAge() public class Parent { private String mName = "John"; private int mAge = 50; public int getAge(){ return mAge; } } If I add a new constructor for the *Child * in my aspect. public aspect MyTest { public Child.new(String parent, int age) { this(parent); System.out.println("Get Age:" + super.getAge()); System.out.println("Child Name:" + this.mParent); } } The above aspect code will trigger an exception. Exception in thread "main" java.lang.NoSuchMethodError: com.test.Child.ajc$superDispatch$com_test_Child$getAge()I at MyTest.ajc$postInterConstructor$MyTest$com_test_Child(MyTest.aj:13) at com.test.Child.<init>(Child.java:1) at MainProgram.main(MainProgram.java:14) Is this a limitation of AspectJ? Is this the only way to resolve this issue? I also attach the src & compiled binary files | resolved fixed | 302c14e | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-22T21:50:14Z" | "2013-07-20T06:00:00Z" | weaver/src/org/aspectj/weaver/bcel/BcelTypeMunger.java | /* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur @AspectJ ITDs
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
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.ClassFormatException;
import org.aspectj.apache.bcel.classfile.ConstantPool;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
import org.aspectj.apache.bcel.generic.FieldGen;
import org.aspectj.apache.bcel.generic.InstructionBranch;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AnnotationAJ;
import org.aspectj.weaver.AnnotationOnTypeMunger;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MemberUtils;
import org.aspectj.weaver.MethodDelegateTypeMunger;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMemberClassTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.PerObjectInterfaceTypeMunger;
import org.aspectj.weaver.PrivilegedAccessMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.model.AsmRelationshipProvider;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.Pointcut;
public class BcelTypeMunger extends ConcreteTypeMunger {
public BcelTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType) {
super(munger, aspectType);
}
@Override
public String toString() {
return "(BcelTypeMunger " + getMunger() + ")";
}
@Override
public boolean shouldOverwrite() {
return false;
}
public boolean munge(BcelClassWeaver weaver) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.MUNGING_WITH, this);
boolean changed = false;
boolean worthReporting = true;
if (weaver.getWorld().isOverWeaving()) {
WeaverStateInfo typeWeaverState = weaver.getLazyClassGen().getType().getWeaverState();
if (typeWeaverState != null && typeWeaverState.isAspectAlreadyApplied(getAspectType())) {
return false;
}
}
if (munger.getKind() == ResolvedTypeMunger.Field) {
changed = mungeNewField(weaver, (NewFieldTypeMunger) munger);
} else if (munger.getKind() == ResolvedTypeMunger.Method) {
changed = mungeNewMethod(weaver, (NewMethodTypeMunger) munger);
} else if (munger.getKind() == ResolvedTypeMunger.InnerClass) {
changed = mungeNewMemberType(weaver, (NewMemberClassTypeMunger) munger);
} else if (munger.getKind() == ResolvedTypeMunger.MethodDelegate2) {
changed = mungeMethodDelegate(weaver, (MethodDelegateTypeMunger) munger);
} else if (munger.getKind() == ResolvedTypeMunger.FieldHost) {
changed = mungeFieldHost(weaver, (MethodDelegateTypeMunger.FieldHostTypeMunger) munger);
} else if (munger.getKind() == ResolvedTypeMunger.PerObjectInterface) {
changed = mungePerObjectInterface(weaver, (PerObjectInterfaceTypeMunger) munger);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.PerTypeWithinInterface) {
// PTWIMPL Transform the target type (add the aspect instance field)
changed = mungePerTypeWithinTransformer(weaver);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.PrivilegedAccess) {
changed = mungePrivilegedAccess(weaver, (PrivilegedAccessMunger) munger);
worthReporting = false;
} else if (munger.getKind() == ResolvedTypeMunger.Constructor) {
changed = mungeNewConstructor(weaver, (NewConstructorTypeMunger) munger);
} else if (munger.getKind() == ResolvedTypeMunger.Parent) {
changed = mungeNewParent(weaver, (NewParentTypeMunger) munger);
} else if (munger.getKind() == ResolvedTypeMunger.AnnotationOnType) {
changed = mungeNewAnnotationOnType(weaver, (AnnotationOnTypeMunger) munger);
worthReporting = false;
} else {
throw new RuntimeException("unimplemented");
}
if (changed && munger.changesPublicSignature()) {
WeaverStateInfo info = weaver.getLazyClassGen().getOrCreateWeaverStateInfo(weaver.getReweavableMode());
info.addConcreteMunger(this);
}
if (changed && worthReporting) {
ResolvedType declaringAspect = null;
AsmManager model = ((BcelWorld) getWorld()).getModelAsAsmManager();
if (model != null) {
if (munger instanceof NewParentTypeMunger) {
NewParentTypeMunger nptMunger = (NewParentTypeMunger) munger;
declaringAspect = nptMunger.getDeclaringType();
if (declaringAspect.isParameterizedOrGenericType()) {
declaringAspect = declaringAspect.getRawType();
}
ResolvedType thisAspect = getAspectType();
AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, thisAspect);
// Add a relationship on the actual declaring aspect too
if (!thisAspect.equals(declaringAspect)) {
// Might be the case the declaring aspect is generic and thisAspect is parameterizing it. In that case
// record the actual parameterizations
ResolvedType target = weaver.getLazyClassGen().getType();
ResolvedType newParent = nptMunger.getNewParent();
IProgramElement thisAspectNode = model.getHierarchy().findElementForType(thisAspect.getPackageName(),
thisAspect.getClassName());
Map<String, List<String>> declareParentsMap = thisAspectNode.getDeclareParentsMap();
if (declareParentsMap == null) {
declareParentsMap = new HashMap<String, List<String>>();
thisAspectNode.setDeclareParentsMap(declareParentsMap);
}
String tname = target.getName();
String pname = newParent.getName();
List<String> newparents = declareParentsMap.get(tname);
if (newparents == null) {
newparents = new ArrayList<String>();
declareParentsMap.put(tname, newparents);
}
newparents.add(pname);
AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, declaringAspect);
}
} else {
declaringAspect = getAspectType();
AsmRelationshipProvider.addRelationship(model, weaver.getLazyClassGen().getType(), munger, declaringAspect);
}
}
}
// TAG: WeavingMessage
if (changed && worthReporting && munger != null && !weaver.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
String tName = weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getName();
if (tName.indexOf("no debug info available") != -1) {
tName = "no debug info available";
} else {
tName = getShortname(weaver.getLazyClassGen().getType().getSourceLocation().getSourceFile().getPath());
}
String fName = getShortname(getAspectType().getSourceLocation().getSourceFile().getPath());
if (munger.getKind().equals(ResolvedTypeMunger.Parent)) {
// This message could come out of AjLookupEnvironment.addParent
// if doing parents munging at compile time only...
NewParentTypeMunger parentTM = (NewParentTypeMunger) munger;
if (parentTM.isMixin()) {
weaver.getWorld()
.getMessageHandler()
.handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_MIXIN, new String[] {
parentTM.getNewParent().getName(), fName, weaver.getLazyClassGen().getType().getName(),
tName }, weaver.getLazyClassGen().getClassName(), getAspectType().getName()));
} else {
if (parentTM.getNewParent().isInterface()) {
weaver.getWorld()
.getMessageHandler()
.handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,
new String[] { weaver.getLazyClassGen().getType().getName(), tName,
parentTM.getNewParent().getName(), fName }, weaver.getLazyClassGen()
.getClassName(), getAspectType().getName()));
} else {
weaver.getWorld()
.getMessageHandler()
.handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,
new String[] { weaver.getLazyClassGen().getType().getName(), tName,
parentTM.getNewParent().getName(), fName }));
// TAG: WeavingMessage DECLARE PARENTS: EXTENDS
// reportDeclareParentsMessage(WeaveMessage.
// WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent);
}
}
} else if (munger.getKind().equals(ResolvedTypeMunger.FieldHost)) {
// hidden
} else {
ResolvedMember declaredSig = munger.getSignature();
String fromString = fName + ":'" + declaredSig + "'";
// if (declaredSig==null) declaredSig= munger.getSignature();
String kindString = munger.getKind().toString().toLowerCase();
if (kindString.equals("innerclass")) {
kindString = "member class";
fromString = fName;
}
weaver.getWorld()
.getMessageHandler()
.handleMessage(
WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ITD, new String[] {
weaver.getLazyClassGen().getType().getName(), tName, kindString, getAspectType().getName(),
fromString }, weaver.getLazyClassGen().getClassName(), getAspectType().getName()));
}
}
CompilationAndWeavingContext.leavingPhase(tok);
return changed;
}
private String getShortname(String path) {
int takefrom = path.lastIndexOf('/');
if (takefrom == -1) {
takefrom = path.lastIndexOf('\\');
}
return path.substring(takefrom + 1);
}
private boolean mungeNewAnnotationOnType(BcelClassWeaver weaver, AnnotationOnTypeMunger munger) {
// FIXME asc this has already been done up front, need to do it here too?
try {
BcelAnnotation anno = (BcelAnnotation) munger.getNewAnnotation();
weaver.getLazyClassGen().addAnnotation(anno.getBcelAnnotation());
} catch (ClassCastException cce) {
throw new IllegalStateException("DiagnosticsFor318237: The typemunger "+munger+" contains an annotation of type "+
munger.getNewAnnotation().getClass().getName()+" when it should be a BcelAnnotation",cce);
}
return true;
}
/**
* For a long time, AspectJ did not allow binary weaving of declare parents. This restriction is now lifted but could do with
* more testing!
*/
private boolean mungeNewParent(BcelClassWeaver weaver, NewParentTypeMunger typeTransformer) {
LazyClassGen newParentTarget = weaver.getLazyClassGen();
ResolvedType newParent = typeTransformer.getNewParent();
boolean performChange = true;
performChange = enforceDecpRule1_abstractMethodsImplemented(weaver, typeTransformer.getSourceLocation(), newParentTarget,
newParent);
performChange = enforceDecpRule2_cantExtendFinalClass(weaver, typeTransformer.getSourceLocation(), newParentTarget,
newParent) && performChange;
List<ResolvedMember> methods = newParent.getMethodsWithoutIterator(false, true, false);
for (ResolvedMember method : methods) {
if (!method.getName().equals("<init>")) {
LazyMethodGen subMethod = findMatchingMethod(newParentTarget, method);
// FIXME asc is this safe for all bridge methods?
if (subMethod != null && !subMethod.isBridgeMethod()) {
if (!(subMethod.isSynthetic() && method.isSynthetic())) {
if (!(subMethod.isStatic() && subMethod.getName().startsWith("access$"))) {
// ignore generated accessors
performChange = enforceDecpRule3_visibilityChanges(weaver, newParent, method, subMethod)
&& performChange;
performChange = enforceDecpRule4_compatibleReturnTypes(weaver, method, subMethod) && performChange;
performChange = enforceDecpRule5_cantChangeFromStaticToNonstatic(weaver,
typeTransformer.getSourceLocation(), method, subMethod)
&& performChange;
}
}
}
}
}
if (!performChange) {
// A rule was violated and an error message already reported
return false;
}
if (newParent.isClass()) {
// Changing the supertype
if (!attemptToModifySuperCalls(weaver, newParentTarget, newParent)) {
return false;
}
newParentTarget.setSuperClass(newParent);
} else {
// Add a new interface
newParentTarget.addInterface(newParent, getSourceLocation());
}
return true;
}
/**
* Rule 1: For the declare parents to be allowed, the target type must override and implement inherited abstract methods (if the
* type is not declared abstract)
*/
private boolean enforceDecpRule1_abstractMethodsImplemented(BcelClassWeaver weaver, ISourceLocation mungerLoc,
LazyClassGen newParentTarget, ResolvedType newParent) {
// Ignore abstract classes or interfaces
if (newParentTarget.isAbstract() || newParentTarget.isInterface()) {
return true;
}
boolean ruleCheckingSucceeded = true;
List<ResolvedMember> newParentMethods = newParent.getMethodsWithoutIterator(false, true, false);
for (ResolvedMember newParentMethod : newParentMethods) {
String newParentMethodName = newParentMethod.getName();
// Ignore abstract ajc$interField prefixed methods
if (newParentMethod.isAbstract() && !newParentMethodName.startsWith("ajc$interField")) {
ResolvedMember discoveredImpl = null;
List<ResolvedMember> targetMethods = newParentTarget.getType().getMethodsWithoutIterator(false, true, false);
for (ResolvedMember targetMethod : targetMethods) {
if (!targetMethod.isAbstract() && targetMethod.getName().equals(newParentMethodName)) {
String newParentMethodSig = newParentMethod.getParameterSignature(); // ([TT;)
String targetMethodSignature = targetMethod.getParameterSignature(); // ([Ljava/lang/Object;)
// could be a match
if (targetMethodSignature.equals(newParentMethodSig)) {
discoveredImpl = targetMethod;
} else {
// Does the erasure match? In which case a bridge method will be created later to
// satisfy the abstract method
if (targetMethod.hasBackingGenericMember()
&& targetMethod.getBackingGenericMember().getParameterSignature().equals(newParentMethodSig)) {
discoveredImpl = targetMethod;
} else if (newParentMethod.hasBackingGenericMember()) {
if (newParentMethod.getBackingGenericMember().getParameterSignature().equals(targetMethodSignature)) {
discoveredImpl = targetMethod;
}
}
}
if (discoveredImpl != null) {
break;
}
}
}
if (discoveredImpl == null) {
// didnt find a valid implementation, lets check the
// ITDs on this type to see if they satisfy it
boolean satisfiedByITD = false;
for (ConcreteTypeMunger m : newParentTarget.getType().getInterTypeMungersIncludingSupers()) {
if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.Method) {
ResolvedMember sig = m.getSignature();
if (!Modifier.isAbstract(sig.getModifiers())) {
// If the ITD shares a type variable with some target type, we need to tailor it
// for that type
if (m.isTargetTypeParameterized()) {
ResolvedType genericOnType = getWorld().resolve(sig.getDeclaringType()).getGenericType();
m = m.parameterizedFor(newParent.discoverActualOccurrenceOfTypeInHierarchy(genericOnType));
// possible sig change when type parameters filled in
sig = m.getSignature();
}
if (ResolvedType.matches(
AjcMemberMaker.interMethod(sig, m.getAspectType(),
sig.getDeclaringType().resolve(weaver.getWorld()).isInterface()), newParentMethod)) {
satisfiedByITD = true;
}
}
} else if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate2) {
// AV - that should be enough, no need to check more
satisfiedByITD = true;
}
}
if (!satisfiedByITD) {
error(weaver,
"The type " + newParentTarget.getName() + " must implement the inherited abstract method "
+ newParentMethod.getDeclaringType() + "." + newParentMethodName
+ newParentMethod.getParameterSignature(), newParentTarget.getType().getSourceLocation(),
new ISourceLocation[] { newParentMethod.getSourceLocation(), mungerLoc });
ruleCheckingSucceeded = false;
}
}
}
}
return ruleCheckingSucceeded;
}
/**
* Rule 2. Can't extend final types
*/
private boolean enforceDecpRule2_cantExtendFinalClass(BcelClassWeaver weaver, ISourceLocation transformerLoc,
LazyClassGen targetType, ResolvedType newParent) {
if (newParent.isFinal()) {
error(weaver, "Cannot make type " + targetType.getName() + " extend final class " + newParent.getName(), targetType
.getType().getSourceLocation(), new ISourceLocation[] { transformerLoc });
return false;
}
return true;
}
/**
* Rule 3. Can't narrow visibility of methods when overriding
*/
private boolean enforceDecpRule3_visibilityChanges(BcelClassWeaver weaver, ResolvedType newParent, ResolvedMember superMethod,
LazyMethodGen subMethod) {
boolean cont = true;
if (Modifier.isPublic(superMethod.getModifiers())) {
if (subMethod.isProtected() || subMethod.isDefault() || subMethod.isPrivate()) {
weaver.getWorld()
.getMessageHandler()
.handleMessage(
MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod
+ "' from " + newParent.getName(), superMethod.getSourceLocation()));
cont = false;
}
} else if (Modifier.isProtected(superMethod.getModifiers())) {
if (subMethod.isDefault() || subMethod.isPrivate()) {
weaver.getWorld()
.getMessageHandler()
.handleMessage(
MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod
+ "' from " + newParent.getName(), superMethod.getSourceLocation()));
cont = false;
}
} else if (superMethod.isDefault()) {
if (subMethod.isPrivate()) {
weaver.getWorld()
.getMessageHandler()
.handleMessage(
MessageUtil.error("Cannot reduce the visibility of the inherited method '" + superMethod
+ "' from " + newParent.getName(), superMethod.getSourceLocation()));
cont = false;
}
}
return cont;
}
/**
* Rule 4. Can't have incompatible return types
*/
private boolean enforceDecpRule4_compatibleReturnTypes(BcelClassWeaver weaver, ResolvedMember superMethod,
LazyMethodGen subMethod) {
boolean cont = true;
String superReturnTypeSig = superMethod.getGenericReturnType().getSignature(); // eg. Pjava/util/Collection<LFoo;>
String subReturnTypeSig = subMethod.getGenericReturnTypeSignature();
superReturnTypeSig = superReturnTypeSig.replace('.', '/');
subReturnTypeSig = subReturnTypeSig.replace('.', '/');
if (!superReturnTypeSig.equals(subReturnTypeSig)) {
// Check for covariance
ResolvedType subType = weaver.getWorld().resolve(subMethod.getReturnType());
ResolvedType superType = weaver.getWorld().resolve(superMethod.getReturnType());
if (!superType.isAssignableFrom(subType)) {
weaver.getWorld()
.getMessageHandler()
.handleMessage(
MessageUtil.error("The return type is incompatible with " + superMethod.getDeclaringType() + "."
+ superMethod.getName() + superMethod.getParameterSignature(),
subMethod.getSourceLocation()));
// this just might be a better error message...
// "The return type '"+subReturnTypeSig+
// "' is incompatible with the overridden method "
// +superMethod.getDeclaringType()+"."+
// superMethod.getName()+superMethod.getParameterSignature()+
// " which returns '"+superReturnTypeSig+"'",
cont = false;
}
}
return cont;
}
/**
* Rule5. Method overrides can't change the staticality (word?) - you can't override and make an instance method static or
* override and make a static method an instance method.
*/
private boolean enforceDecpRule5_cantChangeFromStaticToNonstatic(BcelClassWeaver weaver, ISourceLocation mungerLoc,
ResolvedMember superMethod, LazyMethodGen subMethod) {
boolean superMethodStatic = Modifier.isStatic(superMethod.getModifiers());
if (superMethodStatic && !subMethod.isStatic()) {
error(weaver, "This instance method " + subMethod.getName() + subMethod.getParameterSignature()
+ " cannot override the static method from " + superMethod.getDeclaringType().getName(),
subMethod.getSourceLocation(), new ISourceLocation[] { mungerLoc });
return false;
} else if (!superMethodStatic && subMethod.isStatic()) {
error(weaver, "The static method " + subMethod.getName() + subMethod.getParameterSignature()
+ " cannot hide the instance method from " + superMethod.getDeclaringType().getName(),
subMethod.getSourceLocation(), new ISourceLocation[] { mungerLoc });
return false;
}
return true;
}
public void error(BcelClassWeaver weaver, String text, ISourceLocation primaryLoc, ISourceLocation[] extraLocs) {
IMessage msg = new Message(text, primaryLoc, true, extraLocs);
weaver.getWorld().getMessageHandler().handleMessage(msg);
}
/**
* Search the specified type for a particular method - do not use the return value in the comparison as it is not considered for
* overriding.
*/
private LazyMethodGen findMatchingMethod(LazyClassGen type, ResolvedMember searchMethod) {
String searchName = searchMethod.getName();
String searchSig = searchMethod.getParameterSignature();
for (LazyMethodGen method : type.getMethodGens()) {
if (method.getName().equals(searchName) && method.getParameterSignature().equals(searchSig)) {
return method;
}
}
return null;
}
/**
* The main part of implementing declare parents extends. Modify super ctor calls to target the new type.
*/
public boolean attemptToModifySuperCalls(BcelClassWeaver weaver, LazyClassGen newParentTarget, ResolvedType newParent) {
ResolvedType currentParentType = newParentTarget.getSuperClass();
if (currentParentType.getGenericType() != null) {
currentParentType = currentParentType.getGenericType();
}
String currentParent = currentParentType.getName();
if (newParent.getGenericType() != null) {
newParent = newParent.getGenericType(); // target new super calls at
}
// the generic type if its raw or parameterized
List<LazyMethodGen> mgs = newParentTarget.getMethodGens();
// Look for ctors to modify
for (LazyMethodGen aMethod : mgs) {
if (LazyMethodGen.isConstructor(aMethod)) {
InstructionList insList = aMethod.getBody();
InstructionHandle handle = insList.getStart();
while (handle != null) {
if (handle.getInstruction().opcode == Constants.INVOKESPECIAL) {
ConstantPool cpg = newParentTarget.getConstantPool();
InvokeInstruction invokeSpecial = (InvokeInstruction) handle.getInstruction();
if (invokeSpecial.getClassName(cpg).equals(currentParent)
&& invokeSpecial.getMethodName(cpg).equals("<init>")) {
// System.err.println("Transforming super call '<init>" + invokeSpecial.getSignature(cpg) + "'");
// 1. Check there is a ctor in the new parent with
// the same signature
ResolvedMember newCtor = getConstructorWithSignature(newParent, invokeSpecial.getSignature(cpg));
if (newCtor == null) {
// 2. Check ITDCs to see if the necessary ctor is provided that way
boolean satisfiedByITDC = false;
for (Iterator<ConcreteTypeMunger> ii = newParentTarget.getType()
.getInterTypeMungersIncludingSupers().iterator(); ii.hasNext() && !satisfiedByITDC;) {
ConcreteTypeMunger m = ii.next();
if (m.getMunger() instanceof NewConstructorTypeMunger) {
if (m.getSignature().getSignature().equals(invokeSpecial.getSignature(cpg))) {
satisfiedByITDC = true;
}
}
}
if (!satisfiedByITDC) {
String csig = createReadableCtorSig(newParent, cpg, invokeSpecial);
weaver.getWorld()
.getMessageHandler()
.handleMessage(
MessageUtil.error(
"Unable to modify hierarchy for " + newParentTarget.getClassName()
+ " - the constructor " + csig + " is missing",
this.getSourceLocation()));
return false;
}
}
int idx = cpg.addMethodref(newParent.getName(), invokeSpecial.getMethodName(cpg),
invokeSpecial.getSignature(cpg));
invokeSpecial.setIndex(idx);
}
}
handle = handle.getNext();
}
}
}
return true;
}
/**
* Creates a nice signature for the ctor, something like "(int,Integer,String)"
*/
private String createReadableCtorSig(ResolvedType newParent, ConstantPool cpg, InvokeInstruction invokeSpecial) {
StringBuffer sb = new StringBuffer();
Type[] ctorArgs = invokeSpecial.getArgumentTypes(cpg);
sb.append(newParent.getClassName());
sb.append("(");
for (int i = 0; i < ctorArgs.length; i++) {
String argtype = ctorArgs[i].toString();
if (argtype.lastIndexOf(".") != -1) {
sb.append(argtype.substring(argtype.lastIndexOf(".") + 1));
} else {
sb.append(argtype);
}
if (i + 1 < ctorArgs.length) {
sb.append(",");
}
}
sb.append(")");
return sb.toString();
}
private ResolvedMember getConstructorWithSignature(ResolvedType type, String searchSig) {
for (ResolvedMember method : type.getDeclaredJavaMethods()) {
if (MemberUtils.isConstructor(method)) {
if (method.getSignature().equals(searchSig)) {
return method;
}
}
}
return null;
}
private boolean mungePrivilegedAccess(BcelClassWeaver weaver, PrivilegedAccessMunger munger) {
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedMember member = munger.getMember();
ResolvedType onType = weaver.getWorld().resolve(member.getDeclaringType(), munger.getSourceLocation());
if (onType.isRawType()) {
onType = onType.getGenericType();
}
// System.out.println("munging: " + gen + " with " + member);
if (onType.equals(gen.getType())) {
if (member.getKind() == Member.FIELD) {
// System.out.println("matched: " + gen);
addFieldGetter(gen, member,
AjcMemberMaker.privilegedAccessMethodForFieldGet(aspectType, member, munger.shortSyntax));
addFieldSetter(gen, member,
AjcMemberMaker.privilegedAccessMethodForFieldSet(aspectType, member, munger.shortSyntax));
return true;
} else if (member.getKind() == Member.METHOD) {
addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member));
return true;
} else if (member.getKind() == Member.CONSTRUCTOR) {
for (Iterator<LazyMethodGen> i = gen.getMethodGens().iterator(); i.hasNext();) {
LazyMethodGen m = i.next();
if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) {
// m.getMemberView().equals(member)) {
m.forcePublic();
// return true;
}
}
return true;
// throw new BCException("no match for " + member + " in " +
// gen);
} else if (member.getKind() == Member.STATIC_INITIALIZATION) {
gen.forcePublic();
return true;
} else {
throw new RuntimeException("unimplemented");
}
}
return false;
}
private void addFieldGetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) {
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
if (Modifier.isStatic(field.getModifiers())) {
il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()),
Constants.GETSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), BcelWorld.makeBcelType(field.getType()),
Constants.GETFIELD));
}
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(field.getType())));
mg.getBody().insert(il);
gen.addMethodGen(mg, getSignature().getSourceLocation());
}
private void addFieldSetter(LazyClassGen gen, ResolvedMember field, ResolvedMember accessMethod) {
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
Type fieldType = BcelWorld.makeBcelType(field.getType());
if (Modifier.isStatic(field.getModifiers())) {
il.append(InstructionFactory.createLoad(fieldType, 0));
il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(InstructionFactory.createLoad(fieldType, 1));
il.append(fact.createFieldAccess(gen.getClassName(), field.getName(), fieldType, Constants.PUTFIELD));
}
il.append(InstructionFactory.createReturn(Type.VOID));
mg.getBody().insert(il);
gen.addMethodGen(mg, getSignature().getSourceLocation());
}
private void addMethodDispatch(LazyClassGen gen, ResolvedMember method, ResolvedMember accessMethod) {
LazyMethodGen mg = makeMethodGen(gen, accessMethod);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
Type[] paramTypes = BcelWorld.makeBcelTypes(method.getParameterTypes());
int pos = 0;
if (!Modifier.isStatic(method.getModifiers())) {
il.append(InstructionConstants.ALOAD_0);
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
il.append(InstructionFactory.createLoad(paramType, pos));
pos += paramType.getSize();
}
il.append(Utility.createInvoke(fact, (BcelWorld) aspectType.getWorld(), method));
il.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(method.getReturnType())));
mg.getBody().insert(il);
gen.addMethodGen(mg);
}
protected LazyMethodGen makeMethodGen(LazyClassGen gen, ResolvedMember member) {
try {
Type returnType = BcelWorld.makeBcelType(member.getReturnType());
Type[] parameterTypes = BcelWorld.makeBcelTypes(member.getParameterTypes());
LazyMethodGen ret = new LazyMethodGen(member.getModifiers(), returnType,
member.getName(), parameterTypes, UnresolvedType.getNames(member
.getExceptions()), gen);
// 43972 : Static crosscutting makes interfaces unusable for javac
// ret.makeSynthetic();
return ret;
} catch (ClassFormatException cfe) {
throw new RuntimeException("Problem with makeMethodGen for method "+member.getName()+" in type "+gen.getName()+" ret="+member.getReturnType(),cfe);
}
}
protected FieldGen makeFieldGen(LazyClassGen gen, ResolvedMember member) {
return new FieldGen(member.getModifiers(), BcelWorld.makeBcelType(member.getReturnType()), member.getName(),
gen.getConstantPool());
}
private boolean mungePerObjectInterface(BcelClassWeaver weaver, PerObjectInterfaceTypeMunger munger) {
// System.err.println("Munging perobject ["+munger+"] onto "+weaver.
// getLazyClassGen().getClassName());
LazyClassGen gen = weaver.getLazyClassGen();
if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) {
FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perObjectField(gen.getType(), aspectType));
gen.addField(fg, getSourceLocation());
Type fieldType = BcelWorld.makeBcelType(aspectType);
LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC, fieldType, NameMangler.perObjectInterfaceGet(aspectType),
new Type[0], new String[0], gen);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETFIELD));
il.append(InstructionFactory.createReturn(fieldType));
mg.getBody().insert(il);
gen.addMethodGen(mg);
LazyMethodGen mg1 = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, NameMangler.perObjectInterfaceSet(aspectType),
new Type[] { fieldType, }, new String[0], gen);
InstructionList il1 = new InstructionList();
il1.append(InstructionConstants.ALOAD_0);
il1.append(InstructionFactory.createLoad(fieldType, 1));
il1.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.PUTFIELD));
il1.append(InstructionFactory.createReturn(Type.VOID));
mg1.getBody().insert(il1);
gen.addMethodGen(mg1);
gen.addInterface(munger.getInterfaceType().resolve(weaver.getWorld()), getSourceLocation());
return true;
} else {
return false;
}
}
// PTWIMPL Add field to hold aspect instance and an accessor
private boolean mungePerTypeWithinTransformer(BcelClassWeaver weaver) {
LazyClassGen gen = weaver.getLazyClassGen();
// if (couldMatch(gen.getBcelObjectType(), munger.getTestPointcut())) {
// Add (to the target type) the field that will hold the aspect instance
// e.g ajc$com_blah_SecurityAspect$ptwAspectInstance
FieldGen fg = makeFieldGen(gen, AjcMemberMaker.perTypeWithinField(gen.getType(), aspectType));
gen.addField(fg, getSourceLocation());
// Add an accessor for this new field, the
// ajc$<aspectname>$localAspectOf() method
// e.g.
// "public com_blah_SecurityAspect ajc$com_blah_SecurityAspect$localAspectOf()"
Type fieldType = BcelWorld.makeBcelType(aspectType);
LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC | Modifier.STATIC, fieldType,
NameMangler.perTypeWithinLocalAspectOf(aspectType), new Type[0], new String[0], gen);
InstructionList il = new InstructionList();
// PTWIMPL ?? Should check if it is null and throw
// NoAspectBoundException
InstructionFactory fact = gen.getFactory();
il.append(fact.createFieldAccess(gen.getClassName(), fg.getName(), fieldType, Constants.GETSTATIC));
il.append(InstructionFactory.createReturn(fieldType));
mg.getBody().insert(il);
gen.addMethodGen(mg);
return true;
// } else {
// return false;
// }
}
// ??? Why do we have this method? I thought by now we would know if it
// matched or not
private boolean couldMatch(BcelObjectType bcelObjectType, Pointcut pointcut) {
return !bcelObjectType.isInterface();
}
private boolean mungeNewMemberType(BcelClassWeaver classWeaver, NewMemberClassTypeMunger munger) {
World world = classWeaver.getWorld();
ResolvedType onType = world.resolve(munger.getTargetType());
if (onType.isRawType()) {
onType = onType.getGenericType();
}
return onType.equals(classWeaver.getLazyClassGen().getType());
}
private boolean mungeNewMethod(BcelClassWeaver classWeaver, NewMethodTypeMunger munger) {
World world = classWeaver.getWorld();
// Resolving it will sort out the tvars
ResolvedMember unMangledInterMethod = munger.getSignature().resolve(world);
// do matching on the unMangled one, but actually add them to the mangled method
ResolvedMember interMethodBody = munger.getDeclaredInterMethodBody(aspectType, world);
ResolvedMember interMethodDispatcher = munger.getDeclaredInterMethodDispatcher(aspectType, world);
ResolvedMember memberHoldingAnyAnnotations = interMethodDispatcher;
LazyClassGen classGen = classWeaver.getLazyClassGen();
ResolvedType onType = world.resolve(unMangledInterMethod.getDeclaringType(), munger.getSourceLocation());
if (onType.isRawType()) {
onType = onType.getGenericType();
}
// Simple checks, can't ITD on annotations or enums
if (onType.isAnnotation()) {
signalError(WeaverMessages.ITDM_ON_ANNOTATION_NOT_ALLOWED, classWeaver, onType);
return false;
}
if (onType.isEnum()) {
signalError(WeaverMessages.ITDM_ON_ENUM_NOT_ALLOWED, classWeaver, onType);
return false;
}
boolean mungingInterface = classGen.isInterface();
boolean onInterface = onType.isInterface();
if (onInterface
&& classGen.getLazyMethodGen(unMangledInterMethod.getName(), unMangledInterMethod.getSignature(), true) != null) {
// this is ok, we could be providing the default implementation of a
// method
// that the target has already declared
return false;
}
// If we are processing the intended ITD target type (might be an interface)
if (onType.equals(classGen.getType())) {
ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, onInterface);
LazyMethodGen newMethod = makeMethodGen(classGen, mangledInterMethod);
if (mungingInterface) {
// we want the modifiers of the ITD to be used for all *implementors* of the
// interface, but the method itself we add to the interface must be public abstract
newMethod.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT);
}
// pr98901
// For copying the annotations across, we have to discover the real
// member in the aspect which is holding them.
if (classWeaver.getWorld().isInJava5Mode()) {
AnnotationAJ annotationsOnRealMember[] = null;
ResolvedType toLookOn = aspectType;
if (aspectType.isRawType()) {
toLookOn = aspectType.getGenericType();
}
ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false);
// 266602 - consider it missing to mean that the corresponding aspect had errors
if (realMember == null) {
// signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver);
// throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType);
} else {
annotationsOnRealMember = realMember.getAnnotations();
}
Set<ResolvedType> addedAnnotations = new HashSet<ResolvedType>();
if (annotationsOnRealMember != null) {
for (AnnotationAJ anno : annotationsOnRealMember) {
AnnotationGen a = ((BcelAnnotation) anno).getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a, classGen.getConstantPool(), true);
newMethod.addAnnotation(new BcelAnnotation(ag, classWeaver.getWorld()));
addedAnnotations.add(anno.getType());
}
}
if (realMember != null) {
copyOverParameterAnnotations(newMethod, realMember);
}
// the code below was originally added to cope with the case where an aspect declares an annotation on an ITD
// declared within itself (an unusual situation). However, it also addresses the case where we may not find the
// annotation on the real representation of the ITD. This can happen in a load-time weaving situation where
// we couldn't add the annotation in time - and so here we recheck the declare annotations. Not quite ideal but
// works. pr288635
List<DeclareAnnotation> allDecams = world.getDeclareAnnotationOnMethods();
for (DeclareAnnotation declareAnnotationMC : allDecams) {
if (declareAnnotationMC.matches(unMangledInterMethod, world)) {
// && newMethod.getEnclosingClass().getType() == aspectType) {
AnnotationAJ annotation = declareAnnotationMC.getAnnotation();
if (!addedAnnotations.contains(annotation.getType())) {
newMethod.addAnnotation(annotation);
}
}
}
}
// If it doesn't target an interface and there is a body (i.e. it isnt abstract)
if (!onInterface && !Modifier.isAbstract(mangledInterMethod.getModifiers())) {
InstructionList body = newMethod.getBody();
InstructionFactory fact = classGen.getFactory();
int pos = 0;
if (!Modifier.isStatic(unMangledInterMethod.getModifiers())) {
body.append(InstructionFactory.createThis());
pos++;
}
Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes());
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos += paramType.getSize();
}
body.append(Utility.createInvoke(fact, classWeaver.getWorld(), interMethodBody));
body.append(InstructionFactory.createReturn(BcelWorld.makeBcelType(mangledInterMethod.getReturnType())));
if (classWeaver.getWorld().isInJava5Mode()) { // Don't need bridge
// methods if not in
// 1.5 mode.
createAnyBridgeMethodsForCovariance(classWeaver, munger, unMangledInterMethod, onType, classGen, paramTypes);
}
} else {
// ??? this is okay
// if (!(mg.getBody() == null)) throw new
// RuntimeException("bas");
}
if (world.isInJava5Mode()) {
String basicSignature = mangledInterMethod.getSignature();
String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute();
if (!basicSignature.equals(genericSignature)) {
// Add a signature attribute to it
newMethod.addAttribute(createSignatureAttribute(classGen.getConstantPool(), genericSignature));
}
}
// XXX make sure to check that we set exceptions properly on this
// guy.
classWeaver.addLazyMethodGen(newMethod);
classWeaver.getLazyClassGen().warnOnAddedMethod(newMethod.getMethod(), getSignature().getSourceLocation());
addNeededSuperCallMethods(classWeaver, onType, munger.getSuperMethodsCalled());
return true;
} else if (onInterface && !Modifier.isAbstract(unMangledInterMethod.getModifiers())) {
// This means the 'gen' should be the top most implementor
// - if it is *not* then something went wrong after we worked
// out that it was the top most implementor (see pr49657)
if (!classGen.getType().isTopmostImplementor(onType)) {
ResolvedType rtx = classGen.getType().getTopmostImplementor(onType);
if (rtx == null) {
// pr302460
// null means there is something wrong with what we are looking at
ResolvedType rt = classGen.getType();
if (rt.isInterface()) {
ISourceLocation sloc = munger.getSourceLocation();
classWeaver
.getWorld()
.getMessageHandler()
.handleMessage(
MessageUtil.error(
"ITD target "
+ rt.getName()
+ " is an interface but has been incorrectly determined to be the topmost implementor of "
+ onType.getName() + ". ITD is " + this.getSignature(), sloc));
}
if (!onType.isAssignableFrom(rt)) {
ISourceLocation sloc = munger.getSourceLocation();
classWeaver
.getWorld()
.getMessageHandler()
.handleMessage(
MessageUtil.error(
"ITD target " + rt.getName() + " doesn't appear to implement " + onType.getName()
+ " why did we consider it the top most implementor? ITD is "
+ this.getSignature(), sloc));
}
} else if (!rtx.isExposedToWeaver()) {
ISourceLocation sLoc = munger.getSourceLocation();
classWeaver
.getWorld()
.getMessageHandler()
.handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_NON_EXPOSED_IMPLEMENTOR, rtx,
getAspectType().getName()), (sLoc == null ? getAspectType().getSourceLocation() : sLoc)));
} else {
// XXX what does this state mean?
// We have incorrectly identified what is the top most
// implementor and its not because
// a type wasn't exposed to the weaver
}
return false;
} else {
ResolvedMember mangledInterMethod = AjcMemberMaker.interMethod(unMangledInterMethod, aspectType, false);
LazyMethodGen mg = makeMethodGen(classGen, mangledInterMethod);
// From 98901#29 - need to copy annotations across
if (classWeaver.getWorld().isInJava5Mode()) {
AnnotationAJ annotationsOnRealMember[] = null;
ResolvedType toLookOn = aspectType;
if (aspectType.isRawType()) {
toLookOn = aspectType.getGenericType();
}
ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, memberHoldingAnyAnnotations, false);
if (realMember == null) {
throw new BCException("Couldn't find ITD holder member '" + memberHoldingAnyAnnotations + "' on aspect "
+ aspectType);
}
annotationsOnRealMember = realMember.getAnnotations();
if (annotationsOnRealMember != null) {
for (AnnotationAJ annotationX : annotationsOnRealMember) {
AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a, classWeaver.getLazyClassGen().getConstantPool(), true);
mg.addAnnotation(new BcelAnnotation(ag, classWeaver.getWorld()));
}
}
copyOverParameterAnnotations(mg, realMember);
}
if (mungingInterface) {
// we want the modifiers of the ITD to be used for all
// *implementors* of the
// interface, but the method itself we add to the interface
// must be public abstract
mg.setAccessFlags(Modifier.PUBLIC | Modifier.ABSTRACT);
}
Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes());
Type returnType = BcelWorld.makeBcelType(mangledInterMethod.getReturnType());
InstructionList body = mg.getBody();
InstructionFactory fact = classGen.getFactory();
int pos = 0;
if (!Modifier.isStatic(mangledInterMethod.getModifiers())) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos += paramType.getSize();
}
body.append(Utility.createInvoke(fact, classWeaver.getWorld(), interMethodBody));
Type t = BcelWorld.makeBcelType(interMethodBody.getReturnType());
if (!t.equals(returnType)) {
body.append(fact.createCast(t, returnType));
}
body.append(InstructionFactory.createReturn(returnType));
mg.definingType = onType;
if (world.isInJava5Mode()) {
String basicSignature = mangledInterMethod.getSignature();
String genericSignature = ((ResolvedMemberImpl) mangledInterMethod).getSignatureForAttribute();
if (!basicSignature.equals(genericSignature)) {
// Add a signature attribute to it
mg.addAttribute(createSignatureAttribute(classGen.getConstantPool(), genericSignature));
}
}
classWeaver.addOrReplaceLazyMethodGen(mg);
addNeededSuperCallMethods(classWeaver, onType, munger.getSuperMethodsCalled());
// Work out if we need a bridge method for the new method added to the topmostimplementor.
// Check if the munger being processed is a parameterized form of the original munger
createBridgeIfNecessary(classWeaver, munger, unMangledInterMethod, classGen);
return true;
}
} else {
return false;
}
}
private void createBridgeIfNecessary(BcelClassWeaver classWeaver, NewMethodTypeMunger munger,
ResolvedMember unMangledInterMethod, LazyClassGen classGen) {
if (munger.getDeclaredSignature() != null) {
boolean needsbridging = false;
ResolvedMember mungerSignature = munger.getSignature();
ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,
mungerSignature.getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases());
if (!toBridgeTo.getReturnType().getErasureSignature().equals(mungerSignature.getReturnType().getErasureSignature())) {
needsbridging = true;
}
UnresolvedType[] originalParams = toBridgeTo.getParameterTypes();
UnresolvedType[] newParams = mungerSignature.getParameterTypes();
for (int ii = 0; ii < originalParams.length; ii++) {
if (!originalParams[ii].getErasureSignature().equals(newParams[ii].getErasureSignature())) {
needsbridging = true;
}
}
if (needsbridging) {
createBridge(classWeaver, unMangledInterMethod, classGen, toBridgeTo);
}
}
}
private void copyOverParameterAnnotations(LazyMethodGen receiverMethod, ResolvedMember donorMethod) {
AnnotationAJ[][] pAnnos = donorMethod.getParameterAnnotations();
if (pAnnos != null) {
int offset = receiverMethod.isStatic() ? 0 : 1;
int param = 0;
for (int i = offset; i < pAnnos.length; i++) {
AnnotationAJ[] annosOnParam = pAnnos[i];
if (annosOnParam != null) {
for (AnnotationAJ anno : annosOnParam) {
receiverMethod.addParameterAnnotation(param, anno);
}
}
param++;
}
}
}
private void createBridge(BcelClassWeaver weaver, ResolvedMember unMangledInterMethod, LazyClassGen classGen,
ResolvedMember toBridgeTo) {
Type[] paramTypes;
Type returnType;
InstructionList body;
InstructionFactory fact;
int pos;
ResolvedMember bridgerMethod = AjcMemberMaker.bridgerToInterMethod(unMangledInterMethod, classGen.getType());
ResolvedMember bridgingSetter = AjcMemberMaker.interMethodBridger(toBridgeTo, aspectType, false); // pr250493
LazyMethodGen bridgeMethod = makeMethodGen(classGen, bridgingSetter);
paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes());
Type[] bridgingToParms = BcelWorld.makeBcelTypes(unMangledInterMethod.getParameterTypes());
returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType());
body = bridgeMethod.getBody();
fact = classGen.getFactory();
pos = 0;
if (!Modifier.isStatic(bridgingSetter.getModifiers())) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(
unMangledInterMethod.getParameterTypes()[i].getErasureSignature())) {
// System.err.println("Putting in cast from "+
// paramType+" to "+bridgingToParms[i]);
body.append(fact.createCast(paramType, bridgingToParms[i]));
}
pos += paramType.getSize();
}
body.append(Utility.createInvoke(fact, weaver.getWorld(), bridgerMethod));
body.append(InstructionFactory.createReturn(returnType));
classGen.addMethodGen(bridgeMethod);
// mg.definingType = onType;
}
/**
* Helper method to create a signature attribute based on a string signature: e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;"
*/
private Signature createSignatureAttribute(ConstantPool cp, String signature) {
int nameIndex = cp.addUtf8("Signature");
int sigIndex = cp.addUtf8(signature);
return new Signature(nameIndex, 2, sigIndex, cp);
}
/**
* Create any bridge method required because of covariant returns being used. This method is used in the case where an ITD is
* applied to some type and it may be in an override relationship with a method from the supertype - but due to covariance there
* is a mismatch in return values. Example of when required: Super defines: Object m(String s) Sub defines: String m(String s)
* then we need a bridge method in Sub called 'Object m(String s)' that forwards to 'String m(String s)'
*/
private void createAnyBridgeMethodsForCovariance(BcelClassWeaver weaver, NewMethodTypeMunger munger,
ResolvedMember unMangledInterMethod, ResolvedType onType, LazyClassGen gen, Type[] paramTypes) {
// PERFORMANCE BOTTLENECK? Might need investigating, method analysis
// between types in a hierarchy just seems expensive...
// COVARIANCE BRIDGING
// Algorithm: Step1. Check in this type - has someone already created
// the bridge method?
// Step2. Look above us - do we 'override' a method and yet differ in
// return type (i.e. covariance)
// Step3. Create a forwarding bridge method
// ResolvedType superclass = onType.getSuperclass();
boolean quitRightNow = false;
String localMethodName = unMangledInterMethod.getName();
String erasedSig = unMangledInterMethod.getSignatureErased(); // will be something like (LSuperB;)LFoo;
String localParameterSig = erasedSig.substring(0,erasedSig.lastIndexOf(')')+1);//unMangledInterMethod.getParameterSignature();
// getParameterSignatureErased() does not include parens, which we do need.
String localReturnTypeESig = unMangledInterMethod.getReturnType().getErasureSignature();
// Step1
boolean alreadyDone = false; // Compiler might have done it
ResolvedMember[] localMethods = onType.getDeclaredMethods();
for (int i = 0; i < localMethods.length; i++) {
ResolvedMember member = localMethods[i];
if (member.getName().equals(localMethodName)) {
// Check the params
if (member.getParameterSignature().equals(localParameterSig)) {
alreadyDone = true;
}
}
}
// Step2
if (!alreadyDone) {
// Use the iterator form of 'getMethods()' so we do as little work as necessary
ResolvedType supertype = onType.getSuperclass();
if (supertype != null) {
for (Iterator<ResolvedMember> iter = supertype.getMethods(true, true); iter.hasNext() && !quitRightNow;) {
ResolvedMember aMethod = iter.next();
if (aMethod.getName().equals(localMethodName) && aMethod.getParameterSignature().equals(localParameterSig)) {
// check the return types, if they are different we need a
// bridging method.
if (!aMethod.getReturnType().getErasureSignature().equals(localReturnTypeESig)
&& !Modifier.isPrivate(aMethod.getModifiers())) {
// Step3
createBridgeMethod(weaver.getWorld(), munger, unMangledInterMethod, gen, paramTypes, aMethod);
quitRightNow = true;
}
}
}
}
}
}
/**
* Create a bridge method for a particular munger.
*
* @param world
* @param munger
* @param unMangledInterMethod the method to bridge 'to' that we have already created in the 'subtype'
* @param clazz the class in which to put the bridge method
* @param paramTypes Parameter types for the bridge method, passed in as an optimization since the caller is likely to have
* already created them.
* @param theBridgeMethod
*/
private void createBridgeMethod(BcelWorld world, NewMethodTypeMunger munger, ResolvedMember unMangledInterMethod,
LazyClassGen clazz, Type[] paramTypes, ResolvedMember theBridgeMethod) {
InstructionList body;
InstructionFactory fact;
int pos = 0;
// The bridge method in this type will have the same signature as the one in the supertype
LazyMethodGen bridgeMethod = makeMethodGen(clazz, theBridgeMethod);
bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040 /* BRIDGE = 0x00000040 */);
// UnresolvedType[] newParams = munger.getSignature().getParameterTypes();
Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType());
body = bridgeMethod.getBody();
fact = clazz.getFactory();
if (!Modifier.isStatic(unMangledInterMethod.getModifiers())) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
// if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().
// equals
// (unMangledInterMethod.getParameterTypes()[i].getErasureSignature
// ())) {
// System.err.println("Putting in cast from "+paramType+" to "+
// bridgingToParms[i]);
// body.append(fact.createCast(paramType,bridgingToParms[i]));
// }
pos += paramType.getSize();
}
body.append(Utility.createInvoke(fact, world, unMangledInterMethod));
body.append(InstructionFactory.createReturn(returnType));
clazz.addMethodGen(bridgeMethod);
}
// Unlike toString() on a member, this does not include the declaring type
private String stringifyMember(ResolvedMember member) {
StringBuffer buf = new StringBuffer();
buf.append(member.getReturnType().getName());
buf.append(' ');
buf.append(member.getName());
if (member.getKind() != Member.FIELD) {
buf.append("(");
UnresolvedType[] params = member.getParameterTypes();
if (params.length != 0) {
buf.append(params[0]);
for (int i = 1, len = params.length; i < len; i++) {
buf.append(", ");
buf.append(params[i].getName());
}
}
buf.append(")");
}
return buf.toString();
}
private boolean mungeMethodDelegate(BcelClassWeaver weaver, MethodDelegateTypeMunger munger) {
World world = weaver.getWorld();
LazyClassGen gen = weaver.getLazyClassGen();
if (gen.getType().isAnnotation() || gen.getType().isEnum()) {
// don't signal error as it could be a consequence of a wild type pattern
return false;
}
ResolvedMember introduced = munger.getSignature();
ResolvedType fromType = world.resolve(introduced.getDeclaringType(), munger.getSourceLocation());
if (fromType.isRawType()) {
fromType = fromType.getGenericType();
}
boolean shouldApply = munger.matches(weaver.getLazyClassGen().getType(), aspectType);
if (shouldApply) {
Type bcelReturnType = BcelWorld.makeBcelType(introduced.getReturnType());
// If no implementation class was specified, the intention was that
// the types matching the pattern
// already implemented the interface, let's check that now!
if (munger.getImplClassName() == null && !munger.specifiesDelegateFactoryMethod()) {
boolean isOK = false;
List<LazyMethodGen> existingMethods = gen.getMethodGens();
for (LazyMethodGen m : existingMethods) {
if (m.getName().equals(introduced.getName())
&& m.getParameterSignature().equals(introduced.getParameterSignature())
&& m.getReturnType().equals(bcelReturnType)) {
isOK = true;
}
}
if (!isOK) {
// the class does not implement this method, they needed to
// supply a default impl class
IMessage msg = new Message("@DeclareParents: No defaultImpl was specified but the type '" + gen.getName()
+ "' does not implement the method '" + stringifyMember(introduced) + "' defined on the interface '"
+ introduced.getDeclaringType() + "'", weaver.getLazyClassGen().getType().getSourceLocation(), true,
new ISourceLocation[] { munger.getSourceLocation() });
weaver.getWorld().getMessageHandler().handleMessage(msg);
return false;
}
return true;
}
LazyMethodGen mg = new LazyMethodGen(introduced.getModifiers() - Modifier.ABSTRACT, bcelReturnType,
introduced.getName(), BcelWorld.makeBcelTypes(introduced.getParameterTypes()),
BcelWorld.makeBcelTypesAsClassNames(introduced.getExceptions()), gen);
// annotation copy from annotation on ITD interface
if (weaver.getWorld().isInJava5Mode()) {
AnnotationAJ annotationsOnRealMember[] = null;
ResolvedType toLookOn = weaver.getWorld().lookupOrCreateName(introduced.getDeclaringType());
if (fromType.isRawType()) {
toLookOn = fromType.getGenericType();
}
// lookup the method
ResolvedMember[] ms = toLookOn.getDeclaredJavaMethods();
for (ResolvedMember m : ms) {
if (introduced.getName().equals(m.getName()) && introduced.getSignature().equals(m.getSignature())) {
annotationsOnRealMember = m.getAnnotations();
break;
}
}
if (annotationsOnRealMember != null) {
for (AnnotationAJ anno : annotationsOnRealMember) {
AnnotationGen a = ((BcelAnnotation) anno).getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld()));
}
}
}
InstructionList body = new InstructionList();
InstructionFactory fact = gen.getFactory();
// getfield
body.append(InstructionConstants.ALOAD_0);
body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
InstructionBranch ifNonNull = InstructionFactory.createBranchInstruction(Constants.IFNONNULL, null);
body.append(ifNonNull);
// Create and store a new instance
body.append(InstructionConstants.ALOAD_0); // 'this' is where we'll store the field value
// TODO for non-static case, call aspectOf() then call the factory method on the retval
// TODO decide whether the value can really be cached
// locate the aspect and call the static method in it
if (munger.specifiesDelegateFactoryMethod()) {
ResolvedMember rm = munger.getDelegateFactoryMethod(weaver.getWorld());
// Check the method parameter is compatible with the type of the instance to be passed
if (rm.getArity() != 0) {
ResolvedType parameterType = rm.getParameterTypes()[0].resolve(weaver.getWorld());
if (!parameterType.isAssignableFrom(weaver.getLazyClassGen().getType())) {
signalError("For mixin factory method '" + rm + "': Instance type '" + weaver.getLazyClassGen().getType()
+ "' is not compatible with factory parameter type '" + parameterType + "'", weaver);
return false;
}
}
if (Modifier.isStatic(rm.getModifiers())) {
if (rm.getArity() != 0) {
body.append(InstructionConstants.ALOAD_0);
}
body.append(fact.createInvoke(rm.getDeclaringType().getName(), rm.getName(), rm.getSignature(),
Constants.INVOKESTATIC));
body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
} else {
// Need to call aspectOf() to obtain the aspect instance then call the factory method upon that
UnresolvedType theAspect = munger.getAspect();
body.append(fact.createInvoke(theAspect.getName(), "aspectOf", "()" + theAspect.getSignature(),
Constants.INVOKESTATIC));
if (rm.getArity() != 0) {
body.append(InstructionConstants.ALOAD_0);
}
body.append(fact.createInvoke(rm.getDeclaringType().getName(), rm.getName(), rm.getSignature(),
Constants.INVOKEVIRTUAL));
body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
}
} else {
body.append(fact.createNew(munger.getImplClassName()));
body.append(InstructionConstants.DUP);
body.append(fact.createInvoke(munger.getImplClassName(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
body.append(Utility.createSet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
}
// if not null use the instance we've got
InstructionHandle ifNonNullElse = body.append(InstructionConstants.ALOAD_0);
ifNonNull.setTarget(ifNonNullElse);
body.append(Utility.createGet(fact, munger.getDelegate(weaver.getLazyClassGen().getType())));
// args
int pos = 0;
if (!Modifier.isStatic(introduced.getModifiers())) { // skip 'this' (?? can this really
// happen)
// body.append(InstructionFactory.createThis());
pos++;
}
Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes());
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos += paramType.getSize();
}
body.append(Utility.createInvoke(fact, Constants.INVOKEINTERFACE, introduced));
body.append(InstructionFactory.createReturn(bcelReturnType));
mg.getBody().append(body);
weaver.addLazyMethodGen(mg);
weaver.getLazyClassGen().warnOnAddedMethod(mg.getMethod(), getSignature().getSourceLocation());
return true;
}
return false;
}
private boolean mungeFieldHost(BcelClassWeaver weaver, MethodDelegateTypeMunger.FieldHostTypeMunger munger) {
LazyClassGen gen = weaver.getLazyClassGen();
if (gen.getType().isAnnotation() || gen.getType().isEnum()) {
// don't signal error as it could be a consequence of a wild type
// pattern
return false;
}
// boolean shouldApply =
munger.matches(weaver.getLazyClassGen().getType(), aspectType); // why
// do
// this?
ResolvedMember host = AjcMemberMaker.itdAtDeclareParentsField(weaver.getLazyClassGen().getType(), munger.getSignature()
.getType(), aspectType);
FieldGen field = makeFieldGen(weaver.getLazyClassGen(), host);
field.setModifiers(field.getModifiers() | BcelField.AccSynthetic);
weaver.getLazyClassGen().addField(field, null);
return true;
}
private ResolvedMember getRealMemberForITDFromAspect(ResolvedType aspectType, ResolvedMember lookingFor, boolean isCtorRelated) {
World world = aspectType.getWorld();
boolean debug = false;
if (debug) {
System.err.println("Searching for a member on type: " + aspectType);
System.err.println("Member we are looking for: " + lookingFor);
}
ResolvedMember aspectMethods[] = aspectType.getDeclaredMethods();
UnresolvedType[] lookingForParams = lookingFor.getParameterTypes();
ResolvedMember realMember = null;
for (int i = 0; realMember == null && i < aspectMethods.length; i++) {
ResolvedMember member = aspectMethods[i];
if (member.getName().equals(lookingFor.getName())) {
UnresolvedType[] memberParams = member.getGenericParameterTypes();
if (memberParams.length == lookingForParams.length) {
if (debug) {
System.err.println("Reviewing potential candidates: " + member);
}
boolean matchOK = true;
// If not related to a ctor ITD then the name is enough to
// confirm we have the
// right one. If it is ctor related we need to check the
// params all match, although
// only the erasure.
if (isCtorRelated) {
for (int j = 0; j < memberParams.length && matchOK; j++) {
ResolvedType pMember = memberParams[j].resolve(world);
ResolvedType pLookingFor = lookingForParams[j].resolve(world);
if (pMember.isTypeVariableReference()) {
pMember = ((TypeVariableReference) pMember).getTypeVariable().getFirstBound().resolve(world);
}
if (pMember.isParameterizedType() || pMember.isGenericType()) {
pMember = pMember.getRawType().resolve(aspectType.getWorld());
}
if (pLookingFor.isTypeVariableReference()) {
pLookingFor = ((TypeVariableReference) pLookingFor).getTypeVariable().getFirstBound()
.resolve(world);
}
if (pLookingFor.isParameterizedType() || pLookingFor.isGenericType()) {
pLookingFor = pLookingFor.getRawType().resolve(world);
}
if (debug) {
System.err.println("Comparing parameter " + j + " member=" + pMember + " lookingFor="
+ pLookingFor);
}
if (!pMember.equals(pLookingFor)) {
matchOK = false;
}
}
}
if (matchOK) {
realMember = member;
}
}
}
}
if (debug && realMember == null) {
System.err.println("Didn't find a match");
}
return realMember;
}
private void addNeededSuperCallMethods(BcelClassWeaver weaver, ResolvedType onType, Set<ResolvedMember> neededSuperCalls) {
LazyClassGen gen = weaver.getLazyClassGen();
for (Iterator<ResolvedMember> iter = neededSuperCalls.iterator(); iter.hasNext();) {
ResolvedMember superMethod = iter.next();
if (weaver.addDispatchTarget(superMethod)) {
// System.err.println("super type: " +
// superMethod.getDeclaringType() + ", " + gen.getType());
boolean isSuper = !superMethod.getDeclaringType().equals(gen.getType());
String dispatchName;
if (isSuper) {
dispatchName = NameMangler.superDispatchMethod(onType, superMethod.getName());
} else {
dispatchName = NameMangler.protectedDispatchMethod(onType, superMethod.getName());
}
superMethod = superMethod.resolve(weaver.getWorld());
LazyMethodGen dispatcher = makeDispatcher(gen, dispatchName, superMethod, weaver.getWorld(), isSuper);
weaver.addLazyMethodGen(dispatcher);
}
}
}
private void signalError(String msgid, BcelClassWeaver weaver, UnresolvedType onType) {
IMessage msg = MessageUtil.error(WeaverMessages.format(msgid, onType.getName()), getSourceLocation());
weaver.getWorld().getMessageHandler().handleMessage(msg);
}
// private void signalWarning(String msgString, BcelClassWeaver weaver) {
// IMessage msg = MessageUtil.warn(msgString, getSourceLocation());
// weaver.getWorld().getMessageHandler().handleMessage(msg);
// }
private void signalError(String msgString, BcelClassWeaver weaver) {
IMessage msg = MessageUtil.error(msgString, getSourceLocation());
weaver.getWorld().getMessageHandler().handleMessage(msg);
}
private boolean mungeNewConstructor(BcelClassWeaver weaver, NewConstructorTypeMunger newConstructorTypeMunger) {
final LazyClassGen currentClass = weaver.getLazyClassGen();
final InstructionFactory fact = currentClass.getFactory();
ResolvedMember newConstructorMember = newConstructorTypeMunger.getSyntheticConstructor();
ResolvedType onType = newConstructorMember.getDeclaringType().resolve(weaver.getWorld());
if (onType.isRawType()) {
onType = onType.getGenericType();
}
if (onType.isAnnotation()) {
signalError(WeaverMessages.ITDC_ON_ANNOTATION_NOT_ALLOWED, weaver, onType);
return false;
}
if (onType.isEnum()) {
signalError(WeaverMessages.ITDC_ON_ENUM_NOT_ALLOWED, weaver, onType);
return false;
}
if (!onType.equals(currentClass.getType())) {
return false;
}
ResolvedMember explicitConstructor = newConstructorTypeMunger.getExplicitConstructor();
// int declaredParameterCount =
// newConstructorTypeMunger.getDeclaredParameterCount();
LazyMethodGen mg = makeMethodGen(currentClass, newConstructorMember);
mg.setEffectiveSignature(newConstructorTypeMunger.getSignature(), Shadow.ConstructorExecution, true);
// pr98901
// For copying the annotations across, we have to discover the real
// member in the aspect
// which is holding them.
if (weaver.getWorld().isInJava5Mode()) {
ResolvedMember interMethodDispatcher = AjcMemberMaker.postIntroducedConstructor(aspectType, onType,
newConstructorTypeMunger.getSignature().getParameterTypes());
AnnotationAJ annotationsOnRealMember[] = null;
ResolvedMember realMember = getRealMemberForITDFromAspect(aspectType, interMethodDispatcher, true);
// 266602 - consider it missing to mean that the corresponding aspect had errors
if (realMember == null) {
// signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver);
// throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType);
} else {
annotationsOnRealMember = realMember.getAnnotations();
}
if (annotationsOnRealMember != null) {
for (int i = 0; i < annotationsOnRealMember.length; i++) {
AnnotationAJ annotationX = annotationsOnRealMember[i];
AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld()));
}
}
// the below loop fixes the very special (and very stupid)
// case where an aspect declares an annotation
// on an ITD it declared on itself.
List<DeclareAnnotation> allDecams = weaver.getWorld().getDeclareAnnotationOnMethods();
for (Iterator<DeclareAnnotation> i = allDecams.iterator(); i.hasNext();) {
DeclareAnnotation decaMC = i.next();
if (decaMC.matches(explicitConstructor, weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) {
mg.addAnnotation(decaMC.getAnnotation());
}
}
}
// Might have to remove the default constructor - b275032
// TODO could have tagged the type munger when the fact we needed to do this was detected earlier
if (mg.getArgumentTypes().length == 0) {
LazyMethodGen toRemove = null;
for (LazyMethodGen object : currentClass.getMethodGens()) {
if (object.getName().equals("<init>") && object.getArgumentTypes().length == 0) {
toRemove = object;
}
}
if (toRemove != null) {
currentClass.removeMethodGen(toRemove);
}
}
currentClass.addMethodGen(mg);
// weaver.addLazyMethodGen(freshConstructor);
InstructionList body = mg.getBody();
// add to body: push arts for call to pre, from actual args starting at
// 1 (skipping this), going to
// declared argcount + 1
UnresolvedType[] declaredParams = newConstructorTypeMunger.getSignature().getParameterTypes();
Type[] paramTypes = mg.getArgumentTypes();
int frameIndex = 1;
for (int i = 0, len = declaredParams.length; i < len; i++) {
body.append(InstructionFactory.createLoad(paramTypes[i], frameIndex));
frameIndex += paramTypes[i].getSize();
}
// do call to pre
Member preMethod = AjcMemberMaker.preIntroducedConstructor(aspectType, onType, declaredParams);
body.append(Utility.createInvoke(fact, null, preMethod));
// create a local, and store return pre stuff into it.
int arraySlot = mg.allocateLocal(1);
body.append(InstructionFactory.createStore(Type.OBJECT, arraySlot));
// put this on the stack
body.append(InstructionConstants.ALOAD_0);
// unpack pre args onto stack
UnresolvedType[] superParamTypes = explicitConstructor.getParameterTypes();
for (int i = 0, len = superParamTypes.length; i < len; i++) {
body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot));
body.append(Utility.createConstant(fact, i));
body.append(InstructionFactory.createArrayLoad(Type.OBJECT));
body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(superParamTypes[i])));
}
// call super/this
body.append(Utility.createInvoke(fact, null, explicitConstructor));
// put this back on the stack
body.append(InstructionConstants.ALOAD_0);
// unpack params onto stack
Member postMethod = AjcMemberMaker.postIntroducedConstructor(aspectType, onType, declaredParams);
UnresolvedType[] postParamTypes = postMethod.getParameterTypes();
for (int i = 1, len = postParamTypes.length; i < len; i++) {
body.append(InstructionFactory.createLoad(Type.OBJECT, arraySlot));
body.append(Utility.createConstant(fact, superParamTypes.length + i - 1));
body.append(InstructionFactory.createArrayLoad(Type.OBJECT));
body.append(Utility.createConversion(fact, Type.OBJECT, BcelWorld.makeBcelType(postParamTypes[i])));
}
// call post
body.append(Utility.createInvoke(fact, null, postMethod));
// don't forget to return!!
body.append(InstructionConstants.RETURN);
return true;
}
private static LazyMethodGen makeDispatcher(LazyClassGen onGen, String dispatchName, ResolvedMember superMethod,
BcelWorld world, boolean isSuper) {
Type[] paramTypes = BcelWorld.makeBcelTypes(superMethod.getParameterTypes());
Type returnType = BcelWorld.makeBcelType(superMethod.getReturnType());
int modifiers = Modifier.PUBLIC;
if (onGen.isInterface()) {
modifiers |= Modifier.ABSTRACT;
}
LazyMethodGen mg = new LazyMethodGen(modifiers, returnType, dispatchName, paramTypes, UnresolvedType.getNames(superMethod
.getExceptions()), onGen);
InstructionList body = mg.getBody();
if (onGen.isInterface()) {
return mg;
}
// assert (!superMethod.isStatic())
InstructionFactory fact = onGen.getFactory();
int pos = 0;
body.append(InstructionFactory.createThis());
pos++;
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
pos += paramType.getSize();
}
if (isSuper) {
body.append(Utility.createSuperInvoke(fact, world, superMethod));
} else {
body.append(Utility.createInvoke(fact, world, superMethod));
}
body.append(InstructionFactory.createReturn(returnType));
return mg;
}
private boolean mungeNewField(BcelClassWeaver weaver, NewFieldTypeMunger munger) {
/* ResolvedMember initMethod = */munger.getInitMethod(aspectType);
LazyClassGen gen = weaver.getLazyClassGen();
ResolvedMember field = munger.getSignature();
ResolvedType onType = weaver.getWorld().resolve(field.getDeclaringType(), munger.getSourceLocation());
if (onType.isRawType()) {
onType = onType.getGenericType();
}
boolean onInterface = onType.isInterface();
if (onType.isAnnotation()) {
signalError(WeaverMessages.ITDF_ON_ANNOTATION_NOT_ALLOWED, weaver, onType);
return false;
}
if (onType.isEnum()) {
signalError(WeaverMessages.ITDF_ON_ENUM_NOT_ALLOWED, weaver, onType);
return false;
}
ResolvedMember interMethodBody = munger.getInitMethod(aspectType);
AnnotationAJ annotationsOnRealMember[] = null;
// pr98901
// For copying the annotations across, we have to discover the real
// member in the aspect
// which is holding them.
if (weaver.getWorld().isInJava5Mode()) {
// the below line just gets the method with the same name in
// aspectType.getDeclaredMethods();
ResolvedType toLookOn = aspectType;
if (aspectType.isRawType()) {
toLookOn = aspectType.getGenericType();
}
ResolvedMember realMember = getRealMemberForITDFromAspect(toLookOn, interMethodBody, false);
if (realMember == null) {
// signalWarning("Unable to apply any annotations attached to " + munger.getSignature(), weaver);
// throw new BCException("Couldn't find ITD init member '" + interMethodBody + "' on aspect " + aspectType);
} else {
annotationsOnRealMember = realMember.getAnnotations();
}
}
if (onType.equals(gen.getType())) {
if (onInterface) {
ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, onType, aspectType);
LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter);
gen.addMethodGen(mg);
LazyMethodGen mg1 = makeMethodGen(gen, AjcMemberMaker.interFieldInterfaceSetter(field, onType, aspectType));
gen.addMethodGen(mg1);
} else {
weaver.addInitializer(this);
ResolvedMember newField = AjcMemberMaker.interFieldClassField(field, aspectType,
munger.version == NewFieldTypeMunger.VersionTwo);
FieldGen fg = makeFieldGen(gen, newField);
if (annotationsOnRealMember != null) {
for (int i = 0; i < annotationsOnRealMember.length; i++) {
AnnotationAJ annotationX = annotationsOnRealMember[i];
AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
fg.addAnnotation(ag);
}
}
if (weaver.getWorld().isInJava5Mode()) {
String basicSignature = field.getSignature();
String genericSignature = field.getReturnType().resolve(weaver.getWorld()).getSignatureForAttribute();
// String genericSignature =
// ((ResolvedMemberImpl)field).getSignatureForAttribute();
if (!basicSignature.equals(genericSignature)) {
// Add a signature attribute to it
fg.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature));
}
}
gen.addField(fg, getSourceLocation());
}
return true;
} else if (onInterface && gen.getType().isTopmostImplementor(onType)) {
// we know that we can't be static since we don't allow statics on interfaces
if (Modifier.isStatic(field.getModifiers())) {
throw new RuntimeException("unimplemented");
}
boolean alreadyExists = false;
// only need to check for version 2 style mungers
if (munger.version==NewFieldTypeMunger.VersionTwo) {
for (BcelField fieldgen: gen.getFieldGens()) {
if (fieldgen.getName().equals(field.getName())) {
alreadyExists=true;
break;
}
}
}
// FieldGen fg = makeFieldGen(gen, AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType));
ResolvedMember newField = AjcMemberMaker.interFieldInterfaceField(field, onType, aspectType, munger.version == NewFieldTypeMunger.VersionTwo);
String fieldName = newField.getName();
Type fieldType = BcelWorld.makeBcelType(field.getType());
if (!alreadyExists) {
weaver.addInitializer(this);
FieldGen fg = makeFieldGen(gen,newField);
if (annotationsOnRealMember != null) {
for (int i = 0; i < annotationsOnRealMember.length; i++) {
AnnotationAJ annotationX = annotationsOnRealMember[i];
AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
fg.addAnnotation(ag);
}
}
if (weaver.getWorld().isInJava5Mode()) {
String basicSignature = field.getSignature();
String genericSignature = field.getReturnType().resolve(weaver.getWorld()).getSignatureForAttribute();
// String genericSignature =
// ((ResolvedMemberImpl)field).getSignatureForAttribute();
if (!basicSignature.equals(genericSignature)) {
// Add a signature attribute to it
fg.addAttribute(createSignatureAttribute(gen.getConstantPool(), genericSignature));
}
}
gen.addField(fg, getSourceLocation());
}
// this uses a shadow munger to add init method to constructors
// weaver.getShadowMungers().add(makeInitCallShadowMunger(initMethod)
// );
ResolvedMember itdfieldGetter = AjcMemberMaker.interFieldInterfaceGetter(field, gen.getType()/* onType */, aspectType);
LazyMethodGen mg = makeMethodGen(gen, itdfieldGetter);
InstructionList il = new InstructionList();
InstructionFactory fact = gen.getFactory();
if (Modifier.isStatic(field.getModifiers())) {
il.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.GETSTATIC));
} else {
il.append(InstructionConstants.ALOAD_0);
il.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.GETFIELD));
}
il.append(InstructionFactory.createReturn(fieldType));
mg.getBody().insert(il);
gen.addMethodGen(mg);
// Check if we need bridge methods for the field getter and setter
if (munger.getDeclaredSignature() != null) { // is this munger a
// parameterized
// form of some
// original munger?
ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,
munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases());
boolean needsbridging = false;
if (!toBridgeTo.getReturnType().getErasureSignature()
.equals(munger.getSignature().getReturnType().getErasureSignature())) {
needsbridging = true;
}
if (needsbridging) {
ResolvedMember bridgingGetter = AjcMemberMaker.interFieldInterfaceGetter(toBridgeTo, gen.getType(), aspectType);
createBridgeMethodForITDF(weaver, gen, itdfieldGetter, bridgingGetter);
}
}
ResolvedMember itdfieldSetter = AjcMemberMaker.interFieldInterfaceSetter(field, gen.getType(), aspectType);
LazyMethodGen mg1 = makeMethodGen(gen, itdfieldSetter);
InstructionList il1 = new InstructionList();
if (Modifier.isStatic(field.getModifiers())) {
il1.append(InstructionFactory.createLoad(fieldType, 0));
il1.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.PUTSTATIC));
} else {
il1.append(InstructionConstants.ALOAD_0);
il1.append(InstructionFactory.createLoad(fieldType, 1));
il1.append(fact.createFieldAccess(gen.getClassName(), fieldName, fieldType, Constants.PUTFIELD));
}
il1.append(InstructionFactory.createReturn(Type.VOID));
mg1.getBody().insert(il1);
gen.addMethodGen(mg1);
if (munger.getDeclaredSignature() != null) {
ResolvedMember toBridgeTo = munger.getDeclaredSignature().parameterizedWith(null,
munger.getSignature().getDeclaringType().resolve(getWorld()), false, munger.getTypeVariableAliases());
boolean needsbridging = false;
if (!toBridgeTo.getReturnType().getErasureSignature()
.equals(munger.getSignature().getReturnType().getErasureSignature())) {
needsbridging = true;
}
if (needsbridging) {
ResolvedMember bridgingSetter = AjcMemberMaker.interFieldInterfaceSetter(toBridgeTo, gen.getType(), aspectType);
createBridgeMethodForITDF(weaver, gen, itdfieldSetter, bridgingSetter);
}
}
return true;
} else {
return false;
}
}
// FIXME asc combine with other createBridge.. method in this class, avoid
// the duplication...
private void createBridgeMethodForITDF(BcelClassWeaver weaver, LazyClassGen gen, ResolvedMember itdfieldSetter,
ResolvedMember bridgingSetter) {
InstructionFactory fact;
LazyMethodGen bridgeMethod = makeMethodGen(gen, bridgingSetter);
bridgeMethod.setAccessFlags(bridgeMethod.getAccessFlags() | 0x00000040); // BRIDGE = 0x00000040
Type[] paramTypes = BcelWorld.makeBcelTypes(bridgingSetter.getParameterTypes());
Type[] bridgingToParms = BcelWorld.makeBcelTypes(itdfieldSetter.getParameterTypes());
Type returnType = BcelWorld.makeBcelType(bridgingSetter.getReturnType());
InstructionList body = bridgeMethod.getBody();
fact = gen.getFactory();
int pos = 0;
if (!Modifier.isStatic(bridgingSetter.getModifiers())) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().equals(
itdfieldSetter.getParameterTypes()[i].getErasureSignature())) {
body.append(fact.createCast(paramType, bridgingToParms[i]));
}
pos += paramType.getSize();
}
body.append(Utility.createInvoke(fact, weaver.getWorld(), itdfieldSetter));
body.append(InstructionFactory.createReturn(returnType));
gen.addMethodGen(bridgeMethod);
}
@Override
public ConcreteTypeMunger parameterizedFor(ResolvedType target) {
return new BcelTypeMunger(munger.parameterizedFor(target), aspectType);
}
@Override
public ConcreteTypeMunger parameterizeWith(Map<String, UnresolvedType> m, World w) {
return new BcelTypeMunger(munger.parameterizeWith(m, w), aspectType);
}
/**
* Returns a list of type variable aliases used in this munger. For example, if the ITD is 'int I<A,B>.m(List<A> las,List<B>
* lbs) {}' then this returns a list containing the strings "A" and "B".
*/
public List<String> getTypeVariableAliases() {
return munger.getTypeVariableAliases();
}
@Override
public boolean equals(Object other) {
if (!(other instanceof BcelTypeMunger)) {
return false;
}
BcelTypeMunger o = (BcelTypeMunger) other;
return ((o.getMunger() == null) ? (getMunger() == null) : o.getMunger().equals(getMunger()))
&& ((o.getAspectType() == null) ? (getAspectType() == null) : o.getAspectType().equals(getAspectType()));
// && (AsmManager.getDefault().getHandleProvider().dependsOnLocation() ? ((o.getSourceLocation() == null) ?
// (getSourceLocation() == null)
// : o.getSourceLocation().equals(getSourceLocation()))
// : true); // pr134471 - remove when handles are improved
// to be independent of location
}
private volatile int hashCode = 0;
@Override
public int hashCode() {
if (hashCode == 0) {
int result = 17;
result = 37 * result + ((getMunger() == null) ? 0 : getMunger().hashCode());
result = 37 * result + ((getAspectType() == null) ? 0 : getAspectType().hashCode());
hashCode = result;
}
return hashCode;
}
}
|
368,046 | Bug 368046 configure a set of classloader for which weavers should not be created in an LTW scenario | Prototyped and tested for JspClassLoaders (see the thread 'aspectj and jsp load' on the mailing list). That was done through a system property but it would be easier via aop.xml. However, this would be the first time we have an aop.xml setting that affects global operation of loadtime weaving. When any classloader actually got far enough to load the aop.xmls it would discover this setting and from that point on it would be set. In our JspClassLoader case this would mean that either some non-JspClassLoader is run early enough to discover this setting and turn it off for all JspClassLoaders or the first JspClassLoader will discover the setting and turn it off for all other JspClassLoaders. I think we can live with that mode of operation. | resolved fixed | 0c0adc5 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-30T05:25:23Z" | "2012-01-06T17:13:20Z" | loadtime/src/org/aspectj/weaver/loadtime/Aj.java | /*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.security.ProtectionDomain;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.tools.Trace;
import org.aspectj.weaver.tools.TraceFactory;
import org.aspectj.weaver.tools.WeavingAdaptor;
import org.aspectj.weaver.tools.cache.SimpleCache;
import org.aspectj.weaver.tools.cache.SimpleCacheFactory;
/**
* Adapter between the generic class pre processor interface and the AspectJ weaver Load time weaving consistency relies on
* Bcel.setRepository
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class Aj implements ClassPreProcessor {
private IWeavingContext weavingContext;
public static SimpleCache laCache=SimpleCacheFactory.createSimpleCache();
/**
* References are added to this queue when their associated classloader is removed, and once on here that indicates that we
* should tidy up the adaptor map and remove the adaptor (weaver) from the map we are maintaining from adaptorkey > adaptor
* (weaver)
*/
private static ReferenceQueue adaptorQueue = new ReferenceQueue();
private static Trace trace = TraceFactory.getTraceFactory().getTrace(Aj.class);
public Aj() {
this(null);
}
public Aj(IWeavingContext context) {
if (trace.isTraceEnabled())
trace.enter("<init>", this, new Object[] { context, getClass().getClassLoader() });
this.weavingContext = context;
if (trace.isTraceEnabled())
trace.exit("<init>");
}
/**
* Initialization
*/
public void initialize() {
}
private final static String deleLoader = "sun.reflect.DelegatingClassLoader";
/**
* Weave
*
* @param className
* @param bytes
* @param loader
* @return weaved bytes
*/
public byte[] preProcess(String className, byte[] bytes, ClassLoader loader, ProtectionDomain protectionDomain) {
// TODO AV needs to doc that
if (loader == null || className == null || loader.getClass().getName().equals(deleLoader)) {
// skip boot loader, null classes (hibernate), or those from a reflection loader
return bytes;
}
if (trace.isTraceEnabled())
trace.enter("preProcess", this, new Object[] { className, bytes, loader });
if (trace.isTraceEnabled())
trace.event("preProcess", this, new Object[] { loader.getParent(), Thread.currentThread().getContextClassLoader() });
try {
synchronized (loader) {
if (SimpleCacheFactory.isEnabled()) {
byte[] cacheBytes= laCache.getAndInitialize(className, bytes,loader,protectionDomain);
if (cacheBytes!=null){
return cacheBytes;
}
}
WeavingAdaptor weavingAdaptor = WeaverContainer.getWeaver(loader, weavingContext);
if (weavingAdaptor == null) {
if (trace.isTraceEnabled())
trace.exit("preProcess");
return bytes;
}
try {
weavingAdaptor.setActiveProtectionDomain(protectionDomain);
byte[] newBytes = weavingAdaptor.weaveClass(className, bytes, false);
Dump.dumpOnExit(weavingAdaptor.getMessageHolder(), true);
if (trace.isTraceEnabled())
trace.exit("preProcess", newBytes);
if (SimpleCacheFactory.isEnabled()) {
laCache.put(className, bytes, newBytes);
}
return newBytes;
} finally {
weavingAdaptor.setActiveProtectionDomain(null);
}
}
/* Don't like to do this but JVMTI swallows all exceptions */
} catch (Throwable th) {
trace.error(className, th);
Dump.dumpWithException(th);
// FIXME AV wondering if we should have the option to fail (throw runtime exception) here
// would make sense at least in test f.e. see TestHelper.handleMessage()
if (trace.isTraceEnabled())
trace.exit("preProcess", th);
return bytes;
} finally {
CompilationAndWeavingContext.resetForThread();
}
}
/**
* An AdaptorKey is a WeakReference wrapping a classloader reference that will enqueue to a specified queue when the classloader
* is GC'd. Since the AdaptorKey is used as a key into a hashmap we need to give it a non-varying hashcode/equals
* implementation, and we need that hashcode not to vary even when the internal referent has been GC'd. The hashcode is
* calculated on creation of the AdaptorKey based on the loader instance that it is wrapping. This means even when the referent
* is gone we can still use the AdaptorKey and it will 'point' to the same place as it always did.
*/
private static class AdaptorKey extends WeakReference {
private final int loaderHashCode, sysHashCode, hashValue;
private final String loaderClass;
public AdaptorKey(ClassLoader loader) {
super(loader, adaptorQueue);
loaderHashCode = loader.hashCode();
sysHashCode = System.identityHashCode(loader);
loaderClass = loader.getClass().getName();
hashValue = loaderHashCode + sysHashCode + loaderClass.hashCode();
}
public ClassLoader getClassLoader() {
ClassLoader instance = (ClassLoader) get();
// Assert instance!=null - shouldn't be asked for after a GC of the referent has occurred !
return instance;
}
public boolean equals(Object obj) {
if (!(obj instanceof AdaptorKey)) {
return false;
}
AdaptorKey other = (AdaptorKey) obj;
return (other.loaderHashCode == loaderHashCode)
&& (other.sysHashCode == sysHashCode)
&& loaderClass.equals(other.loaderClass);
}
public int hashCode() {
return hashValue;
}
}
/**
* The reference queue is only processed when a request is made for a weaver adaptor. This means there can be one or two stale
* weavers left around. If the user knows they have finished all their weaving, they might wish to call removeStaleAdaptors
* which will process anything left on the reference queue containing adaptorKeys for garbage collected classloaders.
*
* @param displayProgress produce System.err info on the tidying up process
* @return number of stale weavers removed
*/
public static int removeStaleAdaptors(boolean displayProgress) {
int removed = 0;
synchronized (WeaverContainer.weavingAdaptors) {
if (displayProgress) {
System.err.println("Weaver adaptors before queue processing:");
Map m = WeaverContainer.weavingAdaptors;
Set keys = m.keySet();
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
Object object = iterator.next();
System.err.println(object + " = " + WeaverContainer.weavingAdaptors.get(object));
}
}
Object o = adaptorQueue.poll();
while (o != null) {
if (displayProgress)
System.err.println("Processing referencequeue entry " + o);
AdaptorKey wo = (AdaptorKey) o;
boolean didit = WeaverContainer.weavingAdaptors.remove(wo) != null;
if (didit) {
removed++;
} else {
throw new RuntimeException("Eh?? key=" + wo);
}
if (displayProgress)
System.err.println("Removed? " + didit);
o = adaptorQueue.poll();
}
if (displayProgress) {
System.err.println("Weaver adaptors after queue processing:");
Map m = WeaverContainer.weavingAdaptors;
Set keys = m.keySet();
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
Object object = iterator.next();
System.err.println(object + " = " + WeaverContainer.weavingAdaptors.get(object));
}
}
}
return removed;
}
/**
* @return the number of entries still in the weavingAdaptors map
*/
public static int getActiveAdaptorCount() {
return WeaverContainer.weavingAdaptors.size();
}
/**
* Process the reference queue that contains stale AdaptorKeys - the keys are put on the queue when their classloader referent
* is garbage collected and so the associated adaptor (weaver) should be removed from the map
*/
public static void checkQ() {
synchronized (adaptorQueue) {
Object o = adaptorQueue.poll();
while (o != null) {
AdaptorKey wo = (AdaptorKey) o;
// boolean removed =
WeaverContainer.weavingAdaptors.remove(wo);
// DBG System.err.println("Evicting key " + wo + " = " + didit);
o = adaptorQueue.poll();
}
}
}
static {
// pr271840 - touch the types early and outside the locks
new ExplicitlyInitializedClassLoaderWeavingAdaptor(new ClassLoaderWeavingAdaptor());
}
/**
* Cache of weaver There is one weaver per classloader
*/
static class WeaverContainer {
final static Map weavingAdaptors = Collections.synchronizedMap(new HashMap());
static WeavingAdaptor getWeaver(ClassLoader loader, IWeavingContext weavingContext) {
ExplicitlyInitializedClassLoaderWeavingAdaptor adaptor = null;
AdaptorKey adaptorKey = new AdaptorKey(loader);
String loaderClassName = loader.getClass().getName();
synchronized (weavingAdaptors) {
checkQ();
if(loader.equals(myClassLoader)){
adaptor = myClassLoaderAdpator;
}
else{
adaptor = (ExplicitlyInitializedClassLoaderWeavingAdaptor) weavingAdaptors.get(adaptorKey);
}
if (adaptor == null) {
// create it and put it back in the weavingAdaptors map but avoid any kind of instantiation
// within the synchronized block
ClassLoaderWeavingAdaptor weavingAdaptor = new ClassLoaderWeavingAdaptor();
adaptor = new ExplicitlyInitializedClassLoaderWeavingAdaptor(weavingAdaptor);
if(myClassLoaderAdpator == null){
myClassLoaderAdpator = adaptor;
}
else{
weavingAdaptors.put(adaptorKey, adaptor);
}
}
}
// perform the initialization
return adaptor.getWeavingAdaptor(loader, weavingContext);
}
private static final ClassLoader myClassLoader = WeavingAdaptor.class.getClassLoader();
private static ExplicitlyInitializedClassLoaderWeavingAdaptor myClassLoaderAdpator;
}
static class ExplicitlyInitializedClassLoaderWeavingAdaptor {
private final ClassLoaderWeavingAdaptor weavingAdaptor;
private boolean isInitialized;
public ExplicitlyInitializedClassLoaderWeavingAdaptor(ClassLoaderWeavingAdaptor weavingAdaptor) {
this.weavingAdaptor = weavingAdaptor;
this.isInitialized = false;
}
private void initialize(ClassLoader loader, IWeavingContext weavingContext) {
if (!isInitialized) {
isInitialized = true;
weavingAdaptor.initialize(loader, weavingContext);
}
}
public ClassLoaderWeavingAdaptor getWeavingAdaptor(ClassLoader loader, IWeavingContext weavingContext) {
initialize(loader, weavingContext);
return weavingAdaptor;
}
}
/**
* Returns a namespace based on the contest of the aspects available
*/
public String getNamespace(ClassLoader loader) {
ClassLoaderWeavingAdaptor weavingAdaptor = (ClassLoaderWeavingAdaptor) WeaverContainer.getWeaver(loader, weavingContext);
return weavingAdaptor.getNamespace();
}
/**
* Check to see if any classes have been generated for a particular classes loader. Calls
* ClassLoaderWeavingAdaptor.generatedClassesExist()
*
* @param loader the class cloder
* @return true if classes have been generated.
*/
public boolean generatedClassesExist(ClassLoader loader) {
return ((ClassLoaderWeavingAdaptor) WeaverContainer.getWeaver(loader, weavingContext)).generatedClassesExistFor(null);
}
public void flushGeneratedClasses(ClassLoader loader) {
((ClassLoaderWeavingAdaptor) WeaverContainer.getWeaver(loader, weavingContext)).flushGeneratedClasses();
}
} |
368,046 | Bug 368046 configure a set of classloader for which weavers should not be created in an LTW scenario | Prototyped and tested for JspClassLoaders (see the thread 'aspectj and jsp load' on the mailing list). That was done through a system property but it would be easier via aop.xml. However, this would be the first time we have an aop.xml setting that affects global operation of loadtime weaving. When any classloader actually got far enough to load the aop.xmls it would discover this setting and from that point on it would be set. In our JspClassLoader case this would mean that either some non-JspClassLoader is run early enough to discover this setting and turn it off for all JspClassLoaders or the first JspClassLoader will discover the setting and turn it off for all other JspClassLoaders. I think we can live with that mode of operation. | resolved fixed | 0c0adc5 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-30T05:25:23Z" | "2012-01-06T17:13:20Z" | loadtime/src/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java | /*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
* David Knibb weaving context enhancments
* John Kew (vmware) caching hook
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.ProtectionDomain;
import java.util.*;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.Constants;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.Lint;
import org.aspectj.weaver.Lint.Kind;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWeakClassLoaderReference;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.Utility;
import org.aspectj.weaver.loadtime.definition.Definition;
import org.aspectj.weaver.loadtime.definition.DocumentParser;
import org.aspectj.weaver.ltw.LTWWorld;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.tools.*;
import org.aspectj.weaver.tools.cache.WeavedClassCache;
/**
* @author Alexandre Vasseur
* @author Andy Clement
* @author Abraham Nevado
*/
public class ClassLoaderWeavingAdaptor extends WeavingAdaptor {
private final static String AOP_XML = Constants.AOP_USER_XML + ";" + Constants.AOP_AJC_XML + ";" + Constants.AOP_OSGI_XML;
private boolean initialized;
private List m_dumpTypePattern = new ArrayList();
private boolean m_dumpBefore = false;
private boolean dumpDirPerClassloader = false;
private boolean hasExcludes = false;
private List<TypePattern> excludeTypePattern = new ArrayList<TypePattern>(); // anything
private List<String> excludeStartsWith = new ArrayList<String>(); // com.foo..*
private List<String> excludeStarDotDotStar = new ArrayList<String>(); // *..*CGLIB*
private List<String> excludeExactName = new ArrayList<String>(); // com.foo.Bar
private List<String> excludeEndsWith = new ArrayList<String>(); // com.foo.Bar
private List<String[]> excludeSpecial = new ArrayList<String[]>();
private boolean hasIncludes = false;
private List<TypePattern> includeTypePattern = new ArrayList<TypePattern>();
private List<String> m_includeStartsWith = new ArrayList<String>();
private List<String> includeExactName = new ArrayList<String>();
private boolean includeStar = false;
private List<TypePattern> m_aspectExcludeTypePattern = new ArrayList<TypePattern>();
private List<String> m_aspectExcludeStartsWith = new ArrayList<String>();
private List<TypePattern> m_aspectIncludeTypePattern = new ArrayList<TypePattern>();
private List<String> m_aspectIncludeStartsWith = new ArrayList<String>();
private StringBuffer namespace;
private IWeavingContext weavingContext;
private List<ConcreteAspectCodeGen> concreteAspects = new ArrayList<ConcreteAspectCodeGen>();
private static Trace trace = TraceFactory.getTraceFactory().getTrace(ClassLoaderWeavingAdaptor.class);
public ClassLoaderWeavingAdaptor() {
super();
if (trace.isTraceEnabled()) {
trace.enter("<init>", this);
}
if (trace.isTraceEnabled()) {
trace.exit("<init>");
}
}
/**
* We don't need a reference to the class loader and using it during construction can cause problems with recursion. It also
* makes sense to supply the weaving context during initialization to.
*
* @deprecated
*/
public ClassLoaderWeavingAdaptor(final ClassLoader deprecatedLoader, final IWeavingContext deprecatedContext) {
super();
if (trace.isTraceEnabled()) {
trace.enter("<init>", this, new Object[] { deprecatedLoader, deprecatedContext });
}
if (trace.isTraceEnabled()) {
trace.exit("<init>");
}
}
class SimpleGeneratedClassHandler implements GeneratedClassHandler {
private BcelWeakClassLoaderReference loaderRef;
SimpleGeneratedClassHandler(ClassLoader loader) {
loaderRef = new BcelWeakClassLoaderReference(loader);
}
/**
* Callback when we need to define a Closure in the JVM
*
*/
public void acceptClass (String name, byte[] originalBytes, byte[] wovenBytes) {
try {
if (shouldDump(name.replace('/', '.'), false)) {
dump(name, wovenBytes, false);
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
if (activeProtectionDomain != null) {
defineClass(loaderRef.getClassLoader(), name, wovenBytes, activeProtectionDomain);
} else {
defineClass(loaderRef.getClassLoader(), name, wovenBytes); // could be done lazily using the hook
}
}
}
public void initialize(final ClassLoader classLoader, IWeavingContext context) {
if (initialized) {
return;
}
boolean success = true;
this.weavingContext = context;
if (weavingContext == null) {
weavingContext = new DefaultWeavingContext(classLoader);
}
createMessageHandler();
this.generatedClassHandler = new SimpleGeneratedClassHandler(classLoader);
List definitions = weavingContext.getDefinitions(classLoader, this);
if (definitions.isEmpty()) {
disable(); // TODO maw Needed to ensure messages are flushed
if (trace.isTraceEnabled()) {
trace.exit("initialize", definitions);
}
return;
}
// TODO when the world works in terms of the context, we can remove the loader
bcelWorld = new LTWWorld(classLoader, weavingContext, getMessageHandler(), null);
weaver = new BcelWeaver(bcelWorld);
// register the definitions
success = registerDefinitions(weaver, classLoader, definitions);
if (success) {
// after adding aspects
weaver.prepareForWeave();
enable(); // TODO maw Needed to ensure messages are flushed
success = weaveAndDefineConceteAspects();
}
if (success) {
enable();
} else {
disable();
bcelWorld = null;
weaver = null;
}
if (WeavedClassCache.isEnabled()) {
initializeCache(classLoader, getAspectClassNames(definitions), generatedClassHandler, getMessageHandler());
}
initialized = true;
if (trace.isTraceEnabled()) {
trace.exit("initialize", isEnabled());
}
}
/**
* Get the list of all aspects from the defintion list
* @param definitions
* @return
*/
List<String> getAspectClassNames(List<Definition> definitions) {
List<String> aspects = new LinkedList<String>();
for (Iterator<Definition> it = definitions.iterator(); it.hasNext(); ) {
Definition def = it.next();
List<String> defAspects = def.getAspectClassNames();
if (defAspects != null) {
aspects.addAll(defAspects);
}
}
return aspects;
}
/**
* Load and cache the aop.xml/properties according to the classloader visibility rules
*
* @param loader
*/
List<Definition> parseDefinitions(final ClassLoader loader) {
if (trace.isTraceEnabled()) {
trace.enter("parseDefinitions", this);
}
List<Definition> definitions = new ArrayList<Definition>();
try {
info("register classloader " + getClassLoaderName(loader));
// TODO av underoptimized: we will parse each XML once per CL that see it
// TODO av dev mode needed ? TBD -Daj5.def=...
if (loader.equals(ClassLoader.getSystemClassLoader())) {
String file = System.getProperty("aj5.def", null);
if (file != null) {
info("using (-Daj5.def) " + file);
definitions.add(DocumentParser.parse((new File(file)).toURL()));
}
}
String resourcePath = System.getProperty("org.aspectj.weaver.loadtime.configuration", AOP_XML);
if (trace.isTraceEnabled()) {
trace.event("parseDefinitions", this, resourcePath);
}
StringTokenizer st = new StringTokenizer(resourcePath, ";");
while (st.hasMoreTokens()) {
String nextDefinition = st.nextToken();
if (nextDefinition.startsWith("file:")) {
try {
String fpath = new URL(nextDefinition).getFile();
File configFile = new File(fpath);
if (!configFile.exists()) {
warn("configuration does not exist: " + nextDefinition);
} else {
definitions.add(DocumentParser.parse(configFile.toURL()));
}
} catch (MalformedURLException mue) {
error("malformed definition url: " + nextDefinition);
}
} else {
Enumeration<URL> xmls = weavingContext.getResources(nextDefinition);
// System.out.println("? registerDefinitions: found-aop.xml=" + xmls.hasMoreElements() + ", loader=" + loader);
Set<URL> seenBefore = new HashSet<URL>();
while (xmls.hasMoreElements()) {
URL xml = xmls.nextElement();
if (trace.isTraceEnabled()) {
trace.event("parseDefinitions", this, xml);
}
if (!seenBefore.contains(xml)) {
info("using configuration " + weavingContext.getFile(xml));
definitions.add(DocumentParser.parse(xml));
seenBefore.add(xml);
} else {
debug("ignoring duplicate definition: " + xml);
}
}
}
}
if (definitions.isEmpty()) {
info("no configuration found. Disabling weaver for class loader " + getClassLoaderName(loader));
}
} catch (Exception e) {
definitions.clear();
warn("parse definitions failed", e);
}
if (trace.isTraceEnabled()) {
trace.exit("parseDefinitions", definitions);
}
return definitions;
}
private boolean registerDefinitions(final BcelWeaver weaver, final ClassLoader loader, List<Definition> definitions) {
if (trace.isTraceEnabled()) {
trace.enter("registerDefinitions", this, definitions);
}
boolean success = true;
try {
registerOptions(weaver, loader, definitions);
registerAspectExclude(weaver, loader, definitions);
registerAspectInclude(weaver, loader, definitions);
success = registerAspects(weaver, loader, definitions);
registerIncludeExclude(weaver, loader, definitions);
registerDump(weaver, loader, definitions);
} catch (Exception ex) {
trace.error("register definition failed", ex);
success = false;
warn("register definition failed", (ex instanceof AbortException) ? null : ex);
}
if (trace.isTraceEnabled()) {
trace.exit("registerDefinitions", success);
}
return success;
}
private String getClassLoaderName(ClassLoader loader) {
return weavingContext.getClassLoaderName();
}
/**
* Configure the weaver according to the option directives TODO av - don't know if it is that good to reuse, since we only allow
* a small subset of options in LTW
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerOptions(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
StringBuffer allOptions = new StringBuffer();
for (Definition definition : definitions) {
allOptions.append(definition.getWeaverOptions()).append(' ');
}
Options.WeaverOption weaverOption = Options.parse(allOptions.toString(), loader, getMessageHandler());
// configure the weaver and world
// AV - code duplicates AspectJBuilder.initWorldAndWeaver()
World world = weaver.getWorld();
setMessageHandler(weaverOption.messageHandler);
world.setXlazyTjp(weaverOption.lazyTjp);
world.setXHasMemberSupportEnabled(weaverOption.hasMember);
world.setTiming(weaverOption.timers, true);
world.setOptionalJoinpoints(weaverOption.optionalJoinpoints);
world.setPinpointMode(weaverOption.pinpoint);
weaver.setReweavableMode(weaverOption.notReWeavable);
world.performExtraConfiguration(weaverOption.xSet);
world.setXnoInline(weaverOption.noInline);
// AMC - autodetect as per line below, needed for AtAjLTWTests.testLTWUnweavable
world.setBehaveInJava5Way(LangUtil.is15VMOrGreater());
world.setAddSerialVerUID(weaverOption.addSerialVersionUID);
/* First load defaults */
bcelWorld.getLint().loadDefaultProperties();
/* Second overlay LTW defaults */
bcelWorld.getLint().adviceDidNotMatch.setKind(null);
/* Third load user file using -Xlintfile so that -Xlint wins */
if (weaverOption.lintFile != null) {
InputStream resource = null;
try {
resource = loader.getResourceAsStream(weaverOption.lintFile);
Exception failure = null;
if (resource != null) {
try {
Properties properties = new Properties();
properties.load(resource);
world.getLint().setFromProperties(properties);
} catch (IOException e) {
failure = e;
}
}
if (failure != null || resource == null) {
warn("Cannot access resource for -Xlintfile:" + weaverOption.lintFile, failure);
// world.getMessageHandler().handleMessage(new Message(
// "Cannot access resource for -Xlintfile:"+weaverOption.lintFile,
// IMessage.WARNING,
// failure,
// null));
}
} finally {
try {
resource.close();
} catch (Throwable t) {
}
}
}
/* Fourth override with -Xlint */
if (weaverOption.lint != null) {
if (weaverOption.lint.equals("default")) {// FIXME should be AjBuildConfig.AJLINT_DEFAULT but yetanother deps..
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(weaverOption.lint);
if (weaverOption.lint.equals("ignore")) {
bcelWorld.setAllLintIgnored();
}
}
}
// TODO proceedOnError option
}
private void registerAspectExclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
String fastMatchInfo = null;
for (Definition definition : definitions) {
for (String exclude : definition.getAspectExcludePatterns()) {
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
m_aspectExcludeTypePattern.add(excludePattern);
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
m_aspectExcludeStartsWith.add(fastMatchInfo);
}
}
}
}
private void registerAspectInclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
String fastMatchInfo = null;
for (Definition definition : definitions) {
for (String include : definition.getAspectIncludePatterns()) {
TypePattern includePattern = new PatternParser(include).parseTypePattern();
m_aspectIncludeTypePattern.add(includePattern);
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_aspectIncludeStartsWith.add(fastMatchInfo);
}
}
}
}
protected void lint(String name, String[] infos) {
Lint lint = bcelWorld.getLint();
Kind kind = lint.getLintKind(name);
kind.signal(infos, null, null);
}
@Override
public String getContextId() {
return weavingContext.getId();
}
/**
* Register the aspect, following include / exclude rules
*
* @param weaver
* @param loader
* @param definitions
*/
private boolean registerAspects(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
if (trace.isTraceEnabled()) {
trace.enter("registerAspects", this, new Object[] { weaver, loader, definitions });
}
boolean success = true;
// TODO: the exclude aspect allow to exclude aspect defined upper in the CL hierarchy - is it what we want ??
// if not, review the getResource so that we track which resource is defined by which CL
// iterate aspectClassNames
// exclude if in any of the exclude list
for (Definition definition : definitions) {
for (String aspectClassName : definition.getAspectClassNames()) {
if (acceptAspect(aspectClassName)) {
info("register aspect " + aspectClassName);
// System.err.println("? ClassLoaderWeavingAdaptor.registerAspects() aspectName=" + aspectClassName +
// ", loader=" + loader + ", bundle=" + weavingContext.getClassLoaderName());
String requiredType = definition.getAspectRequires(aspectClassName);
if (requiredType != null) {
// This aspect expresses that it requires a type to be around, otherwise it should 'switch off'
((BcelWorld) weaver.getWorld()).addAspectRequires(aspectClassName, requiredType);
}
String definedScope = definition.getScopeForAspect(aspectClassName);
if (definedScope != null) {
((BcelWorld) weaver.getWorld()).addScopedAspect(aspectClassName, definedScope);
}
// ResolvedType aspect =
weaver.addLibraryAspect(aspectClassName);
// generate key for SC
if (namespace == null) {
namespace = new StringBuffer(aspectClassName);
} else {
namespace = namespace.append(";").append(aspectClassName);
}
} else {
// warn("aspect excluded: " + aspectClassName);
lint("aspectExcludedByConfiguration", new String[] { aspectClassName, getClassLoaderName(loader) });
}
}
}
// iterate concreteAspects
// exclude if in any of the exclude list - note that the user defined name matters for that to happen
for (Definition definition : definitions) {
for (Definition.ConcreteAspect concreteAspect : definition.getConcreteAspects()) {
if (acceptAspect(concreteAspect.name)) {
info("define aspect " + concreteAspect.name);
ConcreteAspectCodeGen gen = new ConcreteAspectCodeGen(concreteAspect, weaver.getWorld());
if (!gen.validate()) {
error("Concrete-aspect '" + concreteAspect.name + "' could not be registered");
success = false;
break;
}
((BcelWorld) weaver.getWorld()).addSourceObjectType(Utility.makeJavaClass(concreteAspect.name, gen.getBytes()),
true);
concreteAspects.add(gen);
weaver.addLibraryAspect(concreteAspect.name);
// generate key for SC
if (namespace == null) {
namespace = new StringBuffer(concreteAspect.name);
} else {
namespace = namespace.append(";" + concreteAspect.name);
}
}
}
}
/* We couldn't register one or more aspects so disable the adaptor */
if (!success) {
warn("failure(s) registering aspects. Disabling weaver for class loader " + getClassLoaderName(loader));
}
/* We didn't register any aspects so disable the adaptor */
else if (namespace == null) {
success = false;
info("no aspects registered. Disabling weaver for class loader " + getClassLoaderName(loader));
}
if (trace.isTraceEnabled()) {
trace.exit("registerAspects", success);
}
return success;
}
private boolean weaveAndDefineConceteAspects() {
if (trace.isTraceEnabled()) {
trace.enter("weaveAndDefineConceteAspects", this, concreteAspects);
}
boolean success = true;
for (ConcreteAspectCodeGen gen : concreteAspects) {
String name = gen.getClassName();
byte[] bytes = gen.getBytes();
try {
byte[] newBytes = weaveClass(name, bytes, true);
this.generatedClassHandler.acceptClass(name, bytes, newBytes);
} catch (IOException ex) {
trace.error("weaveAndDefineConceteAspects", ex);
error("exception weaving aspect '" + name + "'", ex);
}
}
if (trace.isTraceEnabled()) {
trace.exit("weaveAndDefineConceteAspects", success);
}
return success;
}
/**
* Register the include / exclude filters. We duplicate simple patterns in startWith filters that will allow faster matching
* without ResolvedType
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
String fastMatchInfo = null;
for (Definition definition : definitions) {
for (Iterator<String> iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
hasIncludes = true;
String include = iterator1.next();
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
m_includeStartsWith.add(fastMatchInfo);
} else if (include.equals("*")) {
includeStar = true;
} else if ((fastMatchInfo = looksLikeExactName(include)) != null) {
includeExactName.add(fastMatchInfo);
} else {
TypePattern includePattern = new PatternParser(include).parseTypePattern();
includeTypePattern.add(includePattern);
}
}
for (Iterator<String> iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
hasExcludes = true;
String exclude = iterator1.next();
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
excludeStartsWith.add(fastMatchInfo);
} else if ((fastMatchInfo = looksLikeStarDotDotStarExclude(exclude)) != null) {
excludeStarDotDotStar.add(fastMatchInfo);
} else if ((fastMatchInfo = looksLikeExactName(exclude)) != null) {
excludeExactName.add(exclude);
} else if ((fastMatchInfo = looksLikeEndsWith(exclude)) != null) {
excludeEndsWith.add(fastMatchInfo);
} else if (exclude
.equals("org.codehaus.groovy..* && !org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController*")) {
// TODO need a more sophisticated analysis here, to allow for similar situations
excludeSpecial.add(new String[] { "org.codehaus.groovy.",
"org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController" });
// for the related test:
// } else if (exclude.equals("testdata..* && !testdata.sub.Oran*")) {
// excludeSpecial.add(new String[] { "testdata.", "testdata.sub.Oran" });
} else {
TypePattern excludePattern = new PatternParser(exclude).parseTypePattern();
excludeTypePattern.add(excludePattern);
}
}
}
}
/**
* Checks if the pattern looks like "*..*XXXX*" and if so returns XXXX. This will enable fast name matching of CGLIB exclusion
*
*/
private String looksLikeStarDotDotStarExclude(String typePattern) {
if (!typePattern.startsWith("*..*")) {
return null;
}
if (!typePattern.endsWith("*")) {
return null;
}
String subPattern = typePattern.substring(4, typePattern.length() - 1);
if (hasStarDot(subPattern, 0)) {
return null;
}
return subPattern.replace('$', '.');
}
/**
* Checks if the pattern looks like "com.foo.Bar" - an exact name
*/
private String looksLikeExactName(String typePattern) {
if (hasSpaceAnnotationPlus(typePattern, 0) || typePattern.indexOf("*") != -1) {
return null;
}
return typePattern.replace('$', '.');
}
/**
* Checks if the pattern looks like "*Exception"
*/
private String looksLikeEndsWith(String typePattern) {
if (typePattern.charAt(0) != '*') {
return null;
}
if (hasSpaceAnnotationPlus(typePattern, 1) || hasStarDot(typePattern, 1)) {
return null;
}
return typePattern.substring(1).replace('$', '.');
}
/**
* Determine if something in the string is going to affect our ability to optimize. Checks for: ' ' '@' '+'
*/
private boolean hasSpaceAnnotationPlus(String string, int pos) {
for (int i = pos, max = string.length(); i < max; i++) {
char ch = string.charAt(i);
if (ch == ' ' || ch == '@' || ch == '+') {
return true;
}
}
return false;
}
/**
* Determine if something in the string is going to affect our ability to optimize. Checks for: '*' '.'
*/
private boolean hasStarDot(String string, int pos) {
for (int i = pos, max = string.length(); i < max; i++) {
char ch = string.charAt(i);
if (ch == '*' || ch == '.') {
return true;
}
}
return false;
}
/**
* Checks if the type pattern looks like "com.foo..*"
*/
private String looksLikeStartsWith(String typePattern) {
if (hasSpaceAnnotationPlus(typePattern, 0) || typePattern.charAt(typePattern.length() - 1) != '*') {
return null;
}
// now must looks like with "charsss..*" or "cha.rss..*" etc
// note that "*" and "*..*" won't be fast matched
// and that "charsss.*" will not neither
int length = typePattern.length();
if (typePattern.endsWith("..*") && length > 3) {
if (typePattern.indexOf("..") == length - 3 // no ".." before last sequence
&& typePattern.indexOf('*') == length - 1) { // no earlier '*'
return typePattern.substring(0, length - 2).replace('$', '.'); // "charsss." or "char.rss." etc
}
}
return null;
}
/**
* Register the dump filter
*
* @param weaver
* @param loader
* @param definitions
*/
private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
for (Definition definition : definitions) {
for (Iterator<String> iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) {
String dump = iterator1.next();
TypePattern pattern = new PatternParser(dump).parseTypePattern();
m_dumpTypePattern.add(pattern);
}
if (definition.shouldDumpBefore()) {
m_dumpBefore = true;
}
if (definition.createDumpDirPerClassloader()) {
dumpDirPerClassloader = true;
}
}
}
/**
* Determine whether a type should be accepted for weaving, by checking it against any includes/excludes.
*
* @param className the name of the type to possibly accept
* @param bytes the bytecode for the type (in case we need to look inside, eg. annotations)
* @return true if it should be accepted for weaving
*/
@Override
protected boolean accept(String className, byte[] bytes) {
if (!hasExcludes && !hasIncludes) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
String fastClassName = className.replace('/', '.');
for (String excludeStartsWithString : excludeStartsWith) {
if (fastClassName.startsWith(excludeStartsWithString)) {
return false;
}
}
// Fast exclusion of patterns like: "*..*CGLIB*"
if (!excludeStarDotDotStar.isEmpty()) {
for (String namePiece : excludeStarDotDotStar) {
int index = fastClassName.lastIndexOf('.');
if (fastClassName.indexOf(namePiece, index + 1) != -1) {
return false;
}
}
}
fastClassName = fastClassName.replace('$', '.');
if (!excludeEndsWith.isEmpty()) {
for (String lastPiece : excludeEndsWith) {
if (fastClassName.endsWith(lastPiece)) {
return false;
}
}
}
// Fast exclusion of exact names
if (!excludeExactName.isEmpty()) {
for (String name : excludeExactName) {
if (fastClassName.equals(name)) {
return false;
}
}
}
if (!excludeSpecial.isEmpty()) {
for (String[] entry : excludeSpecial) {
String excludeThese = entry[0];
String exceptThese = entry[1];
if (fastClassName.startsWith(excludeThese) && !fastClassName.startsWith(exceptThese)) {
return false;
}
}
}
/*
* Bug 120363 If we have an exclude pattern that cannot be matched using "starts with" then we cannot fast accept
*/
boolean didSomeIncludeMatching = false;
if (excludeTypePattern.isEmpty()) {
if (includeStar) {
return true;
}
if (!includeExactName.isEmpty()) {
didSomeIncludeMatching = true;
for (String exactname : includeExactName) {
if (fastClassName.equals(exactname)) {
return true;
}
}
}
boolean fastAccept = false;// defaults to false if no fast include
for (int i = 0; i < m_includeStartsWith.size(); i++) {
didSomeIncludeMatching = true;
fastAccept = fastClassName.startsWith(m_includeStartsWith.get(i));
if (fastAccept) {
return true;
}
}
// We may have processed all patterns now... check that and return
if (includeTypePattern.isEmpty()) {
return !didSomeIncludeMatching;
}
}
boolean accept;
try {
ensureDelegateInitialized(className, bytes);
ResolvedType classInfo = delegateForCurrentClass.getResolvedTypeX();
// exclude are "AND"ed
for (TypePattern typePattern : excludeTypePattern) {
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
// include are "OR"ed
if (includeStar) {
return true;
}
if (!includeExactName.isEmpty()) {
didSomeIncludeMatching = true;
for (String exactname : includeExactName) {
if (fastClassName.equals(exactname)) {
return true;
}
}
}
for (int i = 0; i < m_includeStartsWith.size(); i++) {
didSomeIncludeMatching = true;
boolean fastaccept = fastClassName.startsWith(m_includeStartsWith.get(i));
if (fastaccept) {
return true;
}
}
accept = !didSomeIncludeMatching; // only true if no includes at all
for (TypePattern typePattern : includeTypePattern) {
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
} finally {
this.bcelWorld.demote();
}
return accept;
}
// FIXME we don't use include/exclude of others aop.xml
// this can be nice but very dangerous as well to change that
private boolean acceptAspect(String aspectClassName) {
// avoid ResolvedType if not needed
if (m_aspectExcludeTypePattern.isEmpty() && m_aspectIncludeTypePattern.isEmpty()) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
// EXCLUDE: if one match then reject
String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
for (int i = 0; i < m_aspectExcludeStartsWith.size(); i++) {
if (fastClassName.startsWith(m_aspectExcludeStartsWith.get(i))) {
return false;
}
}
// INCLUDE: if one match then accept
for (int i = 0; i < m_aspectIncludeStartsWith.size(); i++) {
if (fastClassName.startsWith(m_aspectIncludeStartsWith.get(i))) {
return true;
}
}
// needs further analysis
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(aspectClassName), true);
// exclude are "AND"ed
for (Iterator iterator = m_aspectExcludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// exclude match - skip
return false;
}
}
// include are "OR"ed
boolean accept = true;// defaults to true if no include
for (Iterator iterator = m_aspectIncludeTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
accept = typePattern.matchesStatically(classInfo);
if (accept) {
break;
}
// goes on if this include did not match ("OR"ed)
}
return accept;
}
@Override
protected boolean shouldDump(String className, boolean before) {
// Don't dump before weaving unless asked to
if (before && !m_dumpBefore) {
return false;
}
// avoid ResolvedType if not needed
if (m_dumpTypePattern.isEmpty()) {
return false;
}
// TODO AV - optimize for className.startWith only
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true);
// dump
for (Iterator iterator = m_dumpTypePattern.iterator(); iterator.hasNext();) {
TypePattern typePattern = (TypePattern) iterator.next();
if (typePattern.matchesStatically(classInfo)) {
// dump match
return true;
}
}
return false;
}
@Override
protected String getDumpDir() {
if (dumpDirPerClassloader) {
StringBuffer dir = new StringBuffer();
dir.append("_ajdump").append(File.separator).append(weavingContext.getId());
return dir.toString();
} else {
return super.getDumpDir();
}
}
/*
* shared classes methods
*/
/**
* @return Returns the key.
*/
public String getNamespace() {
// System.out.println("ClassLoaderWeavingAdaptor.getNamespace() classloader=" + weavingContext.getClassLoaderName() +
// ", namespace=" + namespace);
if (namespace == null) {
return "";
} else {
return new String(namespace);
}
}
/**
* Check to see if any classes are stored in the generated classes cache. Then flush the cache if it is not empty
*
* @param className TODO
* @return true if a class has been generated and is stored in the cache
*/
public boolean generatedClassesExistFor(String className) {
// System.err.println("? ClassLoaderWeavingAdaptor.generatedClassesExist() classname=" + className + ", size=" +
// generatedClasses);
if (className == null) {
return !generatedClasses.isEmpty();
} else {
return generatedClasses.containsKey(className);
}
}
/**
* Flush the generated classes cache
*/
public void flushGeneratedClasses() {
// System.err.println("? ClassLoaderWeavingAdaptor.flushGeneratedClasses() generatedClasses=" + generatedClasses);
generatedClasses = new HashMap();
}
private Method defineClassMethod;
private Method defineClassWithProtectionDomainMethod;
private void defineClass(ClassLoader loader, String name, byte[] bytes) {
if (trace.isTraceEnabled()) {
trace.enter("defineClass", this, new Object[] { loader, name, bytes });
}
Object clazz = null;
debug("generating class '" + name + "'");
try {
if (defineClassMethod == null) {
defineClassMethod = ClassLoader.class.getDeclaredMethod("defineClass", new Class[] { String.class,
bytes.getClass(), int.class, int.class });
}
defineClassMethod.setAccessible(true);
clazz = defineClassMethod.invoke(loader, new Object[] { name, bytes, new Integer(0), new Integer(bytes.length) });
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof LinkageError) {
warn("define generated class failed", e.getTargetException());
// is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved)
// TODO maw I don't think this is OK and
} else {
warn("define generated class failed", e.getTargetException());
}
} catch (Exception e) {
warn("define generated class failed", e);
}
if (trace.isTraceEnabled()) {
trace.exit("defineClass", clazz);
}
}
private void defineClass(ClassLoader loader, String name, byte[] bytes, ProtectionDomain protectionDomain) {
if (trace.isTraceEnabled()) {
trace.enter("defineClass", this, new Object[] { loader, name, bytes, protectionDomain });
}
Object clazz = null;
debug("generating class '" + name + "'");
try {
// System.out.println(">> Defining with protection domain " + name + " pd=" + protectionDomain);
if (defineClassWithProtectionDomainMethod == null) {
defineClassWithProtectionDomainMethod = ClassLoader.class.getDeclaredMethod("defineClass", new Class[] {
String.class, bytes.getClass(), int.class, int.class, ProtectionDomain.class });
}
defineClassWithProtectionDomainMethod.setAccessible(true);
clazz = defineClassWithProtectionDomainMethod.invoke(loader, new Object[] { name, bytes, Integer.valueOf(0),
new Integer(bytes.length), protectionDomain });
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof LinkageError) {
warn("define generated class failed", e.getTargetException());
// is already defined (happens for X$ajcMightHaveAspect interfaces since aspects are reweaved)
// TODO maw I don't think this is OK and
} else {
warn("define generated class failed", e.getTargetException());
}
} catch (Exception e) {
warn("define generated class failed", e);
}
if (trace.isTraceEnabled()) {
trace.exit("defineClass", clazz);
}
}
} |
368,046 | Bug 368046 configure a set of classloader for which weavers should not be created in an LTW scenario | Prototyped and tested for JspClassLoaders (see the thread 'aspectj and jsp load' on the mailing list). That was done through a system property but it would be easier via aop.xml. However, this would be the first time we have an aop.xml setting that affects global operation of loadtime weaving. When any classloader actually got far enough to load the aop.xmls it would discover this setting and from that point on it would be set. In our JspClassLoader case this would mean that either some non-JspClassLoader is run early enough to discover this setting and turn it off for all JspClassLoaders or the first JspClassLoader will discover the setting and turn it off for all other JspClassLoaders. I think we can live with that mode of operation. | resolved fixed | 0c0adc5 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-30T05:25:23Z" | "2012-01-06T17:13:20Z" | loadtime/src/org/aspectj/weaver/loadtime/Options.java | /*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.Message;
import org.aspectj.util.LangUtil;
/**
* A class that hanldes LTW options. Note: AV - I choosed to not reuse AjCompilerOptions and alike since those implies too many
* dependancies on jdt and ajdt modules.
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class Options {
private final static String OPTION_15 = "-1.5";
private final static String OPTION_lazyTjp = "-XlazyTjp";
private final static String OPTION_noWarn = "-nowarn";
private final static String OPTION_noWarnNone = "-warn:none";
private final static String OPTION_proceedOnError = "-proceedOnError";
private final static String OPTION_verbose = "-verbose";
private final static String OPTION_debug = "-debug";
private final static String OPTION_reweavable = "-Xreweavable";// notReweavable is default for LTW
private final static String OPTION_noinline = "-Xnoinline";
private final static String OPTION_addSerialVersionUID = "-XaddSerialVersionUID";
private final static String OPTION_hasMember = "-XhasMember";
private final static String OPTION_pinpoint = "-Xdev:pinpoint";
private final static String OPTION_showWeaveInfo = "-showWeaveInfo";
private final static String OPTIONVALUED_messageHandler = "-XmessageHandlerClass:";
private static final String OPTIONVALUED_Xlintfile = "-Xlintfile:";
private static final String OPTIONVALUED_Xlint = "-Xlint:";
private static final String OPTIONVALUED_joinpoints = "-Xjoinpoints:";
private static final String OPTIONVALUED_Xset = "-Xset:";
private static final String OPTION_timers = "-timers";
public static WeaverOption parse(String options, ClassLoader laoder, IMessageHandler imh) {
WeaverOption weaverOption = new WeaverOption(imh);
if (LangUtil.isEmpty(options)) {
return weaverOption;
}
// the first option wins
List flags = LangUtil.anySplit(options, " ");
Collections.reverse(flags);
// do a first round on the message handler since it will report the options themselves
for (Iterator iterator = flags.iterator(); iterator.hasNext();) {
String arg = (String) iterator.next();
if (arg.startsWith(OPTIONVALUED_messageHandler)) {
if (arg.length() > OPTIONVALUED_messageHandler.length()) {
String handlerClass = arg.substring(OPTIONVALUED_messageHandler.length()).trim();
try {
Class handler = Class.forName(handlerClass, false, laoder);
weaverOption.messageHandler = ((IMessageHandler) handler.newInstance());
} catch (Throwable t) {
weaverOption.messageHandler.handleMessage(new Message("Cannot instantiate message handler " + handlerClass,
IMessage.ERROR, t, null));
}
}
}
}
// configure the other options
for (Iterator iterator = flags.iterator(); iterator.hasNext();) {
String arg = (String) iterator.next();
if (arg.equals(OPTION_15)) {
weaverOption.java5 = true;
} else if (arg.equalsIgnoreCase(OPTION_lazyTjp)) {
weaverOption.lazyTjp = true;
} else if (arg.equalsIgnoreCase(OPTION_noinline)) {
weaverOption.noInline = true;
} else if (arg.equalsIgnoreCase(OPTION_addSerialVersionUID)) {
weaverOption.addSerialVersionUID = true;
} else if (arg.equalsIgnoreCase(OPTION_noWarn) || arg.equalsIgnoreCase(OPTION_noWarnNone)) {
weaverOption.noWarn = true;
} else if (arg.equalsIgnoreCase(OPTION_proceedOnError)) {
weaverOption.proceedOnError = true;
} else if (arg.equalsIgnoreCase(OPTION_reweavable)) {
weaverOption.notReWeavable = false;
} else if (arg.equalsIgnoreCase(OPTION_showWeaveInfo)) {
weaverOption.showWeaveInfo = true;
} else if (arg.equalsIgnoreCase(OPTION_hasMember)) {
weaverOption.hasMember = true;
} else if (arg.startsWith(OPTIONVALUED_joinpoints)) {
if (arg.length() > OPTIONVALUED_joinpoints.length()) {
weaverOption.optionalJoinpoints = arg.substring(OPTIONVALUED_joinpoints.length()).trim();
}
} else if (arg.equalsIgnoreCase(OPTION_verbose)) {
weaverOption.verbose = true;
} else if (arg.equalsIgnoreCase(OPTION_debug)) {
weaverOption.debug = true;
} else if (arg.equalsIgnoreCase(OPTION_pinpoint)) {
weaverOption.pinpoint = true;
} else if (arg.startsWith(OPTIONVALUED_messageHandler)) {
// handled in first round
} else if (arg.startsWith(OPTIONVALUED_Xlintfile)) {
if (arg.length() > OPTIONVALUED_Xlintfile.length()) {
weaverOption.lintFile = arg.substring(OPTIONVALUED_Xlintfile.length()).trim();
}
} else if (arg.startsWith(OPTIONVALUED_Xlint)) {
if (arg.length() > OPTIONVALUED_Xlint.length()) {
weaverOption.lint = arg.substring(OPTIONVALUED_Xlint.length()).trim();
}
} else if (arg.startsWith(OPTIONVALUED_Xset)) {
if (arg.length() > OPTIONVALUED_Xlint.length()) {
weaverOption.xSet = arg.substring(OPTIONVALUED_Xset.length()).trim();
}
} else if (arg.equalsIgnoreCase(OPTION_timers)) {
weaverOption.timers = true;
} else {
weaverOption.messageHandler.handleMessage(new Message("Cannot configure weaver with option '" + arg
+ "': unknown option", IMessage.WARNING, null, null));
}
}
// refine message handler configuration
if (weaverOption.noWarn) {
weaverOption.messageHandler.ignore(IMessage.WARNING);
}
if (weaverOption.verbose) {
weaverOption.messageHandler.dontIgnore(IMessage.INFO);
}
if (weaverOption.debug) {
weaverOption.messageHandler.dontIgnore(IMessage.DEBUG);
}
if (weaverOption.showWeaveInfo) {
weaverOption.messageHandler.dontIgnore(IMessage.WEAVEINFO);
}
return weaverOption;
}
public static class WeaverOption {
boolean java5;
boolean lazyTjp;
boolean hasMember;
boolean timers = false;
String optionalJoinpoints;
boolean noWarn;
boolean proceedOnError;
boolean verbose;
boolean debug;
boolean notReWeavable = true;// default to notReweavable for LTW (faster)
boolean noInline;
boolean addSerialVersionUID;
boolean showWeaveInfo;
boolean pinpoint;
IMessageHandler messageHandler;
String lint;
String lintFile;
String xSet;
public WeaverOption(IMessageHandler imh) {
// messageHandler = new DefaultMessageHandler();//default
this.messageHandler = imh;
}
}
}
|
368,046 | Bug 368046 configure a set of classloader for which weavers should not be created in an LTW scenario | Prototyped and tested for JspClassLoaders (see the thread 'aspectj and jsp load' on the mailing list). That was done through a system property but it would be easier via aop.xml. However, this would be the first time we have an aop.xml setting that affects global operation of loadtime weaving. When any classloader actually got far enough to load the aop.xmls it would discover this setting and from that point on it would be set. In our JspClassLoader case this would mean that either some non-JspClassLoader is run early enough to discover this setting and turn it off for all JspClassLoaders or the first JspClassLoader will discover the setting and turn it off for all other JspClassLoaders. I think we can live with that mode of operation. | resolved fixed | 0c0adc5 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-30T05:25:23Z" | "2012-01-06T17:13:20Z" | tests/bugs174/pr368046/Azpect.java | |
368,046 | Bug 368046 configure a set of classloader for which weavers should not be created in an LTW scenario | Prototyped and tested for JspClassLoaders (see the thread 'aspectj and jsp load' on the mailing list). That was done through a system property but it would be easier via aop.xml. However, this would be the first time we have an aop.xml setting that affects global operation of loadtime weaving. When any classloader actually got far enough to load the aop.xmls it would discover this setting and from that point on it would be set. In our JspClassLoader case this would mean that either some non-JspClassLoader is run early enough to discover this setting and turn it off for all JspClassLoaders or the first JspClassLoader will discover the setting and turn it off for all other JspClassLoaders. I think we can live with that mode of operation. | resolved fixed | 0c0adc5 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-30T05:25:23Z" | "2012-01-06T17:13:20Z" | tests/bugs174/pr368046/Code.java | |
368,046 | Bug 368046 configure a set of classloader for which weavers should not be created in an LTW scenario | Prototyped and tested for JspClassLoaders (see the thread 'aspectj and jsp load' on the mailing list). That was done through a system property but it would be easier via aop.xml. However, this would be the first time we have an aop.xml setting that affects global operation of loadtime weaving. When any classloader actually got far enough to load the aop.xmls it would discover this setting and from that point on it would be set. In our JspClassLoader case this would mean that either some non-JspClassLoader is run early enough to discover this setting and turn it off for all JspClassLoaders or the first JspClassLoader will discover the setting and turn it off for all other JspClassLoaders. I think we can live with that mode of operation. | resolved fixed | 0c0adc5 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-07-30T05:25:23Z" | "2012-01-06T17:13:20Z" | tests/src/org/aspectj/systemtest/ajc174/Ajc174Tests.java | /*******************************************************************************
* Copyright (c) 2013 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc174;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
/**
* @author Andy Clement
*/
public class Ajc174Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testSuperItdCtor_413378() throws Exception {
runTest("super itd ctor");
}
// ---
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc174Tests.class);
}
@Override
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc174/ajc174.xml");
}
}
|
418,129 | Bug 418129 Can't introduce annotation onto introduced method from trait-patterned aspect | null | resolved fixed | 2393bef | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-01T17:00:14Z" | "2013-09-26T18:26:40Z" | tests/bugs174/pr418129/Target.java | |
418,129 | Bug 418129 Can't introduce annotation onto introduced method from trait-patterned aspect | null | resolved fixed | 2393bef | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-01T17:00:14Z" | "2013-09-26T18:26:40Z" | tests/bugs174/pr418129/Target2.java | |
418,129 | Bug 418129 Can't introduce annotation onto introduced method from trait-patterned aspect | null | resolved fixed | 2393bef | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-01T17:00:14Z" | "2013-09-26T18:26:40Z" | tests/bugs174/pr418129/Target3.java | |
418,129 | Bug 418129 Can't introduce annotation onto introduced method from trait-patterned aspect | null | resolved fixed | 2393bef | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-01T17:00:14Z" | "2013-09-26T18:26:40Z" | tests/bugs174/pr418129/Target4.java | |
418,129 | Bug 418129 Can't introduce annotation onto introduced method from trait-patterned aspect | null | resolved fixed | 2393bef | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-01T17:00:14Z" | "2013-09-26T18:26:40Z" | tests/src/org/aspectj/systemtest/ajc174/Ajc174Tests.java | /*******************************************************************************
* Copyright (c) 2013 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc174;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
/**
* @author Andy Clement
*/
public class Ajc174Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testSuperItdCtor_413378() throws Exception {
runTest("super itd ctor");
}
// no exclusion, this is how it should work
public void testCLExclusion_pr368046_1_noskippedloaders() {
runTest("classloader exclusion - 1");
}
public void testCLExclusion_pr368046_1_syspropset() {
try {
System.setProperty("aj.weaving.loadersToSkip", "foo");
runTest("classloader exclusion - 2");
} finally {
System.setProperty("aj.weaving.loadersToSkip", "");
}
}
// final repeat this test, to confirm no lingering static
public void testCLExclusion_pr368046_1_again_noskippedloaders() {
runTest("classloader exclusion - 3");
}
public void testCLExclusion_pr368046_2_usingaopxml() {
runTest("classloader exclusion - 4");
}
public void testCLExclusion_pr368046_2_usingaopxmlReal() {
runTest("classloader exclusion - 5");
}
// ---
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc174Tests.class);
}
@Override
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc174/ajc174.xml");
}
}
|
418,129 | Bug 418129 Can't introduce annotation onto introduced method from trait-patterned aspect | null | resolved fixed | 2393bef | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-01T17:00:14Z" | "2013-09-26T18:26:40Z" | weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java | /* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-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.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.ConstantPool;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
import org.aspectj.apache.bcel.generic.FieldGen;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionBranch;
import org.aspectj.apache.bcel.generic.InstructionCP;
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.InstructionLV;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionSelect;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LineNumberTag;
import org.aspectj.apache.bcel.generic.LocalVariableTag;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.MethodGen;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.RET;
import org.aspectj.apache.bcel.generic.Tag;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.asm.AsmManager;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.AnnotationAJ;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IClassWeaver;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MissingResolvedTypeWithKnownSignature;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.UnresolvedTypeVariableReferenceType;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.model.AsmRelationshipProvider;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.ExactTypePattern;
import org.aspectj.weaver.tools.Trace;
import org.aspectj.weaver.tools.TraceFactory;
class BcelClassWeaver implements IClassWeaver {
private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelClassWeaver.class);
public static boolean weave(BcelWorld world, LazyClassGen clazz, List<ShadowMunger> shadowMungers,
List<ConcreteTypeMunger> typeMungers, List<ConcreteTypeMunger> lateTypeMungers, boolean inReweavableMode) {
BcelClassWeaver classWeaver = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers, lateTypeMungers);
classWeaver.setReweavableMode(inReweavableMode);
boolean b = classWeaver.weave();
return b;
}
// --------------------------------------------
private final LazyClassGen clazz;
private final List<ShadowMunger> shadowMungers;
private final List<ConcreteTypeMunger> typeMungers;
private final List<ConcreteTypeMunger> lateTypeMungers;
private List<ShadowMunger>[] indexedShadowMungers;
private boolean canMatchBodyShadows = false;
private final BcelObjectType ty; // alias of clazz.getType()
private final BcelWorld world; // alias of ty.getWorld()
private final ConstantPool cpg; // alias of clazz.getConstantPoolGen()
private final InstructionFactory fact; // alias of clazz.getFactory();
private final List<LazyMethodGen> addedLazyMethodGens = new ArrayList<LazyMethodGen>();
private final Set<ResolvedMember> addedDispatchTargets = new HashSet<ResolvedMember>();
private boolean inReweavableMode = false;
private List<IfaceInitList> addedSuperInitializersAsList = null;
private final Map<ResolvedType, IfaceInitList> addedSuperInitializers = new HashMap<ResolvedType, IfaceInitList>();
private final List<ConcreteTypeMunger> addedThisInitializers = new ArrayList<ConcreteTypeMunger>();
private final List<ConcreteTypeMunger> addedClassInitializers = new ArrayList<ConcreteTypeMunger>();
private final Map<ResolvedMember, ResolvedMember> mapToAnnotationHolder = new HashMap<ResolvedMember, ResolvedMember>();
// 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<BcelShadow> initializationShadows = new ArrayList<BcelShadow>();
private BcelClassWeaver(BcelWorld world, LazyClassGen clazz, List<ShadowMunger> shadowMungers,
List<ConcreteTypeMunger> typeMungers, List<ConcreteTypeMunger> lateTypeMungers) {
super();
this.world = world;
this.clazz = clazz;
this.shadowMungers = shadowMungers;
this.typeMungers = typeMungers;
this.lateTypeMungers = lateTypeMungers;
this.ty = clazz.getBcelObjectType();
this.cpg = clazz.getConstantPool();
this.fact = clazz.getFactory();
indexShadowMungers();
initializeSuperInitializerMap(ty.getResolvedTypeX());
if (!checkedXsetForLowLevelContextCapturing) {
Properties p = world.getExtraConfiguration();
if (p != null) {
String s = p.getProperty(World.xsetCAPTURE_ALL_CONTEXT, "false");
captureLowLevelContext = s.equalsIgnoreCase("true");
if (captureLowLevelContext) {
world.getMessageHandler().handleMessage(
MessageUtil.info("[" + World.xsetCAPTURE_ALL_CONTEXT
+ "=true] Enabling collection of low level context for debug/crash messages"));
}
}
checkedXsetForLowLevelContextCapturing = true;
}
}
private boolean canMatch(Shadow.Kind kind) {
return indexedShadowMungers[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]);
}
}
}
}
/**
* Process the shadow mungers into array 'buckets', each bucket represents a shadow kind and contains a list of shadowmungers
* that could potentially apply at that shadow kind.
*/
private void indexShadowMungers() {
// beware the annoying property that SHADOW_KINDS[i].getKey == (i+1) !
indexedShadowMungers = new List[Shadow.MAX_SHADOW_KIND + 1];
for (ShadowMunger shadowMunger : shadowMungers) {
int couldMatchKinds = shadowMunger.getPointcut().couldMatchKinds();
for (Shadow.Kind kind : Shadow.SHADOW_KINDS) {
if (kind.isSet(couldMatchKinds)) {
byte k = kind.getKey();
if (indexedShadowMungers[k] == null) {
indexedShadowMungers[k] = new ArrayList<ShadowMunger>();
if (!kind.isEnclosingKind()) {
canMatchBodyShadows = true;
}
}
indexedShadowMungers[k].add(shadowMunger);
}
}
}
}
private boolean addSuperInitializer(ResolvedType onType) {
if (onType.isRawType() || onType.isParameterizedType()) {
onType = onType.getGenericType();
}
IfaceInitList l = 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 (Modifier.isStatic(m.getSignature().getModifiers())) {
addedClassInitializers.add(cm);
} else {
if (onType == ty.getResolvedTypeX()) {
addedThisInitializers.add(cm);
} else {
IfaceInitList l = addedSuperInitializers.get(onType);
l.list.add(cm);
}
}
}
private static class IfaceInitList implements PartialOrder.PartialComparable {
final ResolvedType onType;
List<ConcreteTypeMunger> list = new ArrayList<ConcreteTypeMunger>();
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<LazyMethodGen> i = addedLazyMethodGens.iterator(); i.hasNext();) {
LazyMethodGen existing = 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<LazyMethodGen> i = clazz.getMethodGens().iterator(); i.hasNext();) {
LazyMethodGen existing = i.next();
if (signaturesMatch(mg, existing)) {
if (!mg.isAbstract() && existing.isAbstract()) {
i.remove();
return false;
}
return true;
}
}
return false;
}
private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) {
return mg.getName().equals(existing.getName()) && mg.getSignature().equals(existing.getSignature());
}
protected static LazyMethodGen makeBridgeMethod(LazyClassGen gen, ResolvedMember member) {
// remove abstract modifier
int mods = member.getModifiers();
if (Modifier.isAbstract(mods)) {
mods = mods - Modifier.ABSTRACT;
}
LazyMethodGen ret = new LazyMethodGen(mods, BcelWorld.makeBcelType(member.getReturnType()), member.getName(),
BcelWorld.makeBcelTypes(member.getParameterTypes()), UnresolvedType.getNames(member.getExceptions()), gen);
// 43972 : Static crosscutting makes interfaces unusable for javac
// ret.makeSynthetic();
return ret;
}
/**
* Create a single bridge method called 'theBridgeMethod' that bridges to 'whatToBridgeTo'
*/
private static void createBridgeMethod(BcelWorld world, LazyMethodGen whatToBridgeToMethodGen, LazyClassGen clazz, ResolvedMember theBridgeMethod) {
InstructionList body;
InstructionFactory fact;
int pos = 0;
ResolvedMember whatToBridgeTo = whatToBridgeToMethodGen.getMemberView();
if (whatToBridgeTo == null) {
whatToBridgeTo = new ResolvedMemberImpl(Member.METHOD, whatToBridgeToMethodGen.getEnclosingClass().getType(),
whatToBridgeToMethodGen.getAccessFlags(), whatToBridgeToMethodGen.getName(),
whatToBridgeToMethodGen.getSignature());
}
// The bridge method in this type will have the same signature as the one in the supertype
LazyMethodGen bridgeMethod = makeBridgeMethod(clazz, theBridgeMethod);
int newflags = bridgeMethod.getAccessFlags() | 0x00000040;// BRIDGE = 0x00000040
if ((newflags & 0x00000100) != 0) {
newflags = newflags - 0x100;// NATIVE = 0x00000100 - need to clear it
}
bridgeMethod.setAccessFlags(newflags);
Type returnType = BcelWorld.makeBcelType(theBridgeMethod.getReturnType());
Type[] paramTypes = BcelWorld.makeBcelTypes(theBridgeMethod.getParameterTypes());
Type[] newParamTypes = whatToBridgeToMethodGen.getArgumentTypes();
body = bridgeMethod.getBody();
fact = clazz.getFactory();
if (!whatToBridgeToMethodGen.isStatic()) {
body.append(InstructionFactory.createThis());
pos++;
}
for (int i = 0, len = paramTypes.length; i < len; i++) {
Type paramType = paramTypes[i];
body.append(InstructionFactory.createLoad(paramType, pos));
if (!newParamTypes[i].equals(paramTypes[i])) {
if (world.forDEBUG_bridgingCode) {
System.err.println("Bridging: Cast " + newParamTypes[i] + " from " + paramTypes[i]);
}
body.append(fact.createCast(paramTypes[i], newParamTypes[i]));
}
pos += paramType.getSize();
}
body.append(Utility.createInvoke(fact, world, whatToBridgeTo));
body.append(InstructionFactory.createReturn(returnType));
clazz.addMethodGen(bridgeMethod);
}
/**
* Weave a class and indicate through the return value whether the class was modified.
*
* @return true if the class was modified
*/
public boolean weave() {
if (clazz.isWoven() && !clazz.isReweavable()) {
if (world.getLint().nonReweavableTypeEncountered.isEnabled()) {
world.getLint().nonReweavableTypeEncountered.signal(clazz.getType().getName(), ty.getSourceLocation());
}
// Integer uniqueID = new Integer(rm.hashCode() * deca.hashCode());
// if (!reportedProblems.contains(uniqueID)) {
// reportedProblems.add(uniqueID);
// world.getLint().elementAlreadyAnnotated.signal(new String[] { rm.toString(),
// world.showMessage(IMessage.ERROR, WeaverMessages.format(WeaverMessages.ALREADY_WOVEN, clazz.getType().getName()),
// ty.getSourceLocation(), null);
return false;
}
Set<String> aspectsAffectingType = null;
if (inReweavableMode || clazz.getType().isAspect()) {
aspectsAffectingType = new HashSet<String>();
}
boolean isChanged = false;
// we want to "touch" all aspects
if (clazz.getType().isAspect()) {
isChanged = true;
}
WeaverStateInfo typeWeaverState = (world.isOverWeaving() ? getLazyClassGen().getType().getWeaverState() : null);
// start by munging all typeMungers
for (ConcreteTypeMunger o : typeMungers) {
if (!(o instanceof BcelTypeMunger)) {
// ???System.err.println("surprising: " + o);
continue;
}
BcelTypeMunger munger = (BcelTypeMunger) o;
if (typeWeaverState != null && typeWeaverState.isAspectAlreadyApplied(munger.getAspectType())) {
continue;
}
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
isChanged = true;
if (inReweavableMode || clazz.getType().isAspect()) {
aspectsAffectingType.add(munger.getAspectType().getSignature());
}
}
}
// 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<IfaceInitList>(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<LazyMethodGen> methodGens = new ArrayList<LazyMethodGen>(clazz.getMethodGens());
for (LazyMethodGen member : methodGens) {
if (!member.hasBody()) {
continue;
}
if (world.isJoinpointSynchronizationEnabled() && world.areSynchronizationPointcutsInUse()
&& member.getMethod().isSynchronized()) {
transformSynchronizedMethod(member);
}
boolean shadowMungerMatched = match(member);
if (shadowMungerMatched) {
// For matching mungers, add their declaring aspects to the list
// that affected this type
if (inReweavableMode || clazz.getType().isAspect()) {
aspectsAffectingType.addAll(findAspectsForMungers(member));
}
isChanged = true;
}
}
// now we weave all but the initialization shadows
for (LazyMethodGen methodGen : methodGens) {
if (!methodGen.hasBody()) {
continue;
}
implement(methodGen);
}
// 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"
List<LazyMethodGen> recursiveCtors = new ArrayList<LazyMethodGen>();
while (inlineSelfConstructors(methodGens, recursiveCtors)) {
}
positionAndImplement(initializationShadows);
}
// now proceed with late type mungers
if (lateTypeMungers != null) {
for (Iterator<ConcreteTypeMunger> 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().getSignature());
}
}
}
}
}
// FIXME AV - see #75442, for now this is not enough to fix the bug,
// comment that out until we really fix it
// // flush to save some memory
// PerObjectInterfaceTypeMunger.unregisterFromAsAdvisedBy(clazz.getType()
// );
// finally, if we changed, we add in the introduced methods.
if (isChanged) {
clazz.getOrCreateWeaverStateInfo(inReweavableMode);
weaveInAddedMethods(); // FIXME asc are these potentially affected
// by declare annotation?
}
if (inReweavableMode) {
WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo(true);
wsi.addAspectsAffectingType(aspectsAffectingType);
wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes());
wsi.setReweavable(true);
} else {
clazz.getOrCreateWeaverStateInfo(false).setReweavable(false);
}
// tidyup, reduce ongoing memory usage of BcelMethods that hang around
for (LazyMethodGen mg : methodGens) {
BcelMethod method = mg.getMemberView();
if (method != null) {
method.wipeJoinpointSignatures();
}
}
return isChanged;
}
// **************************** start of bridge method creation code
// *****************
// FIXASC tidy this lot up !!
// FIXASC refactor into ResolvedType or even ResolvedMember?
/**
* Check if a particular method is overriding another - refactored into this helper so it can be used from multiple places.
* @return method that is overriding if it
*/
private static ResolvedMember isOverriding(ResolvedType typeToCheck, ResolvedMember methodThatMightBeGettingOverridden,
String mname, String mrettype, int mmods, boolean inSamePackage, UnresolvedType[] methodParamsArray) {
// Check if we can be an override...
if (Modifier.isStatic(methodThatMightBeGettingOverridden.getModifiers())) {
// we can't be overriding a static method
return null;
}
if (Modifier.isPrivate(methodThatMightBeGettingOverridden.getModifiers())) {
// we can't be overriding a private method
return null;
}
if (!methodThatMightBeGettingOverridden.getName().equals(mname)) {
// names do not match (this will also skip <init> and <clinit>)
return null;
}
if (methodThatMightBeGettingOverridden.getParameterTypes().length != methodParamsArray.length) {
// not the same number of parameters
return null;
}
if (!isVisibilityOverride(mmods, methodThatMightBeGettingOverridden, inSamePackage)) {
// not override from visibility point of view
return null;
}
if (typeToCheck.getWorld().forDEBUG_bridgingCode) {
System.err.println(" Bridging:seriously considering this might be getting overridden '"
+ methodThatMightBeGettingOverridden + "'");
}
World w = typeToCheck.getWorld();
// Look at erasures of parameters (List<String> erased is List)
boolean sameParams = true;
for (int p = 0, max = methodThatMightBeGettingOverridden.getParameterTypes().length; p < max; p++) {
UnresolvedType mtmbgoParameter = methodThatMightBeGettingOverridden.getParameterTypes()[p];
UnresolvedType ptype = methodParamsArray[p];
if (mtmbgoParameter.isTypeVariableReference()) {
if (!mtmbgoParameter.resolve(w).isAssignableFrom(ptype.resolve(w))) {
sameParams = false;
}
} else {
// old condition:
boolean b = !methodThatMightBeGettingOverridden.getParameterTypes()[p].getErasureSignature().equals(
methodParamsArray[p].getErasureSignature());
UnresolvedType parameterType = methodThatMightBeGettingOverridden.getParameterTypes()[p];
// Collapse to first bound (isn't that the same as erasure!
if (parameterType instanceof UnresolvedTypeVariableReferenceType) {
parameterType = ((UnresolvedTypeVariableReferenceType) parameterType).getTypeVariable().getFirstBound();
}
if (b) { // !parameterType.resolve(w).equals(parameterType2.resolve(w))) {
sameParams = false;
}
}
//
// if (!ut.getErasureSignature().equals(ut2.getErasureSignature()))
// sameParams = false;
}
// If the 'typeToCheck' represents a parameterized type then the method
// will be the parameterized form of the
// generic method in the generic type. So if the method was 'void
// m(List<T> lt, T t)' and the parameterized type here
// is I<String> then the method we are looking at will be 'void
// m(List<String> lt, String t)' which when erased
// is 'void m(List lt,String t)' - so if the parameters *do* match then
// there is a generic method we are
// overriding
// FIXASC Why bother with the return type? If it is incompatible then the code has other problems!
if (sameParams) {
if (typeToCheck.isParameterizedType()) {
return methodThatMightBeGettingOverridden.getBackingGenericMember();
} else if (!methodThatMightBeGettingOverridden.getReturnType().getErasureSignature().equals(mrettype)) {
// addressing the wierd situation from bug 147801
// just check whether these things are in the right relationship
// for covariance...
ResolvedType superReturn = typeToCheck.getWorld().resolve(
UnresolvedType.forSignature(methodThatMightBeGettingOverridden.getReturnType().getErasureSignature()));
ResolvedType subReturn = typeToCheck.getWorld().resolve(UnresolvedType.forSignature(mrettype));
if (superReturn.isAssignableFrom(subReturn)) {
return methodThatMightBeGettingOverridden;
}
// } else if (typeToCheck.isParameterizedType()) {
// return methodThatMightBeGettingOverridden.getBackingGenericMember();
} else {
return methodThatMightBeGettingOverridden;
}
}
return null;
}
/**
* Looks at the visibility modifiers between two methods, and knows whether they are from classes in the same package, and
* decides whether one overrides the other.
*
* @return true if there is an overrides rather than a 'hides' relationship
*/
static boolean isVisibilityOverride(int methodMods, ResolvedMember inheritedMethod, boolean inSamePackage) {
int inheritedModifiers = inheritedMethod.getModifiers();
if (Modifier.isStatic(inheritedModifiers)) {
return false;
}
if (methodMods == inheritedModifiers) {
return true;
}
if (Modifier.isPrivate(inheritedModifiers)) {
return false;
}
boolean isPackageVisible = !Modifier.isPrivate(inheritedModifiers) && !Modifier.isProtected(inheritedModifiers)
&& !Modifier.isPublic(inheritedModifiers);
if (isPackageVisible && !inSamePackage) {
return false;
}
return true;
}
/**
* This method recurses up a specified type looking for a method that overrides the one passed in.
*
* @return the method being overridden or null if none is found
*/
public static void checkForOverride(ResolvedType typeToCheck, String mname, String mparams, String mrettype,
int mmods, String mpkg, UnresolvedType[] methodParamsArray, List<ResolvedMember> overriddenMethodsCollector) {
if (typeToCheck == null) {
return;
}
if (typeToCheck instanceof MissingResolvedTypeWithKnownSignature) {
return; // we just can't tell !
}
if (typeToCheck.getWorld().forDEBUG_bridgingCode) {
System.err.println(" Bridging:checking for override of " + mname + " in " + typeToCheck);
}
String packageName = typeToCheck.getPackageName();
if (packageName == null) {
packageName = "";
}
// used when looking at visibility rules
boolean inSamePackage = packageName.equals(mpkg);
ResolvedMember[] methods = typeToCheck.getDeclaredMethods();
for (int ii = 0; ii < methods.length; ii++) {
// the method we are going to check
ResolvedMember methodThatMightBeGettingOverridden = methods[ii];
ResolvedMember isOverriding = isOverriding(typeToCheck, methodThatMightBeGettingOverridden, mname, mrettype, mmods,
inSamePackage, methodParamsArray);
if (isOverriding != null) {
overriddenMethodsCollector.add(isOverriding);
}
}
// was: List l = typeToCheck.getInterTypeMungers();
List<ConcreteTypeMunger> l = (typeToCheck.isRawType() ? typeToCheck.getGenericType().getInterTypeMungers() : typeToCheck
.getInterTypeMungers());
for (Iterator<ConcreteTypeMunger> iterator = l.iterator(); iterator.hasNext();) {
ConcreteTypeMunger o = iterator.next();
// FIXME asc if its not a BcelTypeMunger then its an
// EclipseTypeMunger ... do I need to worry about that?
if (o instanceof BcelTypeMunger) {
BcelTypeMunger element = (BcelTypeMunger) o;
if (element.getMunger() instanceof NewMethodTypeMunger) {
if (typeToCheck.getWorld().forDEBUG_bridgingCode) {
System.err.println("Possible ITD candidate " + element);
}
ResolvedMember aMethod = element.getSignature();
ResolvedMember isOverriding = isOverriding(typeToCheck, aMethod, mname, mrettype, mmods, inSamePackage,
methodParamsArray);
if (isOverriding != null) {
overriddenMethodsCollector.add(isOverriding);
}
}
}
}
if (typeToCheck.equals(UnresolvedType.OBJECT)) {
return;
}
ResolvedType superclass = typeToCheck.getSuperclass();
checkForOverride(superclass, mname, mparams, mrettype, mmods, mpkg, methodParamsArray,overriddenMethodsCollector);
ResolvedType[] interfaces = typeToCheck.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
ResolvedType anInterface = interfaces[i];
checkForOverride(anInterface, mname, mparams, mrettype, mmods, mpkg, methodParamsArray,overriddenMethodsCollector);
}
}
/**
* We need to determine if any methods in this type require bridge methods - this method should only be called if necessary to
* do this calculation, i.e. we are on a 1.5 VM (where covariance/generics exist) and the type hierarchy for the specified class
* has changed (via decp/itd).
*
* See pr108101
*/
public static boolean calculateAnyRequiredBridgeMethods(BcelWorld world, LazyClassGen clazz) {
world.ensureAdvancedConfigurationProcessed();
if (!world.isInJava5Mode()) {
return false; // just double check... the caller should have already
}
if (clazz.isInterface()) {
return false; // dont bother if we are an interface
}
boolean didSomething = false; // set if we build any bridge methods
// So what methods do we have right now in this class?
List<LazyMethodGen> methods = clazz.getMethodGens();
// Keep a set of all methods from this type - it'll help us to check if bridge methods
// have already been created, we don't want to do it twice!
Set<String> methodsSet = new HashSet<String>();
for (int i = 0; i < methods.size(); i++) {
LazyMethodGen aMethod = methods.get(i);
StringBuilder sb = new StringBuilder(aMethod.getName());
sb.append(aMethod.getSignature());
methodsSet.add(sb.toString()); // e.g. "foo(Ljava/lang/String;)V"
}
// Now go through all the methods in this type
for (int i = 0; i < methods.size(); i++) {
// This is the local method that we *might* have to bridge to
LazyMethodGen bridgeToCandidate = methods.get(i);
if (bridgeToCandidate.isBridgeMethod()) {
continue; // Doh!
}
String name = bridgeToCandidate.getName();
String psig = bridgeToCandidate.getParameterSignature();
String rsig = bridgeToCandidate.getReturnType().getSignature();
// if (bridgeToCandidate.isAbstract()) continue;
if (bridgeToCandidate.isStatic()) {
continue; // ignore static methods
}
if (name.endsWith("init>")) {
continue; // Skip constructors and static initializers
}
if (world.forDEBUG_bridgingCode) {
System.err.println("Bridging: Determining if we have to bridge to " + clazz.getName() + "." + name + "" + bridgeToCandidate.getSignature());
}
// Let's take a look at the superclass
ResolvedType theSuperclass = clazz.getSuperClass();
if (world.forDEBUG_bridgingCode) {
System.err.println("Bridging: Checking supertype " + theSuperclass);
}
String pkgName = clazz.getPackageName();
UnresolvedType[] bm = BcelWorld.fromBcel(bridgeToCandidate.getArgumentTypes());
List<ResolvedMember> overriddenMethodsCollector = new ArrayList<ResolvedMember>();
checkForOverride(theSuperclass, name, psig, rsig, bridgeToCandidate.getAccessFlags(), pkgName, bm, overriddenMethodsCollector);
if (overriddenMethodsCollector.size() != 0) {
for (ResolvedMember overriddenMethod: overriddenMethodsCollector) {
String key = new StringBuilder(overriddenMethod.getName()).append(overriddenMethod.getSignatureErased()).toString(); // pr237419
boolean alreadyHaveABridgeMethod = methodsSet.contains(key);
if (!alreadyHaveABridgeMethod) {
if (world.forDEBUG_bridgingCode) {
System.err.println("Bridging:bridging to '" + overriddenMethod + "'");
}
createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod);
methodsSet.add(key);
didSomething = true;
}
}
}
// Check superinterfaces
String[] interfaces = clazz.getInterfaceNames();
for (int j = 0; j < interfaces.length; j++) {
if (world.forDEBUG_bridgingCode) {
System.err.println("Bridging:checking superinterface " + interfaces[j]);
}
ResolvedType interfaceType = world.resolve(interfaces[j]);
overriddenMethodsCollector.clear();
checkForOverride(interfaceType, name, psig, rsig, bridgeToCandidate.getAccessFlags(),
clazz.getPackageName(), bm, overriddenMethodsCollector);
for (ResolvedMember overriddenMethod: overriddenMethodsCollector) {
String key = new StringBuffer().append(overriddenMethod.getName()).append(overriddenMethod.getSignatureErased()).toString(); // pr237419
boolean alreadyHaveABridgeMethod = methodsSet.contains(key);
if (!alreadyHaveABridgeMethod) {
createBridgeMethod(world, bridgeToCandidate, clazz, overriddenMethod);
methodsSet.add(key);
didSomething = true;
if (world.forDEBUG_bridgingCode) {
System.err.println("Bridging:bridging to " + overriddenMethod);
}
}
}
}
}
return didSomething;
}
// **************************** end of bridge method creation code *****************
/**
* Weave any declare @method/@ctor statements into the members of the supplied class
*/
private boolean weaveDeclareAtMethodCtor(LazyClassGen clazz) {
List<Integer> reportedProblems = new ArrayList<Integer>();
List<DeclareAnnotation> allDecams = world.getDeclareAnnotationOnMethods();
if (allDecams.isEmpty()) {
return false;
}
boolean isChanged = false;
// deal with ITDs
List<ConcreteTypeMunger> 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<LazyMethodGen> members = clazz.getMethodGens();
List<DeclareAnnotation> decaMs = getMatchingSubset(allDecams, clazz.getType());
if (decaMs.isEmpty()) {
return false; // nothing to do
}
if (!members.isEmpty()) {
Set<DeclareAnnotation> unusedDecams = new HashSet<DeclareAnnotation>();
unusedDecams.addAll(decaMs);
for (int memberCounter = 0; memberCounter < members.size(); memberCounter++) {
LazyMethodGen mg = members.get(memberCounter);
if (!mg.getName().startsWith(NameMangler.PREFIX)) {
// Single first pass
List<DeclareAnnotation> worthRetrying = new ArrayList<DeclareAnnotation>();
boolean modificationOccured = false;
List<AnnotationGen> annotationsToAdd = null;
for (DeclareAnnotation decaM : decaMs) {
if (decaM.matches(mg.getMemberView(), world)) {
if (doesAlreadyHaveAnnotation(mg.getMemberView(), decaM, reportedProblems)) {
// remove the declare @method since don't want
// an error when the annotation is already there
unusedDecams.remove(decaM);
continue; // skip this one...
}
if (annotationsToAdd == null) {
annotationsToAdd = new ArrayList<AnnotationGen>();
}
AnnotationGen a = ((BcelAnnotation) decaM.getAnnotation()).getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a, clazz.getConstantPool(), true);
annotationsToAdd.add(ag);
mg.addAnnotation(decaM.getAnnotation());
AsmRelationshipProvider.addDeclareAnnotationMethodRelationship(decaM.getSourceLocation(),
clazz.getName(), mg.getMemberView(), world.getModelAsAsmManager());// getMethod());
reportMethodCtorWeavingMessage(clazz, mg.getMemberView(), decaM, mg.getDeclarationLineNumber());
isChanged = true;
modificationOccured = true;
// remove the declare @method since have matched
// against it
unusedDecams.remove(decaM);
} else {
if (!decaM.isStarredAnnotationPattern()) {
worthRetrying.add(decaM); // an annotation is
// specified that
// might be put on
// by a subsequent
// decaf
}
}
}
// Multiple secondary passes
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
// lets have another go
List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
for (DeclareAnnotation decaM : worthRetrying) {
if (decaM.matches(mg.getMemberView(), world)) {
if (doesAlreadyHaveAnnotation(mg.getMemberView(), decaM, reportedProblems)) {
// remove the declare @method since don't
// want an error when
// the annotation is already there
unusedDecams.remove(decaM);
continue; // skip this one...
}
if (annotationsToAdd == null) {
annotationsToAdd = new ArrayList<AnnotationGen>();
}
AnnotationGen a = ((BcelAnnotation) decaM.getAnnotation()).getBcelAnnotation();
// create copy to get the annotation type into the right constant pool
AnnotationGen ag = new AnnotationGen(a, clazz.getConstantPool(), true);
annotationsToAdd.add(ag);
mg.addAnnotation(decaM.getAnnotation());
AsmRelationshipProvider.addDeclareAnnotationMethodRelationship(decaM.getSourceLocation(),
clazz.getName(), mg.getMemberView(), world.getModelAsAsmManager());// getMethod());
isChanged = true;
modificationOccured = true;
forRemoval.add(decaM);
// remove the declare @method since have matched
// against it
unusedDecams.remove(decaM);
}
}
worthRetrying.removeAll(forRemoval);
}
if (annotationsToAdd != null) {
Method oldMethod = mg.getMethod();
MethodGen myGen = new MethodGen(oldMethod, clazz.getClassName(), clazz.getConstantPool(), false);
for (AnnotationGen a : annotationsToAdd) {
myGen.addAnnotation(a);
}
Method newMethod = myGen.getMethod();
members.set(memberCounter, new LazyMethodGen(newMethod, clazz));
}
}
}
checkUnusedDeclareAts(unusedDecams, false);
}
return isChanged;
}
// TAG: WeavingMessage
private void reportMethodCtorWeavingMessage(LazyClassGen clazz, ResolvedMember member, DeclareAnnotation decaM,
int memberLineNumber) {
if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
StringBuffer parmString = new StringBuffer("(");
UnresolvedType[] paramTypes = member.getParameterTypes();
for (int i = 0; i < paramTypes.length; i++) {
UnresolvedType type = paramTypes[i];
String s = org.aspectj.apache.bcel.classfile.Utility.signatureToString(type.getSignature());
if (s.lastIndexOf('.') != -1) {
s = s.substring(s.lastIndexOf('.') + 1);
}
parmString.append(s);
if ((i + 1) < paramTypes.length) {
parmString.append(",");
}
}
parmString.append(")");
String methodName = member.getName();
StringBuffer sig = new StringBuffer();
sig.append(org.aspectj.apache.bcel.classfile.Utility.accessToString(member.getModifiers()));
sig.append(" ");
sig.append(member.getReturnType().toString());
sig.append(" ");
sig.append(member.getDeclaringType().toString());
sig.append(".");
sig.append(methodName.equals("<init>") ? "new" : methodName);
sig.append(parmString);
StringBuffer loc = new StringBuffer();
if (clazz.getFileName() == null) {
loc.append("no debug info available");
} else {
loc.append(clazz.getFileName());
if (memberLineNumber != -1) {
loc.append(":" + memberLineNumber);
}
}
getWorld().getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(
WeaveMessage.WEAVEMESSAGE_ANNOTATES,
new String[] { sig.toString(), loc.toString(), decaM.getAnnotationString(),
methodName.startsWith("<init>") ? "constructor" : "method", decaM.getAspect().toString(),
Utility.beautifyLocation(decaM.getSourceLocation()) }));
}
}
/**
* Looks through a list of declare annotation statements and only returns those that could possibly match on a field/method/ctor
* in type.
*/
private List<DeclareAnnotation> getMatchingSubset(List<DeclareAnnotation> declareAnnotations, ResolvedType type) {
List<DeclareAnnotation> subset = new ArrayList<DeclareAnnotation>();
for (DeclareAnnotation da : declareAnnotations) {
if (da.couldEverMatch(type)) {
subset.add(da);
}
}
return subset;
}
/**
* Get a subset of all the type mungers defined on this aspect
*/
private List<ConcreteTypeMunger> getITDSubset(LazyClassGen clazz, ResolvedTypeMunger.Kind wantedKind) {
List<ConcreteTypeMunger> subset = new ArrayList<ConcreteTypeMunger>();
for (ConcreteTypeMunger typeMunger : clazz.getBcelObjectType().getTypeMungers()) {
if (typeMunger.getMunger().getKind() == wantedKind) {
subset.add(typeMunger);
}
}
return subset;
}
public LazyMethodGen locateAnnotationHolderForFieldMunger(LazyClassGen clazz, ConcreteTypeMunger fieldMunger) {
NewFieldTypeMunger newFieldMunger = (NewFieldTypeMunger) fieldMunger.getMunger();
ResolvedMember lookingFor = AjcMemberMaker.interFieldInitializer(newFieldMunger.getSignature(), clazz.getType());
for (LazyMethodGen method : clazz.getMethodGens()) {
if (method.getName().equals(lookingFor.getName())) {
return method;
}
}
return null;
}
// FIXME asc refactor this to neaten it up
public LazyMethodGen locateAnnotationHolderForMethodCtorMunger(LazyClassGen clazz, ConcreteTypeMunger methodCtorMunger) {
ResolvedTypeMunger rtMunger = methodCtorMunger.getMunger();
ResolvedMember lookingFor = null;
if (rtMunger instanceof NewMethodTypeMunger) {
NewMethodTypeMunger nftm = (NewMethodTypeMunger) rtMunger;
lookingFor = AjcMemberMaker.interMethodDispatcher(nftm.getSignature(), methodCtorMunger.getAspectType());
} else if (rtMunger instanceof NewConstructorTypeMunger) {
NewConstructorTypeMunger nftm = (NewConstructorTypeMunger) rtMunger;
lookingFor = AjcMemberMaker.postIntroducedConstructor(methodCtorMunger.getAspectType(), nftm.getSignature()
.getDeclaringType(), nftm.getSignature().getParameterTypes());
} else {
throw new BCException("Not sure what this is: " + methodCtorMunger);
}
String name = lookingFor.getName();
String paramSignature = lookingFor.getParameterSignature();
for (LazyMethodGen member : clazz.getMethodGens()) {
if (member.getName().equals(name) && member.getParameterSignature().equals(paramSignature)) {
return member;
}
}
return null;
}
/**
* 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<DeclareAnnotation> decaFs, List<ConcreteTypeMunger> itdFields,
List<Integer> reportedErrors) {
boolean isChanged = false;
for (Iterator<ConcreteTypeMunger> iter = itdFields.iterator(); iter.hasNext();) {
BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next();
ResolvedMember itdIsActually = fieldMunger.getSignature();
Set<DeclareAnnotation> worthRetrying = new LinkedHashSet<DeclareAnnotation>();
boolean modificationOccured = false;
for (Iterator<DeclareAnnotation> iter2 = decaFs.iterator(); iter2.hasNext();) {
DeclareAnnotation decaF = iter2.next();
if (decaF.matches(itdIsActually, world)) {
if (decaF.isRemover()) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger);
if (annotationHolder.hasAnnotation(decaF.getAnnotationType())) {
isChanged = true;
// something to remove
annotationHolder.removeAnnotation(decaF.getAnnotationType());
AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(),
decaF.getSourceLocation(), itdIsActually.getSourceLocation(), true);
} else {
worthRetrying.add(decaF);
}
} else {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger);
if (doesAlreadyHaveAnnotation(annotationHolder, itdIsActually, decaF, reportedErrors)) {
continue; // skip this one...
}
annotationHolder.addAnnotation(decaF.getAnnotation());
AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(),
decaF.getSourceLocation(), itdIsActually.getSourceLocation(), false);
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<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
for (Iterator<DeclareAnnotation> iter2 = worthRetrying.iterator(); iter2.hasNext();) {
DeclareAnnotation decaF = iter2.next();
if (decaF.matches(itdIsActually, world)) {
if (decaF.isRemover()) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger);
if (annotationHolder.hasAnnotation(decaF.getAnnotationType())) {
isChanged = true;
// something to remove
annotationHolder.removeAnnotation(decaF.getAnnotationType());
AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(),
decaF.getSourceLocation(), itdIsActually.getSourceLocation(), true);
forRemoval.add(decaF);
}
} else {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger);
if (doesAlreadyHaveAnnotation(annotationHolder, itdIsActually, decaF, reportedErrors)) {
continue; // skip this one...
}
annotationHolder.addAnnotation(decaF.getAnnotation());
AsmRelationshipProvider.addDeclareAnnotationRelationship(world.getModelAsAsmManager(),
decaF.getSourceLocation(), itdIsActually.getSourceLocation(), false);
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<DeclareAnnotation> decaMCs,
List<ConcreteTypeMunger> itdsForMethodAndConstructor, List<Integer> reportedErrors) {
boolean isChanged = false;
AsmManager asmManager = world.getModelAsAsmManager();
for (ConcreteTypeMunger methodctorMunger : itdsForMethodAndConstructor) {
// for (Iterator iter = itdsForMethodAndConstructor.iterator(); iter.hasNext();) {
// BcelTypeMunger methodctorMunger = (BcelTypeMunger) iter.next();
ResolvedMember unMangledInterMethod = methodctorMunger.getSignature();
List<DeclareAnnotation> worthRetrying = new ArrayList<DeclareAnnotation>();
boolean modificationOccured = false;
for (Iterator<DeclareAnnotation> iter2 = decaMCs.iterator(); iter2.hasNext();) {
DeclareAnnotation decaMC = iter2.next();
if (decaMC.matches(unMangledInterMethod, world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz, methodctorMunger);
if (annotationHolder == null
|| doesAlreadyHaveAnnotation(annotationHolder, unMangledInterMethod, decaMC, reportedErrors)) {
continue; // skip this one...
}
annotationHolder.addAnnotation(decaMC.getAnnotation());
isChanged = true;
AsmRelationshipProvider.addDeclareAnnotationRelationship(asmManager, decaMC.getSourceLocation(),
unMangledInterMethod.getSourceLocation(), false);
reportMethodCtorWeavingMessage(clazz, unMangledInterMethod, decaMC, -1);
modificationOccured = true;
} else {
// If an annotation is specified, it might be added by one of the other declare annotation statements
if (!decaMC.isStarredAnnotationPattern()) {
worthRetrying.add(decaMC);
}
}
}
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
for (Iterator<DeclareAnnotation> iter2 = worthRetrying.iterator(); iter2.hasNext();) {
DeclareAnnotation decaMC = iter2.next();
if (decaMC.matches(unMangledInterMethod, world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, methodctorMunger);
if (doesAlreadyHaveAnnotation(annotationHolder, unMangledInterMethod, decaMC, reportedErrors)) {
continue; // skip this one...
}
annotationHolder.addAnnotation(decaMC.getAnnotation());
unMangledInterMethod.addAnnotation(decaMC.getAnnotation());
AsmRelationshipProvider.addDeclareAnnotationRelationship(asmManager, decaMC.getSourceLocation(),
unMangledInterMethod.getSourceLocation(), false);
isChanged = true;
modificationOccured = true;
forRemoval.add(decaMC);
}
worthRetrying.removeAll(forRemoval);
}
}
}
return isChanged;
}
private boolean dontAddTwice(DeclareAnnotation decaF, AnnotationAJ[] dontAddMeTwice) {
for (AnnotationAJ ann : dontAddMeTwice) {
if (ann != null && decaF.getAnnotation().getTypeName().equals(ann.getTypeName())) {
return true;
}
}
return false;
}
/**
* Remove an annotation from the supplied array, if it is in there.
*/
private AnnotationAJ[] removeFromAnnotationsArray(AnnotationAJ[] annotations,AnnotationAJ annotation) {
for (int i=0;i<annotations.length;i++) {
if (annotations[i] != null && annotation.getTypeName().equals(annotations[i].getTypeName())) {
// Remove it!
AnnotationAJ[] newArray = new AnnotationAJ[annotations.length-1];
int index=0;
for (int j=0;j<annotations.length;j++) {
if (j!=i) {
newArray[index++]=annotations[j];
}
}
return newArray;
}
}
return annotations;
}
// 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
/**
* Weave any declare @field statements into the fields of the supplied class. This will attempt to apply them to the ITDs too.
*
* 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) {
List<Integer> reportedProblems = new ArrayList<Integer>();
List<DeclareAnnotation> allDecafs = world.getDeclareAnnotationOnFields();
if (allDecafs.isEmpty()) {
return false;
}
boolean typeIsChanged = false;
List<ConcreteTypeMunger> relevantItdFields = getITDSubset(clazz, ResolvedTypeMunger.Field);
if (relevantItdFields != null) {
typeIsChanged = weaveAtFieldRepeatedly(allDecafs, relevantItdFields, reportedProblems);
}
List<DeclareAnnotation> decafs = getMatchingSubset(allDecafs, clazz.getType());
if (decafs.isEmpty()) {
return typeIsChanged;
}
List<BcelField> fields = clazz.getFieldGens();
if (fields != null) {
Set<DeclareAnnotation> unusedDecafs = new HashSet<DeclareAnnotation>();
unusedDecafs.addAll(decafs);
for (BcelField field : fields) {
if (!field.getName().startsWith(NameMangler.PREFIX)) {
// Single first pass
Set<DeclareAnnotation> worthRetrying = new LinkedHashSet<DeclareAnnotation>();
boolean modificationOccured = false;
AnnotationAJ[] dontAddMeTwice = field.getAnnotations();
// go through all the declare @field statements
for (DeclareAnnotation decaf : decafs) {
if (decaf.getAnnotation() == null) {
return false;
}
if (decaf.matches(field, world)) {
if (decaf.isRemover()) {
AnnotationAJ annotation = decaf.getAnnotation();
if (field.hasAnnotation(annotation.getType())) {
// something to remove
typeIsChanged = true;
field.removeAnnotation(annotation);
AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(),
decaf.getSourceLocation(), clazz.getName(), field, true);
reportFieldAnnotationWeavingMessage(clazz, field, decaf, true);
dontAddMeTwice = removeFromAnnotationsArray(dontAddMeTwice, annotation);
} else {
worthRetrying.add(decaf);
}
unusedDecafs.remove(decaf);
} else {
if (!dontAddTwice(decaf, dontAddMeTwice)) {
if (doesAlreadyHaveAnnotation(field, decaf, reportedProblems)) {
// remove the declare @field since don't want an error when the annotation is already there
unusedDecafs.remove(decaf);
continue;
}
field.addAnnotation(decaf.getAnnotation());
}
AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(),
decaf.getSourceLocation(), clazz.getName(), field, false);
reportFieldAnnotationWeavingMessage(clazz, field, decaf, false);
typeIsChanged = true;
modificationOccured = true;
unusedDecafs.remove(decaf);
}
} else if (!decaf.isStarredAnnotationPattern() || decaf.isRemover()) {
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 with any remaining ones
List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
for (Iterator<DeclareAnnotation> iter = worthRetrying.iterator(); iter.hasNext();) {
DeclareAnnotation decaF = iter.next();
if (decaF.matches(field, world)) {
if (decaF.isRemover()) {
AnnotationAJ annotation = decaF.getAnnotation();
if (field.hasAnnotation(annotation.getType())) {
// something to remove
typeIsChanged = modificationOccured = true;
forRemoval.add(decaF);
field.removeAnnotation(annotation);
AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(),
decaF.getSourceLocation(), clazz.getName(), field, true);
reportFieldAnnotationWeavingMessage(clazz, field, decaF, true);
}
} else {
// below code is for recursive things
unusedDecafs.remove(decaF);
if (doesAlreadyHaveAnnotation(field, decaF, reportedProblems)) {
continue;
}
field.addAnnotation(decaF.getAnnotation());
AsmRelationshipProvider.addDeclareAnnotationFieldRelationship(world.getModelAsAsmManager(),
decaF.getSourceLocation(), clazz.getName(), field, false);
typeIsChanged = modificationOccured = true;
forRemoval.add(decaF);
}
}
}
worthRetrying.removeAll(forRemoval);
}
}
}
checkUnusedDeclareAts(unusedDecafs, true);
}
return typeIsChanged;
}
// bug 99191 - put out an error message if the type doesn't exist
/**
* Report an error if the reason a "declare @method/ctor/field" was not used was because the member specified does not exist.
* This method is passed some set of declare statements that didn't match and a flag indicating whether the set contains declare @field
* or declare @method/ctor entries.
*/
private void checkUnusedDeclareAts(Set<DeclareAnnotation> unusedDecaTs, boolean isDeclareAtField) {
for (DeclareAnnotation declA : unusedDecaTs) {
// Error if an exact type pattern was specified
boolean shouldCheck = declA.isExactPattern() || declA.getSignaturePattern().getExactDeclaringTypes().size() != 0;
if (shouldCheck && declA.getKind() != DeclareAnnotation.AT_CONSTRUCTOR) {
if (declA.getSignaturePattern().isMatchOnAnyName()) {
shouldCheck = false;
} else {
List<ExactTypePattern> declaringTypePatterns = declA.getSignaturePattern().getExactDeclaringTypes();
if (declaringTypePatterns.size() == 0) {
shouldCheck = false;
} else {
for (ExactTypePattern exactTypePattern : declaringTypePatterns) {
if (exactTypePattern.isIncludeSubtypes()) {
shouldCheck = false;
break;
}
}
}
}
}
if (shouldCheck) {
// Quickly check if an ITD supplies the 'missing' member
boolean itdMatch = false;
List<ConcreteTypeMunger> lst = clazz.getType().getInterTypeMungers();
for (Iterator<ConcreteTypeMunger> iterator = lst.iterator(); iterator.hasNext() && !itdMatch;) {
ConcreteTypeMunger element = iterator.next();
if (element.getMunger() instanceof NewFieldTypeMunger) {
NewFieldTypeMunger nftm = (NewFieldTypeMunger) element.getMunger();
itdMatch = declA.matches(nftm.getSignature(), world);
} else if (element.getMunger() instanceof NewMethodTypeMunger) {
NewMethodTypeMunger nmtm = (NewMethodTypeMunger) element.getMunger();
itdMatch = declA.matches(nmtm.getSignature(), world);
} else if (element.getMunger() instanceof NewConstructorTypeMunger) {
NewConstructorTypeMunger nctm = (NewConstructorTypeMunger) element.getMunger();
itdMatch = declA.matches(nctm.getSignature(), world);
}
}
if (!itdMatch) {
IMessage message = null;
if (isDeclareAtField) {
message = new Message("The field '" + declA.getSignaturePattern().toString() + "' does not exist",
declA.getSourceLocation(), true);
} else {
message = new Message("The method '" + declA.getSignaturePattern().toString() + "' does not exist",
declA.getSourceLocation(), true);
}
world.getMessageHandler().handleMessage(message);
}
}
}
}
// TAG: WeavingMessage
private void reportFieldAnnotationWeavingMessage(LazyClassGen clazz, BcelField theField, DeclareAnnotation decaf,
boolean isRemove) {
if (!getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
world.getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(
isRemove ? WeaveMessage.WEAVEMESSAGE_REMOVES_ANNOTATION : WeaveMessage.WEAVEMESSAGE_ANNOTATES,
new String[] { theField.getFieldAsIs().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<Integer> reportedProblems) {
if (rm.hasAnnotation(deca.getAnnotationType())) {
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.getAnnotationType().toString() }, rm.getSourceLocation(),
new ISourceLocation[] { deca.getSourceLocation() });
}
}
return true;
}
return false;
}
private boolean doesAlreadyHaveAnnotation(LazyMethodGen rm, ResolvedMember itdfieldsig, DeclareAnnotation deca,
List<Integer> reportedProblems) {
if (rm != null && rm.hasAnnotation(deca.getAnnotationType())) {
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[] { itdfieldsig.toString(),
deca.getAnnotationType().toString() }, rm.getSourceLocation(),
new ISourceLocation[] { deca.getSourceLocation() });
}
}
return true;
}
return false;
}
private Set<String> findAspectsForMungers(LazyMethodGen mg) {
Set<String> aspectsAffectingType = new HashSet<String>();
for (BcelShadow shadow : mg.matchedShadows) {
for (ShadowMunger munger : shadow.getMungers()) {
if (munger instanceof BcelAdvice) {
BcelAdvice bcelAdvice = (BcelAdvice) munger;
if (bcelAdvice.getConcreteAspect() != null) {
aspectsAffectingType.add(bcelAdvice.getConcreteAspect().getSignature());
}
} else {
// It is a 'Checker' - we don't need to remember aspects
// that only contributed Checkers...
}
}
}
return aspectsAffectingType;
}
private boolean inlineSelfConstructors(List<LazyMethodGen> methodGens, List<LazyMethodGen> recursiveCtors) {
boolean inlinedSomething = false;
List<LazyMethodGen> newRecursiveCtors = new ArrayList<LazyMethodGen>();
for (LazyMethodGen methodGen : methodGens) {
if (!methodGen.getName().equals("<init>")) {
continue;
}
InstructionHandle ih = findSuperOrThisCall(methodGen);
if (ih != null && isThisCall(ih)) {
LazyMethodGen donor = getCalledMethod(ih);
if (donor.equals(methodGen)) {
newRecursiveCtors.add(donor);
} else {
if (!recursiveCtors.contains(donor)) {
inlineMethod(donor, methodGen, ih);
inlinedSomething = true;
}
}
}
}
recursiveCtors.addAll(newRecursiveCtors);
return inlinedSomething;
}
private void positionAndImplement(List<BcelShadow> initializationShadows) {
for (BcelShadow s : initializationShadows) {
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(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) {
InvokeInstruction inst = (InvokeInstruction) 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);
}
// public BcelVar genTempVar(UnresolvedType typeX) {
// return new BcelVar(typeX.resolve(world),
// genTempVarIndex(typeX.getSize()));
// }
//
// private int genTempVarIndex(int size) {
// return enclosingMethod.allocateLocal(size);
// }
/**
* Input method is a synchronized method, we remove the bit flag for synchronized and then insert a try..finally block
*
* Some jumping through firey hoops required - depending on the input code level (1.5 or not) we may or may not be able to use
* the LDC instruction that takes a class literal (doesnt on <1.5).
*
* FIXME asc Before promoting -Xjoinpoints:synchronization to be a standard option, this needs a bunch of tidying up - there is
* some duplication that can be removed.
*/
public static void transformSynchronizedMethod(LazyMethodGen synchronizedMethod) {
if (trace.isTraceEnabled()) {
trace.enter("transformSynchronizedMethod", synchronizedMethod);
}
// System.err.println("DEBUG: Transforming synchronized method: "+
// synchronizedMethod.getName());
final InstructionFactory fact = synchronizedMethod.getEnclosingClass().getFactory();
InstructionList body = synchronizedMethod.getBody();
InstructionList prepend = new InstructionList();
Type enclosingClassType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType());
// STATIC METHOD TRANSFORMATION
if (synchronizedMethod.isStatic()) {
// What to do here depends on the level of the class file!
// LDC can handle class literals in Java5 and above *sigh*
if (synchronizedMethod.getEnclosingClass().isAtLeastJava5()) {
// MONITORENTER logic:
// 0: ldc #2; //class C
// 2: dup
// 3: astore_0
// 4: monitorenter
int slotForLockObject = synchronizedMethod.allocateLocal(enclosingClassType);
prepend.append(fact.createConstant(enclosingClassType));
prepend.append(InstructionFactory.createDup(1));
prepend.append(InstructionFactory.createStore(enclosingClassType, slotForLockObject));
prepend.append(InstructionFactory.MONITORENTER);
// MONITOREXIT logic:
// We basically need to wrap the code from the method in a
// finally block that
// will ensure monitorexit is called. Content on the finally
// block seems to
// be always:
//
// E1: ALOAD_1
// MONITOREXIT
// ATHROW
//
// so lets build that:
InstructionList finallyBlock = new InstructionList();
finallyBlock.append(InstructionFactory.createLoad(Type.getType(java.lang.Class.class), slotForLockObject));
finallyBlock.append(InstructionConstants.MONITOREXIT);
finallyBlock.append(InstructionConstants.ATHROW);
// finally -> E1
// | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line
// 21)
// | LDC "hello"
// | INVOKEVIRTUAL java.io.PrintStream.println
// (Ljava/lang/String;)V
// | ALOAD_1 (line 20)
// | MONITOREXIT
// finally -> E1
// GOTO L0
// finally -> E1
// | E1: ALOAD_1
// | MONITOREXIT
// finally -> E1
// ATHROW
// L0: RETURN (line 23)
// search for 'returns' and make them jump to the
// aload_<n>,monitorexit
InstructionHandle walker = body.getStart();
List<InstructionHandle> rets = new ArrayList<InstructionHandle>();
while (walker != null) {
if (walker.getInstruction().isReturnInstruction()) {
rets.add(walker);
}
walker = walker.getNext();
}
if (!rets.isEmpty()) {
// need to ensure targeters for 'return' now instead target
// the load instruction
// (so we never jump over the monitorexit logic)
for (Iterator<InstructionHandle> iter = rets.iterator(); iter.hasNext();) {
InstructionHandle element = iter.next();
InstructionList monitorExitBlock = new InstructionList();
monitorExitBlock.append(InstructionFactory.createLoad(enclosingClassType, slotForLockObject));
monitorExitBlock.append(InstructionConstants.MONITOREXIT);
// monitorExitBlock.append(Utility.copyInstruction(element
// .getInstruction()));
// element.setInstruction(InstructionFactory.createLoad(
// classType,slotForThis));
InstructionHandle monitorExitBlockStart = body.insert(element, monitorExitBlock);
// now move the targeters from the RET to the start of
// the monitorexit block
for (InstructionTargeter targeter : element.getTargetersCopy()) {
// what kinds are there?
if (targeter instanceof LocalVariableTag) {
// ignore
} else if (targeter instanceof LineNumberTag) {
// ignore
// } else if (targeter instanceof
// InstructionBranch &&
// ((InstructionBranch)targeter).isGoto()) {
// // move it...
// targeter.updateTarget(element,
// monitorExitBlockStart);
} else if (targeter instanceof InstructionBranch) {
// move it
targeter.updateTarget(element, monitorExitBlockStart);
} else {
throw new BCException("Unexpected targeter encountered during transform: " + targeter);
}
}
}
}
// now the magic, putting the finally block around the code
InstructionHandle finallyStart = finallyBlock.getStart();
InstructionHandle tryPosition = body.getStart();
InstructionHandle catchPosition = body.getEnd();
body.insert(body.getStart(), prepend); // now we can put the
// monitorenter stuff on
synchronizedMethod.getBody().append(finallyBlock);
synchronizedMethod.addExceptionHandler(tryPosition, catchPosition, finallyStart, null/* ==finally */, false);
synchronizedMethod.addExceptionHandler(finallyStart, finallyStart.getNext(), finallyStart, null, false);
} else {
// TRANSFORMING STATIC METHOD ON PRE JAVA5
// Hideous nightmare, class literal references prior to Java5
// YIKES! this is just the code for MONITORENTER !
// 0: getstatic #59; //Field class$1:Ljava/lang/Class;
// 3: dup
// 4: ifnonnull 32
// 7: pop
// try
// 8: ldc #61; //String java.lang.String
// 10: invokestatic #44; //Method
// java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class;
// 13: dup
// catch
// 14: putstatic #59; //Field class$1:Ljava/lang/Class;
// 17: goto 32
// 20: new #46; //class java/lang/NoClassDefFoundError
// 23: dup_x1
// 24: swap
// 25: invokevirtual #52; //Method
// java/lang/Throwable.getMessage:()Ljava/lang/String;
// 28: invokespecial #54; //Method
// java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V
// 31: athrow
// 32: dup <-- partTwo (branch target)
// 33: astore_0
// 34: monitorenter
//
// plus exceptiontable entry!
// 8 13 20 Class java/lang/ClassNotFoundException
Type classType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType());
Type clazzType = Type.getType(Class.class);
InstructionList parttwo = new InstructionList();
parttwo.append(InstructionFactory.createDup(1));
int slotForThis = synchronizedMethod.allocateLocal(classType);
parttwo.append(InstructionFactory.createStore(clazzType, slotForThis)); // ? should be the real type ? String or
// something?
parttwo.append(InstructionFactory.MONITORENTER);
String fieldname = synchronizedMethod.getEnclosingClass().allocateField("class$");
FieldGen f = new FieldGen(Modifier.STATIC | Modifier.PRIVATE, Type.getType(Class.class), fieldname,
synchronizedMethod.getEnclosingClass().getConstantPool());
synchronizedMethod.getEnclosingClass().addField(f, null);
// 10: invokestatic #44; //Method
// java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class;
// 13: dup
// 14: putstatic #59; //Field class$1:Ljava/lang/Class;
// 17: goto 32
// 20: new #46; //class java/lang/NoClassDefFoundError
// 23: dup_x1
// 24: swap
// 25: invokevirtual #52; //Method
// java/lang/Throwable.getMessage:()Ljava/lang/String;
// 28: invokespecial #54; //Method
// java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V
// 31: athrow
String name = synchronizedMethod.getEnclosingClass().getName();
prepend.append(fact.createGetStatic(name, fieldname, Type.getType(Class.class)));
prepend.append(InstructionFactory.createDup(1));
prepend.append(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, parttwo.getStart()));
prepend.append(InstructionFactory.POP);
prepend.append(fact.createConstant(name));
InstructionHandle tryInstruction = prepend.getEnd();
prepend.append(fact.createInvoke("java.lang.Class", "forName", clazzType,
new Type[] { Type.getType(String.class) }, Constants.INVOKESTATIC));
InstructionHandle catchInstruction = prepend.getEnd();
prepend.append(InstructionFactory.createDup(1));
prepend.append(fact.createPutStatic(synchronizedMethod.getEnclosingClass().getType().getName(), fieldname,
Type.getType(Class.class)));
prepend.append(InstructionFactory.createBranchInstruction(Constants.GOTO, parttwo.getStart()));
// start of catch block
InstructionList catchBlockForLiteralLoadingFail = new InstructionList();
catchBlockForLiteralLoadingFail.append(fact.createNew((ObjectType) Type.getType(NoClassDefFoundError.class)));
catchBlockForLiteralLoadingFail.append(InstructionFactory.createDup_1(1));
catchBlockForLiteralLoadingFail.append(InstructionFactory.SWAP);
catchBlockForLiteralLoadingFail.append(fact.createInvoke("java.lang.Throwable", "getMessage",
Type.getType(String.class), new Type[] {}, Constants.INVOKEVIRTUAL));
catchBlockForLiteralLoadingFail.append(fact.createInvoke("java.lang.NoClassDefFoundError", "<init>", Type.VOID,
new Type[] { Type.getType(String.class) }, Constants.INVOKESPECIAL));
catchBlockForLiteralLoadingFail.append(InstructionFactory.ATHROW);
InstructionHandle catchBlockStart = catchBlockForLiteralLoadingFail.getStart();
prepend.append(catchBlockForLiteralLoadingFail);
prepend.append(parttwo);
// MONITORENTER
// pseudocode: load up 'this' (var0), dup it, store it in a new
// local var (for use with monitorexit) and call
// monitorenter:
// ALOAD_0, DUP, ASTORE_<n>, MONITORENTER
// prepend.append(InstructionFactory.createLoad(classType,0));
// prepend.append(InstructionFactory.createDup(1));
// int slotForThis =
// synchronizedMethod.allocateLocal(classType);
// prepend.append(InstructionFactory.createStore(classType,
// slotForThis));
// prepend.append(InstructionFactory.MONITORENTER);
// MONITOREXIT
// here be dragons
// We basically need to wrap the code from the method in a
// finally block that
// will ensure monitorexit is called. Content on the finally
// block seems to
// be always:
//
// E1: ALOAD_1
// MONITOREXIT
// ATHROW
//
// so lets build that:
InstructionList finallyBlock = new InstructionList();
finallyBlock.append(InstructionFactory.createLoad(Type.getType(java.lang.Class.class), slotForThis));
finallyBlock.append(InstructionConstants.MONITOREXIT);
finallyBlock.append(InstructionConstants.ATHROW);
// finally -> E1
// | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line
// 21)
// | LDC "hello"
// | INVOKEVIRTUAL java.io.PrintStream.println
// (Ljava/lang/String;)V
// | ALOAD_1 (line 20)
// | MONITOREXIT
// finally -> E1
// GOTO L0
// finally -> E1
// | E1: ALOAD_1
// | MONITOREXIT
// finally -> E1
// ATHROW
// L0: RETURN (line 23)
// frameEnv.put(donorFramePos, thisSlot);
// search for 'returns' and make them to the
// aload_<n>,monitorexit
InstructionHandle walker = body.getStart();
List<InstructionHandle> rets = new ArrayList<InstructionHandle>();
while (walker != null) { // !walker.equals(body.getEnd())) {
if (walker.getInstruction().isReturnInstruction()) {
rets.add(walker);
}
walker = walker.getNext();
}
if (rets.size() > 0) {
// need to ensure targeters for 'return' now instead target
// the load instruction
// (so we never jump over the monitorexit logic)
for (InstructionHandle ret : rets) {
// System.err.println("Adding monitor exit block at "+
// element);
InstructionList monitorExitBlock = new InstructionList();
monitorExitBlock.append(InstructionFactory.createLoad(classType, slotForThis));
monitorExitBlock.append(InstructionConstants.MONITOREXIT);
// monitorExitBlock.append(Utility.copyInstruction(element
// .getInstruction()));
// element.setInstruction(InstructionFactory.createLoad(
// classType,slotForThis));
InstructionHandle monitorExitBlockStart = body.insert(ret, monitorExitBlock);
// now move the targeters from the RET to the start of
// the monitorexit block
for (InstructionTargeter targeter : ret.getTargetersCopy()) {
// what kinds are there?
if (targeter instanceof LocalVariableTag) {
// ignore
} else if (targeter instanceof LineNumberTag) {
// ignore
// } else if (targeter instanceof GOTO ||
// targeter instanceof GOTO_W) {
// // move it...
// targeter.updateTarget(element,
// monitorExitBlockStart);
} else if (targeter instanceof InstructionBranch) {
// move it
targeter.updateTarget(ret, monitorExitBlockStart);
} else {
throw new BCException("Unexpected targeter encountered during transform: " + targeter);
}
}
}
}
// body =
// rewriteWithMonitorExitCalls(body,fact,true,slotForThis,
// classType);
// synchronizedMethod.setBody(body);
// now the magic, putting the finally block around the code
InstructionHandle finallyStart = finallyBlock.getStart();
InstructionHandle tryPosition = body.getStart();
InstructionHandle catchPosition = body.getEnd();
body.insert(body.getStart(), prepend); // now we can put the
// monitorenter stuff on
synchronizedMethod.getBody().append(finallyBlock);
synchronizedMethod.addExceptionHandler(tryPosition, catchPosition, finallyStart, null/* ==finally */, false);
synchronizedMethod.addExceptionHandler(tryInstruction, catchInstruction, catchBlockStart,
(ObjectType) Type.getType(ClassNotFoundException.class), true);
synchronizedMethod.addExceptionHandler(finallyStart, finallyStart.getNext(), finallyStart, null, false);
}
} else {
// TRANSFORMING NON STATIC METHOD
Type classType = BcelWorld.makeBcelType(synchronizedMethod.getEnclosingClass().getType());
// MONITORENTER
// pseudocode: load up 'this' (var0), dup it, store it in a new
// local var (for use with monitorexit) and call
// monitorenter:
// ALOAD_0, DUP, ASTORE_<n>, MONITORENTER
prepend.append(InstructionFactory.createLoad(classType, 0));
prepend.append(InstructionFactory.createDup(1));
int slotForThis = synchronizedMethod.allocateLocal(classType);
prepend.append(InstructionFactory.createStore(classType, slotForThis));
prepend.append(InstructionFactory.MONITORENTER);
// body.insert(body.getStart(),prepend);
// MONITOREXIT
// We basically need to wrap the code from the method in a finally
// block that
// will ensure monitorexit is called. Content on the finally block
// seems to
// be always:
//
// E1: ALOAD_1
// MONITOREXIT
// ATHROW
//
// so lets build that:
InstructionList finallyBlock = new InstructionList();
finallyBlock.append(InstructionFactory.createLoad(classType, slotForThis));
finallyBlock.append(InstructionConstants.MONITOREXIT);
finallyBlock.append(InstructionConstants.ATHROW);
// finally -> E1
// | GETSTATIC java.lang.System.out Ljava/io/PrintStream; (line 21)
// | LDC "hello"
// | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V
// | ALOAD_1 (line 20)
// | MONITOREXIT
// finally -> E1
// GOTO L0
// finally -> E1
// | E1: ALOAD_1
// | MONITOREXIT
// finally -> E1
// ATHROW
// L0: RETURN (line 23)
// frameEnv.put(donorFramePos, thisSlot);
// search for 'returns' and make them to the aload_<n>,monitorexit
InstructionHandle walker = body.getStart();
List<InstructionHandle> rets = new ArrayList<InstructionHandle>();
while (walker != null) { // !walker.equals(body.getEnd())) {
if (walker.getInstruction().isReturnInstruction()) {
rets.add(walker);
}
walker = walker.getNext();
}
if (!rets.isEmpty()) {
// need to ensure targeters for 'return' now instead target the
// load instruction
// (so we never jump over the monitorexit logic)
for (Iterator<InstructionHandle> iter = rets.iterator(); iter.hasNext();) {
InstructionHandle element = iter.next();
// System.err.println("Adding monitor exit block at "+element
// );
InstructionList monitorExitBlock = new InstructionList();
monitorExitBlock.append(InstructionFactory.createLoad(classType, slotForThis));
monitorExitBlock.append(InstructionConstants.MONITOREXIT);
// monitorExitBlock.append(Utility.copyInstruction(element.
// getInstruction()));
// element.setInstruction(InstructionFactory.createLoad(
// classType,slotForThis));
InstructionHandle monitorExitBlockStart = body.insert(element, monitorExitBlock);
// now move the targeters from the RET to the start of the
// monitorexit block
for (InstructionTargeter targeter : element.getTargetersCopy()) {
// what kinds are there?
if (targeter instanceof LocalVariableTag) {
// ignore
} else if (targeter instanceof LineNumberTag) {
// ignore
// } else if (targeter instanceof GOTO ||
// targeter instanceof GOTO_W) {
// // move it...
// targeter.updateTarget(element,
// monitorExitBlockStart);
} else if (targeter instanceof InstructionBranch) {
// move it
targeter.updateTarget(element, monitorExitBlockStart);
} else {
throw new BCException("Unexpected targeter encountered during transform: " + targeter);
}
}
}
}
// now the magic, putting the finally block around the code
InstructionHandle finallyStart = finallyBlock.getStart();
InstructionHandle tryPosition = body.getStart();
InstructionHandle catchPosition = body.getEnd();
body.insert(body.getStart(), prepend); // now we can put the
// monitorenter stuff on
synchronizedMethod.getBody().append(finallyBlock);
synchronizedMethod.addExceptionHandler(tryPosition, catchPosition, finallyStart, null/* ==finally */, false);
synchronizedMethod.addExceptionHandler(finallyStart, finallyStart.getNext(), finallyStart, null, false);
// also the exception handling for the finally block jumps to itself
// max locals will already have been modified in the allocateLocal()
// call
// synchronized bit is removed on LazyMethodGen.pack()
}
// gonna have to go through and change all aload_0s to load the var from
// a variable,
// going to add a new variable for the this var
if (trace.isTraceEnabled()) {
trace.exit("transformSynchronizedMethod");
}
}
/**
* 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<InstructionHandle, InstructionHandle> srcToDest = new HashMap<InstructionHandle, InstructionHandle>();
ConstantPool donorCpg = donor.getEnclosingClass().getConstantPool();
ConstantPool recipientCpg = recipient.getEnclosingClass().getConstantPool();
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;
// OPTIMIZE optimize this stuff?
if (fresh.isConstantPoolInstruction()) {
// 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) {
InstructionCP cpi = (InstructionCP) fresh;
cpi.setIndex(recipientCpg.addConstant(donorCpg.getConstant(cpi.getIndex()), donorCpg));
}
}
if (src.getInstruction() == Range.RANGEINSTRUCTION) {
dest = ret.append(Range.RANGEINSTRUCTION);
} else if (fresh.isReturnInstruction()) {
if (keepReturns) {
dest = ret.append(fresh);
} else {
dest = ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end));
}
} else if (fresh instanceof InstructionBranch) {
dest = ret.append((InstructionBranch) fresh);
} else if (fresh.isLocalVariableInstruction() || fresh instanceof RET) {
// IndexedInstruction indexed = (IndexedInstruction) fresh;
int oldIndex = fresh.getIndex();
int freshIndex;
if (!frameEnv.hasKey(oldIndex)) {
freshIndex = recipient.allocateLocal(2);
frameEnv.put(oldIndex, freshIndex);
} else {
freshIndex = frameEnv.get(oldIndex);
}
if (fresh instanceof RET) {
fresh.setIndex(freshIndex);
} else {
fresh = ((InstructionLV) fresh).setIndexAndCopyIfNecessary(freshIndex);
}
dest = ret.append(fresh);
} else {
dest = ret.append(fresh);
}
srcToDest.put(src, dest);
}
// second pass: retarget branch instructions, copy ranges and tags
Map<Tag, Tag> tagMap = new HashMap<Tag, Tag>();
Map<BcelShadow, BcelShadow> shadowMap = new HashMap<BcelShadow, BcelShadow>();
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 InstructionBranch) {
InstructionBranch branch = (InstructionBranch) inst;
InstructionHandle oldTarget = branch.getTarget();
InstructionHandle newTarget = 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 InstructionSelect) {
InstructionSelect select = (InstructionSelect) branch;
InstructionHandle[] oldTargets = select.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
select.setTarget(k, srcToDest.get(oldTargets[k]));
}
}
}
}
// copy over tags and range attributes
Iterator<InstructionTargeter> tIter = src.getTargeters().iterator();
while (tIter.hasNext()) {
InstructionTargeter old = tIter.next();
if (old instanceof Tag) {
Tag oldTag = (Tag) old;
Tag fresh = tagMap.get(oldTag);
if (fresh == null) {
fresh = oldTag.copy();
if (old instanceof LocalVariableTag) {
// LocalVariable
LocalVariableTag lvTag = (LocalVariableTag) old;
LocalVariableTag lvTagFresh = (LocalVariableTag) fresh;
if (lvTag.getSlot() == 0) {
fresh = new LocalVariableTag(lvTag.getRealType().getSignature(), "ajc$aspectInstance",
frameEnv.get(lvTag.getSlot()), 0);
} else {
// // Do not move it - when copying the code from the aspect to the affected target, 'this' is
// // going to change from aspect to affected type. So just fix the type
// System.out.println("For local variable tag at instruction " + src + " changing slot from "
// + lvTag.getSlot() + " > " + frameEnv.get(lvTag.getSlot()));
lvTagFresh.updateSlot(frameEnv.get(lvTag.getSlot()));
}
}
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, srcToDest.get(er.getEnd()), 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, srcToDest.get(oldRange.getEnd()));
shadowMap.put(oldShadow, freshShadow); // 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;
}
// static InstructionList rewriteWithMonitorExitCalls(InstructionList
// sourceList,InstructionFactory fact,boolean keepReturns,int
// monitorVarSlot,Type monitorVarType)
// {
// InstructionList footer = new InstructionList();
// InstructionHandle end = footer.append(InstructionConstants.NOP);
//
// InstructionList newList = new InstructionList();
//
// Map srcToDest = new HashMap();
//
// // 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 (src.getInstruction() == Range.RANGEINSTRUCTION) {
// dest = newList.append(Range.RANGEINSTRUCTION);
// } else if (fresh.isReturnInstruction()) {
// if (keepReturns) {
// newList.append(InstructionFactory.createLoad(monitorVarType,monitorVarSlot
// ));
// newList.append(InstructionConstants.MONITOREXIT);
// dest = newList.append(fresh);
// } else {
// dest =
// newList.append(InstructionFactory.createBranchInstruction(Constants.GOTO,
// end));
// }
// } else if (fresh instanceof InstructionBranch) {
// dest = newList.append((InstructionBranch) fresh);
// } else if (
// fresh.isLocalVariableInstruction() || fresh instanceof RET) {
// //IndexedInstruction indexed = (IndexedInstruction) fresh;
// int oldIndex = fresh.getIndex();
// int freshIndex;
// // if (!frameEnv.hasKey(oldIndex)) {
// // freshIndex = recipient.allocateLocal(2);
// // frameEnv.put(oldIndex, freshIndex);
// // } else {
// freshIndex = oldIndex;//frameEnv.get(oldIndex);
// // }
// if (fresh instanceof RET) {
// fresh.setIndex(freshIndex);
// } else {
// fresh = ((InstructionLV)fresh).setIndexAndCopyIfNecessary(freshIndex);
// }
// dest = newList.append(fresh);
// } else {
// dest = newList.append(fresh);
// }
// srcToDest.put(src, dest);
// }
//
// // second pass: retarget branch instructions, copy ranges and tags
// Map tagMap = new HashMap();
// for (InstructionHandle dest = newList.getStart(), src =
// sourceList.getStart();
// dest != null;
// dest = dest.getNext(), src = src.getNext()) {
// Instruction inst = dest.getInstruction();
//
// // retarget branches
// if (inst instanceof InstructionBranch) {
// InstructionBranch branch = (InstructionBranch) 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 InstructionSelect) {
// InstructionSelect select = (InstructionSelect) 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
// Iterator tIter = src.getTargeters().iterator();
//
// while (tIter.hasNext()) {
// InstructionTargeter old = (InstructionTargeter)tIter.next();
// 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(newList/*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) newList.append(footer);
// return newList;
// }
/**
* 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<LazyMethodGen>() {
public int compare(LazyMethodGen aa, LazyMethodGen bb) {
int i = aa.getName().compareTo(bb.getName());
if (i != 0) {
return i;
}
return aa.getSignature().compareTo(bb.getSignature());
}
});
for (LazyMethodGen addedMember : addedLazyMethodGens) {
clazz.addMethodGen(addedMember);
}
}
// 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.opcode == Constants.INVOKESPECIAL && ((InvokeInstruction) inst).getName(cpg).equals("<init>")) {
depth--;
if (depth == 0) {
return start;
}
} else if (inst.opcode == Constants.NEW) {
depth++;
}
start = start.getNext();
}
}
// ----
private boolean match(LazyMethodGen mg) {
BcelShadow enclosingShadow;
List<BcelShadow> shadowAccumulator = new ArrayList<BcelShadow>();
boolean isOverweaving = world.isOverWeaving();
boolean startsAngly = mg.getName().charAt(0) == '<';
// we want to match ajsynthetic constructors...
if (startsAngly && mg.getName().equals("<init>")) {
return matchInit(mg, shadowAccumulator);
} else if (!shouldWeaveBody(mg)) {
return false;
} else {
if (startsAngly && 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) {
// Don't want ajc$preClinit to be considered for matching
if (isOverweaving && mg.getName().startsWith(NameMangler.PREFIX)) {
return false;
}
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!!)
fixParameterNamesForResolvedMember(rm, mg.getMemberView());
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().charAt(0) == 'a' && mg.getName().startsWith("ajc$interFieldInit"))) {
if (match(enclosingShadow, shadowAccumulator)) {
enclosingShadow.init();
}
}
mg.matchedShadows = shadowAccumulator;
return !shadowAccumulator.isEmpty();
}
}
private boolean matchInit(LazyMethodGen mg, List<BcelShadow> shadowAccumulator) {
BcelShadow enclosingShadow;
// XXX the enclosing join point is wrong for things before ignoreMe.
InstructionHandle superOrThisCall = findSuperOrThisCall(mg);
// we don't walk bodies of things where it's a wrong constructor thingie
if (superOrThisCall == null) {
return false;
}
enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall);
if (mg.getEffectiveSignature() != null) {
enclosingShadow.setMatchingSignature(mg.getEffectiveSignature().getEffectiveSignature());
}
// walk the body
boolean beforeSuperOrThisCall = true;
if (shouldWeaveBody(mg)) {
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart(); h != null; h = h.getNext()) {
if (h == superOrThisCall) {
beforeSuperOrThisCall = false;
continue;
}
match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator);
}
}
if (canMatch(Shadow.ConstructorExecution)) {
match(enclosingShadow, shadowAccumulator);
}
}
// XXX we don't do pre-inits of interfaces
// now add interface inits
if (!isThisCall(superOrThisCall)) {
InstructionHandle curr = enclosingShadow.getRange().getStart();
for (Iterator<IfaceInitList> i = addedSuperInitializersAsList.iterator(); i.hasNext();) {
IfaceInitList l = 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<ConcreteTypeMunger> list, boolean isStatic) {
list = PartialOrder.sort(list);
if (list == null) {
throw new BCException("circularity in inter-types");
}
InstructionList ret = new InstructionList();
for (ConcreteTypeMunger cmunger : list) {
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<BcelShadow> shadowAccumulator) {
Instruction i = ih.getInstruction();
// Exception handlers (pr230817)
if (canMatch(Shadow.ExceptionHandler) && !Range.isRangeHandle(ih)) {
Set<InstructionTargeter> targeters = ih.getTargetersCopy();
// If in Java7 there may be overlapping exception ranges for multi catch - we should recognize that
for (InstructionTargeter t : targeters) {
if (t instanceof ExceptionRange) {
// assert t.getHandler() == ih
ExceptionRange er = (ExceptionRange) t;
if (er.getCatchType() == null) {
continue;
}
if (isInitFailureHandler(ih)) {
return;
}
if (!ih.getInstruction().isStoreInstruction() && ih.getInstruction().getOpcode() != Constants.NOP) {
// If using cobertura, the catch block stats with
// INVOKESTATIC rather than ASTORE, in order that the ranges
// for the methodcall and exceptionhandler shadows
// that occur at this same
// line, we need to modify the instruction list to
// split them - adding a
// NOP before the invokestatic that gets all the targeters
// that were aimed at the INVOKESTATIC
mg.getBody().insert(ih, InstructionConstants.NOP);
InstructionHandle newNOP = ih.getPrev();
// what about a try..catch that starts at the start
// of the exception handler? need to only include
// certain targeters really.
er.updateTarget(ih, newNOP, mg.getBody());
for (InstructionTargeter t2 : targeters) {
newNOP.addTargeter(t2);
}
ih.removeAllTargeters();
match(BcelShadow.makeExceptionHandler(world, er, mg, newNOP, enclosingShadow), shadowAccumulator);
} else {
match(BcelShadow.makeExceptionHandler(world, er, mg, ih, enclosingShadow), shadowAccumulator);
}
}
}
}
if ((i instanceof FieldInstruction) && (canMatch(Shadow.FieldGet) || canMatch(Shadow.FieldSet))) {
FieldInstruction fi = (FieldInstruction) i;
if (fi.opcode == Constants.PUTFIELD || fi.opcode == Constants.PUTSTATIC) {
// check for sets of constant fields. We first check the
// previous
// instruction. If the previous instruction is a LD_WHATEVER
// (push
// constant on the stack) then we must resolve the field to
// determine
// if it's final. If it is final, then we don't generate a
// shadow.
InstructionHandle prevHandle = ih.getPrev();
Instruction prevI = prevHandle.getInstruction();
if (Utility.isConstantPushInstruction(prevI)) {
Member field = BcelWorld.makeFieldJoinPointSignature(clazz, (FieldInstruction) i);
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
} else if (Modifier.isFinal(resolvedField.getModifiers())) {
// it's final, so it's the set of a final constant, so
// it's
// not a join point according to 1.0.6 and 1.1.
} else {
if (canMatch(Shadow.FieldSet)) {
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
}
} else {
if (canMatch(Shadow.FieldSet)) {
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
}
} else {
if (canMatch(Shadow.FieldGet)) {
matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
}
} else if (i instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction) i;
if (ii.getMethodName(clazz.getConstantPool()).equals("<init>")) {
if (canMatch(Shadow.ConstructorCall)) {
match(BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow), shadowAccumulator);
}
} else if (ii.opcode == Constants.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 {
if (ii.getOpcode()!=Constants.INVOKEDYNAMIC) {
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
}
}
} else if (world.isJoinpointArrayConstructionEnabled() && i.isArrayCreationInstruction()) {
if (canMatch(Shadow.ConstructorCall)) {
if (i.opcode == Constants.ANEWARRAY) {
// ANEWARRAY arrayInstruction = (ANEWARRAY)i;
// ObjectType arrayType = i.getLoadClassType(clazz.getConstantPool());
BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world, mg, ih, enclosingShadow);
match(ctorCallShadow, shadowAccumulator);
} else if (i.opcode == Constants.NEWARRAY) {
// NEWARRAY arrayInstruction = (NEWARRAY)i;
// Type arrayType = i.getType();
BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world, mg, ih, enclosingShadow);
match(ctorCallShadow, shadowAccumulator);
} else if (i instanceof MULTIANEWARRAY) {
// MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY) i;
// ObjectType arrayType = arrayInstruction.getLoadClassType(clazz.getConstantPool());
BcelShadow ctorCallShadow = BcelShadow.makeArrayConstructorCall(world, mg, ih, enclosingShadow);
match(ctorCallShadow, shadowAccumulator);
}
}
// see pr77166 if you are thinking about implementing this
// } else if (i instanceof AALOAD ) {
// AALOAD arrayLoad = (AALOAD)i;
// Type arrayType = arrayLoad.getType(clazz.getConstantPoolGen());
// BcelShadow arrayLoadShadow =
// BcelShadow.makeArrayLoadCall(world,mg,ih,enclosingShadow);
// match(arrayLoadShadow,shadowAccumulator);
// } else if (i instanceof AASTORE) {
// // ... magic required
} else if (world.isJoinpointSynchronizationEnabled()
&& ((i.getOpcode() == Constants.MONITORENTER) || (i.getOpcode() == Constants.MONITOREXIT))) {
// if (canMatch(Shadow.Monitoring)) {
if (i.getOpcode() == Constants.MONITORENTER) {
BcelShadow monitorEntryShadow = BcelShadow.makeMonitorEnter(world, mg, ih, enclosingShadow);
match(monitorEntryShadow, shadowAccumulator);
} else {
BcelShadow monitorExitShadow = BcelShadow.makeMonitorExit(world, mg, ih, enclosingShadow);
match(monitorExitShadow, 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().opcode == Constants.PUTSTATIC) {
String name = ((FieldInstruction) 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<BcelShadow> shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) {
return;
}
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (Modifier.isFinal(resolvedField.getModifiers())
&& Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) {
// it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
// Fix for bug 172107 (similar the "get" fix for bug 109728)
BcelShadow bs = BcelShadow.makeFieldSet(world, resolvedField, mg, ih, enclosingShadow);
String cname = fi.getClassName(cpg);
if (!resolvedField.getDeclaringType().getName().equals(cname)) {
bs.setActualTargetType(cname);
}
match(bs, shadowAccumulator);
}
}
private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow,
List<BcelShadow> shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldJoinPointSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) {
return;
}
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
BcelShadow bs = BcelShadow.makeFieldGet(world, resolvedField, mg, ih, enclosingShadow);
String cname = fi.getClassName(cpg);
if (!resolvedField.getDeclaringType().getName().equals(cname)) {
bs.setActualTargetType(cname);
}
match(bs, shadowAccumulator);
}
}
/**
* For some named resolved type, this method looks for a member with a particular name - it should only be used when you truly
* believe there is only one member with that name in the type as it returns the first one it finds.
*/
private ResolvedMember findResolvedMemberNamed(ResolvedType type, String methodName) {
ResolvedMember[] allMethods = type.getDeclaredMethods();
for (int i = 0; i < allMethods.length; i++) {
ResolvedMember member = allMethods[i];
if (member.getName().equals(methodName)) {
return member;
}
}
return null;
}
/**
* Find the specified member in the specified type.
*
* @param type the type to search for the member
* @param methodName the name of the method to find
* @param params the method parameters that the discovered method should have
*/
private ResolvedMember findResolvedMemberNamed(ResolvedType type, String methodName, UnresolvedType[] params) {
ResolvedMember[] allMethods = type.getDeclaredMethods();
List<ResolvedMember> candidates = new ArrayList<ResolvedMember>();
for (int i = 0; i < allMethods.length; i++) {
ResolvedMember candidate = allMethods[i];
if (candidate.getName().equals(methodName)) {
if (candidate.getArity() == params.length) {
candidates.add(candidate);
}
}
}
if (candidates.size() == 0) {
return null;
} else if (candidates.size() == 1) {
return candidates.get(0);
} else {
// multiple candidates
for (ResolvedMember candidate : candidates) {
// These checks will break down with generics... but that would need two ITDs with the same name, same arity and
// generics
boolean allOK = true;
UnresolvedType[] candidateParams = candidate.getParameterTypes();
for (int p = 0; p < candidateParams.length; p++) {
if (!candidateParams[p].getErasureSignature().equals(params[p].getErasureSignature())) {
allOK = false;
break;
}
}
if (allOK) {
return candidate;
}
}
}
return null;
}
/**
* For a given resolvedmember, this will discover the real annotations for it. <b>Should only be used when the resolvedmember is
* the contents of an effective signature attribute, as thats the only time when the annotations aren't stored directly in the
* resolvedMember</b>
*
* @param rm the sig we want it to pretend to be 'int A.m()' or somesuch ITD like thing
* @param declaredSig the real sig 'blah.ajc$xxx'
*/
private void fixParameterNamesForResolvedMember(ResolvedMember rm, ResolvedMember declaredSig) {
UnresolvedType memberHostType = declaredSig.getDeclaringType();
String methodName = declaredSig.getName();
String[] pnames = null;
if (rm.getKind() == Member.METHOD && !rm.isAbstract()) {
if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) {
ResolvedMember resolvedDooberry = world.resolve(declaredSig);
pnames = resolvedDooberry.getParameterNames();
} else {
ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world), memberHostType).resolve(world);
ResolvedMember theRealMember = findResolvedMemberNamed(memberHostType.resolve(world), realthing.getName());
if (theRealMember != null) {
pnames = theRealMember.getParameterNames();
// static ITDs don't need any parameter shifting
if (pnames.length > 0 && pnames[0].equals("ajc$this_")) {
String[] pnames2 = new String[pnames.length - 1];
System.arraycopy(pnames, 1, pnames2, 0, pnames2.length);
pnames = pnames2;
}
}
}
// i think ctors are missing from here... copy code from below...
}
rm.setParameterNames(pnames);
}
/**
* 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();
boolean containsKey = mapToAnnotationHolder.containsKey(rm);
ResolvedMember realAnnotationHolder = mapToAnnotationHolder.get(rm);
String methodName = declaredSig.getName();
// FIXME asc shouldnt really rely on string names !
if (!containsKey) {
if (rm.getKind() == Member.FIELD) {
if (methodName.startsWith("ajc$inlineAccessField")) {
realAnnotationHolder = world.resolve(rm);
} else {
ResolvedMember realthing = AjcMemberMaker.interFieldInitializer(rm, memberHostType);
realAnnotationHolder = world.resolve(realthing);
}
} else if (rm.getKind() == Member.METHOD && !rm.isAbstract()) {
if (methodName.startsWith("ajc$inlineAccessMethod") || methodName.startsWith("ajc$superDispatch")) {
realAnnotationHolder = world.resolve(declaredSig);
} else {
ResolvedMember realthing = AjcMemberMaker.interMethodDispatcher(rm.resolve(world), memberHostType).resolve(world);
realAnnotationHolder = findResolvedMemberNamed(memberHostType.resolve(world), realthing.getName(),realthing.getParameterTypes());
if (realAnnotationHolder == null) {
throw new UnsupportedOperationException(
"Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified");
}
}
} else if (rm.getKind() == Member.CONSTRUCTOR) {
ResolvedMember realThing = AjcMemberMaker.postIntroducedConstructor(memberHostType.resolve(world),rm.getDeclaringType(), rm.getParameterTypes());
realAnnotationHolder = world.resolve(realThing);
// AMC temp guard for M4
if (realAnnotationHolder == null) {
throw new UnsupportedOperationException("Known limitation in M4 - can't find ITD members when type variable is used as an argument and has upper bound specified");
}
}
mapToAnnotationHolder.put(rm, realAnnotationHolder);
}
ResolvedType[] annotationTypes;
AnnotationAJ[] annotations;
if (realAnnotationHolder!=null) {
annotationTypes = realAnnotationHolder.getAnnotationTypes();
annotations = realAnnotationHolder.getAnnotations();
if (annotationTypes==null) {
annotationTypes = ResolvedType.EMPTY_ARRAY;
}
if (annotations==null) {
annotations = AnnotationAJ.EMPTY_ARRAY;
}
} else {
annotations = AnnotationAJ.EMPTY_ARRAY;
annotationTypes = ResolvedType.EMPTY_ARRAY;
}
rm.setAnnotations(annotations);
rm.setAnnotationTypes(annotationTypes);
} catch (UnsupportedOperationException ex) {
throw ex;
} catch (Throwable t) {
// FIXME asc remove this catch after more testing has confirmed the
// above stuff is OK
throw new BCException("Unexpectedly went bang when searching for annotations on " + rm, t);
}
}
private void matchInvokeInstruction(LazyMethodGen mg, InstructionHandle ih, InvokeInstruction invoke,
BcelShadow enclosingShadow, List<BcelShadow> shadowAccumulator) {
String methodName = invoke.getName(cpg);
if (methodName.startsWith(NameMangler.PREFIX)) {
Member jpSig = world.makeJoinPointSignatureForMethodInvocation(clazz, invoke);
ResolvedMember declaredSig = jpSig.resolve(world);
// System.err.println(method + ", declaredSig: " +declaredSig);
if (declaredSig == null) {
return;
}
if (declaredSig.getKind() == Member.FIELD) {
Shadow.Kind kind;
if (jpSig.getReturnType().equals(UnresolvedType.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();
fixParameterNamesForResolvedMember(rm, declaredSig);
fixAnnotationsForResolvedMember(rm, declaredSig); // abracadabra
if (canMatch(effectiveSig.getShadowKind())) {
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow, effectiveSig.getShadowKind(), rm),
shadowAccumulator);
}
}
} else {
if (canMatch(Shadow.MethodCall)) {
boolean proceed = true;
// overweaving needs to ignore some calls added by the previous weave
if (world.isOverWeaving()) {
String s = invoke.getClassName(mg.getConstantPool());
// skip all the inc/dec/isValid/etc
if (s.length() > 4
&& s.charAt(4) == 'a'
&& (s.equals("org.aspectj.runtime.internal.CFlowCounter")
|| s.equals("org.aspectj.runtime.internal.CFlowStack") || s
.equals("org.aspectj.runtime.reflect.Factory"))) {
proceed = false;
} else {
if (methodName.equals("aspectOf")) {
proceed = false;
}
}
}
if (proceed) {
match(BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow), shadowAccumulator);
}
}
}
}
// static ... so all worlds will share the config for the first one
// created...
private static boolean checkedXsetForLowLevelContextCapturing = false;
private static boolean captureLowLevelContext = false;
private boolean match(BcelShadow shadow, List<BcelShadow> shadowAccumulator) {
// Duplicate blocks - one with context one without, seems faster than multiple 'ifs'
if (captureLowLevelContext) {
ContextToken shadowMatchToken = CompilationAndWeavingContext.enteringPhase(
CompilationAndWeavingContext.MATCHING_SHADOW, shadow);
boolean isMatched = false;
Shadow.Kind shadowKind = shadow.getKind();
List<ShadowMunger> candidateMungers = indexedShadowMungers[shadowKind.getKey()];
// System.out.println("Candidates " + candidateMungers);
if (candidateMungers != null) {
for (ShadowMunger munger : candidateMungers) {
ContextToken mungerMatchToken = CompilationAndWeavingContext.enteringPhase(
CompilationAndWeavingContext.MATCHING_POINTCUT, munger.getPointcut());
if (munger.match(shadow, world)) {
shadow.addMunger(munger);
isMatched = true;
if (shadow.getKind() == Shadow.StaticInitialization) {
clazz.warnOnAddedStaticInitializer(shadow, munger.getSourceLocation());
}
}
CompilationAndWeavingContext.leavingPhase(mungerMatchToken);
}
if (isMatched) {
shadowAccumulator.add(shadow);
}
}
CompilationAndWeavingContext.leavingPhase(shadowMatchToken);
return isMatched;
} else {
boolean isMatched = false;
Shadow.Kind shadowKind = shadow.getKind();
List<ShadowMunger> candidateMungers = indexedShadowMungers[shadowKind.getKey()];
// System.out.println("Candidates at " + shadowKind + " are " + candidateMungers);
if (candidateMungers != null) {
for (ShadowMunger munger : candidateMungers) {
if (munger.match(shadow, world)) {
shadow.addMunger(munger);
isMatched = true;
if (shadow.getKind() == Shadow.StaticInitialization) {
clazz.warnOnAddedStaticInitializer(shadow, munger.getSourceLocation());
}
}
}
if (isMatched) {
shadowAccumulator.add(shadow);
}
}
return isMatched;
}
}
// ----
private void implement(LazyMethodGen mg) {
List<BcelShadow> 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 (BcelShadow shadow : shadows) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.IMPLEMENTING_ON_SHADOW,
shadow);
shadow.implement();
CompilationAndWeavingContext.leavingPhase(tok);
}
// int ii =
mg.getMaxLocals();
mg.matchedShadows = null;
}
// ----
public LazyClassGen getLazyClassGen() {
return clazz;
}
public BcelWorld getWorld() {
return world;
}
public void setReweavableMode(boolean mode) {
inReweavableMode = mode;
}
public boolean getReweavableMode() {
return inReweavableMode;
}
@Override
public String toString() {
return "BcelClassWeaver instance for : " + clazz;
}
}
|
418,129 | Bug 418129 Can't introduce annotation onto introduced method from trait-patterned aspect | null | resolved fixed | 2393bef | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-01T17:00:14Z" | "2013-09-26T18:26:40Z" | weaver/src/org/aspectj/weaver/bcel/BcelWorld.java | /* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-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.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.apache.bcel.classfile.ConstantPool;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.util.ClassLoaderReference;
import org.aspectj.apache.bcel.util.ClassLoaderRepository;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.NonCachingClassLoaderRepository;
import org.aspectj.apache.bcel.util.Repository;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.internal.CharOperation;
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.WeaveMessage;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AnnotationAJ;
import org.aspectj.weaver.AnnotationOnTypeMunger;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Checker;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.IWeavingSupport;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MemberImpl;
import org.aspectj.weaver.MemberKind;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.loadtime.definition.Definition;
import org.aspectj.weaver.loadtime.definition.DocumentParser;
import org.aspectj.weaver.model.AsmRelationshipProvider;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.ParserException;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.tools.Trace;
import org.aspectj.weaver.tools.TraceFactory;
public class BcelWorld extends World implements Repository {
private final ClassPathManager classPath;
protected Repository delegate;
private BcelWeakClassLoaderReference loaderRef;
private final BcelWeavingSupport bcelWeavingSupport = new BcelWeavingSupport();
private boolean isXmlConfiguredWorld = false;
private WeavingXmlConfig xmlConfiguration;
private List<TypeDelegateResolver> typeDelegateResolvers;
private static Trace trace = TraceFactory.getTraceFactory().getTrace(BcelWorld.class);
public BcelWorld() {
this("");
}
public BcelWorld(String cp) {
this(makeDefaultClasspath(cp), IMessageHandler.THROW, null);
}
public IRelationship.Kind determineRelKind(ShadowMunger munger) {
AdviceKind ak = ((Advice) munger).getKind();
if (ak.getKey() == AdviceKind.Before.getKey()) {
return IRelationship.Kind.ADVICE_BEFORE;
} else if (ak.getKey() == AdviceKind.After.getKey()) {
return IRelationship.Kind.ADVICE_AFTER;
} else if (ak.getKey() == AdviceKind.AfterThrowing.getKey()) {
return IRelationship.Kind.ADVICE_AFTERTHROWING;
} else if (ak.getKey() == AdviceKind.AfterReturning.getKey()) {
return IRelationship.Kind.ADVICE_AFTERRETURNING;
} else if (ak.getKey() == AdviceKind.Around.getKey()) {
return IRelationship.Kind.ADVICE_AROUND;
} else if (ak.getKey() == AdviceKind.CflowEntry.getKey() || ak.getKey() == AdviceKind.CflowBelowEntry.getKey()
|| ak.getKey() == AdviceKind.InterInitializer.getKey() || ak.getKey() == AdviceKind.PerCflowEntry.getKey()
|| ak.getKey() == AdviceKind.PerCflowBelowEntry.getKey() || ak.getKey() == AdviceKind.PerThisEntry.getKey()
|| ak.getKey() == AdviceKind.PerTargetEntry.getKey() || ak.getKey() == AdviceKind.Softener.getKey()
|| ak.getKey() == AdviceKind.PerTypeWithinEntry.getKey()) {
// System.err.println("Dont want a message about this: "+ak);
return null;
}
throw new RuntimeException("Shadow.determineRelKind: What the hell is it? " + ak);
}
@Override
public void reportMatch(ShadowMunger munger, Shadow shadow) {
if (getCrossReferenceHandler() != null) {
getCrossReferenceHandler().addCrossReference(munger.getSourceLocation(), // What is being applied
shadow.getSourceLocation(), // Where is it being applied
determineRelKind(munger).getName(), // What kind of advice?
((Advice) munger).hasDynamicTests() // Is a runtime test being stuffed in the code?
);
}
if (!getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
reportWeavingMessage(munger, shadow);
}
if (getModel() != null) {
AsmRelationshipProvider.addAdvisedRelationship(getModelAsAsmManager(), shadow, munger);
}
}
/*
* Report a message about the advice weave that has occurred. Some messing about to make it pretty ! This code is just asking
* for an NPE to occur ...
*/
private void reportWeavingMessage(ShadowMunger munger, Shadow shadow) {
Advice advice = (Advice) munger;
AdviceKind aKind = advice.getKind();
// Only report on interesting advice kinds ...
if (aKind == null || advice.getConcreteAspect() == null) {
// We suspect someone is programmatically driving the weaver
// (e.g. IdWeaveTestCase in the weaver testcases)
return;
}
if (!(aKind.equals(AdviceKind.Before) || aKind.equals(AdviceKind.After) || aKind.equals(AdviceKind.AfterReturning)
|| aKind.equals(AdviceKind.AfterThrowing) || aKind.equals(AdviceKind.Around) || aKind.equals(AdviceKind.Softener))) {
return;
}
// synchronized blocks are implemented with multiple monitor_exit instructions in the bytecode
// (one for normal exit from the method, one for abnormal exit), we only want to tell the user
// once we have advised the end of the sync block, even though under the covers we will have
// woven both exit points
if (shadow.getKind() == Shadow.SynchronizationUnlock) {
if (advice.lastReportedMonitorExitJoinpointLocation == null) {
// this is the first time through, let's continue...
advice.lastReportedMonitorExitJoinpointLocation = shadow.getSourceLocation();
} else {
if (areTheSame(shadow.getSourceLocation(), advice.lastReportedMonitorExitJoinpointLocation)) {
// Don't report it again!
advice.lastReportedMonitorExitJoinpointLocation = null;
return;
}
// hmmm, this means some kind of nesting is going on, urgh
advice.lastReportedMonitorExitJoinpointLocation = shadow.getSourceLocation();
}
}
String description = advice.getKind().toString();
String advisedType = shadow.getEnclosingType().getName();
String advisingType = advice.getConcreteAspect().getName();
Message msg = null;
if (advice.getKind().equals(AdviceKind.Softener)) {
msg = WeaveMessage.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_SOFTENS, new String[] { advisedType,
beautifyLocation(shadow.getSourceLocation()), advisingType, beautifyLocation(munger.getSourceLocation()) },
advisedType, advisingType);
} else {
boolean runtimeTest = advice.hasDynamicTests();
String joinPointDescription = shadow.toString();
msg = WeaveMessage
.constructWeavingMessage(WeaveMessage.WEAVEMESSAGE_ADVISES,
new String[] { joinPointDescription, advisedType, beautifyLocation(shadow.getSourceLocation()),
description, advisingType, beautifyLocation(munger.getSourceLocation()),
(runtimeTest ? " [with runtime test]" : "") }, advisedType, advisingType);
// Boolean.toString(runtimeTest)});
}
getMessageHandler().handleMessage(msg);
}
private boolean areTheSame(ISourceLocation locA, ISourceLocation locB) {
if (locA == null) {
return locB == null;
}
if (locB == null) {
return false;
}
if (locA.getLine() != locB.getLine()) {
return false;
}
File fA = locA.getSourceFile();
File fB = locA.getSourceFile();
if (fA == null) {
return fB == null;
}
if (fB == null) {
return false;
}
return fA.getName().equals(fB.getName());
}
/*
* Ensure we report a nice source location - particular in the case where the source info is missing (binary weave).
*/
private String beautifyLocation(ISourceLocation isl) {
StringBuffer nice = new StringBuffer();
if (isl == null || isl.getSourceFile() == null || isl.getSourceFile().getName().indexOf("no debug info available") != -1) {
nice.append("no debug info available");
} else {
// can't use File.getName() as this fails when a Linux box encounters a path created on Windows and vice-versa
int takeFrom = isl.getSourceFile().getPath().lastIndexOf('/');
if (takeFrom == -1) {
takeFrom = isl.getSourceFile().getPath().lastIndexOf('\\');
}
int binary = isl.getSourceFile().getPath().lastIndexOf('!');
if (binary != -1 && binary < takeFrom) {
// we have been woven by a binary aspect
String pathToBinaryLoc = isl.getSourceFile().getPath().substring(0, binary + 1);
if (pathToBinaryLoc.indexOf(".jar") != -1) {
// only want to add the extra info if we're from a jar file
int lastSlash = pathToBinaryLoc.lastIndexOf('/');
if (lastSlash == -1) {
lastSlash = pathToBinaryLoc.lastIndexOf('\\');
}
nice.append(pathToBinaryLoc.substring(lastSlash + 1));
}
}
nice.append(isl.getSourceFile().getPath().substring(takeFrom + 1));
if (isl.getLine() != 0) {
nice.append(":").append(isl.getLine());
}
// if it's a binary file then also want to give the file name
if (isl.getSourceFileName() != null) {
nice.append("(from " + isl.getSourceFileName() + ")");
}
}
return nice.toString();
}
private static List<String> makeDefaultClasspath(String cp) {
List<String> classPath = new ArrayList<String>();
classPath.addAll(getPathEntries(cp));
classPath.addAll(getPathEntries(ClassPath.getClassPath()));
return classPath;
}
private static List<String> getPathEntries(String s) {
List<String> ret = new ArrayList<String>();
StringTokenizer tok = new StringTokenizer(s, File.pathSeparator);
while (tok.hasMoreTokens()) {
ret.add(tok.nextToken());
}
return ret;
}
public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
// this.aspectPath = new ClassPathManager(aspectPath, handler);
this.classPath = new ClassPathManager(classPath, handler);
setMessageHandler(handler);
setCrossReferenceHandler(xrefHandler);
// Tell BCEL to use us for resolving any classes
delegate = this;
}
public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
classPath = cpm;
setMessageHandler(handler);
setCrossReferenceHandler(xrefHandler);
// Tell BCEL to use us for resolving any classes
delegate = this;
}
/**
* Build a World from a ClassLoader, for LTW support
*
* @param loader
* @param handler
* @param xrefHandler
*/
public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
classPath = null;
loaderRef = new BcelWeakClassLoaderReference(loader);
setMessageHandler(handler);
setCrossReferenceHandler(xrefHandler);
// Tell BCEL to use us for resolving any classes
// delegate = getClassLoaderRepositoryFor(loader);
}
public void ensureRepositorySetup() {
if (delegate == null) {
delegate = getClassLoaderRepositoryFor(loaderRef);
}
}
public Repository getClassLoaderRepositoryFor(ClassLoaderReference loader) {
if (bcelRepositoryCaching) {
return new ClassLoaderRepository(loader);
} else {
return new NonCachingClassLoaderRepository(loader);
}
}
public void addPath(String name) {
classPath.addPath(name, this.getMessageHandler());
}
// ---- various interactions with bcel
public static Type makeBcelType(UnresolvedType type) {
return Type.getType(type.getErasureSignature());
}
static Type[] makeBcelTypes(UnresolvedType[] types) {
Type[] ret = new Type[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = makeBcelType(types[i]);
}
return ret;
}
static String[] makeBcelTypesAsClassNames(UnresolvedType[] types) {
String[] ret = new String[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = types[i].getName();
}
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));
}
@Override
protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) {
String name = ty.getName();
ensureAdvancedConfigurationProcessed();
JavaClass jc = lookupJavaClass(classPath, name);
if (jc == null) {
// Anyone else to ask?
if (typeDelegateResolvers != null) {
for (TypeDelegateResolver tdr : typeDelegateResolvers) {
ReferenceTypeDelegate delegate = tdr.getDelegate(ty);
if (delegate != null) {
return delegate;
}
}
}
return null;
} else {
return buildBcelDelegate(ty, jc, false, false);
}
}
public BcelObjectType buildBcelDelegate(ReferenceType type, JavaClass jc, boolean artificial, boolean exposedToWeaver) {
BcelObjectType ret = new BcelObjectType(type, jc, artificial, exposedToWeaver);
return ret;
}
private JavaClass lookupJavaClass(ClassPathManager classPath, String name) {
if (classPath == null) {
try {
ensureRepositorySetup();
JavaClass jc = delegate.loadClass(name);
if (trace.isTraceEnabled()) {
trace.event("lookupJavaClass", this, new Object[] { name, jc });
}
return jc;
} catch (ClassNotFoundException e) {
if (trace.isTraceEnabled()) {
trace.error("Unable to find class '" + name + "' in repository", e);
}
return null;
}
}
ClassPathManager.ClassFile file = null;
try {
file = classPath.find(UnresolvedType.forName(name));
if (file == null) {
return null;
}
ClassParser parser = new ClassParser(file.getInputStream(), file.getPath());
JavaClass jc = parser.parse();
return jc;
} catch (IOException ioe) {
return null;
} finally {
if (file != null) {
file.close();
}
}
}
// public BcelObjectType addSourceObjectType(JavaClass jc) {
// return addSourceObjectType(jc.getClassName(), jc, -1);
// }
public BcelObjectType addSourceObjectType(JavaClass jc, boolean artificial) {
return addSourceObjectType(jc.getClassName(), jc, artificial);
}
public BcelObjectType addSourceObjectType(String classname, JavaClass jc, boolean artificial) {
BcelObjectType ret = null;
if (!jc.getClassName().equals(classname)) {
throw new RuntimeException(jc.getClassName() + "!=" + classname);
}
String signature = UnresolvedType.forName(jc.getClassName()).getSignature();
ResolvedType fromTheMap = typeMap.get(signature);
if (fromTheMap != null && !(fromTheMap instanceof ReferenceType)) {
// what on earth is it then? See pr 112243
StringBuffer exceptionText = new StringBuffer();
exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. ");
exceptionText.append("Signature=[" + signature + "] Found=[" + fromTheMap + "] Class=[" + fromTheMap.getClass() + "]");
throw new BCException(exceptionText.toString());
}
ReferenceType nameTypeX = (ReferenceType) fromTheMap;
if (nameTypeX == null) {
if (jc.isGeneric() && isInJava5Mode()) {
ReferenceType rawType = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()), this);
ret = buildBcelDelegate(rawType, jc, artificial, true);
ReferenceType genericRefType = new ReferenceType(UnresolvedType.forGenericTypeSignature(signature,
ret.getDeclaredGenericSignature()), this);
rawType.setDelegate(ret);
genericRefType.setDelegate(ret);
rawType.setGenericType(genericRefType);
typeMap.put(signature, rawType);
} else {
nameTypeX = new ReferenceType(signature, this);
ret = buildBcelDelegate(nameTypeX, jc, artificial, true);
typeMap.put(signature, nameTypeX);
}
} else {
ret = buildBcelDelegate(nameTypeX, jc, artificial, true);
}
return ret;
}
public BcelObjectType addSourceObjectType(String classname, byte[] bytes, boolean artificial) {
BcelObjectType ret = null;
String signature = UnresolvedType.forName(classname).getSignature();
ResolvedType fromTheMap = typeMap.get(signature);
if (fromTheMap != null && !(fromTheMap instanceof ReferenceType)) {
// what on earth is it then? See pr 112243
StringBuffer exceptionText = new StringBuffer();
exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. ");
exceptionText.append("Signature=[" + signature + "] Found=[" + fromTheMap + "] Class=[" + fromTheMap.getClass() + "]");
throw new BCException(exceptionText.toString());
}
ReferenceType nameTypeX = (ReferenceType) fromTheMap;
if (nameTypeX == null) {
JavaClass jc = Utility.makeJavaClass(classname, bytes);
if (jc.isGeneric() && isInJava5Mode()) {
nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()), this);
ret = buildBcelDelegate(nameTypeX, jc, artificial, 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 = buildBcelDelegate(nameTypeX, jc, artificial, true);
typeMap.put(signature, nameTypeX);
}
} else {
Object o = nameTypeX.getDelegate();
if (!(o instanceof BcelObjectType)) {
throw new IllegalStateException("For " + classname + " should be BcelObjectType, but is " + o.getClass());
}
ret = (BcelObjectType) o;
// byte[] bs = ret.javaClass.getBytes();
// if (bs.length != bytes.length) {
// throw new RuntimeException("");
// }
// If the type is already exposed to the weaver (ret.isExposedToWeaver()) then this is likely
// to be a hotswap reweave so build a new delegate, dont accidentally use the old data
if (ret.isArtificial() || ret.isExposedToWeaver()) {
// System.out.println("Rebuilding " + nameTypeX.getName());
ret = buildBcelDelegate(nameTypeX, Utility.makeJavaClass(classname, bytes), artificial, true);
} else {
ret.setExposedToWeaver(true);
}
}
return ret;
}
void deleteSourceObjectType(UnresolvedType ty) {
typeMap.remove(ty.getSignature());
}
public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) {
ConstantPool cpg = cg.getConstantPool();
return MemberImpl.field(fi.getClassName(cpg),
(fi.opcode == Constants.GETSTATIC || fi.opcode == Constants.PUTSTATIC) ? Modifier.STATIC : 0, fi.getName(cpg),
fi.getSignature(cpg));
}
public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberKind kind) {
Member ret = mg.getMemberView();
if (ret == null) {
int mods = mg.getAccessFlags();
if (mg.getEnclosingClass().isInterface()) {
mods |= Modifier.INTERFACE;
}
return new ResolvedMemberImpl(kind, UnresolvedType.forName(mg.getClassName()), mods, fromBcel(mg.getReturnType()),
mg.getName(), fromBcel(mg.getArgumentTypes()));
} else {
return ret;
}
}
public Member makeJoinPointSignatureForMonitorEnter(LazyClassGen cg, InstructionHandle h) {
return MemberImpl.monitorEnter();
}
public Member makeJoinPointSignatureForMonitorExit(LazyClassGen cg, InstructionHandle h) {
return MemberImpl.monitorExit();
}
public Member makeJoinPointSignatureForArrayConstruction(LazyClassGen cg, InstructionHandle handle) {
Instruction i = handle.getInstruction();
ConstantPool cpg = cg.getConstantPool();
Member retval = null;
if (i.opcode == Constants.ANEWARRAY) {
// ANEWARRAY arrayInstruction = (ANEWARRAY)i;
Type ot = i.getType(cpg);
UnresolvedType ut = fromBcel(ot);
ut = UnresolvedType.makeArray(ut, 1);
retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", new ResolvedType[] { INT });
} else if (i instanceof MULTIANEWARRAY) {
MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY) i;
UnresolvedType ut = null;
short dimensions = arrayInstruction.getDimensions();
ObjectType ot = arrayInstruction.getLoadClassType(cpg);
if (ot != null) {
ut = fromBcel(ot);
ut = UnresolvedType.makeArray(ut, dimensions);
} else {
Type t = arrayInstruction.getType(cpg);
ut = fromBcel(t);
}
ResolvedType[] parms = new ResolvedType[dimensions];
for (int ii = 0; ii < dimensions; ii++) {
parms[ii] = INT;
}
retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", parms);
} else if (i.opcode == Constants.NEWARRAY) {
// NEWARRAY arrayInstruction = (NEWARRAY)i;
Type ot = i.getType();
UnresolvedType ut = fromBcel(ot);
retval = MemberImpl.method(ut, Modifier.PUBLIC, UnresolvedType.VOID, "<init>", new ResolvedType[] { INT });
} else {
throw new BCException("Cannot create array construction signature for this non-array instruction:" + i);
}
return retval;
}
public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) {
ConstantPool cpg = cg.getConstantPool();
String name = ii.getName(cpg);
String declaring = ii.getClassName(cpg);
UnresolvedType declaringType = null;
String signature = ii.getSignature(cpg);
int modifier = (ii instanceof INVOKEINTERFACE) ? Modifier.INTERFACE
: (ii.opcode == Constants.INVOKESTATIC) ? Modifier.STATIC : (ii.opcode == Constants.INVOKESPECIAL && !name
.equals("<init>")) ? Modifier.PRIVATE : 0;
// in Java 1.4 and after, static method call of super class within
// subclass method appears
// as declared by the subclass in the bytecode - but they are not
// see #104212
if (ii.opcode == Constants.INVOKESTATIC) {
ResolvedType appearsDeclaredBy = resolve(declaring);
// look for the method there
for (Iterator<ResolvedMember> iterator = appearsDeclaredBy.getMethods(true, true); iterator.hasNext();) {
ResolvedMember method = iterator.next();
if (Modifier.isStatic(method.getModifiers())) {
if (name.equals(method.getName()) && signature.equals(method.getSignature())) {
// we found it
declaringType = method.getDeclaringType();
break;
}
}
}
}
if (declaringType == null) {
if (declaring.charAt(0) == '[') {
declaringType = UnresolvedType.forSignature(declaring);
} else {
declaringType = UnresolvedType.forName(declaring);
}
}
return MemberImpl.method(declaringType, modifier, name, signature);
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("BcelWorld(");
// buf.append(shadowMungerMap);
buf.append(")");
return buf.toString();
}
/**
* Retrieve a bcel delegate for an aspect - this will return NULL if the delegate is an EclipseSourceType and not a
* BcelObjectType - this happens quite often when incrementally compiling.
*/
public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) {
if (concreteAspect == null) {
return null;
}
if (!(concreteAspect instanceof ReferenceType)) { // Might be Missing
return null;
}
ReferenceTypeDelegate rtDelegate = ((ReferenceType) concreteAspect).getDelegate();
if (rtDelegate instanceof BcelObjectType) {
return (BcelObjectType) rtDelegate;
} else {
return null;
}
}
public void tidyUp() {
// At end of compile, close any open files so deletion of those archives
// is possible
classPath.closeArchives();
typeMap.report();
typeMap.demote(true);
// ResolvedType.resetPrimitives();
}
// / 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) {
// doesn't need to do anything
}
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() {
delegate.clear();
// throw new RuntimeException("Not implemented");
}
/**
* The aim of this method is to make sure a particular type is 'ok'. Some operations on the delegate for a type modify it and
* this method is intended to undo that... see pr85132
*/
@Override
public void validateType(UnresolvedType type) {
ResolvedType result = typeMap.get(type.getSignature());
if (result == null) {
return; // We haven't heard of it yet
}
if (!result.isExposedToWeaver()) {
return; // cant need resetting
}
result.ensureConsistent();
// If we want to rebuild it 'from scratch' then:
// ClassParser cp = new ClassParser(new
// ByteArrayInputStream(newbytes),new String(cs));
// try {
// rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true));
// } catch (ClassFormatException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
/**
* Apply a single declare parents - return true if we change the type
*/
private boolean applyDeclareParents(DeclareParents p, ResolvedType onType) {
boolean didSomething = false;
List<ResolvedType> 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 (ResolvedType newParent : newParents) {
// 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);
onType.addParent(newParent);
ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent, p.getDeclaringType());
newParentMunger.setSourceLocation(p.getSourceLocation());
onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, getCrosscuttingMembersSet()
.findAspectDeclaringParents(p)), false);
}
}
return didSomething;
}
/**
* Apply a declare @type - return true if we change the type
*/
private boolean applyDeclareAtType(DeclareAnnotation decA, ResolvedType onType, boolean reportProblems) {
boolean didSomething = false;
if (decA.matches(onType)) {
if (onType.hasAnnotation(decA.getAnnotation().getType())) {
// already has it
return false;
}
AnnotationAJ annoX = decA.getAnnotation();
// check the annotation is suitable for the target
boolean isOK = checkTargetOK(decA, onType, annoX);
if (isOK) {
didSomething = true;
ResolvedTypeMunger newAnnotationTM = new AnnotationOnTypeMunger(annoX);
newAnnotationTM.setSourceLocation(decA.getSourceLocation());
onType.addInterTypeMunger(new BcelTypeMunger(newAnnotationTM, decA.getAspect().resolve(this)), false);
decA.copyAnnotationTo(onType);
}
}
return didSomething;
}
/**
* Apply the specified declare @field construct to any matching fields in the specified type.
* @param deca the declare annotation targeting fields
* @param type the type to check for members matching the declare annotation
* @return true if something matched and the type was modified
*/
private boolean applyDeclareAtField(DeclareAnnotation deca, ResolvedType type) {
boolean changedType = false;
ResolvedMember[] fields = type.getDeclaredFields();
for (ResolvedMember field: fields) {
if (deca.matches(field, this)) {
AnnotationAJ anno = deca.getAnnotation();
if (!field.hasAnnotation(anno.getType())) {
field.addAnnotation(anno);
changedType=true;
}
}
}
return changedType;
}
/**
* 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 checkTargetOK(DeclareAnnotation decA, ResolvedType onType, AnnotationAJ annoX) {
if (annoX.specifiesTarget()) {
if ((onType.isAnnotation() && !annoX.allowedOnAnnotationType()) || (!annoX.allowedOnRegularType())) {
return false;
}
}
return true;
}
// Hmmm - very similar to the code in BcelWeaver.weaveParentTypeMungers -
// this code
// doesn't need to produce errors/warnings though as it won't really be
// weaving.
protected void weaveInterTypeDeclarations(ResolvedType onType) {
List<DeclareParents> declareParentsList = getCrosscuttingMembersSet().getDeclareParents();
if (onType.isRawType()) {
onType = onType.getGenericType();
}
onType.clearInterTypeMungers();
List<DeclareParents> decpToRepeat = new ArrayList<DeclareParents>();
boolean aParentChangeOccurred = false;
boolean anAnnotationChangeOccurred = false;
// First pass - apply all decp mungers
for (Iterator<DeclareParents> i = declareParentsList.iterator(); i.hasNext();) {
DeclareParents decp = 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 (DeclareAnnotation decA : getCrosscuttingMembersSet().getDeclareAnnotationOnTypes()) {
boolean typeChanged = applyDeclareAtType(decA, onType, true);
if (typeChanged) {
anAnnotationChangeOccurred = true;
}
}
// apply declare @field
for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnFields()) {
if (applyDeclareAtField(deca,onType)) {
anAnnotationChangeOccurred = true;
}
}
while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
anAnnotationChangeOccurred = aParentChangeOccurred = false;
List<DeclareParents> decpToRepeatNextTime = new ArrayList<DeclareParents>();
for (DeclareParents decp: decpToRepeat) {
if (applyDeclareParents(decp, onType)) {
aParentChangeOccurred = true;
} else {
decpToRepeatNextTime.add(decp);
}
}
for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnTypes()) {
if (applyDeclareAtType(deca, onType, false)) {
anAnnotationChangeOccurred = true;
}
}
for (DeclareAnnotation deca: getCrosscuttingMembersSet().getDeclareAnnotationOnFields()) {
if (applyDeclareAtField(deca, onType)) {
anAnnotationChangeOccurred = true;
}
}
decpToRepeat = decpToRepeatNextTime;
}
}
@Override
public IWeavingSupport getWeavingSupport() {
return bcelWeavingSupport;
}
@Override
public void reportCheckerMatch(Checker checker, Shadow shadow) {
IMessage iMessage = new Message(checker.getMessage(shadow), shadow.toString(), checker.isError() ? IMessage.ERROR
: IMessage.WARNING, shadow.getSourceLocation(), null, new ISourceLocation[] { checker.getSourceLocation() }, true,
0, -1, -1);
getMessageHandler().handleMessage(iMessage);
if (getCrossReferenceHandler() != null) {
getCrossReferenceHandler()
.addCrossReference(
checker.getSourceLocation(),
shadow.getSourceLocation(),
(checker.isError() ? IRelationship.Kind.DECLARE_ERROR.getName() : IRelationship.Kind.DECLARE_WARNING
.getName()), false);
}
if (getModel() != null) {
AsmRelationshipProvider.addDeclareErrorOrWarningRelationship(getModelAsAsmManager(), shadow, checker);
}
}
public AsmManager getModelAsAsmManager() {
return (AsmManager) getModel(); // For now... always an AsmManager in a bcel environment
}
void raiseError(String message) {
getMessageHandler().handleMessage(MessageUtil.error(message));
}
/**
* These are aop.xml files that can be used to alter the aspects that actually apply from those passed in - and also their scope
* of application to other files in the system.
*
* @param xmlFiles list of File objects representing any aop.xml files passed in to configure the build process
*/
public void setXmlFiles(List<File> xmlFiles) {
if (!isXmlConfiguredWorld && !xmlFiles.isEmpty()) {
raiseError("xml configuration files only supported by the compiler when -xmlConfigured option specified");
return;
}
if (!xmlFiles.isEmpty()) {
xmlConfiguration = new WeavingXmlConfig(this, WeavingXmlConfig.MODE_COMPILE);
}
for (File xmlfile : xmlFiles) {
try {
Definition d = DocumentParser.parse(xmlfile.toURI().toURL());
xmlConfiguration.add(d);
} catch (MalformedURLException e) {
raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage());
} catch (Exception e) {
raiseError("Unexpected problem processing XML config file '" + xmlfile.getName() + "' :" + e.getMessage());
}
}
}
/**
* Add a scoped aspects where the scoping was defined in an aop.xml file and this world is being used in a LTW configuration
*/
public void addScopedAspect(String name, String scope) {
this.isXmlConfiguredWorld = true;
if (xmlConfiguration == null) {
xmlConfiguration = new WeavingXmlConfig(this, WeavingXmlConfig.MODE_LTW);
}
xmlConfiguration.addScopedAspect(name, scope);
}
public void setXmlConfigured(boolean b) {
this.isXmlConfiguredWorld = b;
}
@Override
public boolean isXmlConfigured() {
return isXmlConfiguredWorld && xmlConfiguration != null;
}
public WeavingXmlConfig getXmlConfiguration() {
return xmlConfiguration;
}
@Override
public boolean isAspectIncluded(ResolvedType aspectType) {
if (!isXmlConfigured()) {
return true;
}
return xmlConfiguration.specifiesInclusionOfAspect(aspectType.getName());
}
@Override
public TypePattern getAspectScope(ResolvedType declaringType) {
return xmlConfiguration.getScopeFor(declaringType.getName());
}
@Override
public boolean hasUnsatisfiedDependency(ResolvedType aspectType) {
if (aspectRequiredTypes == null) {
// no aspects require anything, so there can be no unsatisfied dependencies
return false;
}
String aspectName = aspectType.getName();
if (!aspectRequiredTypesProcessed.contains(aspectName)) {
String requiredTypeName = aspectRequiredTypes.get(aspectName);
if (requiredTypeName==null) {
aspectRequiredTypesProcessed.add(aspectName);
return false;
} else {
ResolvedType rt = resolve(UnresolvedType.forName(requiredTypeName));
if (!rt.isMissing()) {
aspectRequiredTypesProcessed.add(aspectName);
aspectRequiredTypes.remove(aspectName);
return false;
} else {
if (!getMessageHandler().isIgnoring(IMessage.INFO)) {
getMessageHandler().handleMessage(
MessageUtil.info("deactivating aspect '" + aspectName + "' as it requires type '"
+ requiredTypeName + "' which cannot be found on the classpath"));
}
aspectRequiredTypesProcessed.add(aspectName);
return true;
}
}
}
return aspectRequiredTypes.containsKey(aspectName);
}
private List<String> aspectRequiredTypesProcessed = new ArrayList<String>();
private Map<String, String> aspectRequiredTypes = null;
public void addAspectRequires(String aspectClassName, String requiredType) {
if (aspectRequiredTypes == null) {
aspectRequiredTypes = new HashMap<String, String>();
}
aspectRequiredTypes.put(aspectClassName, requiredType);
}
/**
* A WeavingXmlConfig is initially a collection of definitions from XML files - once the world is ready and weaving is running
* it will initialize and transform those definitions into an optimized set of values (eg. resolve type patterns and string
* names to real entities). It can then answer questions quickly: (1) is this aspect included in the weaving? (2) Is there a
* scope specified for this aspect and does it include type X?
*
*/
static class WeavingXmlConfig {
final static int MODE_COMPILE = 1;
final static int MODE_LTW = 2;
private int mode;
private boolean initialized = false; // Lazily done
private List<Definition> definitions = new ArrayList<Definition>();
private List<String> resolvedIncludedAspects = new ArrayList<String>();
private Map<String, TypePattern> scopes = new HashMap<String, TypePattern>();
// these are not set for LTW mode (exclusion of these fast match patterns is handled before the weaver/world are used)
private List<String> includedFastMatchPatterns = Collections.emptyList();
private List<TypePattern> includedPatterns = Collections.emptyList();
private List<String> excludedFastMatchPatterns = Collections.emptyList();
private List<TypePattern> excludedPatterns = Collections.emptyList();
private BcelWorld world;
public WeavingXmlConfig(BcelWorld bcelWorld, int mode) {
this.world = bcelWorld;
this.mode = mode;
}
public void add(Definition d) {
definitions.add(d);
}
public void addScopedAspect(String aspectName, String scope) {
ensureInitialized();
resolvedIncludedAspects.add(aspectName);
try {
TypePattern scopePattern = new PatternParser(scope).parseTypePattern();
scopePattern.resolve(world);
scopes.put(aspectName, scopePattern);
if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
world.getMessageHandler().handleMessage(
MessageUtil.info("Aspect '" + aspectName + "' is scoped to apply against types matching pattern '"
+ scopePattern.toString() + "'"));
}
} catch (Exception e) {
world.getMessageHandler().handleMessage(
MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': " + e.getMessage()));
}
}
public void ensureInitialized() {
if (!initialized) {
try {
resolvedIncludedAspects = new ArrayList<String>();
// Process the definitions into something more optimal
for (Definition definition : definitions) {
List<String> aspectNames = definition.getAspectClassNames();
for (String name : aspectNames) {
resolvedIncludedAspects.add(name);
// TODO check for existence?
// ResolvedType resolvedAspect = resolve(UnresolvedType.forName(name));
// if (resolvedAspect.isMissing()) {
// // ERROR
// } else {
// resolvedIncludedAspects.add(resolvedAspect);
// }
String scope = definition.getScopeForAspect(name);
if (scope != null) {
// Resolve the type pattern
try {
TypePattern scopePattern = new PatternParser(scope).parseTypePattern();
scopePattern.resolve(world);
scopes.put(name, scopePattern);
if (!world.getMessageHandler().isIgnoring(IMessage.INFO)) {
world.getMessageHandler().handleMessage(
MessageUtil.info("Aspect '" + name
+ "' is scoped to apply against types matching pattern '"
+ scopePattern.toString() + "'"));
}
} catch (Exception e) {
// TODO definitions should remember which file they came from, for inclusion in this message
world.getMessageHandler().handleMessage(
MessageUtil.error("Unable to parse scope as type pattern. Scope was '" + scope + "': "
+ e.getMessage()));
}
}
}
try {
List<String> includePatterns = definition.getIncludePatterns();
if (includePatterns.size() > 0) {
includedPatterns = new ArrayList<TypePattern>();
includedFastMatchPatterns = new ArrayList<String>();
}
for (String includePattern : includePatterns) {
if (includePattern.endsWith("..*")) {
// from 'blah.blah.blah..*' leave the 'blah.blah.blah.'
includedFastMatchPatterns.add(includePattern.substring(0, includePattern.length() - 2));
} else {
TypePattern includedPattern = new PatternParser(includePattern).parseTypePattern();
includedPatterns.add(includedPattern);
}
}
List<String> excludePatterns = definition.getExcludePatterns();
if (excludePatterns.size() > 0) {
excludedPatterns = new ArrayList<TypePattern>();
excludedFastMatchPatterns = new ArrayList<String>();
}
for (String excludePattern : excludePatterns) {
if (excludePattern.endsWith("..*")) {
// from 'blah.blah.blah..*' leave the 'blah.blah.blah.'
excludedFastMatchPatterns.add(excludePattern.substring(0, excludePattern.length() - 2));
} else {
TypePattern excludedPattern = new PatternParser(excludePattern).parseTypePattern();
excludedPatterns.add(excludedPattern);
}
}
} catch (ParserException pe) {
// TODO definitions should remember which file they came from, for inclusion in this message
world.getMessageHandler().handleMessage(
MessageUtil.error("Unable to parse type pattern: " + pe.getMessage()));
}
}
} finally {
initialized = true;
}
}
}
public boolean specifiesInclusionOfAspect(String name) {
ensureInitialized();
return resolvedIncludedAspects.contains(name);
}
public TypePattern getScopeFor(String name) {
return scopes.get(name);
}
// Can't quite follow the same rules for exclusion as used for loadtime weaving:
// "The set of types to be woven are those types matched by at least one weaver include element and not matched by any
// weaver
// exclude element. If there are no weaver include statements then all non-excluded types are included."
// Since if the weaver is seeing it during this kind of build, the type is implicitly included. So all we should check
// for is exclusion
public boolean excludesType(ResolvedType type) {
if (mode == MODE_LTW) {
return false;
}
String typename = type.getName();
boolean excluded = false;
for (String excludedPattern : excludedFastMatchPatterns) {
if (typename.startsWith(excludedPattern)) {
excluded = true;
break;
}
}
if (!excluded) {
for (TypePattern excludedPattern : excludedPatterns) {
if (excludedPattern.matchesStatically(type)) {
excluded = true;
break;
}
}
}
return excluded;
}
}
public TypeMap getTypeMap() {
return typeMap;
}
public boolean isLoadtimeWeaving() {
return false;
}
public void addTypeDelegateResolver(TypeDelegateResolver typeDelegateResolver) {
if (typeDelegateResolvers == null) {
typeDelegateResolvers = new ArrayList<TypeDelegateResolver>();
}
typeDelegateResolvers.add(typeDelegateResolver);
}
public void classWriteEvent(char[][] compoundName) {
typeMap.classWriteEvent(new String(CharOperation.concatWith(compoundName, '.')));
}
/**
* Force demote a type.
*/
public void demote(ResolvedType type) {
typeMap.demote(type);
}
}
|
418,129 | Bug 418129 Can't introduce annotation onto introduced method from trait-patterned aspect | null | resolved fixed | 2393bef | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-01T17:00:14Z" | "2013-09-26T18:26:40Z" | weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.java | /* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.ConstantPool;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Synthetic;
import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
import org.aspectj.apache.bcel.generic.BranchHandle;
import org.aspectj.apache.bcel.generic.ClassGenException;
import org.aspectj.apache.bcel.generic.CodeExceptionGen;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionBranch;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionSelect;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.LineNumberTag;
import org.aspectj.apache.bcel.generic.LocalVariableTag;
import org.aspectj.apache.bcel.generic.MethodGen;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.Tag;
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.weaver.AjAttribute;
import org.aspectj.weaver.AjAttribute.WeaverVersionInfo;
import org.aspectj.weaver.AnnotationAJ;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.MemberImpl;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.tools.Traceable;
/**
* A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the low-level Method objects. It converts
* through {@link MethodGen} to create and to serialize, but that's it.
*
* <p>
* At any rate, there are two ways to create LazyMethodGens. One is from a method, which does work through MethodGen to do the
* correct thing. The other is the creation of a completely empty LazyMethodGen, and it is used when we're constructing code from
* scratch.
*
* <p>
* We stay away from targeters for rangey things like Shadows and Exceptions.
*/
public final class LazyMethodGen implements Traceable {
private static final int ACC_SYNTHETIC = 0x1000;
private int modifiers;
private Type returnType;
private final String name;
private Type[] argumentTypes;
// private final String[] argumentNames;
private String[] declaredExceptions;
private InstructionList body;
private List<Attribute> attributes;
private List<AnnotationAJ> newAnnotations;
private List<ResolvedType> annotationsForRemoval;
private AnnotationAJ[][] newParameterAnnotations;
private final LazyClassGen enclosingClass;
private BcelMethod memberView;
private AjAttribute.EffectiveSignatureAttribute effectiveSignature;
int highestLineNumber = 0;
boolean wasPackedOptimally = false;
private Method savedMethod = null;
private static final AnnotationAJ[] NO_ANNOTATIONAJ = new AnnotationAJ[] {};
/*
* We use LineNumberTags and not Gens.
*
* This option specifies whether we let the BCEL classes create LineNumberGens and LocalVariableGens or if we make it create
* LineNumberTags and LocalVariableTags. Up until 1.5.1 we always created Gens - then on return from the MethodGen ctor we took
* them apart, reprocessed them all and created Tags. (see unpackLocals/unpackLineNumbers). As we have our own copy of Bcel, why
* not create the right thing straightaway? So setting this to true will call the MethodGen ctor() in such a way that it creates
* Tags - removing the need for unpackLocals/unpackLineNumbers - HOWEVER see the ensureAllLineNumberSetup() method for some
* other relevant info.
*
* Whats the difference between a Tag and a Gen? A Tag is more lightweight, it doesn't know which instructions it targets, it
* relies on the instructions targettingit - this reduces the amount of targeter manipulation we have to do.
*/
/**
* This is nonnull if this method is the result of an "inlining". We currently copy methods into other classes for around
* advice. We add this field so we can get JSR45 information correct. If/when we do _actual_ inlining, we'll need to subtype
* LineNumberTag to have external line numbers.
*/
String fromFilename = null;
private int maxLocals;
private boolean canInline = true;
private boolean isSynthetic = false;
List<BcelShadow> matchedShadows;
// Used for interface introduction - this is the type of the interface the method is technically on
public ResolvedType definingType = null;
public LazyMethodGen(int modifiers, Type returnType, String name, Type[] paramTypes, String[] declaredExceptions,
LazyClassGen enclosingClass) {
// enclosingClass.getName() + ", " + returnType);
this.memberView = null; // should be okay, since constructed ones aren't woven into
this.modifiers = modifiers;
this.returnType = returnType;
this.name = name;
this.argumentTypes = paramTypes;
// this.argumentNames = Utility.makeArgNames(paramTypes.length);
this.declaredExceptions = declaredExceptions;
if (!Modifier.isAbstract(modifiers)) {
body = new InstructionList();
setMaxLocals(calculateMaxLocals());
} else {
body = null;
}
this.attributes = new ArrayList<Attribute>();
this.enclosingClass = enclosingClass;
assertGoodBody();
// @AJ advice are not inlined by default since requires further analysis and weaving ordering control
// TODO AV - improve - note: no room for improvement as long as aspects are reweavable
// since the inlined version with wrappers and an to be done annotation to keep
// inline state will be garbaged due to reweavable impl
if (memberView != null && isAdviceMethod()) {
if (enclosingClass.getType().isAnnotationStyleAspect()) {
// TODO we could check for @Around advice as well
this.canInline = false;
}
}
}
private int calculateMaxLocals() {
int ret = Modifier.isStatic(modifiers) ? 0 : 1; // will there be a 'this'?
for (Type type : argumentTypes) {
ret += type.getSize();
}
return ret;
}
// build from an existing method, lazy build saves most work for
// initialization
public LazyMethodGen(Method m, LazyClassGen enclosingClass) {
savedMethod = m;
this.enclosingClass = enclosingClass;
if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) {
throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass);
}
if ((m.isAbstract() || m.isNative()) && m.getCode() != null) {
throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass);
}
this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m);
this.modifiers = m.getModifiers();
this.name = m.getName();
// @AJ advice are not inlined by default since requires further analysis
// and weaving ordering control
// TODO AV - improve - note: no room for improvement as long as aspects
// are reweavable
// since the inlined version with wrappers and an to be done annotation
// to keep
// inline state will be garbaged due to reweavable impl
if (memberView != null && isAdviceMethod()) {
if (enclosingClass.getType().isAnnotationStyleAspect()) {
// TODO we could check for @Around advice as well
this.canInline = false;
}
}
}
private boolean isAbstractOrNative(int modifiers) {
return Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers);
}
public LazyMethodGen(BcelMethod m, LazyClassGen enclosingClass) {
savedMethod = m.getMethod();
this.enclosingClass = enclosingClass;
if (!isAbstractOrNative(m.getModifiers()) && savedMethod.getCode() == null) {
throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass);
}
if (isAbstractOrNative(m.getModifiers()) && savedMethod.getCode() != null) {
throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass);
}
// this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(),
// m);
this.memberView = m;
this.modifiers = savedMethod.getModifiers();
this.name = m.getName();
// @AJ advice are not inlined by default since requires further analysis
// and weaving ordering control
// TODO AV - improve - note: no room for improvement as long as aspects
// are reweavable
// since the inlined version with wrappers and an to be done annotation
// to keep
// inline state will be garbaged due to reweavable impl
if (memberView != null && isAdviceMethod()) {
if (enclosingClass.getType().isAnnotationStyleAspect()) {
// TODO we could check for @Around advice as well
this.canInline = false;
}
}
}
public boolean hasDeclaredLineNumberInfo() {
return (memberView != null && memberView.hasDeclarationLineNumberInfo());
}
public int getDeclarationLineNumber() {
if (hasDeclaredLineNumberInfo()) {
return memberView.getDeclarationLineNumber();
} else {
return -1;
}
}
public int getDeclarationOffset() {
if (hasDeclaredLineNumberInfo()) {
return memberView.getDeclarationOffset();
} else {
return 0;
}
}
public void addAnnotation(AnnotationAJ ax) {
initialize();
if (memberView == null) {
// If member view is null, we manage them in newAnnotations
if (newAnnotations == null) {
newAnnotations = new ArrayList<AnnotationAJ>();
}
newAnnotations.add(ax);
} else {
memberView.addAnnotation(ax);
}
}
public void removeAnnotation(ResolvedType annotationType) {
initialize();
if (memberView == null) {
// If member view is null, we manage them in newAnnotations
if (annotationsForRemoval == null) {
annotationsForRemoval = new ArrayList<ResolvedType>();
}
annotationsForRemoval.add(annotationType);
} else {
memberView.removeAnnotation(annotationType);
}
}
public void addParameterAnnotation(int parameterNumber, AnnotationAJ anno) {
initialize();
if (memberView == null) {
if (newParameterAnnotations == null) {
// time to create it
int pcount = getArgumentTypes().length;
newParameterAnnotations = new AnnotationAJ[pcount][];
for (int i = 0; i < pcount; i++) {
if (i == parameterNumber) {
newParameterAnnotations[i] = new AnnotationAJ[1];
newParameterAnnotations[i][0] = anno;
} else {
newParameterAnnotations[i] = NO_ANNOTATIONAJ;
}
}
} else {
AnnotationAJ[] currentAnnoArray = newParameterAnnotations[parameterNumber];
AnnotationAJ[] newAnnoArray = new AnnotationAJ[currentAnnoArray.length + 1];
System.arraycopy(currentAnnoArray, 0, newAnnoArray, 0, currentAnnoArray.length);
newAnnoArray[currentAnnoArray.length] = anno;
newParameterAnnotations[parameterNumber] = newAnnoArray;
}
} else {
memberView.addParameterAnnotation(parameterNumber, anno);
}
}
public boolean hasAnnotation(UnresolvedType annotationType) {
initialize();
if (memberView == null) {
if (annotationsForRemoval != null) {
for (ResolvedType at : annotationsForRemoval) {
if (at.equals(annotationType)) {
return false;
}
}
}
// Check local annotations first
if (newAnnotations != null) {
for (AnnotationAJ annotation : newAnnotations) {
if (annotation.getTypeSignature().equals(annotationType.getSignature())) {
return true;
}
}
}
memberView = new BcelMethod(getEnclosingClass().getBcelObjectType(), getMethod());
return memberView.hasAnnotation(annotationType);
}
return memberView.hasAnnotation(annotationType);
}
private void initialize() {
if (returnType != null) {
return;
}
MethodGen gen = new MethodGen(savedMethod, enclosingClass.getName(), enclosingClass.getConstantPool(), true);
this.returnType = gen.getReturnType();
this.argumentTypes = gen.getArgumentTypes();
this.declaredExceptions = gen.getExceptions();
this.attributes = gen.getAttributes();
// this.annotations = gen.getAnnotations();
this.maxLocals = gen.getMaxLocals();
// this.returnType = BcelWorld.makeBcelType(memberView.getReturnType());
// this.argumentTypes =
// BcelWorld.makeBcelTypes(memberView.getParameterTypes());
//
// this.declaredExceptions =
// UnresolvedType.getNames(memberView.getExceptions());
// //gen.getExceptions();
// this.attributes = new Attribute[0]; //gen.getAttributes();
// this.maxLocals = savedMethod.getCode().getMaxLocals();
if (gen.isAbstract() || gen.isNative()) {
body = null;
} else {
// body = new InstructionList(savedMethod.getCode().getCode());
body = gen.getInstructionList();
unpackHandlers(gen);
ensureAllLineNumberSetup();
highestLineNumber = gen.getHighestlinenumber();
}
assertGoodBody();
}
// XXX we're relying on the javac promise I've just made up that we won't
// have an early exception
// in the list mask a later exception: That is, for two exceptions E and F,
// if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So
// when we add F,
// we add it on the _OUTSIDE_ of any handlers that share starts or ends with
// it.
// with that in mind, we merrily go adding ranges for exceptions.
private void unpackHandlers(MethodGen gen) {
CodeExceptionGen[] exns = gen.getExceptionHandlers();
if (exns != null) {
int len = exns.length;
// if (len > 0) hasExceptionHandlers = true;
int priority = len - 1;
for (int i = 0; i < len; i++, priority--) {
CodeExceptionGen exn = exns[i];
InstructionHandle start = Range.genStart(body, getOutermostExceptionStart(exn.getStartPC()));
InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC()));
// this doesn't necessarily handle overlapping correctly!!!
ExceptionRange er = new ExceptionRange(body, exn.getCatchType() == null ? null : BcelWorld.fromBcel(exn
.getCatchType()), priority);
er.associateWithTargets(start, end, exn.getHandlerPC());
exn.setStartPC(null); // also removes from target
exn.setEndPC(null); // also removes from target
exn.setHandlerPC(null); // also removes from target
}
gen.removeExceptionHandlers();
}
}
private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) {
while (true) {
if (ExceptionRange.isExceptionStart(ih.getPrev())) {
ih = ih.getPrev();
} else {
return ih;
}
}
}
private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) {
while (true) {
if (ExceptionRange.isExceptionEnd(ih.getNext())) {
ih = ih.getNext();
} else {
return ih;
}
}
}
/**
* On entry to this method we have a method whose instruction stream contains a few instructions that have line numbers assigned
* to them (LineNumberTags). The aim is to ensure every instruction has the right line number. This is necessary because some of
* them may be extracted out into other methods - and it'd be useful for them to maintain the source line number for debugging.
*/
public void ensureAllLineNumberSetup() {
LineNumberTag lastKnownLineNumberTag = null;
boolean skip = false;
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
skip = false;
for (InstructionTargeter targeter : ih.getTargeters()) {
if (targeter instanceof LineNumberTag) {
lastKnownLineNumberTag = (LineNumberTag) targeter;
skip = true;
}
}
if (lastKnownLineNumberTag != null && !skip) {
ih.addTargeter(lastKnownLineNumberTag);
}
}
}
// ===============
public int allocateLocal(Type type) {
return allocateLocal(type.getSize());
}
public int allocateLocal(int slots) {
int max = getMaxLocals();
setMaxLocals(max + slots);
return max;
}
public Method getMethod() {
if (savedMethod != null) {
return savedMethod; // ??? this relies on gentle treatment of
// constant pool
}
try {
MethodGen gen = pack();
savedMethod = gen.getMethod();
return savedMethod;
} catch (ClassGenException e) {
enclosingClass
.getBcelObjectType()
.getResolvedTypeX()
.getWorld()
.showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(), this.getName(),
e.getMessage()),
this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null);
// throw e; PR 70201.... let the normal problem reporting
// infrastructure deal with this rather than crashing.
body = null;
MethodGen gen = pack();
return gen.getMethod();
} catch (RuntimeException re) {
if (re.getCause() instanceof ClassGenException) {
enclosingClass
.getBcelObjectType()
.getResolvedTypeX()
.getWorld()
.showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.PROBLEM_GENERATING_METHOD, this.getClassName(),
this.getName(), re.getCause().getMessage()),
this.getMemberView() == null ? null : this.getMemberView().getSourceLocation(), null);
// throw e; PR 70201.... let the normal problem reporting
// infrastructure deal with this rather than crashing.
body = null;
MethodGen gen = pack();
return gen.getMethod();
}
throw re;
}
}
public void markAsChanged() {
if (wasPackedOptimally) {
throw new RuntimeException("Already packed method is being re-modified: " + getClassName() + " " + toShortString());
}
initialize();
savedMethod = null;
}
// =============================
@Override
public String toString() {
BcelObjectType bot = enclosingClass.getBcelObjectType();
WeaverVersionInfo weaverVersion = (bot == null ? WeaverVersionInfo.CURRENT : bot.getWeaverVersionAttribute());
return toLongString(weaverVersion);
}
public String toShortString() {
String access = org.aspectj.apache.bcel.classfile.Utility.accessToString(getAccessFlags());
StringBuffer buf = new StringBuffer();
if (!access.equals("")) {
buf.append(access);
buf.append(" ");
}
buf.append(org.aspectj.apache.bcel.classfile.Utility.signatureToString(getReturnType().getSignature(), true));
buf.append(" ");
buf.append(getName());
buf.append("(");
{
int len = argumentTypes.length;
if (len > 0) {
buf.append(org.aspectj.apache.bcel.classfile.Utility.signatureToString(argumentTypes[0].getSignature(), true));
for (int i = 1; i < argumentTypes.length; i++) {
buf.append(", ");
buf.append(org.aspectj.apache.bcel.classfile.Utility.signatureToString(argumentTypes[i].getSignature(), true));
}
}
}
buf.append(")");
{
int len = declaredExceptions != null ? declaredExceptions.length : 0;
if (len > 0) {
buf.append(" throws ");
buf.append(declaredExceptions[0]);
for (int i = 1; i < declaredExceptions.length; i++) {
buf.append(", ");
buf.append(declaredExceptions[i]);
}
}
}
return buf.toString();
}
public String toLongString(WeaverVersionInfo weaverVersion) {
ByteArrayOutputStream s = new ByteArrayOutputStream();
print(new PrintStream(s), weaverVersion);
return new String(s.toByteArray());
}
public void print(WeaverVersionInfo weaverVersion) {
print(System.out, weaverVersion);
}
public void print(PrintStream out, WeaverVersionInfo weaverVersion) {
out.print(" " + toShortString());
printAspectAttributes(out, weaverVersion);
InstructionList body = getBody();
if (body == null) {
out.println(";");
return;
}
out.println(":");
new BodyPrinter(out).run();
out.println(" end " + toShortString());
}
private void printAspectAttributes(PrintStream out, WeaverVersionInfo weaverVersion) {
ISourceContext context = null;
if (enclosingClass != null && enclosingClass.getType() != null) {
context = enclosingClass.getType().getSourceContext();
}
List<AjAttribute> as = Utility.readAjAttributes(getClassName(), attributes.toArray(new Attribute[] {}), context, null, weaverVersion,
new BcelConstantPoolReader(this.enclosingClass.getConstantPool()));
if (!as.isEmpty()) {
out.println(" " + as.get(0)); // XXX assuming exactly one
// attribute, munger...
}
}
private class BodyPrinter {
Map<InstructionHandle, String> labelMap = new HashMap<InstructionHandle, String>();
InstructionList body;
PrintStream out;
ConstantPool pool;
BodyPrinter(PrintStream out) {
this.pool = enclosingClass.getConstantPool();
this.body = getBodyForPrint();
this.out = out;
}
BodyPrinter(PrintStream out, InstructionList il) {
this.pool = enclosingClass.getConstantPool();
this.body = il;
this.out = out;
}
void run() {
// killNops();
assignLabels();
print();
}
// label assignment
void assignLabels() {
LinkedList<ExceptionRange> exnTable = new LinkedList<ExceptionRange>();
String pendingLabel = null;
// boolean hasPendingTargeters = false;
int lcounter = 0;
for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
Iterator<InstructionTargeter> tIter = ih.getTargeters().iterator();
while (tIter.hasNext()) {
InstructionTargeter t = tIter.next();// targeters
// [
// i
// ]
// ;
if (t instanceof ExceptionRange) {
// assert isRangeHandle(h);
ExceptionRange r = (ExceptionRange) t;
if (r.getStart() == ih) {
insertHandler(r, exnTable);
}
} else if (t instanceof InstructionBranch) {
if (pendingLabel == null) {
pendingLabel = "L" + lcounter++;
}
} else {
// assert isRangeHandle(h)
}
}
if (pendingLabel != null) {
labelMap.put(ih, pendingLabel);
if (!Range.isRangeHandle(ih)) {
pendingLabel = null;
}
}
}
int ecounter = 0;
for (Iterator i = exnTable.iterator(); i.hasNext();) {
ExceptionRange er = (ExceptionRange) i.next();
String exceptionLabel = "E" + ecounter++;
labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel);
labelMap.put(er.getHandler(), exceptionLabel);
}
}
// printing
void print() {
int depth = 0;
int currLine = -1;
bodyPrint: for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) {
if (Range.isRangeHandle(ih)) {
Range r = Range.getRange(ih);
// don't print empty ranges, that is, ranges who contain no
// actual instructions
for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) {
if (xx == r.getEnd()) {
continue bodyPrint;
}
}
// doesn't handle nested: if (r.getStart().getNext() ==
// r.getEnd()) continue;
if (r.getStart() == ih) {
printRangeString(r, depth++);
} else {
if (r.getEnd() != ih) {
throw new RuntimeException("bad");
}
printRangeString(r, --depth);
}
} else {
printInstruction(ih, depth);
int line = getLineNumber(ih, currLine);
if (line != currLine) {
currLine = line;
out.println(" (line " + line + ")");
} else {
out.println();
}
}
}
}
void printRangeString(Range r, int depth) {
printDepth(depth);
out.println(getRangeString(r, labelMap));
}
String getRangeString(Range r, Map<InstructionHandle, String> labelMap) {
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
return er.toString() + " -> " + labelMap.get(er.getHandler());
//
// + " PRI " + er.getPriority();
} else {
return r.toString();
}
}
void printDepth(int depth) {
pad(BODY_INDENT);
while (depth > 0) {
out.print("| ");
depth--;
}
}
void printLabel(String s, int depth) {
int space = Math.max(CODE_INDENT - depth * 2, 0);
if (s == null) {
pad(space);
} else {
space = Math.max(space - (s.length() + 2), 0);
pad(space);
out.print(s);
out.print(": ");
}
}
void printInstruction(InstructionHandle h, int depth) {
printDepth(depth);
printLabel(labelMap.get(h), depth);
Instruction inst = h.getInstruction();
if (inst.isConstantPoolInstruction()) {
out.print(Constants.OPCODE_NAMES[inst.opcode].toUpperCase());
out.print(" ");
out.print(pool.constantToString(pool.getConstant(inst.getIndex())));
} else if (inst instanceof InstructionSelect) {
InstructionSelect sinst = (InstructionSelect) inst;
out.println(Constants.OPCODE_NAMES[sinst.opcode].toUpperCase());
int[] matches = sinst.getMatchs();
InstructionHandle[] targets = sinst.getTargets();
InstructionHandle defaultTarget = sinst.getTarget();
for (int i = 0, len = matches.length; i < len; i++) {
printDepth(depth);
printLabel(null, depth);
out.print(" ");
out.print(matches[i]);
out.print(": \t");
out.println(labelMap.get(targets[i]));
}
printDepth(depth);
printLabel(null, depth);
out.print(" ");
out.print("default: \t");
out.print(labelMap.get(defaultTarget));
} else if (inst instanceof InstructionBranch) {
InstructionBranch brinst = (InstructionBranch) inst;
out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase());
out.print(" ");
out.print(labelMap.get(brinst.getTarget()));
} else if (inst.isLocalVariableInstruction()) {
// LocalVariableInstruction lvinst = (LocalVariableInstruction)
// inst;
out.print(inst.toString(false).toUpperCase());
int index = inst.getIndex();
LocalVariableTag tag = getLocalVariableTag(h, index);
if (tag != null) {
out.print(" // ");
out.print(tag.getType());
out.print(" ");
out.print(tag.getName());
}
} else {
out.print(inst.toString(false).toUpperCase());
}
}
static final int BODY_INDENT = 4;
static final int CODE_INDENT = 16;
void pad(int size) {
for (int i = 0; i < size; i++) {
out.print(" ");
}
}
}
static LocalVariableTag getLocalVariableTag(InstructionHandle ih, int index) {
for (InstructionTargeter t : ih.getTargeters()) {
if (t instanceof LocalVariableTag) {
LocalVariableTag lvt = (LocalVariableTag) t;
if (lvt.getSlot() == index) {
return lvt;
}
}
}
return null;
}
static int getLineNumber(InstructionHandle ih, int prevLine) {
for (InstructionTargeter t : ih.getTargeters()) {
if (t instanceof LineNumberTag) {
return ((LineNumberTag) t).getLineNumber();
}
}
return prevLine;
}
public boolean isStatic() {
return Modifier.isStatic(getAccessFlags());
}
public boolean isAbstract() {
return Modifier.isAbstract(getAccessFlags());
}
public boolean isBridgeMethod() {
return (getAccessFlags() & Constants.ACC_BRIDGE) != 0;
}
public void addExceptionHandler(InstructionHandle start, InstructionHandle end, InstructionHandle handlerStart,
ObjectType catchType, boolean highPriority) {
InstructionHandle start1 = Range.genStart(body, start);
InstructionHandle end1 = Range.genEnd(body, end);
ExceptionRange er = new ExceptionRange(body, (catchType == null ? null : BcelWorld.fromBcel(catchType)), highPriority);
er.associateWithTargets(start1, end1, handlerStart);
}
public int getAccessFlags() {
return modifiers;
}
public int getAccessFlagsWithoutSynchronized() {
if (isSynchronized()) {
return modifiers - Modifier.SYNCHRONIZED;
}
return modifiers;
}
public boolean isSynchronized() {
return (modifiers & Modifier.SYNCHRONIZED) != 0;
}
public void setAccessFlags(int newFlags) {
this.modifiers = newFlags;
}
public Type[] getArgumentTypes() {
initialize();
return argumentTypes;
}
public LazyClassGen getEnclosingClass() {
return enclosingClass;
}
public int getMaxLocals() {
return maxLocals;
}
public String getName() {
return name;
}
public String getGenericReturnTypeSignature() {
if (memberView == null) {
return getReturnType().getSignature();
} else {
return memberView.getGenericReturnType().getSignature();
}
}
public Type getReturnType() {
initialize();
return returnType;
}
public void setMaxLocals(int maxLocals) {
this.maxLocals = maxLocals;
}
public InstructionList getBody() {
markAsChanged();
return body;
}
public InstructionList getBodyForPrint() {
return body;
}
public boolean hasBody() {
if (savedMethod != null) {
return savedMethod.getCode() != null;
}
return body != null;
}
public List<Attribute> getAttributes() {
return attributes;
}
public String[] getDeclaredExceptions() {
return declaredExceptions;
}
public String getClassName() {
return enclosingClass.getName();
}
// ---- packing!
public MethodGen pack() {
forceSyntheticForAjcMagicMembers();
// killNops();
int flags = getAccessFlags();
if (enclosingClass.getWorld().isJoinpointSynchronizationEnabled()
&& enclosingClass.getWorld().areSynchronizationPointcutsInUse()) {
flags = getAccessFlagsWithoutSynchronized();
}
MethodGen gen = new MethodGen(flags, getReturnType(), getArgumentTypes(), null, // getArgumentNames(),
getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPool());
for (int i = 0, len = declaredExceptions.length; i < len; i++) {
gen.addException(declaredExceptions[i]);
}
for (Attribute attr : attributes) {
gen.addAttribute(attr);
}
if (newAnnotations != null) {
for (AnnotationAJ element : newAnnotations) {
gen.addAnnotation(new AnnotationGen(((BcelAnnotation) element).getBcelAnnotation(), gen.getConstantPool(), true));
}
}
if (newParameterAnnotations != null) {
for (int i = 0; i < newParameterAnnotations.length; i++) {
AnnotationAJ[] annos = newParameterAnnotations[i];
for (int j = 0; j < annos.length; j++) {
gen.addParameterAnnotation(i,
new AnnotationGen(((BcelAnnotation) annos[j]).getBcelAnnotation(), gen.getConstantPool(), true));
}
}
}
if (memberView != null && memberView.getAnnotations() != null && memberView.getAnnotations().length != 0) {
AnnotationAJ[] ans = memberView.getAnnotations();
for (int i = 0, len = ans.length; i < len; i++) {
AnnotationGen a = ((BcelAnnotation) ans[i]).getBcelAnnotation();
gen.addAnnotation(new AnnotationGen(a, gen.getConstantPool(), true));
}
}
if (isSynthetic) {
if (enclosingClass.getWorld().isInJava5Mode()) {
gen.setModifiers(gen.getModifiers() | ACC_SYNTHETIC);
}
if (!hasAttribute("Synthetic")) {
// belt and braces, do the attribute even on Java 5 in addition to the modifier flag
ConstantPool cpg = gen.getConstantPool();
int index = cpg.addUtf8("Synthetic");
gen.addAttribute(new Synthetic(index, 0, new byte[0], cpg));
}
}
if (hasBody()) {
if (this.enclosingClass.getWorld().shouldFastPackMethods()) {
if (isAdviceMethod() || getName().equals("<clinit>")) {
packBody(gen);
} else {
optimizedPackBody(gen);
}
} else {
packBody(gen);
}
gen.setMaxLocals();
gen.setMaxStack();
} else {
gen.setInstructionList(null);
}
return gen;
}
private boolean hasAttribute(String attributeName) {
for (Attribute attr: attributes) {
if (attr.getName().equals(attributeName)) {
return true;
}
}
return false;
}
private void forceSyntheticForAjcMagicMembers() {
if (NameMangler.isSyntheticMethod(getName(), inAspect())) {
makeSynthetic();
}
}
private boolean inAspect() {
BcelObjectType objectType = enclosingClass.getBcelObjectType();
return (objectType == null ? false : objectType.isAspect());
}
public void makeSynthetic() {
isSynthetic = true;
}
private static class LVPosition {
InstructionHandle start = null;
InstructionHandle end = null;
}
/**
* fill the newly created method gen with our body, inspired by InstructionList.copy()
*/
public void packBody(MethodGen gen) {
InstructionList fresh = gen.getInstructionList();
Map<InstructionHandle, InstructionHandle> map = copyAllInstructionsExceptRangeInstructionsInto(fresh);
// at this point, no rangeHandles are in fresh. Let's use that...
/*
* Update branch targets and insert various attributes. Insert our exceptionHandlers into a sorted list, so they can be
* added in order later.
*/
InstructionHandle oldInstructionHandle = getBody().getStart();
InstructionHandle newInstructionHandle = fresh.getStart();
LinkedList<ExceptionRange> exceptionList = new LinkedList<ExceptionRange>();
Map<LocalVariableTag, LVPosition> localVariables = new HashMap<LocalVariableTag, LVPosition>();
int currLine = -1;
int lineNumberOffset = (fromFilename == null) ? 0 : getEnclosingClass().getSourceDebugExtensionOffset(fromFilename);
while (oldInstructionHandle != null) {
if (map.get(oldInstructionHandle) == null) {
// must be a range instruction since they're the only things we
// didn't copy across
handleRangeInstruction(oldInstructionHandle, exceptionList);
// just increment ih.
oldInstructionHandle = oldInstructionHandle.getNext();
} else {
// assert map.get(ih) == jh
Instruction oldInstruction = oldInstructionHandle.getInstruction();
Instruction newInstruction = newInstructionHandle.getInstruction();
if (oldInstruction instanceof InstructionBranch) {
handleBranchInstruction(map, oldInstruction, newInstruction);
}
// now deal with line numbers
// and store up info for local variables
for (InstructionTargeter targeter : oldInstructionHandle.getTargeters()) {
if (targeter instanceof LineNumberTag) {
int line = ((LineNumberTag) targeter).getLineNumber();
if (line != currLine) {
gen.addLineNumber(newInstructionHandle, line + lineNumberOffset);
currLine = line;
}
} else if (targeter instanceof LocalVariableTag) {
LocalVariableTag lvt = (LocalVariableTag) targeter;
LVPosition p = localVariables.get(lvt);
// If we don't know about it, create a new position and
// store
// If we do know about it - update its end position
if (p == null) {
LVPosition newp = new LVPosition();
newp.start = newp.end = newInstructionHandle;
localVariables.put(lvt, newp);
} else {
p.end = newInstructionHandle;
}
}
}
// now continue
oldInstructionHandle = oldInstructionHandle.getNext();
newInstructionHandle = newInstructionHandle.getNext();
}
}
addExceptionHandlers(gen, map, exceptionList);
if (localVariables.size() == 0) {
// Might be a case of 173978 where around advice on an execution join point
// has caused everything to be extracted from the method and thus we
// are left with no local variables, not even the ones for 'this' and
// parameters passed to the method
createNewLocalVariables(gen);
} else {
addLocalVariables(gen, localVariables);
}
// JAVAC adds line number tables (with just one entry) to generated
// accessor methods - this
// keeps some tools that rely on finding at least some form of
// linenumbertable happy.
// Let's check if we have one - if we don't then let's add one.
// TODO Could be made conditional on whether line debug info is being
// produced
if (gen.getLineNumbers().length == 0) {
gen.addLineNumber(gen.getInstructionList().getStart(), 1);
}
}
private void createNewLocalVariables(MethodGen gen) {
gen.removeLocalVariables();
// ignore <clinit> or <init> for now
if (!getName().startsWith("<")) {
int slot = 0;
InstructionHandle start = gen.getInstructionList().getStart();
InstructionHandle end = gen.getInstructionList().getEnd();
// Add a 'this' if non-static
if (!isStatic()) {
String cname = this.enclosingClass.getClassName();
if (cname == null) {
return; // give up for now
}
Type enclosingType = BcelWorld.makeBcelType(UnresolvedType.forName(cname));
gen.addLocalVariable("this", enclosingType, slot++, start, end);
}
// Add entries for the method arguments
String[] paramNames = (memberView == null ? null : memberView.getParameterNames());
if (paramNames != null) {
for (int i = 0; i < argumentTypes.length; i++) {
String pname = paramNames[i];
if (pname == null) {
pname = "arg" + i;
}
gen.addLocalVariable(pname, argumentTypes[i], slot, start, end);
slot += argumentTypes[i].getSize();
}
}
}
}
/*
* Optimized packing that does a 'local packing' of the code rather than building a brand new method and packing into it. Only
* usable when the packing is going to be done just once.
*/
public void optimizedPackBody(MethodGen gen) {
InstructionList theBody = getBody();
InstructionHandle iHandle = theBody.getStart();
int currLine = -1;
int lineNumberOffset = (fromFilename == null) ? 0 : getEnclosingClass().getSourceDebugExtensionOffset(fromFilename);
Map<LocalVariableTag, LVPosition> localVariables = new HashMap<LocalVariableTag, LVPosition>();
LinkedList<ExceptionRange> exceptionList = new LinkedList<ExceptionRange>();
Set<InstructionHandle> forDeletion = new HashSet<InstructionHandle>();
Set<BranchHandle> branchInstructions = new HashSet<BranchHandle>();
// OPTIMIZE sort out in here: getRange()/insertHandler() and type of
// exceptionList
while (iHandle != null) {
Instruction inst = iHandle.getInstruction();
// InstructionHandle nextInst = iHandle.getNext();
// OPTIMIZE remove this instructionhandle as it now points to
// nowhere?
if (inst == Range.RANGEINSTRUCTION) {
Range r = Range.getRange(iHandle);
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
if (er.getStart() == iHandle) {
if (!er.isEmpty()) {
// order is important, insert handlers in order of start
insertHandler(er, exceptionList);
}
}
}
forDeletion.add(iHandle);
} else {
if (inst instanceof InstructionBranch) {
branchInstructions.add((BranchHandle) iHandle);
}
for (InstructionTargeter targeter : iHandle.getTargetersCopy()) {
if (targeter instanceof LineNumberTag) {
int line = ((LineNumberTag) targeter).getLineNumber();
if (line != currLine) {
gen.addLineNumber(iHandle, line + lineNumberOffset);
currLine = line;
}
} else if (targeter instanceof LocalVariableTag) {
LocalVariableTag lvt = (LocalVariableTag) targeter;
LVPosition p = localVariables.get(lvt);
// If we don't know about it, create a new position
// and store
// If we do know about it - update its end position
if (p == null) {
LVPosition newp = new LVPosition();
newp.start = newp.end = iHandle;
localVariables.put(lvt, newp);
} else {
p.end = iHandle;
}
}
}
}
iHandle = iHandle.getNext();
}
for (BranchHandle branchHandle : branchInstructions) {
handleBranchInstruction(branchHandle, forDeletion);
}
// now add exception handlers
for (ExceptionRange r : exceptionList) {
if (r.isEmpty()) {
continue;
}
gen.addExceptionHandler(jumpForward(r.getRealStart(), forDeletion), jumpForward(r.getRealEnd(), forDeletion),
jumpForward(r.getHandler(), forDeletion),
(r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType()));
}
for (InstructionHandle handle : forDeletion) {
try {
theBody.delete(handle);
} catch (TargetLostException e) {
e.printStackTrace();
}
}
gen.setInstructionList(theBody);
if (localVariables.size() == 0) {
// Might be a case of 173978 where around advice on an execution join point
// has caused everything to be extracted from the method and thus we
// are left with no local variables, not even the ones for 'this' and
// parameters passed to the method
createNewLocalVariables(gen);
} else {
addLocalVariables(gen, localVariables);
}
// JAVAC adds line number tables (with just one entry) to generated
// accessor methods - this
// keeps some tools that rely on finding at least some form of
// linenumbertable happy.
// Let's check if we have one - if we don't then let's add one.
// TODO Could be made conditional on whether line debug info is being
// produced
if (gen.getLineNumbers().length == 0) {
gen.addLineNumber(gen.getInstructionList().getStart(), 1);
}
wasPackedOptimally = true;
}
private void addLocalVariables(MethodGen gen, Map<LocalVariableTag, LVPosition> localVariables) {
// now add local variables
gen.removeLocalVariables();
// this next iteration _might_ be overkill, but we had problems with
// bcel before with duplicate local variables. Now that we're patching
// bcel we should be able to do without it if we're paranoid enough
// through the rest of the compiler.
InstructionHandle methodStart = gen.getInstructionList().getStart();
InstructionHandle methodEnd = gen.getInstructionList().getEnd();
// Determine how many 'slots' are used by parameters to the method.
// Then below we can determine if a local variable is a parameter variable, if it is
// we force its range to from the method start (as it may have been shuffled down
// due to insertion of advice like cflow entry)
int paramSlots = gen.isStatic() ? 0 : 1;
Type[] argTypes = gen.getArgumentTypes();
if (argTypes != null) {
for (int i = 0; i < argTypes.length; i++) {
if (argTypes[i].getSize() == 2) {
paramSlots += 2;
} else {
paramSlots += 1;
}
}
}
Map<InstructionHandle, Set<Integer>> duplicatedLocalMap = new HashMap<InstructionHandle, Set<Integer>>();
for (LocalVariableTag tag : localVariables.keySet()) {
// have we already added one with the same slot number and start
// location?
// if so, just continue.
LVPosition lvpos = localVariables.get(tag);
InstructionHandle start = (tag.getSlot() < paramSlots ? methodStart : lvpos.start);
InstructionHandle end = (tag.getSlot() < paramSlots ? methodEnd : lvpos.end);
Set<Integer> slots = duplicatedLocalMap.get(start);
if (slots == null) {
slots = new HashSet<Integer>();
duplicatedLocalMap.put(start, slots);
} else if (slots.contains(new Integer(tag.getSlot()))) {
// we already have a var starting at this tag with this slot
continue;
}
slots.add(Integer.valueOf(tag.getSlot()));
Type t = tag.getRealType();
if (t == null) {
t = BcelWorld.makeBcelType(UnresolvedType.forSignature(tag.getType()));
}
gen.addLocalVariable(tag.getName(), t, tag.getSlot(), start, end);
}
}
private void addExceptionHandlers(MethodGen gen, Map<InstructionHandle, InstructionHandle> map,
LinkedList<ExceptionRange> exnList) {
// now add exception handlers
for (ExceptionRange r : exnList) {
if (r.isEmpty()) {
continue;
}
InstructionHandle rMappedStart = remap(r.getRealStart(), map);
InstructionHandle rMappedEnd = remap(r.getRealEnd(), map);
InstructionHandle rMappedHandler = remap(r.getHandler(), map);
gen.addExceptionHandler(rMappedStart, rMappedEnd, rMappedHandler, (r.getCatchType() == null) ? null
: (ObjectType) BcelWorld.makeBcelType(r.getCatchType()));
}
}
private void handleBranchInstruction(Map<InstructionHandle, InstructionHandle> map, Instruction oldInstruction,
Instruction newInstruction) {
InstructionBranch oldBranchInstruction = (InstructionBranch) oldInstruction;
InstructionBranch newBranchInstruction = (InstructionBranch) newInstruction;
InstructionHandle oldTarget = oldBranchInstruction.getTarget(); // old
// target
// New target is in hash map
newBranchInstruction.setTarget(remap(oldTarget, map));
if (oldBranchInstruction instanceof InstructionSelect) {
// Either LOOKUPSWITCH or TABLESWITCH
InstructionHandle[] oldTargets = ((InstructionSelect) oldBranchInstruction).getTargets();
InstructionHandle[] newTargets = ((InstructionSelect) newBranchInstruction).getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
// Update all targets
newTargets[k] = remap(oldTargets[k], map);
newTargets[k].addTargeter(newBranchInstruction);
}
}
}
private InstructionHandle jumpForward(InstructionHandle t, Set<InstructionHandle> handlesForDeletion) {
InstructionHandle target = t;
if (handlesForDeletion.contains(target)) {
do {
target = target.getNext();
} while (handlesForDeletion.contains(target));
}
return target;
}
/**
* Process a branch instruction with respect to instructions that are about to be deleted. If the target for the branch is a
* candidate for deletion, move it to the next valid instruction after the deleted target.
*/
private void handleBranchInstruction(BranchHandle branchHandle, Set<InstructionHandle> handlesForDeletion) {
InstructionBranch branchInstruction = (InstructionBranch) branchHandle.getInstruction();
InstructionHandle target = branchInstruction.getTarget(); // old target
if (handlesForDeletion.contains(target)) {
do {
target = target.getNext();
} while (handlesForDeletion.contains(target));
branchInstruction.setTarget(target);
}
if (branchInstruction instanceof InstructionSelect) {
// Either LOOKUPSWITCH or TABLESWITCH
InstructionSelect iSelect = (InstructionSelect) branchInstruction;
InstructionHandle[] targets = iSelect.getTargets();
for (int k = targets.length - 1; k >= 0; k--) {
InstructionHandle oneTarget = targets[k];
if (handlesForDeletion.contains(oneTarget)) {
do {
oneTarget = oneTarget.getNext();
} while (handlesForDeletion.contains(oneTarget));
iSelect.setTarget(k, oneTarget);
oneTarget.addTargeter(branchInstruction);
}
}
}
}
private void handleRangeInstruction(InstructionHandle ih, LinkedList<ExceptionRange> exnList) {
// we're a range instruction
Range r = Range.getRange(ih);
if (r instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) r;
if (er.getStart() == ih) {
// System.err.println("er " + er);
if (!er.isEmpty()) {
// order is important, insert handlers in order of start
insertHandler(er, exnList);
}
}
} else {
// we must be a shadow range or something equally useless,
// so forget about doing anything
}
}
/*
* Make copies of all instructions, append them to the new list and associate old instruction references with the new ones,
* i.e., a 1:1 mapping.
*/
private Map<InstructionHandle, InstructionHandle> copyAllInstructionsExceptRangeInstructionsInto(InstructionList intoList) {
Map<InstructionHandle, InstructionHandle> map = new HashMap<InstructionHandle, InstructionHandle>();
for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) {
if (Range.isRangeHandle(ih)) {
continue;
}
Instruction inst = ih.getInstruction();
Instruction copy = Utility.copyInstruction(inst);
if (copy instanceof InstructionBranch) {
map.put(ih, intoList.append((InstructionBranch) copy));
} else {
map.put(ih, intoList.append(copy));
}
}
return map;
}
/**
* This procedure should not currently be used.
*/
// public void killNops() {
// InstructionHandle curr = body.getStart();
// while (true) {
// if (curr == null) break;
// InstructionHandle next = curr.getNext();
// if (curr.getInstruction() instanceof NOP) {
// InstructionTargeter[] targeters = curr.getTargeters();
// if (targeters != null) {
// for (int i = 0, len = targeters.length; i < len; i++) {
// InstructionTargeter targeter = targeters[i];
// targeter.updateTarget(curr, next);
// }
// }
// try {
// body.delete(curr);
// } catch (TargetLostException e) {
// }
// }
// curr = next;
// }
// }
// private static InstructionHandle fNext(InstructionHandle ih) {
// while (true) {
// if (ih.getInstruction()==Range.RANGEINSTRUCTION) ih = ih.getNext();
// else return ih;
// }
// }
private static InstructionHandle remap(InstructionHandle handle, Map<InstructionHandle, InstructionHandle> map) {
while (true) {
InstructionHandle ret = map.get(handle);
if (ret == null) {
handle = handle.getNext();
} else {
return ret;
}
}
}
// Update to all these comments, ASC 11-01-2005
// The right thing to do may be to do more with priorities as
// we create new exception handlers, but that is a relatively
// complex task. In the meantime, just taking account of the
// priority here enables a couple of bugs to be fixed to do
// with using return or break in code that contains a finally
// block (pr78021,pr79554).
// exception ordering.
// What we should be doing is dealing with priority inversions way earlier
// than we are
// and counting on the tree structure. In which case, the below code is in
// fact right.
// XXX THIS COMMENT BELOW IS CURRENTLY WRONG.
// An exception A preceeds an exception B in the exception table iff:
// * A and B were in the original method, and A preceeded B in the original
// exception table
// * If A has a higher priority than B, than it preceeds B.
// * If A and B have the same priority, then the one whose START happens
// EARLIEST has LEAST priority.
// in short, the outermost exception has least priority.
// we implement this with a LinkedList. We could possibly implement this
// with a java.util.SortedSet,
// but I don't trust the only implementation, TreeSet, to do the right
// thing.
/* private */static void insertHandler(ExceptionRange fresh, LinkedList<ExceptionRange> l) {
// Old implementation, simply: l.add(0,fresh);
for (ListIterator<ExceptionRange> iter = l.listIterator(); iter.hasNext();) {
ExceptionRange r = iter.next();
// int freal = fresh.getRealStart().getPosition();
// int rreal = r.getRealStart().getPosition();
if (fresh.getPriority() >= r.getPriority()) {
iter.previous();
iter.add(fresh);
return;
}
}
// we have reached the end
l.add(fresh);
}
public boolean isPrivate() {
return Modifier.isPrivate(getAccessFlags());
}
public boolean isProtected() {
return Modifier.isProtected(getAccessFlags());
}
public boolean isDefault() {
return !(isProtected() || isPrivate() || isPublic());
}
public boolean isPublic() {
return Modifier.isPublic(getAccessFlags());
}
// ----
/**
* A good body is a body with the following properties:
*
* <ul>
* <li>For each branch instruction S in body, target T of S is in body.
* <li>For each branch instruction S in body, target T of S has S as a targeter.
* <li>For each instruction T in body, for each branch instruction S that is a targeter of T, S is in body.
* <li>For each non-range-handle instruction T in body, for each instruction S that is a targeter of T, S is either a branch
* instruction, an exception range or a tag
* <li>For each range-handle instruction T in body, there is exactly one targeter S that is a range.
* <li>For each range-handle instruction T in body, the range R targeting T is in body.
* <li>For each instruction T in body, for each exception range R targeting T, R is in body.
* <li>For each exception range R in body, let T := R.handler. T is in body, and R is one of T's targeters
* <li>All ranges are properly nested: For all ranges Q and R, if Q.start preceeds R.start, then R.end preceeds Q.end.
* </ul>
*
* Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and any InstructionHandle stored in a field
* of R (such as an exception handle) is in body".
*/
public void assertGoodBody() {
if (true) {
return; // only enable for debugging
}
assertGoodBody(getBody(), toString());
}
public static void assertGoodBody(InstructionList il, String from) {
if (true) {
return; // only to be enabled for debugging
}
// if (il == null) {
// return;
// }
// Set body = new HashSet();
// Stack<Range> ranges = new Stack<Range>();
// for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
// body.add(ih);
// if (ih.getInstruction() instanceof InstructionBranch) {
// body.add(ih.getInstruction());
// }
// }
//
// for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) {
// assertGoodHandle(ih, body, ranges, from);
// Iterator<InstructionTargeter> tIter = ih.getTargeters().iterator();
// while (tIter.hasNext()) {
// assertGoodTargeter(tIter.next(), ih, body, from);
// }
// }
}
// private static void assertGoodHandle(InstructionHandle ih, Set body, Stack<Range> ranges, String from) {
// Instruction inst = ih.getInstruction();
// if ((inst instanceof InstructionBranch) ^ (ih instanceof BranchHandle)) {
// throw new BCException("bad instruction/handle pair in " + from);
// }
// if (Range.isRangeHandle(ih)) {
// assertGoodRangeHandle(ih, body, ranges, from);
// } else if (inst instanceof InstructionBranch) {
// assertGoodBranchInstruction((BranchHandle) ih, (InstructionBranch) inst, body, ranges, from);
// }
// }
// private static void assertGoodBranchInstruction(BranchHandle ih, InstructionBranch inst, Set body, Stack<Range> ranges,
// String from) {
// if (ih.getTarget() != inst.getTarget()) {
// throw new BCException("bad branch instruction/handle pair in " + from);
// }
// InstructionHandle target = ih.getTarget();
// assertInBody(target, body, from);
// assertTargetedBy(target, inst, from);
// if (inst instanceof InstructionSelect) {
// InstructionSelect sel = (InstructionSelect) inst;
// InstructionHandle[] itargets = sel.getTargets();
// for (int k = itargets.length - 1; k >= 0; k--) {
// assertInBody(itargets[k], body, from);
// assertTargetedBy(itargets[k], inst, from);
// }
// }
// }
/** ih is an InstructionHandle or a BranchInstruction */
// private static void assertInBody(Object ih, Set body, String from) {
// if (!body.contains(ih)) {
// throw new BCException("thing not in body in " + from);
// }
// }
// private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) {
// Range r = getRangeAndAssertExactlyOne(ih, from);
// assertGoodRange(r, body, from);
// if (r.getStart() == ih) {
// ranges.push(r);
// } else if (r.getEnd() == ih) {
// if (ranges.peek() != r) {
// throw new BCException("bad range inclusion in " + from);
// }
// ranges.pop();
// }
// }
// private static void assertGoodRange(Range r, Set body, String from) {
// assertInBody(r.getStart(), body, from);
// assertRangeHandle(r.getStart(), from);
// assertTargetedBy(r.getStart(), r, from);
//
// assertInBody(r.getEnd(), body, from);
// assertRangeHandle(r.getEnd(), from);
// assertTargetedBy(r.getEnd(), r, from);
//
// if (r instanceof ExceptionRange) {
// ExceptionRange er = (ExceptionRange) r;
// assertInBody(er.getHandler(), body, from);
// assertTargetedBy(er.getHandler(), r, from);
// }
// }
// private static void assertRangeHandle(InstructionHandle ih, String from) {
// if (!Range.isRangeHandle(ih)) {
// throw new BCException("bad range handle " + ih + " in " + from);
// }
// }
private static void assertTargetedBy(InstructionHandle target, InstructionTargeter targeter, String from) {
Iterator tIter = target.getTargeters().iterator();
while (tIter.hasNext()) {
if (((InstructionTargeter) tIter.next()) == targeter) {
return;
}
}
throw new RuntimeException("bad targeting relationship in " + from);
}
private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) {
if (targeter instanceof Range) {
Range r = (Range) targeter;
if (r.getStart() == target || r.getEnd() == target) {
return;
}
if (r instanceof ExceptionRange) {
if (((ExceptionRange) r).getHandler() == target) {
return;
}
}
} else if (targeter instanceof InstructionBranch) {
InstructionBranch bi = (InstructionBranch) targeter;
if (bi.getTarget() == target) {
return;
}
if (targeter instanceof InstructionSelect) {
InstructionSelect sel = (InstructionSelect) targeter;
InstructionHandle[] itargets = sel.getTargets();
for (int k = itargets.length - 1; k >= 0; k--) {
if (itargets[k] == target) {
return;
}
}
}
} else if (targeter instanceof Tag) {
return;
}
throw new BCException(targeter + " doesn't target " + target + " in " + from);
}
private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) {
Range ret = null;
Iterator<InstructionTargeter> tIter = ih.getTargeters().iterator();
if (!tIter.hasNext()) {
throw new BCException("range handle with no range in " + from);
}
while (tIter.hasNext()) {
InstructionTargeter ts = tIter.next();
if (ts instanceof Range) {
if (ret != null) {
throw new BCException("range handle with multiple ranges in " + from);
}
ret = (Range) ts;
}
}
if (ret == null) {
throw new BCException("range handle with no range in " + from);
}
return ret;
}
// private static void assertGoodTargeter(InstructionTargeter t, InstructionHandle ih, Set body, String from) {
// assertTargets(t, ih, from);
// if (t instanceof Range) {
// assertGoodRange((Range) t, body, from);
// } else if (t instanceof InstructionBranch) {
// assertInBody(t, body, from);
// }
// }
// ----
boolean isAdviceMethod() {
if (memberView == null) {
return false;
}
return memberView.getAssociatedShadowMunger() != null;
}
boolean isAjSynthetic() {
if (memberView == null) {
return true;
}
return memberView.isAjSynthetic();
}
boolean isSynthetic() {
if (memberView == null) {
return false;
}
return memberView.isSynthetic();
}
public ISourceLocation getSourceLocation() {
if (memberView != null) {
return memberView.getSourceLocation();
}
return null;
}
public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() {
// if (memberView == null) return null;
if (effectiveSignature != null) {
return effectiveSignature;
}
return memberView.getEffectiveSignature();
}
public void setEffectiveSignature(ResolvedMember member, Shadow.Kind kind, boolean shouldWeave) {
this.effectiveSignature = new AjAttribute.EffectiveSignatureAttribute(member, kind, shouldWeave);
}
public String getSignature() {
if (memberView != null) {
return memberView.getSignature();
}
return MemberImpl.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes()), false);
}
public String getParameterSignature() {
if (memberView != null) {
return memberView.getParameterSignature();
}
return MemberImpl.typesToSignature(BcelWorld.fromBcel(getArgumentTypes()));
}
public BcelMethod getMemberView() {
return memberView;
}
public void forcePublic() {
markAsChanged();
modifiers = Utility.makePublic(modifiers);
}
public boolean getCanInline() {
return canInline;
}
public void setCanInline(boolean canInline) {
this.canInline = canInline;
}
public void addAttribute(Attribute attribute) {
attributes.add(attribute);
}
public String toTraceString() {
return toShortString();
}
public ConstantPool getConstantPool() {
return enclosingClass.getConstantPool();
}
public static boolean isConstructor(LazyMethodGen aMethod) {
return aMethod.getName().equals("<init>");
}
}
|
415,266 | Bug 415266 LTW not working when JMX is enabled | When I enable JMX remote management on a JVM along with AspectJ load-time weaving (LTW), our Aspect doesn't appear to get woven in. This are the JVM arguments: -Dvisualvm.display.name=JdbcTimingAspectTest -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=1024 -javaagent:/jars/aspectjweaver.jar -Dorg.aspectj.weaver.loadtime.configuration=com/trgr/cobalt/infrastructure/instrumentation/aspects/timing/jdbc/jdbcmonitor.xml Note that if I don't enable JMX remote management (by remove the -Dcom.sun.management.jmxremote.* JVM arguments), the Aspect works fine. | resolved fixed | 9e992d6 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-01T17:08:31Z" | "2013-08-16T21:53:20Z" | loadtime/src/org/aspectj/weaver/loadtime/Aj.java | /*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.weaver.loadtime;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.tools.Trace;
import org.aspectj.weaver.tools.TraceFactory;
import org.aspectj.weaver.tools.WeavingAdaptor;
import org.aspectj.weaver.tools.cache.SimpleCache;
import org.aspectj.weaver.tools.cache.SimpleCacheFactory;
/**
* Adapter between the generic class pre processor interface and the AspectJ weaver Load time weaving consistency relies on
* Bcel.setRepository
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class Aj implements ClassPreProcessor {
private IWeavingContext weavingContext;
public static SimpleCache laCache=SimpleCacheFactory.createSimpleCache();
/**
* References are added to this queue when their associated classloader is removed, and once on here that indicates that we
* should tidy up the adaptor map and remove the adaptor (weaver) from the map we are maintaining from adaptorkey > adaptor
* (weaver)
*/
private static ReferenceQueue adaptorQueue = new ReferenceQueue();
private static Trace trace = TraceFactory.getTraceFactory().getTrace(Aj.class);
public Aj() {
this(null);
}
public Aj(IWeavingContext context) {
if (trace.isTraceEnabled())
trace.enter("<init>", this, new Object[] { context, getClass().getClassLoader() });
this.weavingContext = context;
if (trace.isTraceEnabled())
trace.exit("<init>");
}
/**
* Initialization
*/
public void initialize() {
}
private final static String deleLoader = "sun.reflect.DelegatingClassLoader";
/**
* Weave
*
* @param className
* @param bytes
* @param loader
* @return woven bytes
*/
public byte[] preProcess(String className, byte[] bytes, ClassLoader loader, ProtectionDomain protectionDomain) {
// TODO AV needs to doc that
if (loader == null || className == null || loader.getClass().getName().equals(deleLoader)) {
// skip boot loader, null classes (hibernate), or those from a reflection loader
return bytes;
}
if (loadersToSkip != null) {
// Check whether to reject it
if (loadersToSkip.contains(loader.getClass().getName())) {
// System.out.println("debug: no weaver created for loader '"+loader.getClass().getName()+"'");
return bytes;
}
}
if (trace.isTraceEnabled())
trace.enter("preProcess", this, new Object[] { className, bytes, loader });
if (trace.isTraceEnabled())
trace.event("preProcess", this, new Object[] { loader.getParent(), Thread.currentThread().getContextClassLoader() });
try {
synchronized (loader) {
if (SimpleCacheFactory.isEnabled()) {
byte[] cacheBytes= laCache.getAndInitialize(className, bytes,loader,protectionDomain);
if (cacheBytes!=null){
return cacheBytes;
}
}
WeavingAdaptor weavingAdaptor = WeaverContainer.getWeaver(loader, weavingContext);
if (weavingAdaptor == null) {
if (trace.isTraceEnabled())
trace.exit("preProcess");
return bytes;
}
try {
weavingAdaptor.setActiveProtectionDomain(protectionDomain);
byte[] newBytes = weavingAdaptor.weaveClass(className, bytes, false);
Dump.dumpOnExit(weavingAdaptor.getMessageHolder(), true);
if (trace.isTraceEnabled())
trace.exit("preProcess", newBytes);
if (SimpleCacheFactory.isEnabled()) {
laCache.put(className, bytes, newBytes);
}
return newBytes;
} finally {
weavingAdaptor.setActiveProtectionDomain(null);
}
}
/* Don't like to do this but JVMTI swallows all exceptions */
} catch (Throwable th) {
trace.error(className, th);
Dump.dumpWithException(th);
// FIXME AV wondering if we should have the option to fail (throw runtime exception) here
// would make sense at least in test f.e. see TestHelper.handleMessage()
if (trace.isTraceEnabled())
trace.exit("preProcess", th);
return bytes;
} finally {
CompilationAndWeavingContext.resetForThread();
}
}
/**
* An AdaptorKey is a WeakReference wrapping a classloader reference that will enqueue to a specified queue when the classloader
* is GC'd. Since the AdaptorKey is used as a key into a hashmap we need to give it a non-varying hashcode/equals
* implementation, and we need that hashcode not to vary even when the internal referent has been GC'd. The hashcode is
* calculated on creation of the AdaptorKey based on the loader instance that it is wrapping. This means even when the referent
* is gone we can still use the AdaptorKey and it will 'point' to the same place as it always did.
*/
private static class AdaptorKey extends WeakReference {
private final int loaderHashCode, sysHashCode, hashValue;
private final String loaderClass;
public AdaptorKey(ClassLoader loader) {
super(loader, adaptorQueue);
loaderHashCode = loader.hashCode();
sysHashCode = System.identityHashCode(loader);
loaderClass = loader.getClass().getName();
hashValue = loaderHashCode + sysHashCode + loaderClass.hashCode();
}
public ClassLoader getClassLoader() {
ClassLoader instance = (ClassLoader) get();
// Assert instance!=null - shouldn't be asked for after a GC of the referent has occurred !
return instance;
}
public boolean equals(Object obj) {
if (!(obj instanceof AdaptorKey)) {
return false;
}
AdaptorKey other = (AdaptorKey) obj;
return (other.loaderHashCode == loaderHashCode)
&& (other.sysHashCode == sysHashCode)
&& loaderClass.equals(other.loaderClass);
}
public int hashCode() {
return hashValue;
}
}
/**
* The reference queue is only processed when a request is made for a weaver adaptor. This means there can be one or two stale
* weavers left around. If the user knows they have finished all their weaving, they might wish to call removeStaleAdaptors
* which will process anything left on the reference queue containing adaptorKeys for garbage collected classloaders.
*
* @param displayProgress produce System.err info on the tidying up process
* @return number of stale weavers removed
*/
public static int removeStaleAdaptors(boolean displayProgress) {
int removed = 0;
synchronized (WeaverContainer.weavingAdaptors) {
if (displayProgress) {
System.err.println("Weaver adaptors before queue processing:");
Map m = WeaverContainer.weavingAdaptors;
Set keys = m.keySet();
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
Object object = iterator.next();
System.err.println(object + " = " + WeaverContainer.weavingAdaptors.get(object));
}
}
Object o = adaptorQueue.poll();
while (o != null) {
if (displayProgress)
System.err.println("Processing referencequeue entry " + o);
AdaptorKey wo = (AdaptorKey) o;
boolean didit = WeaverContainer.weavingAdaptors.remove(wo) != null;
if (didit) {
removed++;
} else {
throw new RuntimeException("Eh?? key=" + wo);
}
if (displayProgress)
System.err.println("Removed? " + didit);
o = adaptorQueue.poll();
}
if (displayProgress) {
System.err.println("Weaver adaptors after queue processing:");
Map m = WeaverContainer.weavingAdaptors;
Set keys = m.keySet();
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
Object object = iterator.next();
System.err.println(object + " = " + WeaverContainer.weavingAdaptors.get(object));
}
}
}
return removed;
}
/**
* @return the number of entries still in the weavingAdaptors map
*/
public static int getActiveAdaptorCount() {
return WeaverContainer.weavingAdaptors.size();
}
/**
* Process the reference queue that contains stale AdaptorKeys - the keys are put on the queue when their classloader referent
* is garbage collected and so the associated adaptor (weaver) should be removed from the map
*/
public static void checkQ() {
synchronized (adaptorQueue) {
Object o = adaptorQueue.poll();
while (o != null) {
AdaptorKey wo = (AdaptorKey) o;
// boolean removed =
WeaverContainer.weavingAdaptors.remove(wo);
// DBG System.err.println("Evicting key " + wo + " = " + didit);
o = adaptorQueue.poll();
}
}
}
public static List<String> loadersToSkip = null;
static {
// pr271840 - touch the types early and outside the locks
new ExplicitlyInitializedClassLoaderWeavingAdaptor(new ClassLoaderWeavingAdaptor());
try {
String loadersToSkipProperty = System.getProperty("aj.weaving.loadersToSkip","");
StringTokenizer st = new StringTokenizer(loadersToSkipProperty, ",");
if (loadersToSkipProperty != null && loadersToSkip == null) {
if (st.hasMoreTokens()) {
// System.out.println("aj.weaving.loadersToSkip is set. Skipping loaders: '"+loadersToSkipProperty+"'");
loadersToSkip = new ArrayList<String>();
}
while (st.hasMoreTokens()) {
String nextLoader = st.nextToken();
loadersToSkip.add(nextLoader);
}
}
} catch (Exception e) {
// Likely security issue related to property access...
}
}
/**
* Cache of weaver There is one weaver per classloader
*/
static class WeaverContainer {
final static Map weavingAdaptors = Collections.synchronizedMap(new HashMap());
static WeavingAdaptor getWeaver(ClassLoader loader, IWeavingContext weavingContext) {
ExplicitlyInitializedClassLoaderWeavingAdaptor adaptor = null;
AdaptorKey adaptorKey = new AdaptorKey(loader);
String loaderClassName = loader.getClass().getName();
synchronized (weavingAdaptors) {
checkQ();
if(loader.equals(myClassLoader)){
adaptor = myClassLoaderAdpator;
}
else{
adaptor = (ExplicitlyInitializedClassLoaderWeavingAdaptor) weavingAdaptors.get(adaptorKey);
}
if (adaptor == null) {
// create it and put it back in the weavingAdaptors map but avoid any kind of instantiation
// within the synchronized block
ClassLoaderWeavingAdaptor weavingAdaptor = new ClassLoaderWeavingAdaptor();
adaptor = new ExplicitlyInitializedClassLoaderWeavingAdaptor(weavingAdaptor);
if(myClassLoaderAdpator == null){
myClassLoaderAdpator = adaptor;
}
else{
weavingAdaptors.put(adaptorKey, adaptor);
}
}
}
// perform the initialization
return adaptor.getWeavingAdaptor(loader, weavingContext);
}
private static final ClassLoader myClassLoader = WeavingAdaptor.class.getClassLoader();
private static ExplicitlyInitializedClassLoaderWeavingAdaptor myClassLoaderAdpator;
}
static class ExplicitlyInitializedClassLoaderWeavingAdaptor {
private final ClassLoaderWeavingAdaptor weavingAdaptor;
private boolean isInitialized;
public ExplicitlyInitializedClassLoaderWeavingAdaptor(ClassLoaderWeavingAdaptor weavingAdaptor) {
this.weavingAdaptor = weavingAdaptor;
this.isInitialized = false;
}
private void initialize(ClassLoader loader, IWeavingContext weavingContext) {
if (!isInitialized) {
isInitialized = true;
weavingAdaptor.initialize(loader, weavingContext);
}
}
public ClassLoaderWeavingAdaptor getWeavingAdaptor(ClassLoader loader, IWeavingContext weavingContext) {
initialize(loader, weavingContext);
return weavingAdaptor;
}
}
/**
* Returns a namespace based on the contest of the aspects available
*/
public String getNamespace(ClassLoader loader) {
ClassLoaderWeavingAdaptor weavingAdaptor = (ClassLoaderWeavingAdaptor) WeaverContainer.getWeaver(loader, weavingContext);
return weavingAdaptor.getNamespace();
}
/**
* Check to see if any classes have been generated for a particular classes loader. Calls
* ClassLoaderWeavingAdaptor.generatedClassesExist()
*
* @param loader the class cloder
* @return true if classes have been generated.
*/
public boolean generatedClassesExist(ClassLoader loader) {
return ((ClassLoaderWeavingAdaptor) WeaverContainer.getWeaver(loader, weavingContext)).generatedClassesExistFor(null);
}
public void flushGeneratedClasses(ClassLoader loader) {
((ClassLoaderWeavingAdaptor) WeaverContainer.getWeaver(loader, weavingContext)).flushGeneratedClasses();
}
} |
419,279 | Bug 419279 ajc option to change -Xlint level per-message without Xlintfile | The -Xlintfile option is not a great fit for controlling message across multiple build projects, specifically in my case from the pluginManagement section of a maven parent pom. The problem is that you need a local file to configure the per-message output levels (ignore/warning/error) when you really want to specify it in the build script or in a shared file. As an alternative to -Xlintfile, it would be handy to be able to change an Xlint warning level per message using command line options. For example: ajc -Xlint:adviceDidNotMatch=ignore would override the XlintDefault.properties file for the adviceDidNotMatch message. With Regards Rob | resolved fixed | b2cd5fa | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-23T19:44:23Z" | "2013-10-11T19:33:20Z" | org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java | /* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* Adrian Colyer added constructor to populate javaOptions with
* default settings - 01.20.2003
* Bugzilla #29768, 29769
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.CompilationResultDestinationManager;
import org.aspectj.util.FileUtil;
/**
* All configuration information needed to run the AspectJ compiler. Compiler options (as opposed to path information) are held in
* an AjCompilerOptions instance
*/
public class AjBuildConfig implements CompilerConfigurationChangeFlags {
private boolean shouldProceed = true;
public static final String AJLINT_IGNORE = "ignore";
public static final String AJLINT_WARN = "warn";
public static final String AJLINT_ERROR = "error";
public static final String AJLINT_DEFAULT = "default";
private File outputDir;
private File outputJar;
private String outxmlName;
private CompilationResultDestinationManager compilationResultDestinationManager = null;
private List<File> sourceRoots = new ArrayList<File>();
private List<File> changedFiles;
private List<File> files = new ArrayList<File>();
private List<File> xmlfiles = new ArrayList<File>();
private List<BinarySourceFile> binaryFiles = new ArrayList<BinarySourceFile>(); // .class files in indirs...
private List<File> inJars = new ArrayList<File>();
private List<File> inPath = new ArrayList<File>();
private Map<String, File> sourcePathResources = new HashMap<String, File>();
private List<File> aspectpath = new ArrayList<File>();
private List<String> classpath = new ArrayList<String>();
private List<String> bootclasspath = new ArrayList<String>();
private List<String> cpElementsWithModifiedContents = new ArrayList<String>();
private File configFile;
private String lintMode = AJLINT_DEFAULT;
private File lintSpecFile = null;
private int changes = EVERYTHING; // bitflags, see CompilerConfigurationChangeFlags
private AjCompilerOptions options;
// incremental variants handled by the compiler client, but parsed here
private boolean incrementalMode;
private File incrementalFile;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("BuildConfig[" + (configFile == null ? "null" : configFile.getAbsoluteFile().toString()) + "] #Files="
+ files.size() + " AopXmls=#" + xmlfiles.size());
return sb.toString();
}
public static class BinarySourceFile {
public BinarySourceFile(File dir, File src) {
this.fromInPathDirectory = dir;
this.binSrc = src;
}
public File fromInPathDirectory;
public File binSrc;
public boolean equals(Object obj) {
if (obj != null && (obj instanceof BinarySourceFile)) {
BinarySourceFile other = (BinarySourceFile) obj;
return (binSrc.equals(other.binSrc));
}
return false;
}
public int hashCode() {
return binSrc != null ? binSrc.hashCode() : 0;
}
}
/**
* Intialises the javaOptions Map to hold the default JDT Compiler settings. Added by AMC 01.20.2003 in reponse to bug #29768
* and enh. 29769. The settings here are duplicated from those set in org.eclipse.jdt.internal.compiler.batch.Main, but I've
* elected to copy them rather than refactor the JDT class since this keeps integration with future JDT releases easier (?).
*/
public AjBuildConfig() {
options = new AjCompilerOptions();
}
/**
* returned files includes
* <ul>
* <li>files explicitly listed on command-line</li>
* <li>files listed by reference in argument list files</li>
* <li>files contained in sourceRootDir if that exists</li>
* </ul>
*
* @return all source files that should be compiled.
*/
public List<File> getFiles() {
return files;
}
public List<File> getXmlFiles() {
return xmlfiles;
}
/**
* returned files includes all .class files found in a directory on the inpath, but does not include .class files contained
* within jars.
*/
public List<BinarySourceFile> getBinaryFiles() {
return binaryFiles;
}
public File getOutputDir() {
return outputDir;
}
public CompilationResultDestinationManager getCompilationResultDestinationManager() {
return this.compilationResultDestinationManager;
}
public void setCompilationResultDestinationManager(CompilationResultDestinationManager mgr) {
this.compilationResultDestinationManager = mgr;
}
public void setFiles(List<File> files) {
this.files = files;
}
public void setXmlFiles(List<File> xmlfiles) {
this.xmlfiles = xmlfiles;
}
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
}
public AjCompilerOptions getOptions() {
return options;
}
/**
* This does not include -bootclasspath but includes -extdirs and -classpath
*/
public List<String> getClasspath() {
return classpath;
}
public void setClasspath(List<String> classpath) {
this.classpath = classpath;
}
public List<String> getBootclasspath() {
return bootclasspath;
}
public void setBootclasspath(List<String> bootclasspath) {
this.bootclasspath = bootclasspath;
}
public File getOutputJar() {
return outputJar;
}
public String getOutxmlName() {
return outxmlName;
}
public List<File> getInpath() {
// Elements of the list are either archives (jars/zips) or directories
return inPath;
}
public List<File> getInJars() {
return inJars;
}
public Map<String, File> getSourcePathResources() {
return sourcePathResources;
}
public void setOutputJar(File outputJar) {
this.outputJar = outputJar;
}
public void setOutxmlName(String name) {
this.outxmlName = name;
}
public void setInJars(List<File> sourceJars) {
this.inJars = sourceJars;
}
public void setInPath(List<File> dirsOrJars) {
inPath = dirsOrJars;
// remember all the class files in directories on the inpath
binaryFiles = new ArrayList<BinarySourceFile>();
FileFilter filter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".class");
}
};
for (Iterator<File> iter = dirsOrJars.iterator(); iter.hasNext();) {
File inpathElement = iter.next();
if (inpathElement.isDirectory()) {
File[] files = FileUtil.listFiles(inpathElement, filter);
for (int i = 0; i < files.length; i++) {
binaryFiles.add(new BinarySourceFile(inpathElement, files[i]));
}
}
}
}
public List<File> getSourceRoots() {
return sourceRoots;
}
public void setSourceRoots(List<File> sourceRootDir) {
this.sourceRoots = sourceRootDir;
}
public File getConfigFile() {
return configFile;
}
public void setConfigFile(File configFile) {
this.configFile = configFile;
}
public void setIncrementalMode(boolean incrementalMode) {
this.incrementalMode = incrementalMode;
}
public boolean isIncrementalMode() {
return incrementalMode;
}
public void setIncrementalFile(File incrementalFile) {
this.incrementalFile = incrementalFile;
}
public boolean isIncrementalFileMode() {
return (null != incrementalFile);
}
/**
* @return List (String) classpath of bootclasspath, injars, inpath, aspectpath entries, specified classpath (extdirs, and
* classpath), and output dir or jar
*/
public List<String> getFullClasspath() {
List<String> full = new ArrayList<String>();
full.addAll(getBootclasspath()); // XXX Is it OK that boot classpath overrides inpath/injars/aspectpath?
for (Iterator<File> i = inJars.iterator(); i.hasNext();) {
full.add((i.next()).getAbsolutePath());
}
for (Iterator<File> i = inPath.iterator(); i.hasNext();) {
full.add((i.next()).getAbsolutePath());
}
for (Iterator<File> i = aspectpath.iterator(); i.hasNext();) {
full.add((i.next()).getAbsolutePath());
}
full.addAll(getClasspath());
// if (null != outputDir) {
// full.add(outputDir.getAbsolutePath());
// } else if (null != outputJar) {
// full.add(outputJar.getAbsolutePath());
// }
return full;
}
public File getLintSpecFile() {
return lintSpecFile;
}
public void setLintSpecFile(File lintSpecFile) {
this.lintSpecFile = lintSpecFile;
}
public List<File> getAspectpath() {
return aspectpath;
}
public void setAspectpath(List<File> aspectpath) {
this.aspectpath = aspectpath;
}
/** @return true if any config file, sourceroots, sourcefiles, injars or inpath */
public boolean hasSources() {
return ((null != configFile) || (0 < sourceRoots.size()) || (0 < files.size()) || (0 < inJars.size()) || (0 < inPath.size()));
}
// /** @return null if no errors, String errors otherwise */
// public String configErrors() {
// StringBuffer result = new StringBuffer();
// // ok, permit both. sigh.
// // if ((null != outputDir) && (null != outputJar)) {
// // result.append("specified both outputDir and outputJar");
// // }
// // incremental => only sourceroots
// //
// return (0 == result.length() ? null : result.toString());
// }
/**
* Install global values into local config unless values conflict:
* <ul>
* <li>Collections are unioned</li>
* <li>values takes local value unless default and global set</li>
* <li>this only sets one of outputDir and outputJar as needed</li>
* <ul>
* This also configures super if javaOptions change.
*
* @param global the AjBuildConfig to read globals from
*/
public void installGlobals(AjBuildConfig global) { // XXX relies on default values
// don't join the options - they already have defaults taken care of.
// Map optionsMap = options.getMap();
// join(optionsMap,global.getOptions().getMap());
// options.set(optionsMap);
options.defaultEncoding = global.options.defaultEncoding;// pr244321
join(aspectpath, global.aspectpath);
join(classpath, global.classpath);
if (null == configFile) {
configFile = global.configFile; // XXX correct?
}
if (!isEmacsSymMode() && global.isEmacsSymMode()) {
setEmacsSymMode(true);
}
join(files, global.files);
join(xmlfiles, global.xmlfiles);
if (!isGenerateModelMode() && global.isGenerateModelMode()) {
setGenerateModelMode(true);
}
if (null == incrementalFile) {
incrementalFile = global.incrementalFile;
}
if (!incrementalMode && global.incrementalMode) {
incrementalMode = true;
}
if (isCheckRuntimeVersion() && !global.isCheckRuntimeVersion()) {
setCheckRuntimeVersion(false);
}
join(inJars, global.inJars);
join(inPath, global.inPath);
if ((null == lintMode) || (AJLINT_DEFAULT.equals(lintMode))) {
setLintMode(global.lintMode);
}
if (null == lintSpecFile) {
lintSpecFile = global.lintSpecFile;
}
if (!isTerminateAfterCompilation() && global.isTerminateAfterCompilation()) {
setTerminateAfterCompilation(true);
}
if ((null == outputDir) && (null == outputJar)) {
if (null != global.outputDir) {
outputDir = global.outputDir;
}
if (null != global.outputJar) {
outputJar = global.outputJar;
}
}
join(sourceRoots, global.sourceRoots);
if (!isXnoInline() && global.isXnoInline()) {
setXnoInline(true);
}
if (!isXserializableAspects() && global.isXserializableAspects()) {
setXserializableAspects(true);
}
if (!isXlazyTjp() && global.isXlazyTjp()) {
setXlazyTjp(true);
}
if (!getProceedOnError() && global.getProceedOnError()) {
setProceedOnError(true);
}
setTargetAspectjRuntimeLevel(global.getTargetAspectjRuntimeLevel());
setXJoinpoints(global.getXJoinpoints());
if (!isXHasMemberEnabled() && global.isXHasMemberEnabled()) {
setXHasMemberSupport(true);
}
if (!isXNotReweavable() && global.isXNotReweavable()) {
setXnotReweavable(true);
}
setOutxmlName(global.getOutxmlName());
setXconfigurationInfo(global.getXconfigurationInfo());
setAddSerialVerUID(global.isAddSerialVerUID());
if (!isXmlConfigured() && global.isXmlConfigured()) {
setXmlConfigured(global.isXmlConfigured());
}
setTiming(global.isTiming());
setMakeReflectable(global.isMakeReflectable());
}
@SuppressWarnings({ "rawtypes", "unchecked" })
void join(Collection local, Collection global) {
for (Iterator iter = global.iterator(); iter.hasNext();) {
Object next = iter.next();
if (!local.contains(next)) {
local.add(next);
}
}
}
public void setSourcePathResources(Map<String, File> map) {
sourcePathResources = map;
}
/**
* used to indicate whether to proceed after parsing config
*/
public boolean shouldProceed() {
return shouldProceed;
}
public void doNotProceed() {
shouldProceed = false;
}
public String getLintMode() {
return lintMode;
}
// options...
public void setLintMode(String lintMode) {
this.lintMode = lintMode;
String lintValue = null;
if (AJLINT_IGNORE.equals(lintMode)) {
lintValue = AjCompilerOptions.IGNORE;
} else if (AJLINT_WARN.equals(lintMode)) {
lintValue = AjCompilerOptions.WARNING;
} else if (AJLINT_ERROR.equals(lintMode)) {
lintValue = AjCompilerOptions.ERROR;
}
if (lintValue != null) {
Map<String, String> lintOptions = new HashMap<String, String>();
lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName, lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName, lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportUnresolvableMember, lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver, lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure, lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall, lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP, lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField, lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion, lintValue);
options.set(lintOptions);
}
}
public boolean isTerminateAfterCompilation() {
return options.terminateAfterCompilation;
}
public void setTerminateAfterCompilation(boolean b) {
options.terminateAfterCompilation = b;
}
public boolean isXserializableAspects() {
return options.xSerializableAspects;
}
public void setXserializableAspects(boolean xserializableAspects) {
options.xSerializableAspects = xserializableAspects;
}
public void setXJoinpoints(String jps) {
options.xOptionalJoinpoints = jps;
}
public String getXJoinpoints() {
return options.xOptionalJoinpoints;
}
public boolean isXnoInline() {
return options.xNoInline;
}
public void setXnoInline(boolean xnoInline) {
options.xNoInline = xnoInline;
}
public boolean isXlazyTjp() {
return options.xLazyThisJoinPoint;
}
public void setXlazyTjp(boolean b) {
options.xLazyThisJoinPoint = b;
}
public void setXnotReweavable(boolean b) {
options.xNotReweavable = b;
}
public void setXconfigurationInfo(String info) {
options.xConfigurationInfo = info;
}
public String getXconfigurationInfo() {
return options.xConfigurationInfo;
}
public void setXHasMemberSupport(boolean enabled) {
options.xHasMember = enabled;
}
public boolean isXHasMemberEnabled() {
return options.xHasMember;
}
public void setXdevPinpointMode(boolean enabled) {
options.xdevPinpoint = enabled;
}
public boolean isXdevPinpoint() {
return options.xdevPinpoint;
}
public void setAddSerialVerUID(boolean b) {
options.addSerialVerUID = b;
}
public boolean isAddSerialVerUID() {
return options.addSerialVerUID;
}
public void setXmlConfigured(boolean b) {
options.xmlConfigured = b;
}
public void setMakeReflectable(boolean b) {
options.makeReflectable = b;
}
public boolean isXmlConfigured() {
return options.xmlConfigured;
}
public boolean isMakeReflectable() {
return options.makeReflectable;
}
public boolean isXNotReweavable() {
return options.xNotReweavable;
}
public boolean isGenerateJavadocsInModelMode() {
return options.generateJavaDocsInModel;
}
public void setGenerateJavadocsInModelMode(boolean generateJavadocsInModelMode) {
options.generateJavaDocsInModel = generateJavadocsInModelMode;
}
public boolean isGenerateCrossRefsMode() {
return options.generateCrossRefs;
}
public void setGenerateCrossRefsMode(boolean on) {
options.generateCrossRefs = on;
}
public boolean isCheckRuntimeVersion() {
return options.checkRuntimeVersion;
}
public void setCheckRuntimeVersion(boolean on) {
options.checkRuntimeVersion = on;
}
public boolean isEmacsSymMode() {
return options.generateEmacsSymFiles;
}
public void setEmacsSymMode(boolean emacsSymMode) {
options.generateEmacsSymFiles = emacsSymMode;
}
public boolean isGenerateModelMode() {
return options.generateModel;
}
public void setGenerateModelMode(boolean structureModelMode) {
options.generateModel = structureModelMode;
}
public boolean isNoAtAspectJAnnotationProcessing() {
return options.noAtAspectJProcessing;
}
public void setNoAtAspectJAnnotationProcessing(boolean noProcess) {
options.noAtAspectJProcessing = noProcess;
}
public void setShowWeavingInformation(boolean b) {
options.showWeavingInformation = true;
}
public boolean getShowWeavingInformation() {
return options.showWeavingInformation;
}
public void setProceedOnError(boolean b) {
options.proceedOnError = b;
}
public boolean getProceedOnError() {
return options.proceedOnError;
}
public void setBehaveInJava5Way(boolean b) {
options.behaveInJava5Way = b;
}
public boolean getBehaveInJava5Way() {
return options.behaveInJava5Way;
}
public void setTiming(boolean b) {
options.timing = b;
}
public boolean isTiming() {
return options.timing;
}
public void setTargetAspectjRuntimeLevel(String level) {
options.targetAspectjRuntimeLevel = level;
}
public String getTargetAspectjRuntimeLevel() {
return options.targetAspectjRuntimeLevel;
}
/**
* Indicates what has changed in this configuration compared to the last time it was used, allowing the state management logic
* to make intelligent optimizations and skip unnecessary work.
*
* @param changes set of bitflags, see {@link CompilerConfigurationChangeFlags} for flags
*/
public void setChanged(int changes) {
this.changes = changes;
}
/**
* Return the bit flags indicating what has changed since the last time this config was used.
*
* @return the bitflags according too {@link CompilerConfigurationChangeFlags}
*/
public int getChanged() {
return this.changes;
}
public void setModifiedFiles(List<File> projectSourceFilesChanged) {
this.changedFiles = projectSourceFilesChanged;
}
public List<File> getModifiedFiles() {
return this.changedFiles;
}
public void setClasspathElementsWithModifiedContents(List<String> cpElementsWithModifiedContents) {
this.cpElementsWithModifiedContents = cpElementsWithModifiedContents;
}
public List<String> getClasspathElementsWithModifiedContents() {
return this.cpElementsWithModifiedContents;
}
public void setProjectEncoding(String projectEncoding) {
options.defaultEncoding = projectEncoding;
}
}
|
419,279 | Bug 419279 ajc option to change -Xlint level per-message without Xlintfile | The -Xlintfile option is not a great fit for controlling message across multiple build projects, specifically in my case from the pluginManagement section of a maven parent pom. The problem is that you need a local file to configure the per-message output levels (ignore/warning/error) when you really want to specify it in the build script or in a shared file. As an alternative to -Xlintfile, it would be handy to be able to change an Xlint warning level per message using command line options. For example: ajc -Xlint:adviceDidNotMatch=ignore would override the XlintDefault.properties file for the adviceDidNotMatch message. With Regards Rob | resolved fixed | b2cd5fa | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-23T19:44:23Z" | "2013-10-11T19:33:20Z" | org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java | /* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter;
import org.aspectj.ajdt.internal.compiler.AjPipeliningCompilerAdapter;
import org.aspectj.ajdt.internal.compiler.CompilationResultDestinationManager;
import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider;
import org.aspectj.ajdt.internal.compiler.ICompilerAdapter;
import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory;
import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor;
import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.AnonymousClassPublisher;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.CountingMessageHandler;
import org.aspectj.bridge.ILifecycleAware;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.bridge.Version;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextFormatter;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.core.compiler.IProblem;
import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathLocation;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.IrritantSet;
import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.aspectj.tools.ajc.Main;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.CustomMungerFactory;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.eclipse.core.runtime.OperationCanceledException;
public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySourceProvider, ICompilerAdapterFactory {
private static final String CROSSREFS_FILE_NAME = "build.lst";
private static final String CANT_WRITE_RESULT = "unable to write compilation result";
private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
public static boolean COPY_INPATH_DIR_RESOURCES = false;
// AJDT doesn't want this check, so Main enables it.
private static boolean DO_RUNTIME_VERSION_CHECK = false;
// If runtime version check fails, warn or fail? (unset?)
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private static final FileFilter binarySourceFilter = new FileFilter() {
public boolean accept(File f) {
return f.getName().endsWith(".class");
}
};
/**
* This builder is static so that it can be subclassed and reset. However, note that there is only one builder present, so if
* two extendsion reset it, only the latter will get used.
*/
public static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder();
static {
// CompilationAndWeavingContext.setMultiThreaded(false);
CompilationAndWeavingContext.registerFormatter(CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter());
CompilationAndWeavingContext
.registerFormatter(CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter());
}
private IProgressListener progressListener = null;
private boolean environmentSupportsIncrementalCompilation = false;
private int compiledCount;
private int sourceFileCount;
private JarOutputStream zos;
private boolean batchCompile = true;
private INameEnvironment environment;
private Map /* String -> List<UCF> */binarySourcesForTheNextCompile = new HashMap();
// FIXME asc should this really be in here?
// private AsmManager structureModel;
public AjBuildConfig buildConfig;
private boolean ignoreOutxml;
private boolean wasFullBuild = true; // true if last build was a full build rather than an incremental build
AjState state = new AjState(this);
/**
* Enable check for runtime version, used only by Ant/command-line Main.
*
* @param main Main unused except to limit to non-null clients.
*/
public static void enableRuntimeVersionCheck(Main caller) {
DO_RUNTIME_VERSION_CHECK = null != caller;
}
public BcelWeaver getWeaver() {
return state.getWeaver();
}
public BcelWorld getBcelWorld() {
return state.getBcelWorld();
}
public CountingMessageHandler handler;
private CustomMungerFactory customMungerFactory;
public AjBuildManager(IMessageHandler holder) {
super();
this.handler = CountingMessageHandler.makeCountingMessageHandler(holder);
}
public void environmentSupportsIncrementalCompilation(boolean itDoes) {
this.environmentSupportsIncrementalCompilation = itDoes;
if (itDoes) {
org.aspectj.weaver.loadtime.definition.DocumentParser.deactivateCaching();
}
}
/** @return true if we should generate a model as a side-effect */
public boolean doGenerateModel() {
return buildConfig.isGenerateModelMode();
}
public boolean batchBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException {
return performBuild(buildConfig, baseHandler, true);
}
public boolean incrementalBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler) throws IOException, AbortException {
return performBuild(buildConfig, baseHandler, false);
}
/**
* Perform a build.
*
* @return true if the build was successful (ie. no errors)
*/
private boolean performBuild(AjBuildConfig buildConfig, IMessageHandler baseHandler, boolean isFullBuild) throws IOException,
AbortException {
boolean ret = true;
batchCompile = isFullBuild;
wasFullBuild = isFullBuild;
if (baseHandler instanceof ILifecycleAware) {
((ILifecycleAware) baseHandler).buildStarting(!isFullBuild);
}
CompilationAndWeavingContext.reset();
int phase = isFullBuild ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD;
ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase, buildConfig);
try {
if (isFullBuild) {
this.state = new AjState(this);
}
this.state.setCouldBeSubsequentIncrementalBuild(this.environmentSupportsIncrementalCompilation);
boolean canIncremental = state.prepareForNextBuild(buildConfig);
if (!canIncremental && !isFullBuild) { // retry as batch?
CompilationAndWeavingContext.leavingPhase(ct);
if (state.listenerDefined()) {
state.getListener().recordDecision("Falling back to batch compilation");
}
return performBuild(buildConfig, baseHandler, true);
}
this.handler = CountingMessageHandler.makeCountingMessageHandler(baseHandler);
if (buildConfig == null || buildConfig.isCheckRuntimeVersion()) {
if (DO_RUNTIME_VERSION_CHECK) {
String check = checkRtJar(buildConfig);
if (check != null) {
if (FAIL_IF_RUNTIME_NOT_FOUND) {
MessageUtil.error(handler, check);
CompilationAndWeavingContext.leavingPhase(ct);
return false;
} else {
MessageUtil.warn(handler, check);
}
}
}
}
// if (batch) {
setBuildConfig(buildConfig);
// }
if (isFullBuild || !AsmManager.attemptIncrementalModelRepairs) {
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
setupModel(buildConfig);
// }
}
if (isFullBuild) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
if (buildConfig.getOutputJar() != null) {
if (!openOutputStream(buildConfig.getOutputJar())) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
}
if (isFullBuild) {
// System.err.println("XXXX batch: " + buildConfig.getFiles());
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
AsmManager.setLastActiveStructureModel(state.getStructureModel());
getWorld().setModel(state.getStructureModel());
// in incremental build, only get updated model?
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
performCompilation(buildConfig.getFiles());
state.clearBinarySourceFiles(); // we don't want these hanging around...
if (!proceedOnError() && handler.hasErrors()) {
CompilationAndWeavingContext.leavingPhase(ct);
if (AsmManager.isReporting()) {
state.getStructureModel().reportModelInfo("After a batch build");
}
return false;
}
if (AsmManager.isReporting()) {
state.getStructureModel().reportModelInfo("After a batch build");
}
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
AsmManager.setLastActiveStructureModel(state.getStructureModel());
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
Set<File> files = state.getFilesToCompile(true);
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
if (AsmManager.attemptIncrementalModelRepairs) {
state.getStructureModel().resetDeltaProcessing();
state.getStructureModel().processDelta(files, state.getAddedFiles(), state.getDeletedFiles());
}
}
boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
for (int i = 0; (i < 5) && hereWeGoAgain; i++) {
if (state.listenerDefined()) {
state.getListener()
.recordInformation("Starting incremental compilation loop " + (i + 1) + " of possibly 5");
// System.err.println("XXXX inc: " + files);
}
performCompilation(files);
if ((!proceedOnError() && handler.hasErrors())
|| (progressListener != null && progressListener.isCancelledRequested())) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
if (state.requiresFullBatchBuild()) {
if (state.listenerDefined()) {
state.getListener().recordInformation(" Dropping back to full build");
}
return batchBuild(buildConfig, baseHandler);
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false);
files = state.getFilesToCompile(false);
hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
// TODO Andy - Needs some thought here...
// I think here we might want to pass empty addedFiles/deletedFiles as they were
// dealt with on the first call to processDelta - we are going through this loop
// again because in compiling something we found something else we needed to
// rebuild. But what case causes this?
if (hereWeGoAgain) {
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
if (AsmManager.attemptIncrementalModelRepairs) {
state.getStructureModel().processDelta(files, state.getAddedFiles(), state.getDeletedFiles());
}
}
}
}
if (!files.isEmpty()) {
CompilationAndWeavingContext.leavingPhase(ct);
return batchBuild(buildConfig, baseHandler);
} else {
if (AsmManager.isReporting()) {
state.getStructureModel().reportModelInfo("After an incremental build");
}
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel(state.getStructureModel());
}
// for bug 113554: support ajsym file generation for command line builds
if (buildConfig.isGenerateCrossRefsMode()) {
File configFileProxy = new File(buildConfig.getOutputDir(), CROSSREFS_FILE_NAME);
state.getStructureModel().writeStructureModel(configFileProxy.getAbsolutePath());
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig, isFullBuild);
// For a full compile, copy resources to the destination
// - they should not get deleted on incremental and AJDT
// will handle changes to them that require a recopying
if (isFullBuild) {
copyResourcesToDestination();
}
if (buildConfig.getOutxmlName() != null) {
writeOutxmlFile();
}
/* boolean weaved = */// weaveAndGenerateClassFiles();
// if not weaved, then no-op build, no model changes
// but always returns true
// XXX weaved not in Mik's incremental
if (buildConfig.isGenerateModelMode()) {
state.getStructureModel().fireModelUpdated();
}
CompilationAndWeavingContext.leavingPhase(ct);
} finally {
if (baseHandler instanceof ILifecycleAware) {
((ILifecycleAware) baseHandler).buildFinished(!isFullBuild);
}
if (zos != null) {
closeOutputStream(buildConfig.getOutputJar());
}
ret = !handler.hasErrors();
if (getBcelWorld() != null) {
BcelWorld bcelWorld = getBcelWorld();
bcelWorld.reportTimers();
bcelWorld.tidyUp();
}
if (getWeaver() != null) {
getWeaver().tidyUp();
// bug 59895, don't release reference to handler as may be needed by a nested call
// handler = null;
}
}
return ret;
}
/**
* Open an output jar file in which to write the compiler output.
*
* @param outJar the jar file to open
* @return true if successful
*/
private boolean openOutputStream(File outJar) {
try {
OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar());
zos = new JarOutputStream(os, getWeaver().getManifest(true));
} catch (IOException ex) {
IMessage message = new Message("Unable to open outjar " + outJar.getPath() + "(" + ex.getMessage() + ")",
new SourceLocation(outJar, 0), true);
handler.handleMessage(message);
return false;
}
return true;
}
private void closeOutputStream(File outJar) {
try {
if (zos != null) {
zos.close();
if (buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileWrite(outJar.getPath(),
CompilationResultDestinationManager.FILETYPE_OUTJAR);
}
}
zos = null;
/* Ensure we don't write an incomplete JAR bug-71339 */
if (handler.hasErrors()) {
outJar.delete();
if (buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileRemove(outJar.getPath(),
CompilationResultDestinationManager.FILETYPE_OUTJAR);
}
}
} catch (IOException ex) {
IMessage message = new Message("Unable to write outjar " + outJar.getPath() + "(" + ex.getMessage() + ")",
new SourceLocation(outJar, 0), true);
handler.handleMessage(message);
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) {
File inJar = (File) i.next();
copyResourcesFromJarFile(inJar);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) {
File inPathElement = (File) i.next();
if (inPathElement.isDirectory()) {
copyResourcesFromDirectory(inPathElement);
} else {
copyResourcesFromJarFile(inPathElement);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext();) {
String resource = (String) i.next();
File from = buildConfig.getSourcePathResources().get(resource);
copyResourcesFromFile(from, resource, from);
}
}
writeManifest();
}
private void copyResourcesFromJarFile(File jarFile) throws IOException {
JarInputStream inStream = null;
try {
inStream = new JarInputStream(new FileInputStream(jarFile));
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) {
break;
}
String filename = entry.getName();
// System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'");
if (entry.isDirectory()) {
writeDirectory(filename, jarFile);
} else if (acceptResource(filename, false)) {
byte[] bytes = FileUtil.readAsByteArray(inStream);
writeResource(filename, bytes, jarFile);
}
inStream.closeEntry();
}
} finally {
if (inStream != null) {
inStream.close();
}
}
}
private void copyResourcesFromDirectory(File dir) throws IOException {
if (!COPY_INPATH_DIR_RESOURCES) {
return;
}
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(dir, new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class"));
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1);
copyResourcesFromFile(files[i], filename, dir);
}
}
private void copyResourcesFromFile(File f, String filename, File src) throws IOException {
if (!acceptResource(filename, true)) {
return;
}
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
writeResource(filename, bytes, src);
} catch (FileNotFoundException fnfe) {
// pr359332: looks like the file moved (refactoring?) just as this copy was starting
// that is OK
} finally {
if (fis != null) {
fis.close();
}
}
}
/**
* Add a directory entry to the output zip file. Don't do anything if not writing out to a zip file. A directory entry is one
* whose filename ends with '/'
*
* @param directory the directory path
* @param srcloc the src of the directory entry, for use when creating a warning message
* @throws IOException if something goes wrong creating the new zip entry
*/
private void writeDirectory(String directory, File srcloc) throws IOException {
if (state.hasResource(directory)) {
IMessage msg = new Message("duplicate resource: '" + directory + "'", IMessage.WARNING, null, new SourceLocation(
srcloc, 0));
handler.handleMessage(msg);
return;
}
if (zos != null) {
ZipEntry newEntry = new ZipEntry(directory);
zos.putNextEntry(newEntry);
zos.closeEntry();
state.recordResource(directory, srcloc);
}
// Nothing to do if not writing to a zip file
}
private void writeResource(String filename, byte[] content, File srcLocation) throws IOException {
if (state.hasResource(filename)) {
IMessage msg = new Message("duplicate resource: '" + filename + "'", IMessage.WARNING, null, new SourceLocation(
srcLocation, 0));
handler.handleMessage(msg);
return;
}
if (filename.equals(buildConfig.getOutxmlName())) {
ignoreOutxml = true;
IMessage msg = new Message("-outxml/-outxmlfile option ignored because resource already exists: '" + filename + "'",
IMessage.WARNING, null, new SourceLocation(srcLocation, 0));
handler.handleMessage(msg);
}
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename); // ??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(content);
zos.closeEntry();
} else {
File destDir = buildConfig.getOutputDir();
if (buildConfig.getCompilationResultDestinationManager() != null) {
destDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForResource(srcLocation);
}
try {
File outputLocation = new File(destDir, filename);
OutputStream fos = FileUtil.makeOutputStream(outputLocation);
fos.write(content);
fos.close();
if (buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputLocation.getPath(),
CompilationResultDestinationManager.FILETYPE_RESOURCE);
}
} catch (FileNotFoundException fnfe) {
IMessage msg = new Message("unable to copy resource to output folder: '" + filename + "' - reason: "
+ fnfe.getMessage(), IMessage.ERROR, null, new SourceLocation(srcLocation, 0));
handler.handleMessage(msg);
}
}
state.recordResource(filename, srcLocation);
}
/*
* If we are writing to an output directory copy the manifest but only if we already have one
*/
private void writeManifest() throws IOException {
Manifest manifest = getWeaver().getManifest(false);
if (manifest != null && zos == null) {
File outputDir = buildConfig.getOutputDir();
if (buildConfig.getCompilationResultDestinationManager() != null) {
// Manifests are only written if we have a jar on the inpath. Therefore,
// we write the manifest to the defaultOutputLocation because this is
// where we sent the classes that were on the inpath
outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation();
}
if (outputDir == null) {
return;
}
File outputLocation = new File(outputDir, MANIFEST_NAME);
OutputStream fos = FileUtil.makeOutputStream(outputLocation);
manifest.write(fos);
fos.close();
if (buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputLocation.getPath(),
CompilationResultDestinationManager.FILETYPE_RESOURCE);
}
}
}
private boolean acceptResource(String resourceName, boolean fromFile) {
if ((resourceName.startsWith("CVS/")) || (resourceName.indexOf("/CVS/") != -1) || (resourceName.endsWith("/CVS"))
|| (resourceName.endsWith(".class")) || (resourceName.startsWith(".svn/"))
|| (resourceName.indexOf("/.svn/") != -1) || (resourceName.endsWith("/.svn")) ||
// Do not copy manifests if either they are coming from a jar or we are writing to a jar
(resourceName.toUpperCase().equals(MANIFEST_NAME) && (!fromFile || zos != null))) {
return false;
} else {
return true;
}
}
private void writeOutxmlFile() throws IOException {
if (ignoreOutxml) {
return;
}
String filename = buildConfig.getOutxmlName();
// System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename);
Map<File, List<String>> outputDirsAndAspects = findOutputDirsForAspects();
Set<Map.Entry<File, List<String>>> outputDirs = outputDirsAndAspects.entrySet();
for (Iterator<Map.Entry<File, List<String>>> iterator = outputDirs.iterator(); iterator.hasNext();) {
Map.Entry<File, List<String>> entry = iterator.next();
File outputDir = entry.getKey();
List<String> aspects = entry.getValue();
ByteArrayOutputStream baos = getOutxmlContents(aspects);
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename);
zos.putNextEntry(newEntry);
zos.write(baos.toByteArray());
zos.closeEntry();
} else {
File outputFile = new File(outputDir, filename);
OutputStream fos = FileUtil.makeOutputStream(outputFile);
fos.write(baos.toByteArray());
fos.close();
if (buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputFile.getPath(),
CompilationResultDestinationManager.FILETYPE_RESOURCE);
}
}
}
}
private ByteArrayOutputStream getOutxmlContents(List aspectNames) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.println("<aspectj>");
ps.println("<aspects>");
if (aspectNames != null) {
for (Iterator i = aspectNames.iterator(); i.hasNext();) {
String name = (String) i.next();
ps.println("<aspect name=\"" + name + "\"/>");
}
}
ps.println("</aspects>");
ps.println("</aspectj>");
ps.println();
ps.close();
return baos;
}
/**
* Returns a map where the keys are File objects corresponding to all the output directories and the values are a list of
* aspects which are sent to that ouptut directory
*/
private Map<File, List<String>> findOutputDirsForAspects() {
Map<File, List<String>> outputDirsToAspects = new HashMap<File, List<String>>();
Map<String, char[]> aspectNamesToFileNames = state.getAspectNamesToFileNameMap();
if (buildConfig.getCompilationResultDestinationManager() == null
|| buildConfig.getCompilationResultDestinationManager().getAllOutputLocations().size() == 1) {
// we only have one output directory...which simplifies things
File outputDir = buildConfig.getOutputDir();
if (buildConfig.getCompilationResultDestinationManager() != null) {
outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation();
}
List<String> aspectNames = new ArrayList<String>();
if (aspectNamesToFileNames != null) {
Set<String> keys = aspectNamesToFileNames.keySet();
for (String name : keys) {
aspectNames.add(name);
}
}
outputDirsToAspects.put(outputDir, aspectNames);
} else {
List outputDirs = buildConfig.getCompilationResultDestinationManager().getAllOutputLocations();
for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
File outputDir = (File) iterator.next();
outputDirsToAspects.put(outputDir, new ArrayList<String>());
}
if (aspectNamesToFileNames != null) {
Set<Map.Entry<String, char[]>> entrySet = aspectNamesToFileNames.entrySet();
for (Iterator<Map.Entry<String, char[]>> iterator = entrySet.iterator(); iterator.hasNext();) {
Map.Entry<String, char[]> entry = iterator.next();
String aspectName = entry.getKey();
char[] fileName = entry.getValue();
File outputDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(
new File(new String(fileName)));
if (!outputDirsToAspects.containsKey(outputDir)) {
outputDirsToAspects.put(outputDir, new ArrayList<String>());
}
((List) outputDirsToAspects.get(outputDir)).add(aspectName);
}
}
}
return outputDirsToAspects;
}
// public static void dumprels() {
// IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
// int ctr = 1;
// Set entries = irm.getEntries();
// for (Iterator iter = entries.iterator(); iter.hasNext();) {
// String hid = (String) iter.next();
// List rels = irm.get(hid);
// for (Iterator iterator = rels.iterator(); iterator.hasNext();) {
// IRelationship ir = (IRelationship) iterator.next();
// List targets = ir.getTargets();
// for (Iterator iterator2 = targets.iterator();
// iterator2.hasNext();
// ) {
// String thid = (String) iterator2.next();
// System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid);
// }
// }
// }
// }
/**
* Responsible for managing the ASM model between builds. Contains the policy for maintaining the persistance of elements in the
* model.
*
* This code is driven before each 'fresh' (batch) build to create a new model.
*/
private void setupModel(AjBuildConfig config) {
if (!(config.isEmacsSymMode() || config.isGenerateModelMode())) {
return;
}
// AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode());
// if (!AsmManager.isCreatingModel())
// return;
CompilationResultDestinationManager crdm = config.getCompilationResultDestinationManager();
AsmManager structureModel = AsmManager.createNewStructureModel(crdm == null ? Collections.EMPTY_MAP : crdm.getInpathMap());
// AsmManager.getDefault().getRelationshipMap().clear();
IHierarchy model = structureModel.getHierarchy();
String rootLabel = "<root>";
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath());
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(structureModel, rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap<String, IProgramElement>());
// setStructureModel(model);
state.setStructureModel(structureModel);
// state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap());
}
//
// private void dumplist(List l) {
// System.err.println("---- "+l.size());
// for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i));
// }
// private void accumulateFileNodes(IProgramElement ipe,List store) {
// if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA ||
// ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) {
// if (!ipe.getName().equals("<root>")) {
// store.add(ipe);
// return;
// }
// }
// for (Iterator i = ipe.getChildren().iterator();i.hasNext();) {
// accumulateFileNodes((IProgramElement)i.next(),store);
// }
// }
// LTODO delegate to BcelWeaver?
// XXX hideous, should not be Object
public void setCustomMungerFactory(Object o) {
customMungerFactory = (CustomMungerFactory) o;
}
public Object getCustomMungerFactory() {
return customMungerFactory;
}
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
List cp = buildConfig.getFullClasspath(); // pr145693
// buildConfig.getBootclasspath();
// cp.addAll(buildConfig.getClasspath());
BcelWorld bcelWorld = new BcelWorld(cp, handler, null);
bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way());
bcelWorld.setTiming(buildConfig.isTiming(), false);
bcelWorld.setAddSerialVerUID(buildConfig.isAddSerialVerUID());
bcelWorld.setXmlConfigured(buildConfig.isXmlConfigured());
bcelWorld.setXmlFiles(buildConfig.getXmlFiles());
bcelWorld.performExtraConfiguration(buildConfig.getXconfigurationInfo());
bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel());
bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints());
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp());
bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled());
bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint());
bcelWorld.setErrorAndWarningThreshold(buildConfig.getOptions().errorThreshold.isSet(24), buildConfig.getOptions().warningThreshold.isSet(24));
BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld);
bcelWeaver.setCustomMungerFactory(customMungerFactory);
state.setWorld(bcelWorld);
state.setWeaver(bcelWeaver);
state.clearBinarySourceFiles();
if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) {
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(buildConfig.getLintMode());
}
if (buildConfig.getLintSpecFile() != null) {
bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile());
}
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) {
File f = (File) i.next();
if (!f.exists()) {
IMessage message = new Message("invalid aspectpath entry: " + f.getName(), null, true);
handler.handleMessage(message);
} else {
bcelWeaver.addLibraryJarFile(f);
}
}
// String lintMode = buildConfig.getLintMode();
File outputDir = buildConfig.getOutputDir();
if (outputDir == null && buildConfig.getCompilationResultDestinationManager() != null) {
// send all output from injars and inpath to the default output location
// (will also later send the manifest there too)
outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation();
}
// ??? incremental issues
for (File inJar : buildConfig.getInJars()) {
List<UnwovenClassFile> unwovenClasses = bcelWeaver.addJarFile(inJar, outputDir, false);
state.recordBinarySource(inJar.getPath(), unwovenClasses);
}
for (File inPathElement : buildConfig.getInpath()) {
if (!inPathElement.isDirectory()) {
// its a jar file on the inpath
// the weaver method can actually handle dirs, but we don't call it, see next block
List<UnwovenClassFile> unwovenClasses = bcelWeaver.addJarFile(inPathElement, outputDir, true);
state.recordBinarySource(inPathElement.getPath(), unwovenClasses);
} else {
// add each class file in an in-dir individually, this gives us the best error reporting
// (they are like 'source' files then), and enables a cleaner incremental treatment of
// class file changes in indirs.
File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter);
for (int j = 0; j < binSrcs.length; j++) {
UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, outputDir);
List<UnwovenClassFile> ucfl = new ArrayList<UnwovenClassFile>();
ucfl.add(ucf);
state.recordBinarySource(binSrcs[j].getPath(), ucfl);
}
}
}
bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable());
// check for org.aspectj.runtime.JoinPoint
ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint");
if (joinPoint.isMissing()) {
IMessage message = new Message(
"classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)",
null, true);
handler.handleMessage(message);
}
}
public World getWorld() {
return getBcelWorld();
}
// void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException {
// for (Iterator i = addedClassFiles.iterator(); i.hasNext();) {
// UnwovenClassFile classFile = (UnwovenClassFile) i.next();
// getWeaver().addClassFile(classFile);
// }
// }
public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) {
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) {//$NON-NLS-1$
defaultEncoding = null;
}
// Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every
// element of the classpath is likely to be a directory. If we ensure every element of the array is set to
// only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build
// a classpathDirectory object that will attempt to look for source when it can't find binary.
// int[] classpathModes = new int[classpaths.length];
// for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY;
return new FileSystem(classpaths, filenames, defaultEncoding, ClasspathLocation.BINARY);
}
public IProblemFactory getProblemFactory() {
return new DefaultProblemFactory(Locale.getDefault());
}
/*
* Build the set of compilation source units
*/
public CompilationUnit[] getCompilationUnits(String[] filenames) {
int fileCount = filenames.length;
CompilationUnit[] units = new CompilationUnit[fileCount];
// HashtableOfObject knownFileNames = new HashtableOfObject(fileCount);
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) {//$NON-NLS-1$
defaultEncoding = null;
}
for (int i = 0; i < fileCount; i++) {
units[i] = new CompilationUnit(null, filenames[i], defaultEncoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(Collection<File> files) {
if (progressListener != null) {
compiledCount = 0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
// Translate from strings to File objects
String[] filenames = new String[files.size()];
int idx = 0;
for (Iterator<File> fIterator = files.iterator(); fIterator.hasNext();) {
File f = fIterator.next();
filenames[idx++] = f.getPath();
}
environment = state.getNameEnvironment();
boolean environmentNeedsRebuilding = false;
// Might be a bit too cautious, but let us see how it goes
if (buildConfig.getChanged() != AjBuildConfig.NO_CHANGES) {
environmentNeedsRebuilding = true;
}
if (environment == null || environmentNeedsRebuilding) {
List<String> cps = buildConfig.getFullClasspath();
Dump.saveFullClasspath(cps);
String[] classpaths = new String[cps.size()];
for (int i = 0; i < cps.size(); i++) {
classpaths[i] = cps.get(i);
}
environment = new StatefulNameEnvironment(getLibraryAccess(classpaths, filenames), state.getClassNameToFileMap(), state);
state.setNameEnvironment(environment);
} else {
((StatefulNameEnvironment) environment).update(state.getClassNameToFileMap(), state.deltaAddedClasses);
state.deltaAddedClasses.clear();
}
org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this);
org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler = new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(
environment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), buildConfig.getOptions().getMap(),
getBatchRequestor(), getProblemFactory());
compiler.options.produceReferenceInfo = true; // TODO turn off when not needed
try {
compiler.compile(getCompilationUnits(filenames));
} catch (OperationCanceledException oce) {
handler.handleMessage(new Message("build cancelled:" + oce.getMessage(), IMessage.WARNING, null, null));
}
// cleanup
org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null);
AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null);
environment.cleanup();
// environment = null;
}
public void cleanupEnvironment() {
if (environment != null) {
environment.cleanup();
environment = null;
// le = null;
}
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public IIntermediateResultsRequestor getInterimResultRequestor() {
return new IIntermediateResultsRequestor() {
public void acceptResult(InterimCompilationResult result) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount / 2.0) / sourceFileCount);
progressListener.setText("compiled: " + result.fileName());
}
state.noteResult(result);
if (progressListener != null && progressListener.isCancelledRequested()) {
throw new AbortCompilation(true, new OperationCanceledException("Compilation cancelled as requested"));
}
}
};
}
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
public void acceptResult(CompilationResult unitResult) {
// end of compile, must now write the results to the output destination
// this is either a jar file or a file in a directory
boolean hasErrors = unitResult.hasErrors();
if (!hasErrors || proceedOnError()) {
Collection<ClassFile> classFiles = unitResult.compiledTypes.values();
boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null);
for (Iterator<ClassFile> iter = classFiles.iterator(); iter.hasNext();) {
ClassFile classFile = iter.next();
String filename = new String(classFile.fileName());
String classname = filename.replace('/', '.');
filename = filename.replace('/', File.separatorChar) + ".class";
try {
if (buildConfig.getOutputJar() == null) {
String outfile = writeDirectoryEntry(unitResult, classFile, filename);
getWorld().classWriteEvent(classFile.getCompoundName());
if (environmentSupportsIncrementalCompilation) {
if (!classname.endsWith("$ajcMightHaveAspect")) {
ResolvedType type = getBcelWorld().resolve(classname);
if (type.isAspect()) {
state.recordAspectClassFile(outfile);
}
}
}
} else {
writeZipEntry(classFile, filename);
}
if (shouldAddAspectName && !classname.endsWith("$ajcMightHaveAspect")) {
addAspectName(classname, unitResult.getFileName());
}
} catch (IOException ex) {
IMessage message = EclipseAdapterUtils.makeErrorMessage(new String(unitResult.fileName),
CANT_WRITE_RESULT, ex);
handler.handleMessage(message);
}
}
state.noteNewResult(unitResult);
unitResult.compiledTypes.clear(); // free up references to AjClassFile instances
}
if (unitResult.hasProblems() || unitResult.hasTasks()) {
IProblem[] problems = unitResult.getAllProblems();
for (int i = 0; i < problems.length; i++) {
IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i], getBcelWorld(),
progressListener);
handler.handleMessage(message);
}
}
}
private String writeDirectoryEntry(CompilationResult unitResult, ClassFile classFile, String filename)
throws IOException {
File destinationPath = buildConfig.getOutputDir();
if (buildConfig.getCompilationResultDestinationManager() != null) {
destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(
new File(new String(unitResult.fileName)));
}
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
try {
BufferedOutputStream os = FileUtil.makeOutputStream(new File(outFile));
os.write(classFile.getBytes());
os.close();
} catch (FileNotFoundException fnfe) {
IMessage msg = new Message("unable to write out class file: '" + filename + "' - reason: " + fnfe.getMessage(),
IMessage.ERROR, null, new SourceLocation(new File(outFile), 0));
handler.handleMessage(msg);
}
if (buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileWrite(outFile,
CompilationResultDestinationManager.FILETYPE_CLASS);
}
return outFile;
}
private void writeZipEntry(ClassFile classFile, String name) throws IOException {
name = name.replace(File.separatorChar, '/');
ZipEntry newEntry = new ZipEntry(name); // ??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(classFile.getBytes());
zos.closeEntry();
}
private void addAspectName(String name, char[] fileContainingAspect) {
BcelWorld world = getBcelWorld();
ResolvedType type = world.resolve(name);
// System.err.println("? writeAspectName() type=" + type);
if (type.isAspect()) {
if (state.getAspectNamesToFileNameMap() == null) {
state.initializeAspectNamesToFileNameMap();
}
if (!state.getAspectNamesToFileNameMap().containsKey(name)) {
state.getAspectNamesToFileNameMap().put(name, fileContainingAspect);
}
}
}
};
}
protected boolean proceedOnError() {
return buildConfig.getProceedOnError();
}
// public void noteClassFiles(AjCompiler.InterimResult result) {
// if (result == null) return;
// CompilationResult unitResult = result.result;
// String sourceFileName = result.fileName();
// if (!(unitResult.hasErrors() && !proceedOnError())) {
// List unwovenClassFiles = new ArrayList();
// Enumeration classFiles = unitResult.compiledTypes.elements();
// while (classFiles.hasMoreElements()) {
// ClassFile classFile = (ClassFile) classFiles.nextElement();
// String filename = new String(classFile.fileName());
// filename = filename.replace('/', File.separatorChar) + ".class";
//
// File destinationPath = buildConfig.getOutputDir();
// if (destinationPath == null) {
// filename = new File(filename).getName();
// filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
// } else {
// filename = new File(destinationPath, filename).getPath();
// }
//
// //System.out.println("classfile: " + filename);
// unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
// }
// state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
// // System.out.println("file: " + sourceFileName);
// // for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
// // System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
// // }
// // for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
// // System.out.println("qualified: " +
// // new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
// // }
// } else {
// state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
// }
// }
//
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
if (!this.environmentSupportsIncrementalCompilation) {
this.environmentSupportsIncrementalCompilation = (buildConfig.isIncrementalMode() || buildConfig
.isIncrementalFileMode());
}
handler.reset();
}
String makeClasspathString(AjBuildConfig buildConfig) {
if (buildConfig == null || buildConfig.getFullClasspath() == null) {
return "";
}
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext();) {
if (first) {
first = false;
} else {
buf.append(File.pathSeparator);
}
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version. Otherwise it will return a string message
* indicating the problem.
*/
private String checkRtJar(AjBuildConfig buildConfig) {
// omitting dev info
if (Version.text.equals(Version.DEVELOPMENT)) {
// in the development version we can't do this test usefully
// MessageUtil.info(holder, "running development version of aspectj compiler");
return null;
}
if (buildConfig == null || buildConfig.getFullClasspath() == null) {
return "no classpath specified";
}
String ret = null;
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext();) {
File p = new File((String) it.next());
// pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar
if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.text;
continue;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.text + " found "
+ version;
continue;
}
} catch (IOException ioe) {
ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null; // this is the "OK" return value!
} else if (p.isFile() && p.getName().indexOf("org.aspectj.runtime") != -1) {
// likely to be a variant from the springsource bundle repo b272591
return null;
} else {
// might want to catch other classpath errors
}
}
if (ret != null) {
return ret; // last error found in potentially matching jars...
}
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig);
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
//
// public void setStructureModel(IHierarchy structureModel) {
// this.structureModel = structureModel;
// }
/**
* Returns null if there is no structure model
*/
public AsmManager getStructureModel() {
return (state == null ? null : state.getStructureModel());
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
/*
* (non-Javadoc)
*
* @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[])
*/
public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) {
String filename = new String(eclipseClassFileName);
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
if (buildConfig.getCompilationResultDestinationManager() != null) {
File f = new File(new String(result.getFileName()));
destinationPath = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(f);
}
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
return outFile;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler)
*/
public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
// complete compiler config and return a suitable adapter...
populateCompilerOptionsFromLintSettings(forCompiler);
AjProblemReporter pr = new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), forCompiler.options,
getProblemFactory());
forCompiler.problemReporter = pr;
AjLookupEnvironment le = new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le, this);
le.factory = factory;
pr.factory = factory;
forCompiler.lookupEnvironment = le;
forCompiler.parser = new Parser(pr, forCompiler.options.parseLiteralExpressionsAsConstants);
if (getBcelWorld().shouldPipelineCompilation()) {
IMessage message = MessageUtil.info("Pipelining compilation");
handler.handleMessage(message);
return new AjPipeliningCompilerAdapter(forCompiler, batchCompile, getBcelWorld(), getWeaver(), factory,
getInterimResultRequestor(), progressListener,
this, // IOutputFilenameProvider
this, // IBinarySourceProvider
state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(),
buildConfig.isNoAtAspectJAnnotationProcessing(), buildConfig.isMakeReflectable(), state);
} else {
return new AjCompilerAdapter(forCompiler, batchCompile, getBcelWorld(), getWeaver(), factory,
getInterimResultRequestor(), progressListener,
this, // IOutputFilenameProvider
this, // IBinarySourceProvider
state.getBinarySourceMap(), buildConfig.isTerminateAfterCompilation(), buildConfig.getProceedOnError(),
buildConfig.isNoAtAspectJAnnotationProcessing(), buildConfig.isMakeReflectable(), state);
}
}
/**
* Some AspectJ lint options need to be known about in the compiler. This is how we pass them over...
*
* @param forCompiler
*/
private void populateCompilerOptionsFromLintSettings(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
BcelWorld world = this.state.getBcelWorld();
IMessage.Kind swallowedExceptionKind = world.getLint().swallowedExceptionInCatchBlock.getKind();
Map optionsMap = new HashMap();
optionsMap.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock, swallowedExceptionKind == null ? "ignore"
: swallowedExceptionKind.toString());
forCompiler.options.set(optionsMap);
}
/*
* (non-Javadoc)
*
* @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave()
*/
public Map getBinarySourcesForThisWeave() {
return binarySourcesForTheNextCompile;
}
public static AsmHierarchyBuilder getAsmHierarchyBuilder() {
return asmHierarchyBuilder;
}
/**
* Override the the default hierarchy builder.
*/
public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) {
asmHierarchyBuilder = newBuilder;
}
public AjState getState() {
return state;
}
public void setState(AjState buildState) {
state = buildState;
}
private static class AjBuildContexFormatter implements ContextFormatter {
public String formatEntry(int phaseId, Object data) {
StringBuffer sb = new StringBuffer();
if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) {
sb.append("batch building ");
} else {
sb.append("incrementally building ");
}
AjBuildConfig config = (AjBuildConfig) data;
List classpath = config.getClasspath();
sb.append("with classpath: ");
for (Iterator iter = classpath.iterator(); iter.hasNext();) {
sb.append(iter.next().toString());
sb.append(File.pathSeparator);
}
return sb.toString();
}
}
public boolean wasFullBuild() {
return wasFullBuild;
}
}
|
419,279 | Bug 419279 ajc option to change -Xlint level per-message without Xlintfile | The -Xlintfile option is not a great fit for controlling message across multiple build projects, specifically in my case from the pluginManagement section of a maven parent pom. The problem is that you need a local file to configure the per-message output levels (ignore/warning/error) when you really want to specify it in the build script or in a shared file. As an alternative to -Xlintfile, it would be handy to be able to change an Xlint warning level per message using command line options. For example: ajc -Xlint:adviceDidNotMatch=ignore would override the XlintDefault.properties file for the adviceDidNotMatch message. With Regards Rob | resolved fixed | b2cd5fa | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-23T19:44:23Z" | "2013-10-11T19:33:20Z" | org.aspectj.matcher/src/org/aspectj/weaver/Lint.java | /* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.weaver.tools.Trace;
import org.aspectj.weaver.tools.TraceFactory;
public class Lint {
Map<String, Lint.Kind> kinds = new HashMap<String, Lint.Kind>();
/* private */World world;
public final Kind invalidAbsoluteTypeName = new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}");
public final Kind invalidWildcardTypeName = new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}");
public final Kind unresolvableMember = new Kind("unresolvableMember", "can not resolve this member: {0}");
public final Kind typeNotExposedToWeaver = new Kind("typeNotExposedToWeaver",
"this affected type is not exposed to the weaver: {0}");
public final Kind shadowNotInStructure = new Kind("shadowNotInStructure",
"the shadow for this join point is not exposed in the structure model: {0}");
public final Kind unmatchedSuperTypeInCall = new Kind("unmatchedSuperTypeInCall",
"does not match because declaring type is {0}, if match desired use target({1})");
public final Kind unmatchedTargetKind = new Kind("unmatchedTargetKind", "does not match because annotation {0} has @Target{1}");
public final Kind canNotImplementLazyTjp = new Kind("canNotImplementLazyTjp",
"can not implement lazyTjp on this joinpoint {0} because around advice is used");
public final Kind multipleAdviceStoppingLazyTjp = new Kind("multipleAdviceStoppingLazyTjp",
"can not implement lazyTjp at joinpoint {0} because of advice conflicts, see secondary locations to find conflicting advice");
public final Kind needsSerialVersionUIDField = new Kind("needsSerialVersionUIDField",
"serialVersionUID of type {0} needs to be set because of {1}");
public final Kind serialVersionUIDBroken = new Kind("brokeSerialVersionCompatibility",
"serialVersionUID of type {0} is broken because of added field {1}");
public final Kind noInterfaceCtorJoinpoint = new Kind("noInterfaceCtorJoinpoint",
"no interface constructor-execution join point - use {0}+ for implementing classes");
public final Kind noJoinpointsForBridgeMethods = new Kind(
"noJoinpointsForBridgeMethods",
"pointcut did not match on the method call to a bridge method. Bridge methods are generated by the compiler and have no join points");
public final Kind enumAsTargetForDecpIgnored = new Kind("enumAsTargetForDecpIgnored",
"enum type {0} matches a declare parents type pattern but is being ignored");
public final Kind annotationAsTargetForDecpIgnored = new Kind("annotationAsTargetForDecpIgnored",
"annotation type {0} matches a declare parents type pattern but is being ignored");
public final Kind cantMatchArrayTypeOnVarargs = new Kind("cantMatchArrayTypeOnVarargs",
"an array type as the last parameter in a signature does not match on the varargs declared method: {0}");
public final Kind adviceDidNotMatch = new Kind("adviceDidNotMatch", "advice defined in {0} has not been applied");
public final Kind invalidTargetForAnnotation = new Kind("invalidTargetForAnnotation",
"{0} is not a valid target for annotation {1}, this annotation can only be applied to {2}");
public final Kind elementAlreadyAnnotated = new Kind("elementAlreadyAnnotated",
"{0} - already has an annotation of type {1}, cannot add a second instance");
public final Kind runtimeExceptionNotSoftened = new Kind("runtimeExceptionNotSoftened",
"{0} will not be softened as it is already a RuntimeException");
public final Kind uncheckedArgument = new Kind("uncheckedArgument",
"unchecked match of {0} with {1} when argument is an instance of {2} at join point {3}");
public final Kind uncheckedAdviceConversion = new Kind("uncheckedAdviceConversion",
"unchecked conversion when advice applied at shadow {0}, expected {1} but advice uses {2}");
public final Kind noGuardForLazyTjp = new Kind("noGuardForLazyTjp",
"can not build thisJoinPoint lazily for this advice since it has no suitable guard");
public final Kind noExplicitConstructorCall = new Kind("noExplicitConstructorCall",
"inter-type constructor does not contain explicit constructor call: field initializers in the target type will not be executed");
public final Kind aspectExcludedByConfiguration = new Kind("aspectExcludedByConfiguration",
"aspect {0} exluded for class loader {1}");
public final Kind unorderedAdviceAtShadow = new Kind("unorderedAdviceAtShadow",
"at this shadow {0} no precedence is specified between advice applying from aspect {1} and aspect {2}");
public final Kind swallowedExceptionInCatchBlock = new Kind("swallowedExceptionInCatchBlock",
"exception swallowed in catch block");
public final Kind calculatingSerialVersionUID = new Kind("calculatingSerialVersionUID",
"calculated SerialVersionUID for type {0} to be {1}");
public final Kind nonReweavableTypeEncountered = new Kind("nonReweavableTypeEncountered",
"class '{0}' is already woven and has not been built in reweavable mode");
// there are a lot of messages in the cant find type family - I'm defining an umbrella lint warning that
// allows a user to control their severity (for e.g. ltw or binary weaving)
public final Kind cantFindType = new Kind("cantFindType", "{0}");
public final Kind cantFindTypeAffectingJoinPointMatch = new Kind("cantFindTypeAffectingJPMatch", "{0}");
public final Kind advisingSynchronizedMethods = new Kind("advisingSynchronizedMethods",
"advice matching the synchronized method shadow ''{0}'' will be executed outside the lock rather than inside (compiler limitation)");
public final Kind mustWeaveXmlDefinedAspects = new Kind(
"mustWeaveXmlDefinedAspects",
"XML Defined aspects must be woven in cases where cflow pointcuts are involved. Currently the include/exclude patterns exclude ''{0}''");
public final Kind cannotAdviseJoinpointInInterfaceWithAroundAdvice = new Kind(
"cannotAdviseJoinpointInInterfaceWithAroundAdvice",
"The joinpoint ''{0}'' cannot be advised and is being skipped as the compiler implementation will lead to creation of methods with bodies in an interface (compiler limitation)");
/**
* Indicates an aspect could not be found when attempting reweaving.
*/
public final Kind missingAspectForReweaving = new Kind("missingAspectForReweaving",
"aspect {0} cannot be found when reweaving {1}");
private static Trace trace = TraceFactory.getTraceFactory().getTrace(Lint.class);
public Lint(World world) {
if (trace.isTraceEnabled()) {
trace.enter("<init>", this, world);
}
this.world = world;
if (trace.isTraceEnabled()) {
trace.exit("<init>");
}
}
public void setAll(String messageKind) {
if (trace.isTraceEnabled()) {
trace.enter("setAll", this, messageKind);
}
setAll(getMessageKind(messageKind));
if (trace.isTraceEnabled()) {
trace.exit("setAll");
}
}
private void setAll(IMessage.Kind messageKind) {
for (Kind kind : kinds.values()) {
kind.setKind(messageKind);
}
}
public void setFromProperties(File file) {
if (trace.isTraceEnabled()) {
trace.enter("setFromProperties", this, file);
}
InputStream s = null;
try {
s = new FileInputStream(file);
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINT_LOAD_ERROR, file.getPath(), ioe.getMessage()));
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
// ignore
}
}
}
if (trace.isTraceEnabled()) {
trace.exit("setFromProperties");
}
}
public void loadDefaultProperties() {
InputStream s = getClass().getResourceAsStream("XlintDefault.properties");
if (s == null) {
MessageUtil.warn(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_ERROR));
return;
}
try {
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_PROBLEM, ioe.getMessage()));
} finally {
try {
s.close();
} catch (IOException ioe) {
// ignore
}
}
}
private void setFromProperties(InputStream s) throws IOException {
Properties p = new Properties();
p.load(s);
setFromProperties(p);
}
@SuppressWarnings("rawtypes")
public void setFromProperties(Properties properties) {
for (Iterator i = properties.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
Kind kind = kinds.get(entry.getKey());
if (kind == null) {
MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINT_KEY_ERROR, entry.getKey()));
} else {
kind.setKind(getMessageKind((String) entry.getValue()));
}
}
}
public Collection<Kind> allKinds() {
return kinds.values();
}
public Kind getLintKind(String name) {
return kinds.get(name);
}
// temporarily suppress the given lint messages
public void suppressKinds(Collection<Kind> lintKind) {
if (lintKind.isEmpty()) {
return;
}
for (Kind k : lintKind) {
k.setSuppressed(true);
}
}
// remove any suppression of lint warnings in place
public void clearAllSuppressions() {
for (Kind k : kinds.values()) {
k.setSuppressed(false);
}
}
public void clearSuppressions(Collection<Lint.Kind> lintKinds) {
for (Kind k : lintKinds) {
k.setSuppressed(false);
}
}
private IMessage.Kind getMessageKind(String v) {
if (v.equals("ignore")) {
return null;
} else if (v.equals("warning")) {
return IMessage.WARNING;
} else if (v.equals("error")) {
return IMessage.ERROR;
}
MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINT_VALUE_ERROR, v));
return null;
}
public Kind fromKey(String lintkey) {
return kinds.get(lintkey);
}
public class Kind {
private final String name;
private final String message;
private IMessage.Kind kind = IMessage.WARNING;
private boolean isSupressed = false; // by SuppressAjWarnings
public Kind(String name, String message) {
this.name = name;
this.message = message;
kinds.put(this.name, this);
}
public void setSuppressed(boolean shouldBeSuppressed) {
this.isSupressed = shouldBeSuppressed;
}
public boolean isEnabled() {
return (kind != null) && !isSupressed();
}
private boolean isSupressed() {
// can't suppress errors!
return isSupressed && (kind != IMessage.ERROR);
}
public String getName() {
return name;
}
public IMessage.Kind getKind() {
return kind;
}
public void setKind(IMessage.Kind kind) {
this.kind = kind;
}
public void signal(String info, ISourceLocation location) {
if (kind == null) {
return;
}
String text = MessageFormat.format(message, new Object[] { info });
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(new LintMessage(text, kind, location, null, getLintKind(name)));
}
public void signal(String[] infos, ISourceLocation location, ISourceLocation[] extraLocations) {
if (kind == null) {
return;
}
String text = MessageFormat.format(message, (Object[]) infos);
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(new LintMessage(text, kind, location, extraLocations, getLintKind(name)));
}
}
}
|
419,279 | Bug 419279 ajc option to change -Xlint level per-message without Xlintfile | The -Xlintfile option is not a great fit for controlling message across multiple build projects, specifically in my case from the pluginManagement section of a maven parent pom. The problem is that you need a local file to configure the per-message output levels (ignore/warning/error) when you really want to specify it in the build script or in a shared file. As an alternative to -Xlintfile, it would be handy to be able to change an Xlint warning level per message using command line options. For example: ajc -Xlint:adviceDidNotMatch=ignore would override the XlintDefault.properties file for the adviceDidNotMatch message. With Regards Rob | resolved fixed | b2cd5fa | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-23T19:44:23Z" | "2013-10-11T19:33:20Z" | testing/newsrc/org/aspectj/testing/CompileSpec.java | /* *******************************************************************
* Copyright (c) 2004 IBM Corporation
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer,
* ******************************************************************/
package org.aspectj.testing;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.aspectj.tools.ajc.AjcTestCase;
import org.aspectj.tools.ajc.CompilationResult;
/**
* @author colyer
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class CompileSpec implements ITestStep {
private List expected = new ArrayList();
private String files;
private boolean includeClassesDir;
private String aspectpath;
private String classpath;
private String inpath;
private String sourceroots;
private String outjar;
private String outxml;
private String xlintfile;
private String options;
private String baseDir;
private String extdirs;
private AjcTest myTest;
public CompileSpec() {
}
public void execute(AjcTestCase inTestCase) {
File base = new File(baseDir);
String[] args = buildArgs();
CompilationResult result = inTestCase.ajc(base,args);
AjcTestCase.MessageSpec messageSpec = buildMessageSpec();
String failMessage = "test \"" + myTest.getTitle() + "\" failed";
inTestCase.assertMessages(result,failMessage,messageSpec);
inTestCase.setShouldEmptySandbox(false); // so subsequent steps in same test see my results
}
public void addExpectedMessage(ExpectedMessageSpec message) {
expected.add(message);
}
public void setBaseDir(String dir) {
this.baseDir = dir;
}
protected String getBaseDir() { return baseDir; }
public void setTest(AjcTest t) {
this.myTest = t;
if (options != null && (options.indexOf("-1.5") != -1)) {
myTest.setVm("1.5");
}
}
protected AjcTest getTest() { return myTest; }
/**
* @return Returns the aspectpath.
*/
public String getAspectpath() {
return aspectpath;
}
/**
* @param aspectpath The aspectpath to set.
*/
public void setAspectpath(String aspectpath) {
this.aspectpath = aspectpath.replace(',',File.pathSeparatorChar);
}
/**
* @return Returns the classpath.
*/
public String getClasspath() {
return classpath;
}
/**
* @param classpath The classpath to set.
*/
public void setClasspath(String classpath) {
this.classpath = classpath.replace(',',File.pathSeparatorChar);
}
/**
* @return Returns the files.
*/
public String getFiles() {
return files;
}
/**
* @param files The files to set.
*/
public void setFiles(String files) {
this.files = files;
}
/**
* @return Returns the includeClassesDir.
*/
public boolean isIncludeClassesDir() {
return includeClassesDir;
}
/**
* @param includeClassesDir The includeClassesDir to set.
*/
public void setIncludeClassesDir(boolean includeClassesDir) {
this.includeClassesDir = includeClassesDir;
}
/**
* @return Returns the inpath.
*/
public String getInpath() {
return inpath;
}
/**
* @param inpath The inpath to set.
*/
public void setInpath(String inpath) {
this.inpath = inpath.replace(',',File.pathSeparatorChar).replace(';',File.pathSeparatorChar);
}
/**
* @return Returns the options.
*/
public String getOptions() {
return options;
}
/**
* @param options The options to set.
*/
public void setOptions(String options) {
int i = options.indexOf("!eclipse");
if (i != -1) {
this.options = options.substring(0,i);
this.options += options.substring(i + "!eclipse".length());
} else {
this.options = options;
}
}
/**
* @return Returns the outjar.
*/
public String getOutjar() {
return outjar;
}
/**
* @param outjar The outjar to set.
*/
public void setOutjar(String outjar) {
this.outjar = outjar;
}
/**
* @return Returns the outxml.
*/
public String getOutxmlfile() {
return outxml;
}
/**
* @param outxml The the of the aop.xml file to generate
*/
public void setOutxmlfile(String outxml) {
this.outxml = outxml;
}
/**
* @return Returns the sourceroots.
*/
public String getSourceroots() {
return sourceroots;
}
/**
* @param sourceroots The sourceroots to set.
*/
public void setSourceroots(String sourceroots) {
this.sourceroots = sourceroots;
}
/**
* @return Returns the xlintfile.
*/
public String getXlintfile() {
return xlintfile;
}
/**
* @param xlintfile The xlintfile to set.
*/
public void setXlintfile(String xlintfile) {
this.xlintfile = xlintfile;
}
public String getExtdirs() { return extdirs;}
public void setExtdirs(String extdirs) { this.extdirs = extdirs; }
protected String[] buildArgs() {
StringBuffer args = new StringBuffer();
// add any set options, and then files to compile at the end
if (getAspectpath() != null) {
args.append("-aspectpath ");
args.append(getAspectpath());
args.append(" ");
}
if (getSourceroots() != null) {
args.append("-sourceroots ");
args.append(getSourceroots());
args.append(" ");
}
if (getOutjar() != null) {
args.append("-outjar ");
args.append(getOutjar());
args.append(" ");
}
if (getOutxmlfile() != null) {
args.append("-outxmlfile ");
args.append(getOutxmlfile());
args.append(" ");
}
if (getOptions() != null) {
StringTokenizer strTok = new StringTokenizer(getOptions(),",");
while (strTok.hasMoreTokens()) {
args.append(strTok.nextToken());
args.append(" ");
}
}
if (getClasspath() != null) {
args.append("-classpath ");
args.append(getClasspath());
args.append(" ");
}
if (getXlintfile() != null) {
args.append("-Xlintfile ");
args.append(getXlintfile());
args.append(" ");
}
if (getExtdirs() != null) {
args.append("-extdirs ");
args.append(getExtdirs());
args.append(" ");
}
List fileList = new ArrayList();
List jarList = new ArrayList();
// convention that any jar on file list should be added to inpath
String files = getFiles();
if (files == null) files = "";
StringTokenizer strTok = new StringTokenizer(files,",");
while (strTok.hasMoreTokens()) {
final String file = strTok.nextToken();
if (file.endsWith(".jar")) {
jarList.add(file);
} else {
fileList.add(file);
}
}
if ((getInpath() != null) || !jarList.isEmpty()) {
args.append("-inpath ");
if (getInpath() != null) args.append(getInpath());
for (Iterator iter = jarList.iterator(); iter.hasNext();) {
String jar = (String) iter.next();
args.append(File.pathSeparator);
args.append(jar);
}
args.append(" ");
}
for (Iterator iter = fileList.iterator(); iter.hasNext();) {
String file = (String) iter.next();
args.append(file);
args.append(" ");
}
String argumentString = args.toString();
strTok = new StringTokenizer(argumentString," ");
String[] ret = new String[strTok.countTokens()];
for (int i = 0; i < ret.length; i++) {
ret[i] = strTok.nextToken();
}
return ret;
}
protected AjcTestCase.MessageSpec buildMessageSpec() {
List infos = null;
List warnings = new ArrayList();
List errors = new ArrayList();
List fails = new ArrayList();
List weaveInfos = new ArrayList();
for (Iterator iter = expected.iterator(); iter.hasNext();) {
ExpectedMessageSpec exMsg = (ExpectedMessageSpec) iter.next();
String kind = exMsg.getKind();
if (kind.equals("info")) {
if (infos == null) infos = new ArrayList();
infos.add(exMsg.toMessage());
} else if (kind.equals("warning")) {
warnings.add(exMsg.toMessage());
} else if (kind.equals("error")) {
errors.add(exMsg.toMessage());
} else if (kind.equals("fail")) {
fails.add(exMsg.toMessage());
} else if (kind.equals("abort")) {
fails.add(exMsg.toMessage());
} else if (kind.equals("weave")) {
weaveInfos.add(exMsg.toMessage());
}
}
return new AjcTestCase.MessageSpec(infos,warnings,errors,fails,weaveInfos);
}
}
|
419,279 | Bug 419279 ajc option to change -Xlint level per-message without Xlintfile | The -Xlintfile option is not a great fit for controlling message across multiple build projects, specifically in my case from the pluginManagement section of a maven parent pom. The problem is that you need a local file to configure the per-message output levels (ignore/warning/error) when you really want to specify it in the build script or in a shared file. As an alternative to -Xlintfile, it would be handy to be able to change an Xlint warning level per message using command line options. For example: ajc -Xlint:adviceDidNotMatch=ignore would override the XlintDefault.properties file for the adviceDidNotMatch message. With Regards Rob | resolved fixed | b2cd5fa | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-23T19:44:23Z" | "2013-10-11T19:33:20Z" | tests/bugs174/pr419279/Code.java | |
419,279 | Bug 419279 ajc option to change -Xlint level per-message without Xlintfile | The -Xlintfile option is not a great fit for controlling message across multiple build projects, specifically in my case from the pluginManagement section of a maven parent pom. The problem is that you need a local file to configure the per-message output levels (ignore/warning/error) when you really want to specify it in the build script or in a shared file. As an alternative to -Xlintfile, it would be handy to be able to change an Xlint warning level per message using command line options. For example: ajc -Xlint:adviceDidNotMatch=ignore would override the XlintDefault.properties file for the adviceDidNotMatch message. With Regards Rob | resolved fixed | b2cd5fa | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-23T19:44:23Z" | "2013-10-11T19:33:20Z" | tests/src/org/aspectj/systemtest/ajc174/Ajc174Tests.java | /*******************************************************************************
* Copyright (c) 2013 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc174;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
/**
* @author Andy Clement
*/
public class Ajc174Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testAnnotatedItd_418129() throws Exception {
runTest("annotated itd");
}
public void testAnnotatedItd_418129_2() throws Exception {
runTest("annotated itd 2");
}
public void testAnnotatedItd_418129_3() throws Exception {
runTest("annotated itd 3");
}
public void testAnnotatedItd_418129_4() throws Exception {
runTest("annotated itd 4");
}
public void testSuperItdCtor_413378() throws Exception {
runTest("super itd ctor");
}
// no exclusion, this is how it should work
public void testCLExclusion_pr368046_1_noskippedloaders() {
runTest("classloader exclusion - 1");
}
public void testCLExclusion_pr368046_1_syspropset() {
try {
System.setProperty("aj.weaving.loadersToSkip", "foo");
runTest("classloader exclusion - 2");
} finally {
System.setProperty("aj.weaving.loadersToSkip", "");
}
}
// final repeat this test, to confirm no lingering static
public void testCLExclusion_pr368046_1_again_noskippedloaders() {
runTest("classloader exclusion - 3");
}
public void testCLExclusion_pr368046_2_usingaopxml() {
runTest("classloader exclusion - 4");
}
public void testCLExclusion_pr368046_2_usingaopxmlReal() {
runTest("classloader exclusion - 5");
}
// ---
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc174Tests.class);
}
@Override
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc174/ajc174.xml");
}
}
|
420,210 | Bug 420210 Support additional message insert keys in declare error/warning | It would be good to be able to insert the enclosing class name or enclosing member for a joinpoint. | resolved fixed | 9319e34 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-23T20:16:20Z" | "2013-10-23T20:26:40Z" | org.aspectj.matcher/src/org/aspectj/weaver/Checker.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 Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* Representation of a shadow munger for a declare error or warning declaration.
*
* @author Andy Clement
*/
public class Checker extends ShadowMunger {
private boolean isError; // if not error then it is a warning
private String message;
private volatile int hashCode = -1;
@SuppressWarnings("unused")
private Checker() {
}
/**
* Create a Checker for a declare error or declare warning.
*
* @param deow the declare error or declare warning for which to create the checker munger
*/
public Checker(DeclareErrorOrWarning deow) {
super(deow.getPointcut(), deow.getStart(), deow.getEnd(), deow.getSourceContext(), ShadowMungerDeow);
this.message = deow.getMessage();
this.isError = deow.isError();
}
/**
* Only used when filling in a parameterized Checker
*/
private Checker(Pointcut pointcut, int start, int end, ISourceContext context, String message, boolean isError) {
super(pointcut, start, end, context, ShadowMungerDeow);
this.message = message;
this.isError = isError;
}
public boolean isError() {
return isError;
}
public String getMessage(Shadow shadow) {
return format(this.message, shadow);
}
@Override
public void specializeOn(Shadow shadow) {
throw new IllegalStateException("Cannot call specializeOn(...) for a Checker");
}
@Override
public boolean implementOn(Shadow shadow) {
throw new IllegalStateException("Cannot call implementOn(...) for a Checker");
}
/**
* Determine if the Checker matches at a shadow. If it does then we can immediately report the message. Currently, there can
* never be a non-statically determinable match.
*
* @param shadow the shadow which to match against
* @param world the world through which to access message handlers
*/
@Override
public boolean match(Shadow shadow, World world) {
if (super.match(shadow, world)) {
world.reportCheckerMatch(this, shadow);
}
return false;
}
// implementation for PartialOrder.PartialComparable
public int compareTo(Object other) {
return 0;
}
@Override
public boolean mustCheckExceptions() {
return true;
}
@Override
public Collection<ResolvedType> getThrownExceptions() {
return Collections.emptyList();
}
// FIXME this perhaps ought to take account of the other fields in advice (use super.equals?)
@Override
public boolean equals(Object other) {
if (!(other instanceof Checker)) {
return false;
}
Checker o = (Checker) other;
return o.isError == isError && ((o.pointcut == null) ? (pointcut == null) : o.pointcut.equals(pointcut));
}
@Override
public int hashCode() {
if (hashCode == -1) {
int result = 17;
result = 37 * result + (isError ? 1 : 0);
result = 37 * result + ((pointcut == null) ? 0 : pointcut.hashCode());
hashCode = result;
}
return hashCode;
}
/**
* Parameterize the Checker by parameterizing the pointcut
*/
@Override
public ShadowMunger parameterizeWith(ResolvedType declaringType, Map<String, UnresolvedType> typeVariableMap) {
Checker ret = new Checker(this.pointcut.parameterizeWith(typeVariableMap, declaringType.getWorld()), this.start, this.end,
this.sourceContext, this.message, this.isError);
return ret;
}
/**
* Concretize this Checker by concretizing the pointcut
*/
@Override
public ShadowMunger concretize(ResolvedType theAspect, World world, PerClause clause) {
this.pointcut = this.pointcut.concretize(theAspect, getDeclaringType(), 0, this);
this.hashCode = -1;
return this;
}
@Override
public ResolvedType getConcreteAspect() {
return getDeclaringType();
}
// public void write(DataOutputStream stream) throws IOException {
// super.write(stream);
// stream.writeBoolean(isError);
// stream.writeUTF(message);
// }
//
// public static Checker read(DataInputStream stream, World world) throws IOException {
// Checker checker = new Checker();
// checker.isError = stream.readBoolean();
// checker.message = stream.readUTF();
// return checker;
// }
// Return the next non-escaped (with a '\') open curly
private int nextCurly(String string, int pos) {
do {
int curlyIndex = string.indexOf('{', pos);
if (curlyIndex == -1) {
return -1;
}
if (curlyIndex == 0) {
return 0;
}
if (string.charAt(curlyIndex - 1) != '\\') {
return curlyIndex;
}
pos = curlyIndex + 1;
} while (pos < string.length());
return -1;
}
private String format(String msg, Shadow shadow) {
int pos = 0;
int curlyIndex = nextCurly(msg, 0);
if (curlyIndex == -1) {
// was there an escaped one?
if (msg.indexOf('{') != -1) {
return msg.replace("\\{", "{");
} else {
return msg;
}
}
StringBuffer ret = new StringBuffer();
while (curlyIndex >= 0) {
if (curlyIndex > 0) {
ret.append(msg.substring(pos, curlyIndex).replace("\\{", "{"));
}
int endCurly = msg.indexOf('}', curlyIndex);
if (endCurly == -1) {
// wasn't closed properly - ignore it
ret.append('{');
pos = curlyIndex + 1;
} else {
ret.append(getValue(msg.substring(curlyIndex + 1, endCurly), shadow));
}
pos = endCurly + 1;
curlyIndex = nextCurly(msg, pos);
}
ret.append(msg.substring(pos, msg.length()));
return ret.toString();
}
/**
* @param buf the buffer in which to insert the substitution
* @param shadow shadow from which to draw context info
* @param c the substitution character
*/
private String getValue(String key, Shadow shadow) {
if (key.equalsIgnoreCase("joinpoint")) {
return shadow.toString();
} else if (key.equalsIgnoreCase("joinpoint.kind")) {
return shadow.getKind().getName();
} else if (key.equalsIgnoreCase("joinpoint.signature")) {
return shadow.getSignature().toString();
} else if (key.equalsIgnoreCase("joinpoint.signature.declaringtype")) {
return shadow.getSignature().getDeclaringType().toString();
} else if (key.equalsIgnoreCase("joinpoint.signature.name")) {
return shadow.getSignature().getName();
} else if (key.equalsIgnoreCase("joinpoint.sourcelocation.sourcefile")) {
ISourceLocation loc = shadow.getSourceLocation();
if ((loc != null) && (loc.getSourceFile() != null)) {
return loc.getSourceFile().toString();
} else {
return "UNKNOWN";
}
} else if (key.equalsIgnoreCase("joinpoint.sourcelocation.line")) {
ISourceLocation loc = shadow.getSourceLocation();
if (loc != null) {
return Integer.toString(loc.getLine());
} else {
return "-1";
}
} else if (key.equalsIgnoreCase("advice.aspecttype")) {
return getDeclaringType().getName();
} else if (key.equalsIgnoreCase("advice.sourcelocation.line")) {
ISourceLocation loc = getSourceLocation();
if ((loc != null) && (loc.getSourceFile() != null)) {
return Integer.toString(loc.getLine());
} else {
return "-1";
}
} else if (key.equalsIgnoreCase("advice.sourcelocation.sourcefile")) {
ISourceLocation loc = getSourceLocation();
if ((loc != null) && (loc.getSourceFile() != null)) {
return loc.getSourceFile().toString();
} else {
return "UNKNOWN";
}
} else {
return "UNKNOWN_KEY{" + key + "}";
}
}
}
|
420,210 | Bug 420210 Support additional message insert keys in declare error/warning | It would be good to be able to insert the enclosing class name or enclosing member for a joinpoint. | resolved fixed | 9319e34 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-23T20:16:20Z" | "2013-10-23T20:26:40Z" | tests/bugs174/extra_inserts/Code.java | |
420,210 | Bug 420210 Support additional message insert keys in declare error/warning | It would be good to be able to insert the enclosing class name or enclosing member for a joinpoint. | resolved fixed | 9319e34 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-10-23T20:16:20Z" | "2013-10-23T20:26:40Z" | tests/src/org/aspectj/systemtest/ajc174/Ajc174Tests.java | /*******************************************************************************
* Copyright (c) 2013 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc174;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
/**
* @author Andy Clement
*/
public class Ajc174Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testMoreConfigurableLint_419279() throws Exception {
runTest("more configurable lint");
}
public void testAnnotatedItd_418129() throws Exception {
runTest("annotated itd");
}
public void testAnnotatedItd_418129_2() throws Exception {
runTest("annotated itd 2");
}
public void testAnnotatedItd_418129_3() throws Exception {
runTest("annotated itd 3");
}
public void testAnnotatedItd_418129_4() throws Exception {
runTest("annotated itd 4");
}
public void testSuperItdCtor_413378() throws Exception {
runTest("super itd ctor");
}
// no exclusion, this is how it should work
public void testCLExclusion_pr368046_1_noskippedloaders() {
runTest("classloader exclusion - 1");
}
public void testCLExclusion_pr368046_1_syspropset() {
try {
System.setProperty("aj.weaving.loadersToSkip", "foo");
runTest("classloader exclusion - 2");
} finally {
System.setProperty("aj.weaving.loadersToSkip", "");
}
}
// final repeat this test, to confirm no lingering static
public void testCLExclusion_pr368046_1_again_noskippedloaders() {
runTest("classloader exclusion - 3");
}
public void testCLExclusion_pr368046_2_usingaopxml() {
runTest("classloader exclusion - 4");
}
public void testCLExclusion_pr368046_2_usingaopxmlReal() {
runTest("classloader exclusion - 5");
}
// ---
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc174Tests.class);
}
@Override
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc174/ajc174.xml");
}
}
|
423,257 | Bug 423257 LTW - java.lang.VerifyError: Bad return type with generics and local variables | null | resolved fixed | dd88d21 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-12-06T18:33:48Z" | "2013-12-04T23:33: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 Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* Andy Clement overhauled
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.ajdt.internal.compiler.CompilationResultDestinationManager;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.ajdt.internal.core.builder.AjBuildConfig.BinarySourceFile;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.asm.AsmManager;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
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.compiler.env.IBinaryAnnotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryField;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryMethod;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryNestedType;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
import org.aspectj.org.eclipse.jdt.internal.core.builder.ReferenceCollection;
import org.aspectj.org.eclipse.jdt.internal.core.builder.StringSet;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.CompressingDataOutputStream;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.TypeDelegateResolver;
import org.aspectj.weaver.bcel.UnwovenClassFile;
/**
* Maintains state needed for incremental compilation
*/
public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateResolver {
// SECRETAPI configures whether we use state instead of lastModTime - see pr245566
public static boolean CHECK_STATE_FIRST = true;
// SECRETAPI static so beware of multi-threading bugs...
public static IStateListener stateListener = null;
public static boolean FORCE_INCREMENTAL_DURING_TESTING = false;
static int PATHID_CLASSPATH = 0;
static int PATHID_ASPECTPATH = 1;
static int PATHID_INPATH = 2;
private static int CLASS_FILE_NO_CHANGES = 0;
private static int CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD = 1;
private static int CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD = 2;
private static final char[][] EMPTY_CHAR_ARRAY = new char[0][];
// now follows non static, but transient state - no need to write out, doesn't need reinitializing
// State recreated for each build:
/**
* When looking at changes on the classpath, this set accumulates files in our state instance that affected by those changes.
* Then if we can do an incremental build - these must be compiled.
*/
private final Set<File> affectedFiles = new HashSet<File>();
// these are references created on a particular compile run - when looping round in
// addAffectedSourceFiles(), if some have been created then we look at which source files
// touch upon those and get them recompiled.
private StringSet qualifiedStrings = new StringSet(3);
private StringSet simpleStrings = new StringSet(3);
private Set<File> addedFiles;
private Set<File> deletedFiles;
private Set<BinarySourceFile> addedBinaryFiles;
private Set<BinarySourceFile> deletedBinaryFiles;
// For a particular build run, this set records the changes to classesFromName
public final Set<String> deltaAddedClasses = new HashSet<String>();
// now follows non static, but transient state - no need to write out, DOES need reinitializing when read AjState instance
// reloaded
private final AjBuildManager buildManager;
private INameEnvironment nameEnvironment;
// now follows normal state that must be written out
private boolean couldBeSubsequentIncrementalBuild = false;
private boolean batchBuildRequiredThisTime = false;
private AjBuildConfig buildConfig;
private long lastSuccessfulFullBuildTime = -1;
private final Hashtable<String, Long> structuralChangesSinceLastFullBuild = new Hashtable<String, Long>();
private long lastSuccessfulBuildTime = -1;
private long currentBuildTime = -1;
private AsmManager structureModel;
/**
* For a given source file, records the ClassFiles (which contain a fully qualified name and a file name) that were created when
* the source file was compiled. Populated in noteResult and used in addDependentsOf(File)
*/
private final Map<File, List<ClassFile>> fullyQualifiedTypeNamesResultingFromCompilationUnit = new HashMap<File, List<ClassFile>>();
/**
* Source files defining aspects Populated in noteResult and used in processDeletedFiles
*/
private final Set<File> sourceFilesDefiningAspects = new HashSet<File>();
/**
* Populated in noteResult to record the set of types that should be recompiled if the given file is modified or deleted.
* Referred to during addAffectedSourceFiles when calculating incremental compilation set.
*/
private final Map<File, ReferenceCollection> references = new HashMap<File, ReferenceCollection>();
/**
* Holds UnwovenClassFiles (byte[]s) originating from the given file source. This could be a jar file, a directory, or an
* individual .class file. This is an *expensive* map. It is cleared immediately following a batch build, and the cheaper
* inputClassFilesBySource map is kept for processing of any subsequent incremental builds.
*
* Populated during AjBuildManager.initBcelWorld().
*
* Passed into AjCompiler adapter as the set of binary input files to reweave if the weaver determines a full weave is required.
*
* Cleared during initBcelWorld prior to repopulation.
*
* Used when a file is deleted during incremental compilation to delete all of the class files in the output directory that
* resulted from the weaving of File.
*
* Used during getBinaryFilesToCompile when compiling incrementally to determine which files should be recompiled if a given
* input file has changed.
*
*/
private Map<String, List<UnwovenClassFile>> binarySourceFiles = new HashMap<String, List<UnwovenClassFile>>();
/**
* Initially a duplicate of the information held in binarySourceFiles, with the key difference that the values are ClassFiles
* (type name, File) not UnwovenClassFiles (which also have all the byte code in them). After a batch build, binarySourceFiles
* is cleared, leaving just this much lighter weight map to use in processing subsequent incremental builds.
*/
private final Map<String, List<ClassFile>> inputClassFilesBySource = new HashMap<String, List<ClassFile>>();
/**
* A list of the .class files created by this state that contain aspects.
*/
private final List<String> aspectClassFiles = new ArrayList<String>();
/**
* Holds structure information on types as they were at the end of the last build. It would be nice to get rid of this too, but
* can't see an easy way to do that right now.
*/
private final Map<String, CompactTypeStructureRepresentation> resolvedTypeStructuresFromLastBuild = new HashMap<String, CompactTypeStructureRepresentation>();
/**
* Populated in noteResult to record the set of UnwovenClassFiles (intermediate results) that originated from compilation of the
* class with the given fully-qualified name.
*
* Used in removeAllResultsOfLastBuild to remove .class files from output directory.
*
* Passed into StatefulNameEnvironment during incremental compilation to support findType lookups.
*/
private final Map<String, File> classesFromName = new HashMap<String, File>();
/**
* Populated by AjBuildManager to record the aspects with the file name in which they're contained. This is later used when
* writing the outxml file in AjBuildManager. Need to record the file name because want to write an outxml file for each of the
* output directories and in order to ask the OutputLocationManager for the output location for a given aspect we need the file
* in which it is contained.
*/
private Map<String, char[]> aspectsFromFileNames;
private Set<File> compiledSourceFiles = new HashSet<File>();
private final Map<String, File> resources = new HashMap<String, File>();
SoftHashMap/* <baseDir,SoftHashMap<theFile,className>> */fileToClassNameMap = new SoftHashMap();
private BcelWeaver weaver;
private BcelWorld world;
// --- below here is unsorted state
// ---
public AjState(AjBuildManager buildManager) {
this.buildManager = buildManager;
}
public void setCouldBeSubsequentIncrementalBuild(boolean yesThereCould) {
this.couldBeSubsequentIncrementalBuild = yesThereCould;
}
void successfulCompile(AjBuildConfig config, boolean wasFullBuild) {
buildConfig = config;
lastSuccessfulBuildTime = currentBuildTime;
if (stateListener != null) {
stateListener.buildSuccessful(wasFullBuild);
}
if (wasFullBuild) {
lastSuccessfulFullBuildTime = currentBuildTime;
}
}
/**
* Returns false if a batch build is needed.
*/
public boolean prepareForNextBuild(AjBuildConfig newBuildConfig) {
currentBuildTime = System.currentTimeMillis();
if (!maybeIncremental()) {
if (listenerDefined()) {
getListener().recordDecision(
"Preparing for build: not going to be incremental because either not in AJDT or incremental deactivated");
}
return false;
}
if (this.batchBuildRequiredThisTime) {
this.batchBuildRequiredThisTime = false;
if (listenerDefined()) {
getListener().recordDecision(
"Preparing for build: not going to be incremental this time because batch build explicitly forced");
}
return false;
}
if (lastSuccessfulBuildTime == -1 || buildConfig == null) {
structuralChangesSinceLastFullBuild.clear();
if (listenerDefined()) {
getListener().recordDecision(
"Preparing for build: not going to be incremental because no successful previous full build");
}
return false;
}
// we don't support incremental with an outjar yet
if (newBuildConfig.getOutputJar() != null) {
structuralChangesSinceLastFullBuild.clear();
if (listenerDefined()) {
getListener().recordDecision("Preparing for build: not going to be incremental because outjar being used");
}
return false;
}
affectedFiles.clear();
// 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();
if (stateListener != null) {
stateListener.pathChangeDetected();
}
structuralChangesSinceLastFullBuild.clear();
if (listenerDefined()) {
getListener()
.recordDecision(
"Preparing for build: not going to be incremental because path change detected (one of classpath/aspectpath/inpath/injars)");
}
return false;
}
if (simpleStrings.elementSize > 20) {
simpleStrings = new StringSet(3);
} else {
simpleStrings.clear();
}
if (qualifiedStrings.elementSize > 20) {
qualifiedStrings = new StringSet(3);
} else {
qualifiedStrings.clear();
}
if ((newBuildConfig.getChanged() & PROJECTSOURCEFILES_CHANGED) == 0) {
addedFiles = Collections.emptySet();
deletedFiles = Collections.emptySet();
} else {
Set<File> oldFiles = new HashSet<File>(buildConfig.getFiles());
Set<File> newFiles = new HashSet<File>(newBuildConfig.getFiles());
addedFiles = new HashSet<File>(newFiles);
addedFiles.removeAll(oldFiles);
deletedFiles = new HashSet<File>(oldFiles);
deletedFiles.removeAll(newFiles);
}
Set<BinarySourceFile> oldBinaryFiles = new HashSet<BinarySourceFile>(buildConfig.getBinaryFiles());
Set<BinarySourceFile> newBinaryFiles = new HashSet<BinarySourceFile>(newBuildConfig.getBinaryFiles());
addedBinaryFiles = new HashSet<BinarySourceFile>(newBinaryFiles);
addedBinaryFiles.removeAll(oldBinaryFiles);
deletedBinaryFiles = new HashSet<BinarySourceFile>(oldBinaryFiles);
deletedBinaryFiles.removeAll(newBinaryFiles);
boolean couldStillBeIncremental = processDeletedFiles(deletedFiles);
if (!couldStillBeIncremental) {
if (listenerDefined()) {
getListener().recordDecision("Preparing for build: not going to be incremental because an aspect was deleted");
}
return false;
}
if (listenerDefined()) {
getListener().recordDecision("Preparing for build: planning to be an incremental build");
}
return true;
}
/**
* Checks if any of the files in the set passed in contains an aspect declaration. If one is found then we start the process of
* batch building, i.e. we remove all the results of the last build, call any registered listener to tell them whats happened
* and return false.
*
* @return false if we discovered an aspect declaration
*/
private boolean processDeletedFiles(Set<File> deletedFiles) {
for (File deletedFile : deletedFiles) {
if (this.sourceFilesDefiningAspects.contains(deletedFile)) {
removeAllResultsOfLastBuild();
if (stateListener != null) {
stateListener.detectedAspectDeleted(deletedFile);
}
return false;
}
List<ClassFile> classes = fullyQualifiedTypeNamesResultingFromCompilationUnit.get(deletedFile);
if (classes != null) {
for (ClassFile cf : classes) {
resolvedTypeStructuresFromLastBuild.remove(cf.fullyQualifiedTypeName);
}
}
}
return true;
}
private Collection<File> getModifiedFiles() {
return getModifiedFiles(lastSuccessfulBuildTime);
}
Collection<File> getModifiedFiles(long lastBuildTime) {
Set<File> ret = new HashSet<File>();
// Check if the build configuration knows what files have changed...
List<File> modifiedFiles = buildConfig.getModifiedFiles();
if (modifiedFiles == null) {
// do not know, so need to go looking
// not our job to account for new and deleted files
for (Iterator<File> i = buildConfig.getFiles().iterator(); i.hasNext();) {
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);
}
}
} else {
ret.addAll(modifiedFiles);
}
ret.addAll(affectedFiles);
return ret;
}
private Collection<BinarySourceFile> getModifiedBinaryFiles() {
return getModifiedBinaryFiles(lastSuccessfulBuildTime);
}
Collection<BinarySourceFile> getModifiedBinaryFiles(long lastBuildTime) {
List<BinarySourceFile> ret = new ArrayList<BinarySourceFile>();
// not our job to account for new and deleted files
for (Iterator<BinarySourceFile> i = buildConfig.getBinaryFiles().iterator(); i.hasNext();) {
AjBuildConfig.BinarySourceFile bsfile = 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 void recordDecision(String decision) {
getListener().recordDecision(decision);
}
/**
* Analyse .class files in the directory specified, if they have changed since the last successful build then see if we can
* determine which source files in our project depend on the change. If we can then we can still do an incremental build, if we
* can't then we have to do a full build.
*
*/
private int classFileChangedInDirSinceLastBuildRequiringFullBuild(File dir, int pathid) {
if (!dir.isDirectory()) {
if (listenerDefined()) {
recordDecision("ClassFileChangeChecking: not a directory so forcing full build: '" + dir.getPath() + "'");
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
}
// Are we managing that output directory?
AjState state = IncrementalStateManager.findStateManagingOutputLocation(dir);
if (listenerDefined()) {
if (state != null) {
recordDecision("ClassFileChangeChecking: found state instance managing output location : " + dir);
} else {
recordDecision("ClassFileChangeChecking: failed to find a state instance managing output location : " + dir);
}
}
// pr268827 - this guard will cause us to exit quickly if the state says there really is
// nothing of interest. This will not catch the case where a user modifies the .class files outside of
// eclipse because the state will not be aware of it. But that seems an unlikely scenario and
// we are paying a heavy price to check it
if (state != null && !state.hasAnyStructuralChangesSince(lastSuccessfulBuildTime)) {
if (listenerDefined()) {
getListener().recordDecision("ClassFileChangeChecking: no reported changes in that state");
}
return CLASS_FILE_NO_CHANGES;
}
if (state == null) {
// This may be because the directory is the output path of a Java project upon which we depend
// we need to call back into AJDT to ask about that projects state.
CompilationResultDestinationManager crdm = buildConfig.getCompilationResultDestinationManager();
if (crdm != null) {
int i = crdm.discoverChangesSince(dir, lastSuccessfulBuildTime);
// 0 = dontknow if it has changed
// 1 = definetly not changed at all
// further numbers can determine more granular changes
if (i == 1) {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: queried JDT and '" + dir
+ "' is apparently unchanged so not performing timestamp check");
}
return CLASS_FILE_NO_CHANGES;
}
}
}
List<File> classFiles = FileUtil.listClassFiles(dir);
for (Iterator<File> iterator = classFiles.iterator(); iterator.hasNext();) {
File classFile = iterator.next();
if (CHECK_STATE_FIRST && state != null) {
// Next section reworked based on bug 270033:
// if it is an aspect we may or may not be in trouble depending on whether (a) we depend on it (b) it is on the
// classpath or the aspectpath
if (state.isAspect(classFile)) {
boolean hasStructuralChanges = state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime);
if (hasStructuralChanges || isTypeWeReferTo(classFile)) {
if (hasStructuralChanges) {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: aspect found that has structurally changed : " + classFile);
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
} else {
// must be 'isTypeWeReferTo()'
if (pathid == PATHID_CLASSPATH) {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: aspect found that this project refers to : " + classFile
+ " but only referred to via classpath");
}
} else {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: aspect found that this project refers to : " + classFile
+ " from either inpath/aspectpath, switching to full build");
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
}
}
} else {
// it is an aspect but we don't refer to it:
// - for CLASSPATH I think this is OK, we can continue and try an
// incremental build
// - for ASPECTPATH we don't know what else might be touched in this project
// and must rebuild
if (pathid == PATHID_CLASSPATH) {
if (listenerDefined()) {
getListener()
.recordDecision(
"ClassFileChangeChecking: found aspect on classpath but this project doesn't reference it, continuing to try for incremental build : "
+ classFile);
}
} else {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: found aspect on aspectpath/inpath - can't determine if this project is affected, must full build: "
+ classFile);
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
}
}
}
if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime)) {
if (listenerDefined()) {
getListener().recordDecision("ClassFileChangeChecking: structural change detected in : " + classFile);
}
isTypeWeReferTo(classFile);
}
} else {
long modTime = classFile.lastModified();
if ((modTime + 1000) >= lastSuccessfulBuildTime) {
// so the class on disk has changed since the last successful build for this state object
// BUG? we stop on the first change that leads us to an incremental build, surely we need to continue and look
// at all files incase another change means we need to incremental a bit more stuff?
// To work out if it is a real change we should ask any state
// object managing the output location whether the file has
// structurally changed or not
if (state != null) {
if (state.isAspect(classFile)) {
if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime) || isTypeWeReferTo(classFile)) {
// further improvements possible
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: aspect found that has structurally changed or that this project depends upon : "
+ classFile);
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
} else {
// it is an aspect but we don't refer to it:
// - for CLASSPATH I think this is OK, we can continue and try an
// incremental build
// - for ASPECTPATH we don't know what else might be touched in this project
// and must rebuild
if (pathid == PATHID_CLASSPATH) {
if (listenerDefined()) {
getListener()
.recordDecision(
"ClassFileChangeChecking: found aspect on classpath but this project doesn't reference it, continuing to try for incremental build : "
+ classFile);
}
} else {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: found aspect on aspectpath/inpath - can't determine if this project is affected, must full build: "
+ classFile);
}
return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
}
}
}
if (state.hasStructuralChangedSince(classFile, lastSuccessfulBuildTime)) {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: structural change detected in : " + classFile);
}
isTypeWeReferTo(classFile);
} else {
if (listenerDefined()) {
getListener().recordDecision(
"ClassFileChangeChecking: change detected in " + classFile + " but it is not structural");
}
}
} else {
// No state object to ask, so it only matters if we know which type depends on this file
if (isTypeWeReferTo(classFile)) {
return CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD;
} else {
return CLASS_FILE_NO_CHANGES;
}
}
}
}
}
return CLASS_FILE_NO_CHANGES;
}
private boolean isAspect(File file) {
return aspectClassFiles.contains(file.getAbsolutePath());
}
@SuppressWarnings("rawtypes")
public static class SoftHashMap extends AbstractMap {
private final Map map;
private final ReferenceQueue rq = new ReferenceQueue();
public SoftHashMap(Map map) {
this.map = map;
}
public SoftHashMap() {
this(new HashMap());
}
public SoftHashMap(Map map, boolean b) {
this(map);
}
class SoftReferenceKnownKey extends SoftReference {
private final Object key;
@SuppressWarnings("unchecked")
SoftReferenceKnownKey(Object k, Object v) {
super(v, rq);
this.key = k;
}
}
private void processQueue() {
SoftReferenceKnownKey sv = null;
while ((sv = (SoftReferenceKnownKey) rq.poll()) != null) {
map.remove(sv.key);
}
}
public Object get(Object key) {
SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.get(key);
if (value == null) {
return null;
}
if (value.get() == null) {
// it got GC'd
map.remove(value.key);
return null;
} else {
return value.get();
}
}
public Object put(Object k, Object v) {
processQueue();
return map.put(k, new SoftReferenceKnownKey(k, v));
}
public Set entrySet() {
return map.entrySet();
}
public void clear() {
processQueue();
map.clear();
}
public int size() {
processQueue();
return map.size();
}
public Object remove(Object k) {
processQueue();
SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.remove(k);
if (value == null) {
return null;
}
if (value.get() != null) {
return value.get();
}
return null;
}
}
/**
* If a class file has changed in a path on our classpath, it may not be for a type that any of our source files care about.
* This method checks if any of our source files have a dependency on the class in question and if not, we don't consider it an
* interesting change.
*/
private boolean isTypeWeReferTo(File file) {
String fpath = file.getAbsolutePath();
int finalSeparator = fpath.lastIndexOf(File.separator);
String baseDir = fpath.substring(0, finalSeparator);
String theFile = fpath.substring(finalSeparator + 1);
SoftHashMap classNames = (SoftHashMap) fileToClassNameMap.get(baseDir);
if (classNames == null) {
classNames = new SoftHashMap();
fileToClassNameMap.put(baseDir, classNames);
}
char[] className = (char[]) classNames.get(theFile);
if (className == null) {
// if (listenerDefined())
// getListener().recordDecision("Cache miss, looking up classname for : " + fpath);
ClassFileReader cfr;
try {
cfr = ClassFileReader.read(file);
} catch (ClassFormatException e) {
return true;
} catch (IOException e) {
return true;
}
className = cfr.getName();
classNames.put(theFile, className);
// } else {
// if (listenerDefined())
// getListener().recordDecision("Cache hit, looking up classname for : " + fpath);
}
char[][][] qualifiedNames = null;
char[][] simpleNames = null;
if (CharOperation.indexOf('/', className) != -1) {
qualifiedNames = new char[1][][];
qualifiedNames[0] = CharOperation.splitOn('/', className);
qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedNames);
} else {
simpleNames = new char[1][];
simpleNames[0] = className;
simpleNames = ReferenceCollection.internSimpleNames(simpleNames, true);
}
int newlyAffectedFiles = 0;
for (Iterator<Map.Entry<File, ReferenceCollection>> i = references.entrySet().iterator(); i.hasNext();) {
Map.Entry<File, ReferenceCollection> entry = i.next();
ReferenceCollection refs = entry.getValue();
if (refs != null && refs.includes(qualifiedNames, simpleNames)) {
if (listenerDefined()) {
getListener().recordDecision(
toString() + ": type " + new String(className) + " is depended upon by '" + entry.getKey() + "'");
}
newlyAffectedFiles++;
// possibly the beginnings of addressing the second point in 270033 comment 3
// List/*ClassFile*/ cfs = (List)this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(entry.getKey());
affectedFiles.add(entry.getKey());
}
}
if (newlyAffectedFiles > 0) {
return true;
}
if (listenerDefined()) {
getListener().recordDecision(toString() + ": type " + new String(className) + " is not depended upon by this state");
}
return false;
}
// /**
// * For a given class file, determine which source file it came from. This will only succeed if the class file is from a source
// * file within this project.
// */
// private File getSourceFileForClassFile(File classfile) {
// Set sourceFiles = fullyQualifiedTypeNamesResultingFromCompilationUnit.keySet();
// for (Iterator sourceFileIterator = sourceFiles.iterator(); sourceFileIterator.hasNext();) {
// File sourceFile = (File) sourceFileIterator.next();
// List/* ClassFile */classesFromSourceFile = (List/* ClassFile */) fullyQualifiedTypeNamesResultingFromCompilationUnit
// .get(sourceFile);
// for (int i = 0; i < classesFromSourceFile.size(); i++) {
// if (((ClassFile) classesFromSourceFile.get(i)).locationOnDisk.equals(classfile))
// return sourceFile;
// }
// }
// return null;
// }
public String toString() {
StringBuffer sb = new StringBuffer();
// null config means failed build i think as it is only set on successful full build?
sb.append("AjState(").append((buildConfig == null ? "NULLCONFIG" : buildConfig.getConfigFile().toString())).append(")");
return sb.toString();
}
/**
* Determine if a file has changed since a given time, using the local information recorded in the structural changes data
* structure.
*
* @param file the file we are wondering about
* @param lastSuccessfulBuildTime the last build time for the state asking the question
*/
private boolean hasStructuralChangedSince(File file, long lastSuccessfulBuildTime) {
// long lastModTime = file.lastModified();
Long l = structuralChangesSinceLastFullBuild.get(file.getAbsolutePath());
long strucModTime = -1;
if (l != null) {
strucModTime = l.longValue();
} else {
strucModTime = this.lastSuccessfulFullBuildTime;
}
// we now have:
// 'strucModTime'-> the last time the class was structurally changed
return (strucModTime > lastSuccessfulBuildTime);
}
/**
* Determine if anything has changed since a given time.
*/
private boolean hasAnyStructuralChangesSince(long lastSuccessfulBuildTime) {
Set<Map.Entry<String, Long>> entries = structuralChangesSinceLastFullBuild.entrySet();
for (Iterator<Map.Entry<String, Long>> iterator = entries.iterator(); iterator.hasNext();) {
Map.Entry<String, Long> entry = iterator.next();
Long l = entry.getValue();
if (l != null) {
long lvalue = l.longValue();
if (lvalue > lastSuccessfulBuildTime) {
if (listenerDefined()) {
getListener().recordDecision(
"Seems this has changed " + entry.getKey() + "modtime=" + lvalue + " lsbt="
+ this.lastSuccessfulFullBuildTime + " incoming check value=" + lastSuccessfulBuildTime);
}
return true;
}
}
}
return (this.lastSuccessfulFullBuildTime > lastSuccessfulBuildTime);
}
/**
* Determine if something has changed on the classpath/inpath/aspectpath and a full build is required rather than an incremental
* one.
*
* @param previousConfig the previous configuration used
* @param newConfig the new configuration being used
* @return true if full build required
*/
private boolean pathChange(AjBuildConfig previousConfig, AjBuildConfig newConfig) {
int changes = newConfig.getChanged();
if ((changes & (CLASSPATH_CHANGED | ASPECTPATH_CHANGED | INPATH_CHANGED | OUTPUTDESTINATIONS_CHANGED | INJARS_CHANGED)) != 0) {
List<File> oldOutputLocs = getOutputLocations(previousConfig);
Set<String> alreadyAnalysedPaths = new HashSet<String>();
List<String> oldClasspath = previousConfig.getClasspath();
List<String> newClasspath = newConfig.getClasspath();
if (stateListener != null) {
stateListener.aboutToCompareClasspaths(oldClasspath, newClasspath);
}
if (classpathChangedAndNeedsFullBuild(oldClasspath, newClasspath, true, oldOutputLocs, alreadyAnalysedPaths)) {
return true;
}
List<File> oldAspectpath = previousConfig.getAspectpath();
List<File> newAspectpath = newConfig.getAspectpath();
if (changedAndNeedsFullBuild(oldAspectpath, newAspectpath, true, oldOutputLocs, alreadyAnalysedPaths, PATHID_ASPECTPATH)) {
return true;
}
List<File> oldInPath = previousConfig.getInpath();
List<File> newInPath = newConfig.getInpath();
if (changedAndNeedsFullBuild(oldInPath, newInPath, false, oldOutputLocs, alreadyAnalysedPaths, PATHID_INPATH)) {
return true;
}
List<File> oldInJars = previousConfig.getInJars();
List<File> newInJars = newConfig.getInJars();
if (changedAndNeedsFullBuild(oldInJars, newInJars, false, oldOutputLocs, alreadyAnalysedPaths, PATHID_INPATH)) {
return true;
}
} else if (newConfig.getClasspathElementsWithModifiedContents() != null) {
// Although the classpath entries themselves are the same as before, the contents of one of the
// directories on the classpath has changed - rather than go digging around to find it, let's ask
// the compiler configuration. This will allow for projects with long classpaths where classpaths
// are also capturing project dependencies - when a project we depend on is rebuilt, we can just check
// it as a standalone element on our classpath rather than going through them all
List<String> modifiedCpElements = newConfig.getClasspathElementsWithModifiedContents();
for (Iterator<String> iterator = modifiedCpElements.iterator(); iterator.hasNext();) {
File cpElement = new File(iterator.next());
if (cpElement.exists() && !cpElement.isDirectory()) {
if (cpElement.lastModified() > lastSuccessfulBuildTime) {
return true;
}
} else {
int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(cpElement, PATHID_CLASSPATH);
if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) {
return true;
}
}
}
}
return false;
}
/**
* Return a list of the output locations - this includes any 'default' output location and then any known by a registered
* CompilationResultDestinationManager.
*
* @param config the build configuration for which the output locations should be determined
* @return a list of file objects
*/
private List<File> getOutputLocations(AjBuildConfig config) {
List<File> outputLocs = new ArrayList<File>();
// Is there a default location?
if (config.getOutputDir() != null) {
try {
outputLocs.add(config.getOutputDir().getCanonicalFile());
} catch (IOException e) {
}
}
if (config.getCompilationResultDestinationManager() != null) {
List<File> dirs = config.getCompilationResultDestinationManager().getAllOutputLocations();
for (Iterator<File> iterator = dirs.iterator(); iterator.hasNext();) {
File f = iterator.next();
try {
File cf = f.getCanonicalFile();
if (!outputLocs.contains(cf)) {
outputLocs.add(cf);
}
} catch (IOException e) {
}
}
}
return outputLocs;
}
private File getOutputLocationFor(AjBuildConfig config, File aResourceFile) {
if (config.getCompilationResultDestinationManager() != null) {
File outputLoc = config.getCompilationResultDestinationManager().getOutputLocationForResource(aResourceFile);
if (outputLoc != null) {
return outputLoc;
}
}
// Is there a default location?
if (config.getOutputDir() != null) {
return config.getOutputDir();
}
return null;
}
/**
* Check the old and new paths, if they vary by length or individual elements then that is considered a change. Or if the last
* modified time of a path entry has changed (or last modified time of a classfile in that path entry has changed) then return
* true. The outputlocations are supplied so they can be 'ignored' in the comparison.
*
* @param oldPath
* @param newPath
* @param checkClassFiles whether to examine individual class files within directories
* @param outputLocs the output locations that should be ignored if they occur on the paths being compared
* @return true if a change is detected that requires a full build
*/
private boolean changedAndNeedsFullBuild(List oldPath, List newPath, boolean checkClassFiles, List<File> outputLocs,
Set<String> alreadyAnalysedPaths, int pathid) {
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 (checkClassFiles && f.exists() && f.isDirectory()) {
// We should use here a list/set of directories we know have or have not changed - some kind of
// List<File> buildConfig.getClasspathEntriesWithChangedContents()
// and then only proceed to look inside directories if it is one of these, ignoring others -
// that should save a massive amount of processing for incremental builds in a multi project scenario
boolean foundMatch = false;
for (Iterator<File> iterator = outputLocs.iterator(); !foundMatch && iterator.hasNext();) {
File dir = iterator.next();
if (f.equals(dir)) {
foundMatch = true;
}
}
if (!foundMatch) {
if (!alreadyAnalysedPaths.contains(f.getAbsolutePath())) { // Do not check paths more than once
alreadyAnalysedPaths.add(f.getAbsolutePath());
int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(f, pathid);
if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) {
return true;
}
}
}
}
}
return false;
}
/**
* Check the old and new paths, if they vary by length or individual elements then that is considered a change. Or if the last
* modified time of a path entry has changed (or last modified time of a classfile in that path entry has changed) then return
* true. The outputlocations are supplied so they can be 'ignored' in the comparison.
*
* @param oldPath
* @param newPath
* @param checkClassFiles whether to examine individual class files within directories
* @param outputLocs the output locations that should be ignored if they occur on the paths being compared
* @return true if a change is detected that requires a full build
*/
private boolean classpathChangedAndNeedsFullBuild(List<String> oldPath, List<String> newPath, boolean checkClassFiles,
List<File> outputLocs, Set<String> alreadyAnalysedPaths) {
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;
}
File f = new File(oldPath.get(i));
if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) {
return true;
}
if (checkClassFiles && f.exists() && f.isDirectory()) {
// We should use here a list/set of directories we know have or have not changed - some kind of
// List<File> buildConfig.getClasspathEntriesWithChangedContents()
// and then only proceed to look inside directories if it is one of these, ignoring others -
// that should save a massive amount of processing for incremental builds in a multi project scenario
boolean foundMatch = false;
for (Iterator<File> iterator = outputLocs.iterator(); !foundMatch && iterator.hasNext();) {
File dir = iterator.next();
if (f.equals(dir)) {
foundMatch = true;
}
}
if (!foundMatch) {
if (!alreadyAnalysedPaths.contains(f.getAbsolutePath())) { // Do not check paths more than once
alreadyAnalysedPaths.add(f.getAbsolutePath());
int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(f, PATHID_CLASSPATH);
if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD) {
return true;
}
}
}
}
}
return false;
}
public Set<File> getFilesToCompile(boolean firstPass) {
Set<File> thisTime = new HashSet<File>();
if (firstPass) {
compiledSourceFiles = new HashSet<File>();
Collection<File> 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);
// }
if (addedFiles != null) {
for (Iterator<File> fIter = addedFiles.iterator(); fIter.hasNext();) {
File o = fIter.next();
// TODO isn't it a set?? why do this
if (!thisTime.contains(o)) {
thisTime.add(o);
}
}
// thisTime.addAll(addedFiles);
}
deleteClassFiles();
// Do not delete resources on incremental build, AJDT will handle
// copying updates to the output folder. AspectJ only does a copy
// of them on full build (see copyResourcesToDestination() call
// in AjBuildManager)
// deleteResources();
addAffectedSourceFiles(thisTime, thisTime);
} else {
addAffectedSourceFiles(thisTime, compiledSourceFiles);
}
compiledSourceFiles = thisTime;
return thisTime;
}
private boolean maybeIncremental() {
return (FORCE_INCREMENTAL_DURING_TESTING || this.couldBeSubsequentIncrementalBuild);
}
public Map<String, List<UnwovenClassFile>> getBinaryFilesToCompile(boolean firstTime) {
if (lastSuccessfulBuildTime == -1 || buildConfig == null || !maybeIncremental()) {
return binarySourceFiles;
}
// else incremental...
Map<String, List<UnwovenClassFile>> toWeave = new HashMap<String, List<UnwovenClassFile>>();
if (firstTime) {
List<BinarySourceFile> addedOrModified = new ArrayList<BinarySourceFile>();
addedOrModified.addAll(addedBinaryFiles);
addedOrModified.addAll(getModifiedBinaryFiles());
for (Iterator<BinarySourceFile> iter = addedOrModified.iterator(); iter.hasNext();) {
AjBuildConfig.BinarySourceFile bsf = iter.next();
UnwovenClassFile ucf = createUnwovenClassFile(bsf);
if (ucf == null) {
continue;
}
List<UnwovenClassFile> ucfs = new ArrayList<UnwovenClassFile>();
ucfs.add(ucf);
recordTypeChanged(ucf.getClassName());
binarySourceFiles.put(bsf.binSrc.getPath(), ucfs);
List<ClassFile> cfs = new ArrayList<ClassFile>(1);
cfs.add(getClassFileFor(ucf));
this.inputClassFilesBySource.put(bsf.binSrc.getPath(), cfs);
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<List<ClassFile>> iter = this.inputClassFilesBySource.values().iterator(); iter.hasNext();) {
List<ClassFile> cfs = iter.next();
for (ClassFile cf : cfs) {
cf.deleteFromFileSystem(buildConfig);
}
}
for (Iterator<File> iterator = classesFromName.values().iterator(); iterator.hasNext();) {
File f = iterator.next();
new ClassFile("", f).deleteFromFileSystem(buildConfig);
}
Set<Map.Entry<String, File>> resourceEntries = resources.entrySet();
for (Iterator<Map.Entry<String, File>> iter = resourceEntries.iterator(); iter.hasNext();) {
Map.Entry<String, File> resourcePair = iter.next();
File sourcePath = resourcePair.getValue();
File outputLoc = getOutputLocationFor(buildConfig, sourcePath);
if (outputLoc != null) {
outputLoc = new File(outputLoc, resourcePair.getKey());
if (!outputLoc.getPath().equals(sourcePath.getPath()) && outputLoc.exists()) {
outputLoc.delete();
if (buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileRemove(outputLoc.getPath(),
CompilationResultDestinationManager.FILETYPE_RESOURCE);
}
}
}
}
}
private void deleteClassFiles() {
if (deletedFiles == null) {
return;
}
for (File deletedFile : deletedFiles) {
addDependentsOf(deletedFile);
List<ClassFile> cfs = this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(deletedFile);
this.fullyQualifiedTypeNamesResultingFromCompilationUnit.remove(deletedFile);
if (cfs != null) {
for (ClassFile cf : cfs) {
deleteClassFile(cf);
}
}
}
}
private void deleteBinaryClassFiles() {
// range of bsf is ucfs, domain is files (.class and jars) in inpath/jars
for (BinarySourceFile deletedFile : deletedBinaryFiles) {
List<ClassFile> cfs = this.inputClassFilesBySource.get(deletedFile.binSrc.getPath());
for (Iterator<ClassFile> iterator = cfs.iterator(); iterator.hasNext();) {
deleteClassFile(iterator.next());
}
this.inputClassFilesBySource.remove(deletedFile.binSrc.getPath());
}
}
// 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();
// List outputDirs = getOutputLocations(buildConfig);
// for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
// File dir = (File) iterator.next();
// File f = new File(dir, victim);
// if (f.exists()) {
// f.delete();
// }
// resources.remove(victim);
// }
// }
// }
// private void maybeDeleteResource(String resName, List oldResources) {
// if (resources.contains(resName)) {
// oldResources.remove(resName);
// List outputDirs = getOutputLocations(buildConfig);
// for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
// File dir = (File) iterator.next();
// File source = new File(dir, resName);
// if (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 = null;
// try {
// filename = files[i].getCanonicalPath().substring(dir.getCanonicalPath().length() + 1);
// } catch (IOException e) {
// // we are in trouble if this happens...
// IMessage msg = new Message("call to getCanonicalPath() failed for file " + files[i] + " with: " + e.getMessage(),
// new SourceLocation(files[i], 0), false);
// buildManager.handler.handleMessage(msg);
// filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1);
// }
//
// maybeDeleteResource(filename, oldResources);
// }
// }
private void deleteClassFile(ClassFile cf) {
classesFromName.remove(cf.fullyQualifiedTypeName);
weaver.deleteClassFile(cf.fullyQualifiedTypeName);
cf.deleteFromFileSystem(buildConfig);
}
private UnwovenClassFile createUnwovenClassFile(AjBuildConfig.BinarySourceFile bsf) {
UnwovenClassFile ucf = null;
try {
File outputDir = buildConfig.getOutputDir();
if (buildConfig.getCompilationResultDestinationManager() != null) {
// createUnwovenClassFile is called only for classes that are on the inpath,
// all inpath classes are put in the defaultOutputLocation, therefore,
// this is the output dir
outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation();
}
ucf = weaver.addClassFile(bsf.binSrc, bsf.fromInPathDirectory, outputDir);
} 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) {
if (!maybeIncremental()) {
return;
}
File sourceFile = new File(result.fileName());
CompilationResult cr = result.result();
references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences,cr.rootReferences));
UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles();
for (int i = 0; i < unwovenClassFiles.length; i++) {
File lastTimeRound = classesFromName.get(unwovenClassFiles[i].getClassName());
recordClassFile(unwovenClassFiles[i], lastTimeRound);
String name = unwovenClassFiles[i].getClassName();
if (lastTimeRound == null) {
deltaAddedClasses.add(name);
}
classesFromName.put(name, new File(unwovenClassFiles[i].getFilename()));
}
// need to do this before types are deleted from the World...
recordWhetherCompilationUnitDefinedAspect(sourceFile, cr);
deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles);
recordFQNsResultingFromCompilationUnit(sourceFile, result);
}
public void noteNewResult(CompilationResult cr) {
// if (!maybeIncremental()) {
// return;
// }
//
// // File sourceFile = new File(result.fileName());
// // CompilationResult cr = result.result();
// if (new String(cr.getFileName()).indexOf("C") != -1) {
// cr.references.put(new String(cr.getFileName()),
// new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences));
// int stop = 1;
// }
// references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences));
//
// UnwovenClassFile[] unwovenClassFiles = cr.unwovenClassFiles();
// for (int i = 0; i < unwovenClassFiles.length; i++) {
// File lastTimeRound = (File) classesFromName.get(unwovenClassFiles[i].getClassName());
// recordClassFile(unwovenClassFiles[i], lastTimeRound);
// classesFromName.put(unwovenClassFiles[i].getClassName(), new File(unwovenClassFiles[i].getFilename()));
// }
// need to do this before types are deleted from the World...
// recordWhetherCompilationUnitDefinedAspect(sourceFile, cr);
// deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles);
//
// recordFQNsResultingFromCompilationUnit(sourceFile, result);
}
/**
* @param sourceFile
* @param unwovenClassFiles
*/
private void deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(File sourceFile,
UnwovenClassFile[] unwovenClassFiles) {
List<ClassFile> classFiles = this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile);
if (classFiles != null) {
for (int i = 0; i < unwovenClassFiles.length; i++) {
// deleting also deletes types from the weaver... don't do this if they are
// still present this time around...
removeFromClassFilesIfPresent(unwovenClassFiles[i].getClassName(), classFiles);
}
for (ClassFile cf : classFiles) {
recordTypeChanged(cf.fullyQualifiedTypeName);
resolvedTypeStructuresFromLastBuild.remove(cf.fullyQualifiedTypeName);
// }
// for (ClassFile cf : classFiles) {
deleteClassFile(cf);
}
}
}
private void removeFromClassFilesIfPresent(String className, List<ClassFile> classFiles) {
ClassFile victim = null;
for (ClassFile cf : classFiles) {
if (cf.fullyQualifiedTypeName.equals(className)) {
victim = cf;
break;
}
}
if (victim != null) {
classFiles.remove(victim);
}
}
/**
* Record the fully-qualified names of the types that were declared in the given source file.
*
* @param sourceFile, the compilation unit
* @param icr, the CompilationResult from compiling it
*/
private void recordFQNsResultingFromCompilationUnit(File sourceFile, InterimCompilationResult icr) {
List<ClassFile> classFiles = new ArrayList<ClassFile>();
UnwovenClassFile[] types = icr.unwovenClassFiles();
for (int i = 0; i < types.length; i++) {
classFiles.add(new ClassFile(types[i].getClassName(), new File(types[i].getFilename())));
}
this.fullyQualifiedTypeNamesResultingFromCompilationUnit.put(sourceFile, classFiles);
}
/**
* If this compilation unit defined an aspect, we need to know in case it is modified in a future increment.
*
* @param sourceFile
* @param cr
*/
private void recordWhetherCompilationUnitDefinedAspect(File sourceFile, CompilationResult cr) {
this.sourceFilesDefiningAspects.remove(sourceFile);
if (cr != null) {
Map compiledTypes = cr.compiledTypes;
if (compiledTypes != null) {
for (Iterator<char[]> iterator = compiledTypes.keySet().iterator(); iterator.hasNext();) {
char[] className = iterator.next();
String typeName = new String(className).replace('/', '.');
if (typeName.indexOf(BcelWeaver.SYNTHETIC_CLASS_POSTFIX) == -1) {
ResolvedType rt = world.resolve(typeName);
if (rt.isMissing()) {
// This can happen in a case where another problem has occurred that prevented it being
// correctly added to the world. Eg. pr148285. Duplicate types
// throw new IllegalStateException("Type '" + rt.getSignature() + "' not found in world!");
} else if (rt.isAspect()) {
this.sourceFilesDefiningAspects.add(sourceFile);
break;
}
}
}
}
}
}
// 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, File lastTime) {
if (simpleStrings == null) {
// batch build
// record resolved type for structural comparisons in future increments
// this records a second reference to a structure already held in memory
// by the world.
ResolvedType rType = world.resolve(thisTime.getClassName());
if (!rType.isMissing()) {
try {
ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null);
boolean isAspect = false;
if (rType instanceof ReferenceType && ((ReferenceType) rType).getDelegate() != null) {
isAspect = ((ReferenceType) rType).isAspect();
}
this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(), new CompactTypeStructureRepresentation(
reader, isAspect));
} catch (ClassFormatException cfe) {
throw new BCException("Unexpected problem processing class", cfe);
}
}
return;
}
CompactTypeStructureRepresentation existingStructure = this.resolvedTypeStructuresFromLastBuild
.get(thisTime.getClassName());
ResolvedType newResolvedType = world.resolve(thisTime.getClassName());
if (!newResolvedType.isMissing()) {
try {
ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null);
boolean isAspect = false;
if (newResolvedType instanceof ReferenceType && ((ReferenceType) newResolvedType).getDelegate() != null) {
isAspect = ((ReferenceType) newResolvedType).isAspect();
}
this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(), new CompactTypeStructureRepresentation(
reader, isAspect));
} catch (ClassFormatException cfe) {
try {
String s = System.getProperty("aspectj.debug377096","false");
if (s.equalsIgnoreCase("true")) {
String location = System.getProperty("java.io.tmpdir","/tmp");
String name = thisTime.getClassName();
File f = File.createTempFile(location+File.separator+name, ".class");
StringBuilder debug = new StringBuilder();
debug.append("Debug377096: Dumping class called "+name+" to "+f.getName()+" size:"+thisTime.getBytes().length);
DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
dos.write(thisTime.getBytes());
dos.close();
throw new BCException(debug.toString(), cfe);
}
} catch (Exception e) {
e.printStackTrace();
}
throw new BCException("Unexpected problem processing class", cfe);
}
}
if (lastTime == null) {
recordTypeChanged(thisTime.getClassName());
return;
}
if (newResolvedType.isMissing()) {
return;
}
world.ensureAdvancedConfigurationProcessed();
byte[] newBytes = thisTime.getBytes();
try {
ClassFileReader reader = new ClassFileReader(newBytes, lastTime.getAbsolutePath().toCharArray());
// ignore local types since they're only visible inside a single method
if (!(reader.isLocal() || reader.isAnonymous())) {
if (hasStructuralChanges(reader, existingStructure)) {
if (world.forDEBUG_structuralChangesCode) {
System.err.println("Detected a structural change in " + thisTime.getFilename());
}
structuralChangesSinceLastFullBuild.put(thisTime.getFilename(), new Long(currentBuildTime));
recordTypeChanged(new String(reader.getName()).replace('/', '.'));
}
}
} catch (ClassFormatException e) {
recordTypeChanged(thisTime.getClassName());
}
}
/**
* Compare the class structure of the new intermediate (unwoven) class with the existingResolvedType of the same class that we
* have in the world, looking for any structural differences (and ignoring aj members resulting from weaving....)
*
* Some notes from Andy... lot of problems here, which I've eventually resolved by building the compactstructure based on a
* classfilereader, rather than on a ResolvedType. There are accessors for inner types and funky fields that the compiler
* creates to support the language - for non-static inner types it also mangles ctors to be prefixed with an instance of the
* surrounding type.
*
* @param reader
* @param existingType
* @return
*/
private boolean hasStructuralChanges(ClassFileReader reader, CompactTypeStructureRepresentation existingType) {
if (existingType == null) {
return true;
}
// modifiers
if (!modifiersEqual(reader.getModifiers(), existingType.modifiers)) {
return true;
}
// generic signature
if (!CharOperation.equals(reader.getGenericSignature(), existingType.genericSignature)) {
return true;
}
// superclass name
if (!CharOperation.equals(reader.getSuperclassName(), existingType.superclassName)) {
return true;
}
// have annotations changed on the type?
IBinaryAnnotation[] newAnnos = reader.getAnnotations();
if (newAnnos == null || newAnnos.length == 0) {
if (existingType.annotations != null && existingType.annotations.length != 0) {
return true;
}
} else {
IBinaryAnnotation[] existingAnnos = existingType.annotations;
if (existingAnnos == null || existingAnnos.length != newAnnos.length) {
return true;
}
// Does not allow for an order switch
// Does not cope with a change in values set on the annotation (hard to create a testcase where this is a problem tho)
for (int i = 0; i < newAnnos.length; i++) {
if (!CharOperation.equals(newAnnos[i].getTypeName(), existingAnnos[i].getTypeName())) {
return true;
}
}
}
// interfaces
char[][] existingIfs = existingType.interfaces;
char[][] newIfsAsChars = reader.getInterfaceNames();
if (newIfsAsChars == null) {
newIfsAsChars = EMPTY_CHAR_ARRAY;
} // damn I'm lazy...
if (existingIfs == null) {
existingIfs = EMPTY_CHAR_ARRAY;
}
if (existingIfs.length != newIfsAsChars.length) {
return true;
}
new_interface_loop: for (int i = 0; i < newIfsAsChars.length; i++) {
for (int j = 0; j < existingIfs.length; j++) {
if (CharOperation.equals(existingIfs[j], newIfsAsChars[i])) {
continue new_interface_loop;
}
}
return true;
}
// fields
// CompactMemberStructureRepresentation[] existingFields = existingType.fields;
IBinaryField[] newFields = reader.getFields();
if (newFields == null) {
newFields = CompactTypeStructureRepresentation.NoField;
}
// all redundant for now ... could be an optimization at some point...
// remove any ajc$XXX fields from those we compare with
// the existing fields - bug 129163
// List nonGenFields = new ArrayList();
// for (int i = 0; i < newFields.length; i++) {
// IBinaryField field = newFields[i];
// //if (!CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,field.getName())) { // this would skip ajc$ fields
// //if ((field.getModifiers()&0x1000)==0) // 0x1000 => synthetic - this will skip synthetic fields (eg. this$0)
// nonGenFields.add(field);
// //}
// }
IBinaryField[] existingFs = existingType.binFields;
if (newFields.length != existingFs.length) {
return true;
}
new_field_loop: for (int i = 0; i < newFields.length; i++) {
IBinaryField field = newFields[i];
char[] fieldName = field.getName();
for (int j = 0; j < existingFs.length; j++) {
if (CharOperation.equals(existingFs[j].getName(), fieldName)) {
IBinaryField existing = existingFs[j];
if (!modifiersEqual(field.getModifiers(), existing.getModifiers())) {
return true;
}
if (!CharOperation.equals(existing.getTypeName(), field.getTypeName())) {
return true;
}
char[] existingGSig = existing.getGenericSignature();
char[] fieldGSig = field.getGenericSignature();
if ((existingGSig == null && fieldGSig != null) || (existingGSig != null && fieldGSig == null)) {
return true;
}
if (existingGSig != null) {
if (!CharOperation.equals(existingGSig, fieldGSig)) {
return true;
}
}
continue new_field_loop;
}
}
return true;
}
// methods
// CompactMemberStructureRepresentation[] existingMethods = existingType.methods;
IBinaryMethod[] newMethods = reader.getMethods();
if (newMethods == null) {
newMethods = CompactTypeStructureRepresentation.NoMethod;
}
// all redundant for now ... could be an optimization at some point...
// Ctors in a non-static inner type have an 'extra parameter' of the enclosing type.
// If skippableDescriptorPrefix gets set here then it is set to the descriptor portion
// for this 'extra parameter'. For an inner class of pkg.Foo the skippable descriptor
// prefix will be '(Lpkg/Foo;' - so later when comparing <init> methods we know what to
// compare.
// IF THIS CODE NEEDS TO GET MORE COMPLICATED, I THINK ITS WORTH RIPPING IT ALL OUT AND
// CREATING THE STRUCTURAL CHANGES OBJECT BASED ON CLASSREADER OUTPUT RATHER THAN
// THE RESOLVEDTYPE - THEN THERE WOULD BE NO NEED TO TREAT SOME METHODS IN A PECULIAR
// WAY.
// char[] skippableDescriptorPrefix = null;
// char[] enclosingTypeName = reader.getEnclosingTypeName();
// boolean isStaticType = Modifier.isStatic(reader.getModifiers());
// if (!isStaticType && enclosingTypeName!=null) {
// StringBuffer sb = new StringBuffer();
// sb.append("(L").append(new String(enclosingTypeName)).append(";");
// skippableDescriptorPrefix = sb.toString().toCharArray();
// }
//
//
// // remove the aspectOf, hasAspect, clinit and ajc$XXX methods
// // from those we compare with the existing methods - bug 129163
// List nonGenMethods = new ArrayList();
// for (int i = 0; i < newMethods.length; i++) {
// IBinaryMethod method = newMethods[i];
// // if ((method.getModifiers() & 0x1000)!=0) continue; // 0x1000 => synthetic - will cause us to skip access$0 - is this
// always safe?
// char[] methodName = method.getSelector();
// // if (!CharOperation.equals(methodName,NameMangler.METHOD_ASPECTOF) &&
// // !CharOperation.equals(methodName,NameMangler.METHOD_HASASPECT) &&
// // !CharOperation.equals(methodName,NameMangler.STATIC_INITIALIZER) &&
// // !CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,methodName) &&
// // !CharOperation.prefixEquals(NameMangler.CLINIT,methodName)) {
// nonGenMethods.add(method);
// // }
// }
IBinaryMethod[] existingMs = existingType.binMethods;
if (newMethods.length != existingMs.length) {
return true;
}
new_method_loop: for (int i = 0; i < newMethods.length; i++) {
IBinaryMethod method = newMethods[i];
char[] methodName = method.getSelector();
for (int j = 0; j < existingMs.length; j++) {
if (CharOperation.equals(existingMs[j].getSelector(), methodName)) {
// candidate match
if (!CharOperation.equals(method.getMethodDescriptor(), existingMs[j].getMethodDescriptor())) {
// ok, the descriptors don't match, but is this a funky ctor on a non-static inner
// type?
// boolean mightBeOK =
// skippableDescriptorPrefix!=null && // set for inner types
// CharOperation.equals(methodName,NameMangler.INIT) && // ctor
// CharOperation.prefixEquals(skippableDescriptorPrefix,method.getMethodDescriptor()); // checking for
// prefix on the descriptor
// if (mightBeOK) {
// // OK, so the descriptor starts something like '(Lpkg/Foo;' - we now may need to look at the rest of the
// // descriptor if it takes >1 parameter.
// // eg. could be (Lpkg/C;Ljava/lang/String;) where the skippablePrefix is (Lpkg/C;
// char [] md = method.getMethodDescriptor();
// char[] remainder = CharOperation.subarray(md, skippableDescriptorPrefix.length, md.length);
// if (CharOperation.equals(remainder,BRACKET_V)) continue new_method_loop; // no other parameters to worry
// about
// char[] comparableSig = CharOperation.subarray(existingMethods[j].signature, 1,
// existingMethods[j].signature.length);
// boolean match = CharOperation.equals(comparableSig, remainder);
// if (match) continue new_method_loop;
// }
continue; // might be overloading
} else {
// matching sigs
IBinaryMethod existing = existingMs[j];
if (!modifiersEqual(method.getModifiers(), existing.getModifiers())) {
return true;
}
if (exceptionClausesDiffer(existing, method)) {
return true;
}
char[] existingGSig = existing.getGenericSignature();
char[] methodGSig = method.getGenericSignature();
if ((existingGSig == null && methodGSig != null) || (existingGSig != null && methodGSig == null)) {
return true;
}
if (existingGSig != null) {
if (!CharOperation.equals(existingGSig, methodGSig)) {
return true;
}
}
continue new_method_loop;
}
}
}
return true; // (no match found)
}
// check for differences in inner types
// TODO could make order insensitive
IBinaryNestedType[] binaryNestedTypes = reader.getMemberTypes();
IBinaryNestedType[] existingBinaryNestedTypes = existingType.getMemberTypes();
if ((binaryNestedTypes == null && existingBinaryNestedTypes != null)
|| (binaryNestedTypes != null && existingBinaryNestedTypes == null)) {
return true;
}
if (binaryNestedTypes != null) {
int bnLength = binaryNestedTypes.length;
if (existingBinaryNestedTypes.length != bnLength) {
return true;
}
for (int m = 0; m < bnLength; m++) {
IBinaryNestedType bnt = binaryNestedTypes[m];
IBinaryNestedType existingBnt = existingBinaryNestedTypes[m];
if (!CharOperation.equals(bnt.getName(), existingBnt.getName())) {
return true;
}
}
}
return false;
}
/**
* For two methods, discover if there has been a change in the exception types specified.
*
* @return true if the exception types have changed
*/
private boolean exceptionClausesDiffer(IBinaryMethod lastMethod, IBinaryMethod newMethod) {
char[][] previousExceptionTypeNames = lastMethod.getExceptionTypeNames();
char[][] newExceptionTypeNames = newMethod.getExceptionTypeNames();
int pLength = previousExceptionTypeNames.length;
int nLength = newExceptionTypeNames.length;
if (pLength != nLength) {
return true;
}
if (pLength == 0) {
return false;
}
// TODO could be insensitive to an order change
for (int i = 0; i < pLength; i++) {
if (!CharOperation.equals(previousExceptionTypeNames[i], newExceptionTypeNames[i])) {
return true;
}
}
return false;
}
private boolean modifiersEqual(int eclipseModifiers, int resolvedTypeModifiers) {
resolvedTypeModifiers = resolvedTypeModifiers & ExtraCompilerModifiers.AccJustFlag;
eclipseModifiers = eclipseModifiers & ExtraCompilerModifiers.AccJustFlag;
// if ((eclipseModifiers & CompilerModifiers.AccSuper) != 0) {
// eclipseModifiers -= CompilerModifiers.AccSuper;
// }
return (eclipseModifiers == resolvedTypeModifiers);
}
// 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;
// }
private String stringifySet(Set<?> l) {
StringBuffer sb = new StringBuffer();
sb.append("{");
for (Iterator<?> iter = l.iterator(); iter.hasNext();) {
Object el = iter.next();
sb.append(el);
if (iter.hasNext()) {
sb.append(",");
}
}
sb.append("}");
return sb.toString();
}
protected void addAffectedSourceFiles(Set<File> addTo, Set<File> lastTimeSources) {
if (qualifiedStrings.elementSize == 0 && simpleStrings.elementSize == 0) {
return;
}
if (listenerDefined()) {
getListener().recordDecision(
"Examining whether any other files now need compilation based on just compiling: '"
+ stringifySet(lastTimeSources) + "'");
}
// the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X'
char[][][] qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedStrings);
// if a well known qualified name was found then we can skip over these
if (qualifiedNames.length < qualifiedStrings.elementSize) {
qualifiedNames = null;
}
char[][] simpleNames = ReferenceCollection.internSimpleNames(simpleStrings);
// if a well known name was found then we can skip over these
if (simpleNames.length < simpleStrings.elementSize) {
simpleNames = null;
}
// System.err.println("simple: " + simpleStrings);
// System.err.println("qualif: " + qualifiedStrings);
for (Iterator<Map.Entry<File, ReferenceCollection>> i = references.entrySet().iterator(); i.hasNext();) {
Map.Entry<File, ReferenceCollection> entry = i.next();
ReferenceCollection refs = entry.getValue();
if (refs != null && refs.includes(qualifiedNames, simpleNames)) {
File file = entry.getKey();
if (file.exists()) {
if (!lastTimeSources.contains(file)) { // ??? O(n**2)
if (listenerDefined()) {
getListener().recordDecision("Need to recompile '" + file.getName().toString() + "'");
}
addTo.add(file);
}
}
}
}
// add in the things we compiled previously - I know that seems crap but otherwise we may pull woven
// stuff off disk (since we no longer have UnwovenClassFile objects) in order to satisfy references
// in the new files we are about to compile (see pr133532)
if (addTo.size() > 0) {
addTo.addAll(lastTimeSources);
}
// // XXX Promote addTo to a Set - then we don't need this rubbish? but does it need to be ordered?
// if (addTo.size()>0) {
// for (Iterator iter = lastTimeSources.iterator(); iter.hasNext();) {
// Object element = (Object) iter.next();
// if (!addTo.contains(element)) addTo.add(element);
// }
// }
qualifiedStrings.clear();
simpleStrings.clear();
}
/**
* Record that a particular type has been touched during a compilation run. Information is used to ensure any types depending
* upon this one are also recompiled.
*
* @param typename (possibly qualified) type name
*/
protected void recordTypeChanged(String typename) {
int lastDot = typename.lastIndexOf('.');
String typeName;
if (lastDot != -1) {
String packageName = typename.substring(0, lastDot).replace('.', '/');
qualifiedStrings.add(packageName);
typeName = typename.substring(lastDot + 1);
} else {
qualifiedStrings.add("");
typeName = typename;
}
int memberIndex = typeName.indexOf('$');
if (memberIndex > 0) {
typeName = typeName.substring(0, memberIndex);
}
simpleStrings.add(typeName);
}
/**
* Record some additional dependencies between types. When any of the types specified in fullyQualifiedTypeNames changes, we
* need to recompile the file named in the CompilationResult. This method patches that information into the existing data
* structures.
*/
public boolean recordDependencies(File file, String[] typeNameDependencies) {
try {
File sourceFile = new File(new String(file.getCanonicalPath()));
ReferenceCollection existingCollection = references.get(sourceFile);
if (existingCollection != null) {
existingCollection.addDependencies(typeNameDependencies);
return true;
} else {
ReferenceCollection rc = new ReferenceCollection(null, null, null);
rc.addDependencies(typeNameDependencies);
references.put(sourceFile, rc);
return true;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return false;
}
protected void addDependentsOf(File sourceFile) {
List<ClassFile> cfs = this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile);
if (cfs != null) {
for (ClassFile cf : cfs) {
recordTypeChanged(cf.fullyQualifiedTypeName);
}
}
}
public void setStructureModel(AsmManager structureModel) {
this.structureModel = structureModel;
}
public AsmManager getStructureModel() {
return structureModel;
}
public void setWeaver(BcelWeaver bw) {
weaver = bw;
}
public BcelWeaver getWeaver() {
return weaver;
}
public void setWorld(BcelWorld bw) {
world = bw;
world.addTypeDelegateResolver(this);
}
public BcelWorld getBcelWorld() {
return world;
}
//
// public void setRelationshipMap(IRelationshipMap irm) {
// relmap = irm;
// }
//
// public IRelationshipMap getRelationshipMap() {
// return relmap;
// }
public int getNumberOfStructuralChangesSinceLastFullBuild() {
return structuralChangesSinceLastFullBuild.size();
}
/** Returns last time we did a full or incremental build. */
public long getLastBuildTime() {
return lastSuccessfulBuildTime;
}
/** Returns last time we did a full build */
public long getLastFullBuildTime() {
return lastSuccessfulFullBuildTime;
}
/**
* @return Returns the buildConfig.
*/
public AjBuildConfig getBuildConfig() {
return this.buildConfig;
}
public void clearBinarySourceFiles() {
this.binarySourceFiles = new HashMap<String, List<UnwovenClassFile>>();
}
public void recordBinarySource(String fromPathName, List<UnwovenClassFile> unwovenClassFiles) {
this.binarySourceFiles.put(fromPathName, unwovenClassFiles);
if (this.maybeIncremental()) {
List<ClassFile> simpleClassFiles = new LinkedList<ClassFile>();
for (UnwovenClassFile ucf : unwovenClassFiles) {
ClassFile cf = getClassFileFor(ucf);
simpleClassFiles.add(cf);
}
this.inputClassFilesBySource.put(fromPathName, simpleClassFiles);
}
}
/**
* @param ucf
* @return
*/
private ClassFile getClassFileFor(UnwovenClassFile ucf) {
return new ClassFile(ucf.getClassName(), new File(ucf.getFilename()));
}
public Map<String, List<UnwovenClassFile>> getBinarySourceMap() {
return this.binarySourceFiles;
}
public Map<String, File> getClassNameToFileMap() {
return this.classesFromName;
}
public boolean hasResource(String resourceName) {
return this.resources.keySet().contains(resourceName);
}
public void recordResource(String resourceName, File resourceSourceLocation) {
this.resources.put(resourceName, resourceSourceLocation);
}
/**
* @return Returns the addedFiles.
*/
public Set<File> getAddedFiles() {
return this.addedFiles;
}
/**
* @return Returns the deletedFiles.
*/
public Set<File> getDeletedFiles() {
return this.deletedFiles;
}
public void forceBatchBuildNextTimeAround() {
this.batchBuildRequiredThisTime = true;
}
public boolean requiresFullBatchBuild() {
return this.batchBuildRequiredThisTime;
}
private static class ClassFile {
public String fullyQualifiedTypeName;
public File locationOnDisk;
public ClassFile(String fqn, File location) {
this.fullyQualifiedTypeName = fqn;
this.locationOnDisk = location;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append("ClassFile(type=").append(fullyQualifiedTypeName).append(",location=").append(locationOnDisk).append(")");
return s.toString();
}
public void deleteFromFileSystem(AjBuildConfig buildConfig) {
String namePrefix = locationOnDisk.getName();
namePrefix = namePrefix.substring(0, namePrefix.lastIndexOf('.'));
final String targetPrefix = namePrefix + BcelWeaver.CLOSURE_CLASS_PREFIX;
File dir = locationOnDisk.getParentFile();
if (dir != null) {
File[] weaverGenerated = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(targetPrefix);
}
});
if (weaverGenerated != null) {
for (int i = 0; i < weaverGenerated.length; i++) {
weaverGenerated[i].delete();
if (buildConfig != null && buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileRemove(weaverGenerated[i].getPath(),
CompilationResultDestinationManager.FILETYPE_CLASS);
}
}
}
}
locationOnDisk.delete();
if (buildConfig != null && buildConfig.getCompilationResultDestinationManager() != null) {
buildConfig.getCompilationResultDestinationManager().reportFileRemove(locationOnDisk.getPath(),
CompilationResultDestinationManager.FILETYPE_CLASS);
}
}
}
public void wipeAllKnowledge() {
buildManager.state = null;
// buildManager.setStructureModel(null);
}
public Map<String, char[]> getAspectNamesToFileNameMap() {
return aspectsFromFileNames;
}
public void initializeAspectNamesToFileNameMap() {
this.aspectsFromFileNames = new HashMap<String, char[]>();
}
// Will allow us to record decisions made during incremental processing, hopefully aid in debugging
public boolean listenerDefined() {
return stateListener != null;
}
public IStateListener getListener() {
return stateListener;
}
public IBinaryType checkPreviousBuild(String name) {
return resolvedTypeStructuresFromLastBuild.get(name);
}
public AjBuildManager getAjBuildManager() {
return buildManager;
}
public INameEnvironment getNameEnvironment() {
return this.nameEnvironment;
}
public void setNameEnvironment(INameEnvironment nameEnvironment) {
this.nameEnvironment = nameEnvironment;
}
/**
* Record an aspect that came in on the aspect path. When a .class file changes on the aspect path we can then recognize it as
* an aspect and know to do more than just a tiny incremental build. <br>
* TODO but this doesn't allow for a new aspect created on the aspectpath?
*
* @param aspectFile path to the file, eg. c:/temp/foo/Fred.class
*/
public void recordAspectClassFile(String aspectFile) {
aspectClassFiles.add(aspectFile);
}
public void write(CompressingDataOutputStream dos) throws IOException {
// weaver
weaver.write(dos);
// world
// model
// local state
}
/**
* See if we can create a delegate from a CompactTypeStructure - TODO better comment
*/
public ReferenceTypeDelegate getDelegate(ReferenceType referenceType) {
File f = classesFromName.get(referenceType.getName());
if (f == null) {
return null; // not heard of it
}
try {
ClassParser parser = new ClassParser(f.toString());
return world.buildBcelDelegate(referenceType, parser.parse(), true, false);
} catch (IOException e) {
IMessage msg = new Message("Failed to recover " + referenceType, referenceType.getSourceLocation(), false);
buildManager.handler.handleMessage(msg);
}
return null;
}
}
|
423,257 | Bug 423257 LTW - java.lang.VerifyError: Bad return type with generics and local variables | null | resolved fixed | dd88d21 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-12-06T18:33:48Z" | "2013-12-04T23:33:20Z" | tests/bugs175/pr423257/AspectX.java | |
423,257 | Bug 423257 LTW - java.lang.VerifyError: Bad return type with generics and local variables | null | resolved fixed | dd88d21 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-12-06T18:33:48Z" | "2013-12-04T23:33:20Z" | tests/bugs175/pr423257/Test.java | |
423,257 | Bug 423257 LTW - java.lang.VerifyError: Bad return type with generics and local variables | null | resolved fixed | dd88d21 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-12-06T18:33:48Z" | "2013-12-04T23:33:20Z" | tests/src/org/aspectj/systemtest/AllTests17.java | /*
* Created on 19-01-2005
*/
package org.aspectj.systemtest;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.aspectj.systemtest.ajc170.AllTestsAspectJ170;
import org.aspectj.systemtest.ajc171.AllTestsAspectJ171;
import org.aspectj.systemtest.ajc172.AllTestsAspectJ172;
import org.aspectj.systemtest.ajc173.AllTestsAspectJ173;
import org.aspectj.systemtest.ajc174.AllTestsAspectJ174;
public class AllTests17 {
public static Test suite() {
TestSuite suite = new TestSuite("AspectJ System Test Suite - 1.7");
// $JUnit-BEGIN$
suite.addTest(AllTestsAspectJ174.suite());
suite.addTest(AllTestsAspectJ173.suite());
suite.addTest(AllTestsAspectJ172.suite());
suite.addTest(AllTestsAspectJ171.suite());
suite.addTest(AllTestsAspectJ170.suite());
suite.addTest(AllTests16.suite());
suite.addTest(AllTests15.suite());
// $JUnit-END$
return suite;
}
}
|
423,257 | Bug 423257 LTW - java.lang.VerifyError: Bad return type with generics and local variables | null | resolved fixed | dd88d21 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-12-06T18:33:48Z" | "2013-12-04T23:33:20Z" | tests/src/org/aspectj/systemtest/ajc175/Ajc175Tests.java | |
423,257 | Bug 423257 LTW - java.lang.VerifyError: Bad return type with generics and local variables | null | resolved fixed | dd88d21 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-12-06T18:33:48Z" | "2013-12-04T23:33:20Z" | tests/src/org/aspectj/systemtest/ajc175/AllTestsAspectJ175.java | |
423,257 | Bug 423257 LTW - java.lang.VerifyError: Bad return type with generics and local variables | null | resolved fixed | dd88d21 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-12-06T18:33:48Z" | "2013-12-04T23:33:20Z" | tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java | /********************************************************************
* Copyright (c) 2005 Contributors. All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* Helen Hawkins Converted to new interface (bug 148190)
*******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.aspectj.ajde.core.ICompilerConfiguration;
import org.aspectj.ajde.core.TestOutputLocationManager;
import org.aspectj.ajde.core.internal.AjdeCoreBuildManager;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IProgramElement.Kind;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.tools.ajc.Ajc;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.World;
/**
* The superclass knows all about talking through Ajde to the compiler. The superclass isn't in charge of knowing how to simulate
* overlays for incremental builds, that is in here. As is the ability to generate valid build configs based on a directory
* structure. To support this we just need access to a sandbox directory - this sandbox is managed by the superclass (it only
* assumes all builds occur in <sandboxDir>/<projectName>/ )
*
* The idea is you can initialize multiple projects in the sandbox and they can all be built independently, hopefully exploiting
* incremental compilation. Between builds you can alter the contents of a project using the alter() method that overlays some set
* of new files onto the current set (adding new files/changing existing ones) - you can then drive a new build and check it behaves
* as expected.
*/
public class MultiProjectIncrementalTests extends AbstractMultiProjectIncrementalAjdeInteractionTestbed {
public void testIncremental_344326() throws Exception {
AjdeInteractionTestbed.VERBOSE = true;
String p = "pr344326";
initialiseProject(p);
build(p);
checkWasFullBuild();
checkCompileWeaveCount(p, 3, 4);
alter(p, "inc1");
build(p);
checkWasntFullBuild();
checkCompileWeaveCount(p, 1, 1);
}
public void testMissingRel_328121() throws Exception {
String p = "pr328121";
initialiseProject(p);
build(p);
checkWasFullBuild();
assertNoErrors(p);
// Check the annotations:
runMethod(p, "TestRequirements.TestRequirements", "foo");
assertEquals(4, getRelationshipCount(p));
}
public void testEncoding_pr290741() throws Exception {
String p = "pr290741";
initialiseProject(p);
setProjectEncoding(p, "UTF-8");
build(p);
checkWasFullBuild();
assertNoErrors(p);
runMethod(p, "demo.ConverterTest", "run");
}
private void runMethod(String projectName, String classname, String methodname) throws Exception {
File f = getProjectOutputRelativePath(projectName, "");
ClassLoader cl = new URLClassLoader(new URL[] { f.toURI().toURL() });
Class<?> clazz = Class.forName(classname, false, cl);
clazz.getDeclaredMethod(methodname).invoke(null);
}
public void testIncrementalITDInners4() throws Exception {
String p = "prInner4";
initialiseProject(p);
build(p);
checkWasFullBuild();
assertNoErrors(p);
// touch the aspect making the ITD member type
alter(p, "inc1");
build(p);
checkWasntFullBuild();
assertNoErrors(p);
}
public void testIncrementalITDInners3() throws Exception {
AjdeInteractionTestbed.VERBOSE = true;
String p = "prInner3";
initialiseProject(p);
build(p);
checkWasFullBuild();
// touch the aspect making the ITD member type
alter(p, "inc1");
build(p);
checkWasntFullBuild();
// touch the aspect making the ITD that depends on the member type
alter(p, "inc2");
build(p);
checkWasntFullBuild();
// touch the type affected by the ITDs
alter(p, "inc3");
build(p);
checkWasntFullBuild();
}
// mixing ITDs with inner type intertypes
public void testIncrementalITDInners2() throws Exception {
String p = "prInner2";
initialiseProject(p);
build(p);
checkWasFullBuild();
// touch the aspect making the ITD member type
alter(p, "inc1");
build(p);
checkWasntFullBuild();
// touch the aspect making the ITD that depends on the member type
alter(p, "inc2");
build(p);
checkWasntFullBuild();
// touch the type affected by the ITDs
alter(p, "inc3");
build(p);
checkWasntFullBuild();
}
public void testIncrementalITDInners() throws Exception {
String p = "prInner";
initialiseProject(p);
build(p);
checkWasFullBuild();
alter(p, "inc1");
build(p);
checkWasntFullBuild();
}
/*
* public void testIncrementalAspectWhitespace() throws Exception { AjdeInteractionTestbed.VERBOSE = true; String p = "xxx";
* initialiseProject(p); configureNonStandardCompileOptions(p, "-showWeaveInfo"); configureShowWeaveInfoMessages(p, true);
* build(p);
*
* List weaveMessages = getWeavingMessages(p); if (weaveMessages.size() != 0) { for (Iterator iterator =
* weaveMessages.iterator(); iterator.hasNext();) { Object object = iterator.next(); System.out.println(object); } }
* checkWasFullBuild(); assertNoErrors(p); alter(p, "inc1"); build(p); checkWasntFullBuild(); assertNoErrors(p); }
*/
public void testIncrementalGenericItds_pr280676() throws Exception {
String p = "pr280676";
initialiseProject(p);
build(p);
checkWasFullBuild();
assertNoErrors(p);
alter(p, "inc1"); // remove type variables from ITD field
build(p);
checkWasFullBuild();
assertNoErrors(p);
alter(p, "inc2"); // remove type variables from ITD method
build(p);
checkWasFullBuild();
assertNoErrors(p);
alter(p, "inc3"); // readded type variables on ITD method
build(p);
checkWasFullBuild();
assertNoErrors(p);
}
public void testIncrementalGenericItds_pr280676_2() throws Exception {
String p = "pr280676_2";
initialiseProject(p);
build(p);
checkWasFullBuild();
assertNoErrors(p);
alter(p, "inc1"); // remove type variables from target type
build(p);
List<IMessage> errors = getErrorMessages(p);
// Build errors:
// error at N:\temp\ajcSandbox\aspectj16_3\ajcTest60379.tmp\pr280676_2\src\p\A.java:8:0::0 a.ls cannot be resolved or is not
// a field
// error at N:\temp\ajcSandbox\aspectj16_3\ajcTest60379.tmp\pr280676_2\src\p\Foo.aj:8:0::0 Type parameters can not be
// specified in the ITD target type - the target type p.A is not generic.
// error at N:\temp\ajcSandbox\aspectj16_3\ajcTest60379.tmp\pr280676_2\src\p\Foo.aj:12:0::0 Type parameters can not be
// specified in the ITD target type - the target type p.A is not generic.
// error at N:\temp\ajcSandbox\aspectj16_3\ajcTest60379.tmp\pr280676_2\src\p\Foo.aj:8:0::0 Type parameters can not be
// specified in the ITD target type - the target type p.A is not generic.
// error at N:\temp\ajcSandbox\aspectj16_3\ajcTest60379.tmp\pr280676_2\src\p\Foo.aj:12:0::0 Type parameters can not be
// specified in the ITD target type - the target type p.A is not generic.
assertEquals(5, errors.size());
}
public void testAdviceHandles_pr284771() throws Exception {
String p = "pr284771";
initialiseProject(p);
build(p);
IRelationshipMap irm = getModelFor(p).getRelationshipMap();
List<IRelationship> rels = irm.get("=pr284771<test*AspectTrace.aj'AspectTrace&before");
assertNotNull(rels);
assertEquals(2, ((Relationship) rels.get(0)).getTargets().size());
rels = irm.get("=pr284771<test*AspectTrace.aj'AspectTrace&before!2");
assertNotNull(rels);
assertEquals(2, ((Relationship) rels.get(0)).getTargets().size());
}
public void testDeclareSoftHandles_329111() throws Exception {
String p = "pr329111";
initialiseProject(p);
build(p);
printModel(p);
IRelationshipMap irm = getModelFor(p).getRelationshipMap();
List<IRelationship> rels = irm.get("=pr329111<{AJ.java'AJ`declare soft");
assertNotNull(rels);
rels = irm.get("=pr329111<{AJ2.java'AJ2`declare soft");
assertNotNull(rels);
rels = irm.get("=pr329111<{AJ2.java'AJ2`declare soft!2");
assertNotNull(rels);
rels = irm.get("=pr329111<{AJ2.java'AJ2`declare soft!3");
assertNotNull(rels);
rels = irm.get("=pr329111<{AJ3.java'AJ3`declare warning");
assertNotNull(rels);
rels = irm.get("=pr329111<{AJ3.java'AJ3`declare warning!2");
assertNotNull(rels);
rels = irm.get("=pr329111<{AJ3.java'AJ3`declare error");
assertNotNull(rels);
rels = irm.get("=pr329111<{AJ3.java'AJ3`declare error!2");
assertNotNull(rels);
}
/**
* Test that the declare parents in the super aspect gets a relationship from the type declaring it.
*/
public void testAspectInheritance_322446() throws Exception {
String p = "pr322446";
initialiseProject(p);
build(p);
IRelationshipMap irm = getModelFor(p).getRelationshipMap();
// Hid:1:(targets=1) =pr322446<{Class.java[Class (aspect declarations) =pr322446<{AbstractAspect.java'AbstractAspect`declare
// parents
// Hid:2:(targets=1) =pr322446<{AbstractAspect.java'AbstractAspect`declare parents (declared on) =pr322446<{Class.java[Class
List<IRelationship> rels = irm.get("=pr322446<{AbstractAspect.java'AbstractAspect`declare parents");
assertNotNull(rels);
}
public void testAspectInheritance_322446_2() throws Exception {
String p = "pr322446_2";
initialiseProject(p);
build(p);
IProgramElement thisAspectNode = getModelFor(p).getHierarchy().findElementForType("", "Sub");
assertEquals("{Code=[I]}", thisAspectNode.getDeclareParentsMap().toString());
}
public void testBinaryAspectsAndTheModel_343001() throws Exception {
String lib = "pr343001_lib";
initialiseProject(lib);
build(lib);
// Check the 'standard build' - the library also has a type affected by the decp so we can check what happens on an 'all
// source' build
IProgramElement theAspect = getModelFor(lib).getHierarchy().findElementForHandleOrCreate("=pr343001_lib<{Super.java'Super",
false);
assertNotNull(theAspect);
IProgramElement sourcelevelDecp = getModelFor(lib).getHierarchy().findElementForHandleOrCreate(
"=pr343001_lib<{Super.java'Super`declare parents", false);
assertNotNull(sourcelevelDecp);
assertEquals("[java.io.Serializable]", sourcelevelDecp.getParentTypes().toString());
String p = "pr343001";
initialiseProject(p);
configureAspectPath(p, getProjectRelativePath(lib, "bin"));
build(p);
IProgramElement theBinaryAspect = getModelFor(p).getHierarchy().findElementForHandleOrCreate(
"=pr343001/binaries<(Super.class'Super", false);
assertNotNull(theBinaryAspect);
IProgramElement binaryDecp = getModelFor(p).getHierarchy().findElementForHandleOrCreate(
"=pr343001/binaries<(Super.class'Super`declare parents", false);
assertNotNull(binaryDecp);
assertEquals("[java.io.Serializable]", (binaryDecp.getParentTypes() == null ? "" : binaryDecp.getParentTypes().toString()));
}
// found whilst looking at 322446 hence that is the testdata name
public void testAspectInheritance_322664() throws Exception {
AjdeInteractionTestbed.VERBOSE = true;
String p = "pr322446_3";
initialiseProject(p);
build(p);
assertNoErrors(p);
alter(p, "inc1");
build(p);
// should be some errors:
// error at N:\temp\ajcSandbox\aspectj16_1\ajcTest3209787521625191676.tmp\pr322446_3\src\AbstractAspect.java:5:0::0 can't
// bind type name 'T'
// error at N:\temp\ajcSandbox\aspectj16_1\ajcTest3209787521625191676.tmp\pr322446_3\src\AbstractAspect.java:8:0::0
// Incorrect number of arguments for type AbstractAspect<S>; it cannot be parameterized with arguments <X, Y>
List<IMessage> errors = getErrorMessages(p);
assertTrue(errors != null && errors.size() > 0);
alter(p, "inc2");
build(p);
// that build would contain an exception if the bug were around
assertNoErrors(p);
}
// TODO (asc) these tests don't actually verify anything!
// public void testAtDeclareParents_280658() throws Exception {
// AjdeInteractionTestbed.VERBOSE = true;
// String lib = "pr280658_decp";
// initialiseProject(lib);
// build(lib);
// checkWasFullBuild();
//
// String cli = "pr280658_target";
// initialiseProject(cli);
//
// configureAspectPath(cli, getProjectRelativePath(lib, "bin"));
// build(cli);
// checkWasFullBuild();
// printModel(cli);
// }
//
// public void testAtDeclareMixin_280651() throws Exception {
// AjdeInteractionTestbed.VERBOSE = true;
// String lib = "pr280651_decmix";
// initialiseProject(lib);
// build(lib);
// checkWasFullBuild();
//
// String cli = "pr280658_target";
// initialiseProject(cli);
//
// configureAspectPath(cli, getProjectRelativePath(lib, "bin"));
// build(cli);
// checkWasFullBuild();
// printModel(cli);
// }
// Testing that declare annotation model entries preserve the fully qualified type of the annotation
public void testDecAnnoState_pr286539() throws Exception {
String p = "pr286539";
initialiseProject(p);
build(p);
printModel(p);
IProgramElement decpPE = getModelFor(p).getHierarchy().findElementForHandle(
"=pr286539<p.q.r{Aspect.java'Asp`declare parents");
assertNotNull(decpPE);
String s = ((decpPE.getParentTypes()).get(0));
assertEquals("p.q.r.Int", s);
decpPE = getModelFor(p).getHierarchy().findElementForHandle("=pr286539<p.q.r{Aspect.java'Asp`declare parents!2");
assertNotNull(decpPE);
s = ((decpPE.getParentTypes()).get(0));
assertEquals("p.q.r.Int", s);
IProgramElement decaPE = getModelFor(p).getHierarchy().findElementForHandle(
"=pr286539<p.q.r{Aspect.java'Asp`declare \\@type");
assertNotNull(decaPE);
assertEquals("p.q.r.Foo", decaPE.getAnnotationType());
decaPE = getModelFor(p).getHierarchy().findElementForHandle("=pr286539<p.q.r{Aspect.java'Asp`declare \\@type!2");
assertNotNull(decaPE);
assertEquals("p.q.r.Goo", decaPE.getAnnotationType());
decaPE = getModelFor(p).getHierarchy().findElementForHandle("=pr286539<p.q.r{Aspect.java'Asp`declare \\@field");
assertNotNull(decaPE);
assertEquals("p.q.r.Foo", decaPE.getAnnotationType());
decaPE = getModelFor(p).getHierarchy().findElementForHandle("=pr286539<p.q.r{Aspect.java'Asp`declare \\@method");
assertNotNull(decaPE);
assertEquals("p.q.r.Foo", decaPE.getAnnotationType());
decaPE = getModelFor(p).getHierarchy().findElementForHandle("=pr286539<p.q.r{Aspect.java'Asp`declare \\@constructor");
assertNotNull(decaPE);
assertEquals("p.q.r.Foo", decaPE.getAnnotationType());
}
public void testQualifiedInnerTypeRefs_269082() throws Exception {
String p = "pr269082";
initialiseProject(p);
configureNonStandardCompileOptions(p, "-Xset:minimalModel=false");
build(p);
printModel(p);
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
IProgramElement ipe = findElementAtLine(root, 7);
assertEquals("=pr269082<a{ClassUsingInner.java[ClassUsingInner~foo~QMyInner;~QObject;~QString;", ipe.getHandleIdentifier());
ipe = findElementAtLine(root, 9);
assertEquals("=pr269082<a{ClassUsingInner.java[ClassUsingInner~goo~QClassUsingInner.MyInner;~QObject;~QString;",
ipe.getHandleIdentifier());
ipe = findElementAtLine(root, 11);
assertEquals("=pr269082<a{ClassUsingInner.java[ClassUsingInner~hoo~Qa.ClassUsingInner.MyInner;~QObject;~QString;",
ipe.getHandleIdentifier());
}
// just simple incremental build - no code change, just the aspect touched
public void testIncrementalFqItds_280380() throws Exception {
String p = "pr280380";
initialiseProject(p);
build(p);
// printModel(p);
alter(p, "inc1");
build(p);
// should not be an error about f.AClass not being found
assertNoErrors(p);
// printModel(p);
}
public void testIncrementalAdvisingItdJoinpointsAccessingPrivFields_307120() throws Exception {
String p = "pr307120";
initialiseProject(p);
build(p);
// Hid:1:(targets=1) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) (advised by) =pr307120<{Test.java}Test&before
// Hid:2:(targets=1) =pr307120<{A.java[A (aspect declarations) =pr307120<{Test.java}Test)A.getFoo
// Hid:3:(targets=1) =pr307120<{Test.java}Test&before (advises) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo)
// Hid:4:(targets=1) =pr307120<{Test.java}Test)A.getFoo (declared on) =pr307120<{A.java[A
alter(p, "inc1");
assertEquals(4, getRelationshipCount(p));
build(p);
// Hid:1:(targets=1) =pr307120<{A.java[A (aspect declarations) =pr307120<{Test.java}Test)A.getFoo
// Hid:2:(targets=1) =pr307120<{Test.java}Test)A.getFoo (declared on) =pr307120<{A.java[A
// These two are missing without the fix:
// Hid:1:(targets=1) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) (advised by) =pr307120<{Test.java}Test&before
// Hid:7:(targets=1) =pr307120<{Test.java}Test&before (advises) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo)
assertNoErrors(p);
assertEquals(4, getRelationshipCount(p));
}
public void testIncrementalAdvisingItdJoinpointsAccessingPrivFields_307120_pipelineOff() throws Exception {
String p = "pr307120";
initialiseProject(p);
configureNonStandardCompileOptions(p, "-Xset:pipelineCompilation=false");
build(p);
// Hid:1:(targets=1) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) (advised by) =pr307120<{Test.java}Test&before
// Hid:2:(targets=1) =pr307120<{A.java[A (aspect declarations) =pr307120<{Test.java}Test)A.getFoo
// Hid:3:(targets=1) =pr307120<{Test.java}Test&before (advises) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo)
// Hid:4:(targets=1) =pr307120<{Test.java}Test)A.getFoo (declared on) =pr307120<{A.java[A
alter(p, "inc1");
assertEquals(4, getRelationshipCount(p));
build(p);
// Hid:1:(targets=1) =pr307120<{A.java[A (aspect declarations) =pr307120<{Test.java}Test)A.getFoo
// Hid:2:(targets=1) =pr307120<{Test.java}Test)A.getFoo (declared on) =pr307120<{A.java[A
// These two are missing without the fix:
// Hid:1:(targets=1) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo) (advised by) =pr307120<{Test.java}Test&before
// Hid:7:(targets=1) =pr307120<{Test.java}Test&before (advises) =pr307120<{Test.java}Test)A.getFoo?field-get(int A.foo)
assertNoErrors(p);
assertEquals(4, getRelationshipCount(p));
}
// More sophisticated variant of above.
public void testIncrementalAdvisingItdJoinpointsAccessingPrivFields_307120_2_pipelineOff() throws Exception {
String p = "pr307120_3";
initialiseProject(p);
configureNonStandardCompileOptions(p, "-Xset:pipelineCompilation=false");
build(p);
assertNoErrors(p);
// Hid:1:(targets=1) =pr307120_3<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString; (declared on)
// =pr307120_3<{Target.java[Target
// Hid:2:(targets=1) =pr307120_3<{Target.java[Target (aspect declarations)
// =pr307120_3<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString;
// these are missing under this bug:
// Hid:3:(targets=1) =pr307120_3<{Advisor.java}Advisor&around&QObject;&QObject; (advises)
// =pr307120_3<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString;?field-set(java.lang.String Target.it)
// Hid:4:(targets=1) =pr307120_3<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString;?field-set(java.lang.String
// Target.it) (advised by) =pr307120_3<{Advisor.java}Advisor&around&QObject;&QObject;
assertEquals(4, getRelationshipCount(p));
alter(p, "inc1");
build(p);
assertEquals(4, getRelationshipCount(p));
assertNoErrors(p);
}
// More sophisticated variant of above.
public void testIncrementalAdvisingItdJoinpointsAccessingPrivFields_307120_2() throws Exception {
String p = "pr307120_2";
initialiseProject(p);
build(p);
assertNoErrors(p);
// Hid:2:(targets=1) =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString; (declared on)
// =pr307120_2<{Target.java[Target
// Hid:8:(targets=1) =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.getIt (declared on)
// =pr307120_2<{Target.java[Target
// Hid:5:(targets=2) =pr307120_2<{Target.java[Target (aspect declarations)
// =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.getIt
// Hid:6:(targets=2) =pr307120_2<{Target.java[Target (aspect declarations)
// =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString;
// Hid:1:(targets=1) =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString;?field-set(java.lang.String
// Target.it) (advised by) =pr307120_2<{Advisor.java}Advisor&around&QObject;&QObject;
// Hid:3:(targets=1) =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.getIt?field-get(java.lang.String Target.it)
// (advised by) =pr307120_2<{Advisor.java}Advisor&around&QObject;
// Hid:4:(targets=1) =pr307120_2<{Advisor.java}Advisor&around&QObject; (advises)
// =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.getIt?field-get(java.lang.String Target.it)
// Hid:7:(targets=1) =pr307120_2<{Advisor.java}Advisor&around&QObject;&QObject; (advises)
// =pr307120_2<{TargetAugmenter.java}TargetAugmenter)Target.setIt)QString;?field-set(java.lang.String Target.it)
assertEquals(8, getRelationshipCount(p));
alter(p, "inc1");
build(p);
assertEquals(8, getRelationshipCount(p));
assertNoErrors(p);
}
// // More sophisticated variant of above.
// public void testIncrementalAdvisingItdJoinpointsAccessingPrivFields_307120_4_pipelineOff() throws Exception {
// String p = "pr307120_4";
// initialiseProject(p);
// configureNonStandardCompileOptions(p, "-Xset:pipelineCompilation=false");
// build(p);
// assertNoErrors(p);
//
// printModel(p);
// assertEquals(4, getRelationshipCount(p));
// alter(p, "inc1");
// build(p);
//
// assertEquals(4, getRelationshipCount(p));
// assertNoErrors(p);
// }
// modified aspect so target is fully qualified on the incremental change
public void testIncrementalFqItds_280380_2() throws Exception {
String p = "pr280380";
initialiseProject(p);
build(p);
// printModel(p);
assertEquals(4, getModelFor(p).getRelationshipMap().getEntries().size());
// Hid:1:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx
// Hid:2:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.y
// Hid:3:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new
// Hid:4:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.y (declared on) =pr280380<f{AClass.java[AClass
// Hid:5:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new (declared on) =pr280380<f{AClass.java[AClass
// Hid:6:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx (declared on) =pr280380<f{AClass.java[AClass
alter(p, "inc2");
build(p);
// should not be an error about f.AClass not being found
assertNoErrors(p);
// printModel(p);
assertEquals(4, getModelFor(p).getRelationshipMap().getEntries().size());
// Hid:1:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx
// Hid:2:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.y
// Hid:3:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new
// Hid:4:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.y (declared on) =pr280380<f{AClass.java[AClass
// Hid:5:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new (declared on) =pr280380<f{AClass.java[AClass
// Hid:6:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx (declared on) =pr280380<f{AClass.java[AClass
}
public void testIncrementalFqItds_280380_3() throws Exception {
String p = "pr280380";
initialiseProject(p);
build(p);
// printModel(p);
assertEquals(4, getModelFor(p).getRelationshipMap().getEntries().size());
// Hid:1:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx
// Hid:2:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.y
// Hid:3:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new
// Hid:4:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.y (declared on) =pr280380<f{AClass.java[AClass
// Hid:5:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new (declared on) =pr280380<f{AClass.java[AClass
// Hid:6:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx (declared on) =pr280380<f{AClass.java[AClass
printModel(p);
assertNotNull(getModelFor(p).getRelationshipMap().get("=pr280380<g*AnAspect.aj'AnAspect,AClass.xxxx"));
alter(p, "inc2");
build(p);
assertNoErrors(p);
printModel(p);
// On this build the relationship should have changed to include the fully qualified target
assertEquals(4, getModelFor(p).getRelationshipMap().getEntries().size());
assertNotNull(getModelFor(p).getRelationshipMap().get("=pr280380<g*AnAspect.aj'AnAspect,AClass.xxxx"));
// Hid:1:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx
// Hid:2:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.y
// Hid:3:(targets=3) =pr280380<f{AClass.java[AClass (aspect declarations) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new
// Hid:4:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.y (declared on) =pr280380<f{AClass.java[AClass
// Hid:5:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.AClass_new (declared on) =pr280380<f{AClass.java[AClass
// Hid:6:(targets=1) =pr280380<g*AnAspect.aj}AnAspect)AClass.xxxx (declared on) =pr280380<f{AClass.java[AClass
}
public void testFQItds_322039() throws Exception {
String p = "pr322039";
initialiseProject(p);
build(p);
printModel(p);
IRelationshipMap irm = getModelFor(p).getRelationshipMap();
List<IRelationship> rels = irm.get("=pr322039<p{Azpect.java'Azpect)q2.Code.something2");
assertNotNull(rels);
}
public void testIncrementalCtorItdHandle_280383() throws Exception {
String p = "pr280383";
initialiseProject(p);
build(p);
printModel(p);
IRelationshipMap irm = getModelFor(p).getRelationshipMap();
List<IRelationship> rels = irm.get("=pr280383<f{AnAspect.java'AnAspect)f.AClass.f_AClass_new");
assertNotNull(rels);
}
// public void testArraysGenerics() throws Exception {
// String p = "pr283864";
// initialiseProject(p);
// build(p);
// printModel(p);
// // IRelationshipMap irm = getModelFor(p).getRelationshipMap();
// // List rels = irm.get("=pr280383<f{AnAspect.java}AnAspect)f.AClass.f_AClass_new");
// // assertNotNull(rels);
// }
public void testSimilarITDS() throws Exception {
String p = "pr283657";
initialiseProject(p);
build(p);
printModel(p);
// Hid:1:(targets=1) =pr283657<{Aspect.java}Aspect)Target.foo (declared on) =pr283657<{Aspect.java[Target
// Hid:2:(targets=1) =pr283657<{Aspect.java}Aspect)Target.foo!2 (declared on) =pr283657<{Aspect.java[Target
// Hid:3:(targets=2) =pr283657<{Aspect.java[Target (aspect declarations) =pr283657<{Aspect.java}Aspect)Target.foo
// Hid:4:(targets=2) =pr283657<{Aspect.java[Target (aspect declarations) =pr283657<{Aspect.java}Aspect)Target.foo!2
IRelationshipMap irm = getModelFor(p).getRelationshipMap();
List<IRelationship> rels = irm.get("=pr283657<{Aspect.java'Aspect,Target.foo");
assertNotNull(rels);
rels = irm.get("=pr283657<{Aspect.java'Aspect)Target.foo!2");
assertNotNull(rels);
}
public void testIncrementalAnnotationMatched_276399() throws Exception {
String p = "pr276399";
initialiseProject(p);
addSourceFolderForSourceFile(p, getProjectRelativePath(p, "src/X.aj"), "src");
addSourceFolderForSourceFile(p, getProjectRelativePath(p, "src/C.java"), "src");
build(p);
IRelationshipMap irm = getModelFor(p).getRelationshipMap();
IRelationship ir = irm.get("=pr276399/src<*X.aj'X&after").get(0);
assertNotNull(ir);
alter(p, "inc1");
build(p);
printModel(p);
irm = getModelFor(p).getRelationshipMap();
List<IRelationship> rels = irm.get("=pr276399/src<*X.aj'X&after"); // should be gone after the inc build
assertNull(rels);
}
public void testHandleCountDecA_pr278255() throws Exception {
String p = "pr278255";
initialiseProject(p);
build(p);
printModelAndRelationships(p);
IRelationshipMap irm = getModelFor(p).getRelationshipMap();
List<IRelationship> l = irm.get("=pr278255<{A.java'X`declare \\@type");
assertNotNull(l);
IRelationship ir = l.get(0);
assertNotNull(ir);
}
public void testIncrementalItdDefaultCtor() {
String p = "pr275032";
initialiseProject(p);
build(p);
assertEquals(0, getErrorMessages(p).size());
alter(p, "inc1");
build(p);
// error is: inter-type declaration from X conflicts with existing member: void A.<init>()
// List ms =
getErrorMessages(p);
assertEquals(4, getErrorMessages(p).size());
// Why 4 errors? I believe the problem is:
// 2 errors are reported when there is a clash - one against the aspect, one against the affected target type.
// each of the two errors are recorded against the compilation result for the aspect and the target
// So it comes out as 4 - but for now I am tempted to leave it because at least it shows there is a problem...
assertTrue("Was:" + getErrorMessages(p).get(0), getErrorMessages(p).get(0).toString().indexOf("conflicts") != -1);
}
public void testOutputLocationCallbacks2() {
String p = "pr268827_ol_res";
initialiseProject(p);
Map<String,File> m = new HashMap<String,File>();
m.put("a.txt", new File(getFile(p, "src/a.txt")));
configureResourceMap(p, m);
CustomOLM olm = new CustomOLM(getProjectRelativePath(p, ".").toString());
configureOutputLocationManager(p, olm);
build(p);
checkCompileWeaveCount(p, 2, 2);
assertEquals(3, olm.writeCount);
alter(p, "inc1"); // this contains a new B.java that doesn't have the aspect inside it
build(p);
checkCompileWeaveCount(p, 3, 1);
assertEquals(1, olm.removeCount); // B.class removed
}
public void testOutputLocationCallbacks() {
String p = "pr268827_ol";
initialiseProject(p);
CustomOLM olm = new CustomOLM(getProjectRelativePath(p, ".").toString());
configureOutputLocationManager(p, olm);
build(p);
checkCompileWeaveCount(p, 2, 3);
alter(p, "inc1"); // this contains a new Foo.java that no longer has Extra class in it
build(p);
checkCompileWeaveCount(p, 1, 1);
assertEquals(1, olm.removeCount);
}
public void testOutputLocationCallbacksFileAdd() {
String p = "pr268827_ol2";
initialiseProject(p);
CustomOLM olm = new CustomOLM(getProjectRelativePath(p, ".").toString());
configureOutputLocationManager(p, olm);
build(p);
assertEquals(3, olm.writeCount);
olm.writeCount = 0;
checkCompileWeaveCount(p, 2, 3);
alter(p, "inc1"); // this contains a new file Boo.java
build(p);
assertEquals(1, olm.writeCount);
checkCompileWeaveCount(p, 1, 1);
// assertEquals(1, olm.removeCount);
}
static class CustomOLM extends TestOutputLocationManager {
public int writeCount = 0;
public int removeCount = 0;
public CustomOLM(String testProjectPath) {
super(testProjectPath);
}
@Override
public void reportFileWrite(String outputfile, int filetype) {
super.reportFileWrite(outputfile, filetype);
writeCount++;
System.out.println("Written " + outputfile);
// System.out.println("Written " + outputfile + " " + filetype);
}
@Override
public void reportFileRemove(String outputfile, int filetype) {
super.reportFileRemove(outputfile, filetype);
removeCount++;
System.out.println("Removed " + outputfile);
// System.out.println("Removed " + outputfile + " " + filetype);
}
}
public void testBrokenCodeDeca_268611() {
String p = "pr268611";
initialiseProject(p);
build(p);
checkWasFullBuild();
assertEquals(1, getErrorMessages(p).size());
assertTrue(((Message) getErrorMessages(p).get(0)).getMessage().indexOf(
"Syntax error on token \")\", \"name pattern\" expected") != -1);
}
public void testIncrementalMixin() {
String p = "mixin";
initialiseProject(p);
build(p);
checkWasFullBuild();
assertEquals(0, getErrorMessages(p).size());
alter(p, "inc1");
build(p);
checkWasntFullBuild();
assertEquals(0, getErrorMessages(p).size());
}
public void testUnusedPrivates_pr266420() {
String p = "pr266420";
initialiseProject(p);
Hashtable<String,String> javaOptions = new Hashtable<String,String>();
javaOptions.put("org.eclipse.jdt.core.compiler.compliance", "1.6");
javaOptions.put("org.eclipse.jdt.core.compiler.codegen.targetPlatform", "1.6");
javaOptions.put("org.eclipse.jdt.core.compiler.source", "1.6");
javaOptions.put("org.eclipse.jdt.core.compiler.problem.unusedPrivateMember", "warning");
configureJavaOptionsMap(p, javaOptions);
build(p);
checkWasFullBuild();
List<IMessage> warnings = getWarningMessages(p);
assertEquals(0, warnings.size());
alter(p, "inc1");
build(p);
checkWasntFullBuild();
warnings = getWarningMessages(p);
assertEquals(0, warnings.size());
}
public void testExtendingITDAspectOnClasspath_PR298704() throws Exception {
String base = "pr298704_baseaspects";
String test = "pr298704_testaspects";
initialiseProject(base);
initialiseProject(test);
configureNewProjectDependency(test, base);
build(base);
build(test);
checkWasFullBuild();
assertNoErrors(test);
IRelationshipMap irm = getModelFor(test).getRelationshipMap();
assertEquals(7, irm.getEntries().size());
}
public void testPR265729() {
AjdeInteractionTestbed.VERBOSE = true;
String lib = "pr265729_lib";
initialiseProject(lib);
// addClasspathEntryChanged(lib, getProjectRelativePath(p1,
// "bin").toString());
build(lib);
checkWasFullBuild();
String cli = "pr265729_client";
initialiseProject(cli);
// addClasspathEntry(cli, new File("../lib/junit/junit.jar"));
configureAspectPath(cli, getProjectRelativePath(lib, "bin"));
build(cli);
checkWasFullBuild();
IProgramElement root = getModelFor(cli).getHierarchy().getRoot();
// dumptree(root, 0);
// PrintWriter pw = new PrintWriter(System.out);
// try {
// getModelFor(cli).dumprels(pw);
// pw.flush();
// } catch (Exception e) {
// }
IRelationshipMap irm = getModelFor(cli).getRelationshipMap();
IRelationship ir = irm.get("=pr265729_client<be.cronos.aop{App.java[App").get(0);
// This type should be affected by an ITD and a declare parents
// could be either way round
String h1 = ir.getTargets().get(0);
String h2 = ir.getTargets().get(1);
// For some ITD: public void I.g(String s) {}
// Node in tree: I.g(java.lang.String) [inter-type method]
// Handle: =pr265729_client<be.cronos.aop{App.java}X)I.g)QString;
if (!h1.endsWith("parents")) {
String h3 = h1;
h1 = h2;
h2 = h3;
}
// ITD from the test program:
// public String InterTypeAspectInterface.foo(int i,List list,App a) {
assertEquals("=pr265729_client/binaries<be.cronos.aop.aspects(InterTypeAspect.class'InterTypeAspect`declare parents", h1);
assertEquals(
"=pr265729_client/binaries<be.cronos.aop.aspects(InterTypeAspect.class'InterTypeAspect)InterTypeAspectInterface.foo)I)QList;)QSerializable;",
h2);
IProgramElement binaryDecp = getModelFor(cli).getHierarchy().getElement(h1);
assertNotNull(binaryDecp);
IProgramElement binaryITDM = getModelFor(cli).getHierarchy().getElement(h2);
assertNotNull(binaryITDM);
// @see AsmRelationshipProvider.createIntertypeDeclaredChild()
List<char[]> ptypes = binaryITDM.getParameterTypes();
assertEquals("int", new String((char[]) ptypes.get(0)));
assertEquals("java.util.List", new String((char[]) ptypes.get(1)));
assertEquals("java.io.Serializable", new String((char[]) ptypes.get(2)));
// param names not set
// List pnames = binaryITDM.getParameterNames();
// assertEquals("i", new String((char[]) pnames.get(0)));
// assertEquals("list", new String((char[]) pnames.get(1)));
// assertEquals("b", new String((char[]) pnames.get(2)));
assertEquals("java.lang.String", binaryITDM.getCorrespondingType(true));
}
public void testXmlConfiguredProject() {
AjdeInteractionTestbed.VERBOSE = true;
String p = "xmlone";
initialiseProject(p);
configureNonStandardCompileOptions(p, "-showWeaveInfo");// -xmlConfigured");
configureShowWeaveInfoMessages(p, true);
addXmlConfigFile(p, getProjectRelativePath(p, "p/aop.xml").toString());
build(p);
checkWasFullBuild();
List<IMessage> weaveMessages = getWeavingMessages(p);
if (weaveMessages.size() != 1) {
for (Iterator<IMessage> iterator = weaveMessages.iterator(); iterator.hasNext();) {
Object object = iterator.next();
System.out.println(object);
}
fail("Expected just one weave message. The aop.xml should have limited the weaving");
}
}
public void testDeclareParentsInModel() {
String p = "decps";
initialiseProject(p);
build(p);
IProgramElement decp = getModelFor(p).getHierarchy().findElementForHandle("=decps<a{A.java'A`declare parents");
List<String> ps = decp.getParentTypes();
assertNotNull(ps);
assertEquals(2, ps.size());
int count = 0;
for (Iterator<String> iterator = ps.iterator(); iterator.hasNext();) {
String type = iterator.next();
if (type.equals("java.io.Serializable")) {
count++;
}
if (type.equals("a.Goo")) {
count++;
}
}
assertEquals("Should have found the two types in: " + ps, 2, count);
}
public void testConstructorAdvice_pr261380() throws Exception {
String p = "261380";
initialiseProject(p);
build(p);
IRelationshipMap irm = getModelFor(p).getRelationshipMap();
IRelationship ir = irm.get("=261380<test{C.java'X&before").get(0);
List<String> targets = ir.getTargets();
assertEquals(1, targets.size());
System.out.println(targets.get(0));
String handle = (String) targets.get(0);
assertEquals("Expected the handle for the code node inside the constructor decl",
"=261380<test{C.java[C~C?constructor-call(void test.C.<init>())", handle);
}
/*
* A.aj package pack; public aspect A { pointcut p() : call( C.method before() : p() { // line 7 } }
*
* C.java package pack; public class C { public void method1() { method2(); // line 6 } public void method2() { } public void
* method3() { method2(); // line 13 }
*
* }
*/
public void testDontLoseAdviceMarkers_pr134471() {
try {
// see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=false;
initialiseProject("P4");
build("P4");
Ajc.dumpAJDEStructureModel(getModelFor("P4"), "after full build where advice is applying");
// should be 4 relationship entries
// In inc1 the first advised line is 'commented out'
alter("P4", "inc1");
build("P4");
checkWasntFullBuild();
Ajc.dumpAJDEStructureModel(getModelFor("P4"), "after inc build where first advised line is gone");
// should now be 2 relationship entries
// This will be the line 6 entry in C.java
IProgramElement codeElement = findCode(checkForNode(getModelFor("P4"), "pack", "C", true));
// This will be the line 7 entry in A.java
IProgramElement advice = findAdvice(checkForNode(getModelFor("P4"), "pack", "A", true));
IRelationshipMap asmRelMap = getModelFor("P4").getRelationshipMap();
assertEquals("There should be two relationships in the relationship map", 2, asmRelMap.getEntries().size());
for (Iterator<String> iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = getModelFor("P4").getHierarchy().findElementForHandle(sourceOfRelationship);
assertNotNull("expected to find IProgramElement with handle " + sourceOfRelationship + " but didn't", ipe);
if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) {
assertEquals("expected source of relationship to be " + advice.toString() + " but found " + ipe.toString(),
advice, ipe);
} else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
assertEquals(
"expected source of relationship to be " + codeElement.toString() + " but found " + ipe.toString(),
codeElement, ipe);
} else {
fail("found unexpected relationship source " + ipe + " with kind " + ipe.getKind()
+ " when looking up handle: " + sourceOfRelationship);
}
List<IRelationship> relationships = asmRelMap.get(ipe);
assertNotNull("expected " + ipe.getName() + " to have some " + "relationships", relationships);
for (Iterator<IRelationship> iterator = relationships.iterator(); iterator.hasNext();) {
Relationship rel = (Relationship) iterator.next();
List<String> targets = rel.getTargets();
for (Iterator<String> iterator2 = targets.iterator(); iterator2.hasNext();) {
String t = (String) iterator2.next();
IProgramElement link = getModelFor("P4").getHierarchy().findElementForHandle(t);
if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) {
assertEquals(
"expected target of relationship to be " + codeElement.toString() + " but found "
+ link.toString(), codeElement, link);
} else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
assertEquals(
"expected target of relationship to be " + advice.toString() + " but found " + link.toString(),
advice, link);
} else {
fail("found unexpected relationship source " + ipe.getName() + " with kind " + ipe.getKind());
}
}
}
}
} finally {
// see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=true;
// configureBuildStructureModel(false);
}
}
public void testPr148285() {
String p = "PR148285_2";
initialiseProject(p); // Single source file A.aj defines A and C
build(p);
checkWasFullBuild();
alter(p, "inc1"); // Second source introduced C.java, defines C
build(p);
checkWasntFullBuild();
List msgs = getErrorMessages(p);
assertEquals("error message should be 'The type C is already defined' ", "The type C is already defined",
((IMessage) msgs.get(0)).getMessage());
alter("PR148285_2", "inc2"); // type C in A.aj is commented out
build("PR148285_2");
checkWasntFullBuild();
msgs = getErrorMessages(p);
assertTrue("There should be no errors reported:\n" + getErrorMessages(p), msgs.isEmpty());
}
public void testIncrementalAndAnnotations() {
initialiseProject("Annos");
build("Annos");
checkWasFullBuild();
checkCompileWeaveCount("Annos", 4, 4);
AsmManager model = getModelFor("Annos");
assertEquals("Should be 3 relationships ", 3, model.getRelationshipMap().getEntries().size());
alter("Annos", "inc1"); // Comment out the annotation on Parent
build("Annos");
checkWasntFullBuild();
assertEquals("Should be no relationships ", 0, model.getRelationshipMap().getEntries().size());
checkCompileWeaveCount("Annos", 3, 3);
alter("Annos", "inc2"); // Add the annotation back onto Parent
build("Annos");
checkWasntFullBuild();
assertEquals("Should be 3 relationships ", 3, model.getRelationshipMap().getEntries().size());
checkCompileWeaveCount("Annos", 3, 3);
}
// package a.b.c;
//
// public class A {
// }
//
// aspect X {
// B A.foo(C c) { return null; }
// declare parents: A implements java.io.Serializable;
// }
//
// class B {}
// class C {}
public void testITDFQNames_pr252702() {
String p = "itdfq";
AjdeInteractionTestbed.VERBOSE = true;
initialiseProject(p);
build(p);
AsmManager model = getModelFor(p);
dumptree(model.getHierarchy().getRoot(), 0);
IProgramElement root = model.getHierarchy().getRoot();
ProgramElement theITD = (ProgramElement) findElementAtLine(root, 7);
Map<String, Object> m = theITD.kvpairs;
for (Iterator<String> iterator = m.keySet().iterator(); iterator.hasNext();) {
String type = iterator.next();
System.out.println(type + " = " + m.get(type));
}
// return type of the ITD
assertEquals("a.b.c.B", theITD.getCorrespondingType(true));
List<char[]> ptypes = theITD.getParameterTypes();
for (Iterator<char[]> iterator = ptypes.iterator(); iterator.hasNext();) {
char[] object = iterator.next();
System.out.println("p = " + new String(object));
}
ProgramElement decp = (ProgramElement) findElementAtLine(root, 8);
m = decp.kvpairs;
for (Iterator<String> iterator = m.keySet().iterator(); iterator.hasNext();) {
String type = iterator.next();
System.out.println(type + " = " + m.get(type));
}
List<String> l = decp.getParentTypes();
assertEquals("java.io.Serializable", l.get(0));
ProgramElement ctorDecp = (ProgramElement) findElementAtLine(root, 16);
String ctordecphandle = ctorDecp.getHandleIdentifier();
assertEquals("=itdfq<a.b.c{A.java'XX)B.B_new)QString;", ctordecphandle); // 252702
// ,
// comment
// 7
}
public void testBrokenHandles_pr247742() {
String p = "BrokenHandles";
initialiseProject(p);
// alter(p, "inc1");
build(p);
// alter(p, "inc2");
// build(p);
AsmManager model = getModelFor(p);
dumptree(model.getHierarchy().getRoot(), 0);
IProgramElement root = model.getHierarchy().getRoot();
IProgramElement ipe = findElementAtLine(root, 4);
assertEquals("=BrokenHandles<p{GetInfo.java'GetInfo`declare warning", ipe.getHandleIdentifier());
ipe = findElementAtLine(root, 5);
assertEquals("=BrokenHandles<p{GetInfo.java'GetInfo`declare warning!2", ipe.getHandleIdentifier());
ipe = findElementAtLine(root, 6);
assertEquals("=BrokenHandles<p{GetInfo.java'GetInfo`declare parents", ipe.getHandleIdentifier());
}
public void testNPEIncremental_pr262218() {
AjdeInteractionTestbed.VERBOSE = true;
String p = "pr262218";
initialiseProject(p);
build(p);
checkWasFullBuild();
alter(p, "inc1");
build(p);
checkWasntFullBuild();
List l = getCompilerErrorMessages(p);
assertEquals("Unexpected compiler error", 0, l.size());
}
public void testDeclareAnnotationNPE_298504() {
AjdeInteractionTestbed.VERBOSE = true;
String p = "pr298504";
initialiseProject(p);
build(p);
List l = getErrorMessages(p);
assertTrue(l.toString().indexOf("ManagedResource cannot be resolved to a type") != -1);
// checkWasFullBuild();
alter(p, "inc1");
build(p);
// checkWasntFullBuild();
l = getCompilerErrorMessages(p);
assertTrue(l.toString().indexOf("NullPointerException") == -1);
l = getErrorMessages(p);
assertTrue(l.toString().indexOf("ManagedResource cannot be resolved to a type") != -1);
}
public void testIncrementalAnnoStyle_pr286341() {
AjdeInteractionTestbed.VERBOSE = true;
String base = "pr286341_base";
initialiseProject(base);
build(base);
checkWasFullBuild();
String p = "pr286341";
initialiseProject(p);
configureAspectPath(p, getProjectRelativePath(base, "bin"));
addClasspathEntry(p, getProjectRelativePath(base, "bin"));
build(p);
checkWasFullBuild();
assertNoErrors(p);
alter(p, "inc1");
build(p);
checkWasntFullBuild();
assertNoErrors(p);
}
public void testImports_pr263487() {
String p2 = "importProb2";
initialiseProject(p2);
build(p2);
checkWasFullBuild();
String p = "importProb";
initialiseProject(p);
build(p);
configureAspectPath(p, getProjectRelativePath(p2, "bin"));
checkWasFullBuild();
build(p);
build(p);
build(p);
alter(p, "inc1");
addProjectSourceFileChanged(p, getProjectRelativePath(p, "src/p/Code.java"));
// addProjectSourceFileChanged(p, getProjectRelativePath(p,
// "src/q/Asp.java"));
build(p);
checkWasntFullBuild();
List<IMessage> l = getCompilerErrorMessages(p);
assertEquals("Unexpected compiler error", 0, l.size());
}
public void testBuildingBrokenCode_pr263323() {
AjdeInteractionTestbed.VERBOSE = true;
String p = "brokenCode";
initialiseProject(p);
build(p);
checkWasFullBuild();
alter(p, "inc1"); // break the aspect
build(p);
checkWasntFullBuild();
alter(p, "inc2"); // whitespace change on affected file
build(p);
checkWasntFullBuild();
List l = getCompilerErrorMessages(p);
assertEquals("Unexpected compiler error", 0, l.size());
}
/*
* public void testNPEGenericCtor_pr260944() { AjdeInteractionTestbed.VERBOSE = true; String p = "pr260944";
* initialiseProject(p); build(p); checkWasFullBuild(); alter(p, "inc1"); build(p); checkWasntFullBuild(); List l =
* getCompilerErrorMessages(p); assertEquals("Unexpected compiler error", 0, l.size()); }
*/
public void testItdProb() {
AjdeInteractionTestbed.VERBOSE = true;
String p = "itdprob";
initialiseProject(p);
build(p);
checkWasFullBuild();
alter(p, "inc1");
build(p);
checkWasntFullBuild();
List<IMessage> l = getCompilerErrorMessages(p);
assertEquals("Unexpected compiler error", 0, l.size());
}
/*
* public void testGenericITD_pr262257() throws IOException { String p = "pr262257"; initialiseProject(p); build(p);
* checkWasFullBuild();
*
* dumptree(getModelFor(p).getHierarchy().getRoot(), 0); PrintWriter pw = new PrintWriter(System.out);
* getModelFor(p).dumprels(pw); pw.flush(); }
*/
public void testAnnotations_pr262154() {
String p = "pr262154";
initialiseProject(p);
build(p);
checkWasFullBuild();
alter(p, "inc1");
build(p);
List<IMessage> l = getCompilerErrorMessages(p);
assertEquals("Unexpected compiler error", 0, l.size());
}
public void testAnnotations_pr255555() {
String p = "pr255555";
initialiseProject(p);
build(p);
checkCompileWeaveCount(p, 2, 1);
}
public void testSpacewarHandles() {
// String p = "SpaceWar";
String p = "Simpler";
initialiseProject(p);
build(p);
dumptree(getModelFor(p).getHierarchy().getRoot(), 0);
// incomplete
}
/**
* Test what is in the model for package declarations and import statements. Package Declaration nodes are new in AspectJ 1.6.4.
* Import statements are contained with an 'import references' node.
*/
public void testImportHandles() {
String p = "Imports";
initialiseProject(p);
configureNonStandardCompileOptions(p, "-Xset:minimalModel=false");
build(p);
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
// Looking for 'package p.q'
IProgramElement ipe = findFile(root, "Example.aj");// findElementAtLine(root, 1);
ipe = ipe.getChildren().get(0); // package decl is first entry in the type
assertEquals(IProgramElement.Kind.PACKAGE_DECLARATION, ipe.getKind());
assertEquals("package p.q;", ipe.getSourceSignature());
assertEquals("=Imports<p.q*Example.aj%p.q", ipe.getHandleIdentifier());
assertEquals(ipe.getSourceLocation().getOffset(), 8); // "package p.q" - location of p.q
// Looking for import containing containing string and integer
ipe = findElementAtLine(root, 3); // first import
ipe = ipe.getParent(); // imports container
assertEquals("=Imports<p.q*Example.aj#", ipe.getHandleIdentifier());
}
public void testAdvisingCallJoinpointsInITDS_pr253067() {
String p = "pr253067";
initialiseProject(p);
build(p);
// Check for a code node at line 5 - if there is one then we created it
// correctly when building
// the advice relationship
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
IProgramElement code = findElementAtLine(root, 5);
assertEquals("=pr253067<aa*AdvisesC.aj'AdvisesC)C.nothing?method-call(int aa.C.nothing())", code.getHandleIdentifier());
// dumptree(getModelFor(p).getHierarchy().getRoot(), 0);
// Ajc.dumpAJDEStructureModel(getModelFor("pr253067"),
// "after inc build where first advised line is gone");
}
public void testHandles_DeclareAnno_pr249216_c9() {
String p = "pr249216";
initialiseProject(p);
build(p);
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
IProgramElement code = findElementAtLine(root, 4);
// the @ should be escapified
assertEquals("=pr249216<{Deca.java'X`declare \\@type", code.getHandleIdentifier());
// dumptree(getModelFor(p).getHierarchy().getRoot(), 0);
// Ajc.dumpAJDEStructureModel(getModelFor(p),
// "after inc build where first advised line is gone");
}
public void testNullDelegateBrokenCode_pr251940() {
String p = "pr251940";
initialiseProject(p);
build(p);
checkForError(p, "The type F must implement the inherited");
}
public void testBeanExample() throws Exception {
String p = "BeanExample";
initialiseProject(p);
build(p);
dumptree(getModelFor(p).getHierarchy().getRoot(), 0);
PrintWriter pw = new PrintWriter(System.out);
getModelFor(p).dumprels(pw);
pw.flush();
// incomplete
}
// private void checkIfContainsFile(Set s, String filename, boolean shouldBeFound) {
// StringBuffer sb = new StringBuffer("Set of files\n");
// for (Iterator iterator = s.iterator(); iterator.hasNext();) {
// Object object = iterator.next();
// sb.append(object).append("\n");
// }
// for (Iterator iterator = s.iterator(); iterator.hasNext();) {
// File fname = (File) iterator.next();
// if (fname.getName().endsWith(filename)) {
// if (!shouldBeFound) {
// System.out.println(sb.toString());
// fail("Unexpectedly found file " + filename);
// } else {
// return;
// }
// }
// }
// if (shouldBeFound) {
// System.out.println(sb.toString());
// fail("Did not find filename " + filename);
// }
// }
// /**
// * Checking return values of the AsmManager API calls that can be invoked
// post incremental build that tell the caller which
// * files had their relationships altered. As well as the affected (woven)
// files, it is possible to query the aspects that wove
// * those files.
// */
// public void testChangesOnBuild() throws Exception {
// String p = "ChangesOnBuild";
// initialiseProject(p);
// build(p);
// // Not incremental
// checkIfContainsFile(AsmManager.getDefault().getModelChangesOnLastBuild(),
// "A.java", false);
// alter(p, "inc1");
// build(p);
// // Incremental
// checkIfContainsFile(AsmManager.getDefault().getModelChangesOnLastBuild(),
// "A.java", true);
// checkIfContainsFile(AsmManager.getDefault().
// getAspectsWeavingFilesOnLastBuild(), "X.java", true);
// checkIfContainsFile(AsmManager.getDefault().
// getAspectsWeavingFilesOnLastBuild(), "Y.java", false);
// }
public void testITDIncremental_pr192877() {
String p = "PR192877";
initialiseProject(p);
build(p);
checkWasFullBuild();
alter(p, "inc1");
build(p);
checkWasntFullBuild();
}
public void testIncrementalBuildsWithItds_pr259528() {
String p = "pr259528";
AjdeInteractionTestbed.VERBOSE = true;
initialiseProject(p);
build(p);
checkWasFullBuild();
alter(p, "inc1");
build(p);
checkWasntFullBuild();
}
public void testAdviceHandlesAreJDTCompatible() {
String p = "AdviceHandles";
initialiseProject(p);
addSourceFolderForSourceFile(p, getProjectRelativePath(p, "src/Handles.aj"), "src");
build(p);
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
IProgramElement typeDecl = findElementAtLine(root, 4);
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles", typeDecl.getHandleIdentifier());
IProgramElement advice1 = findElementAtLine(root, 7);
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles&before", advice1.getHandleIdentifier());
IProgramElement advice2 = findElementAtLine(root, 11);
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles&before!2", advice2.getHandleIdentifier());
IProgramElement advice3 = findElementAtLine(root, 15);
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles&before&I", advice3.getHandleIdentifier());
IProgramElement advice4 = findElementAtLine(root, 20);
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles&before&I!2", advice4.getHandleIdentifier());
IProgramElement advice5 = findElementAtLine(root, 25);
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles&after", advice5.getHandleIdentifier());
IProgramElement advice6 = findElementAtLine(root, 30);
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles&afterReturning", advice6.getHandleIdentifier());
IProgramElement advice7 = findElementAtLine(root, 35);
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles&afterThrowing", advice7.getHandleIdentifier());
IProgramElement advice8 = findElementAtLine(root, 40);
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles&afterThrowing&I", advice8.getHandleIdentifier());
IProgramElement namedInnerClass = findElementAtLine(root, 46);
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles~x[NamedClass", namedInnerClass.getHandleIdentifier());
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles~foo[", findElementAtLine(root, 55).getHandleIdentifier());
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles~foo[!2", findElementAtLine(root, 56).getHandleIdentifier());
// From 247742: comment 3: two anon class declarations
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles~b~QString;[", findElementAtLine(root, 62)
.getHandleIdentifier());
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles~b~QString;[!2", findElementAtLine(root, 63)
.getHandleIdentifier());
// From 247742: comment 6: two diff anon class declarations
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles~c~QString;[", findElementAtLine(root, 66)
.getHandleIdentifier());
assertEquals("=AdviceHandles/src<spacewar*Handles.aj'Handles~c~QString;[!2", findElementAtLine(root, 67)
.getHandleIdentifier());
// // From 247742: comment 4
// assertEquals(
// "=AdviceHandles/src<spacewar*Handles.aj}Foo&afterReturning&QString;",
// findElementAtLine(root,
// 72).getHandleIdentifier());
// assertEquals(
// "=AdviceHandles/src<spacewar*Handles.aj}Foo&afterReturning&QString;!2"
// , findElementAtLine(root,
// 73).getHandleIdentifier());
}
// Testing code handles - should they included positional information? seems
// to be what AJDT wants but we
// only have the declaration start position in the programelement
// public void testHandlesForCodeElements() {
// String p = "CodeHandles";
// initialiseProject(p);
// addSourceFolderForSourceFile(p, getProjectRelativePath(p,
// "src/Handles.aj"), "src");
// build(p);
// IProgramElement root = AsmManager.getDefault().getHierarchy().getRoot();
// IProgramElement typeDecl = findElementAtLine(root, 3);
// assertEquals("=CodeHandles/src<spacewar*Handles.aj[C",
// typeDecl.getHandleIdentifier());
//
// IProgramElement code = findElementAtLine(root, 6);
// assertEquals(
// "=CodeHandles/src<spacewar*Handles.aj[C~m?method-call(void spacewar.C.foo(int))"
// , code.getHandleIdentifier());
// code = findElementAtLine(root, 7);
// assertEquals(
// "=CodeHandles/src<spacewar*Handles.aj[C~m?method-call(void spacewar.C.foo(int))!2"
// , code.getHandleIdentifier());
//
// }
private IProgramElement findFile(IProgramElement whereToLook, String filesubstring) {
if (whereToLook.getSourceLocation() != null && whereToLook.getKind().isSourceFile()
&& whereToLook.getSourceLocation().getSourceFile().toString().indexOf(filesubstring) != -1) {
return whereToLook;
}
for (IProgramElement element : whereToLook.getChildren()) {
Kind k = element.getKind();
ISourceLocation sloc = element.getSourceLocation();
if (sloc != null && k.isSourceFile() && sloc.getSourceFile().toString().indexOf(filesubstring) != -1) {
return element;
}
if (k.isSourceFile()) {
continue; // no need to look further down
}
IProgramElement gotSomething = findFile(element, filesubstring);
if (gotSomething != null) {
return gotSomething;
}
}
return null;
}
private IProgramElement findElementAtLine(IProgramElement whereToLook, int line) {
if (whereToLook == null) {
return null;
}
if (whereToLook.getSourceLocation() != null && whereToLook.getSourceLocation().getLine() == line) {
return whereToLook;
}
for (IProgramElement object : whereToLook.getChildren()) {
if (object.getSourceLocation() != null && object.getSourceLocation().getLine() == line) {
return object;
}
IProgramElement gotSomething = findElementAtLine(object, line);
if (gotSomething != null) {
return gotSomething;
}
}
return null;
}
public void testModelWithMultipleSourceFolders() {
initialiseProject("MultiSource");
// File sourceFolderOne = getProjectRelativePath("MultiSource", "src1");
// File sourceFolderTwo = getProjectRelativePath("MultiSource", "src2");
// File sourceFolderThree = getProjectRelativePath("MultiSource",
// "src3");
// src1 source folder slashed as per 264563
addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src1/CodeOne.java"), "src1/");
addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src2/CodeTwo.java"), "src2");
addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src3/pkg/CodeThree.java"), "src3");
build("MultiSource");
IProgramElement srcOne = getModelFor("MultiSource").getHierarchy().findElementForHandle("=MultiSource/src1");
IProgramElement CodeOneClass = getModelFor("MultiSource").getHierarchy().findElementForHandle(
"=MultiSource/src1{CodeOne.java[CodeOne");
IProgramElement srcTwoPackage = getModelFor("MultiSource").getHierarchy().findElementForHandle("=MultiSource/src2<pkg");
IProgramElement srcThreePackage = getModelFor("MultiSource").getHierarchy().findElementForHandle("=MultiSource/src3<pkg");
assertNotNull(srcOne);
assertNotNull(CodeOneClass);
assertNotNull(srcTwoPackage);
assertNotNull(srcThreePackage);
if (srcTwoPackage.equals(srcThreePackage)) {
throw new RuntimeException(
"Should not have found these package nodes to be the same, they are in different source folders");
}
// dumptree(AsmManager.getDefault().getHierarchy().getRoot(), 0);
}
// Now the source folders are more complex 'src/java/main' and
// 'src/java/tests'
public void testModelWithMultipleSourceFolders2() {
initialiseProject("MultiSource");
// File sourceFolderOne = getProjectRelativePath("MultiSource",
// "src/java/main");
// File sourceFolderTwo = getProjectRelativePath("MultiSource", "src2");
// File sourceFolderThree = getProjectRelativePath("MultiSource",
// "src3");
addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src1/CodeOne.java"), "src/java/main");
addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src2/CodeTwo.java"), "src/java/main");
addSourceFolderForSourceFile("MultiSource", getProjectRelativePath("MultiSource", "src3/pkg/CodeThree.java"),
"src/java/tests");
build("MultiSource");
IProgramElement srcOne = getModelFor("MultiSource").getHierarchy().findElementForHandleOrCreate(
"=MultiSource/src\\/java\\/main", false);
IProgramElement CodeOneClass = getModelFor("MultiSource").getHierarchy().findElementForHandle(
"=MultiSource/src\\/java\\/main{CodeOne.java[CodeOne");
IProgramElement srcTwoPackage = getModelFor("MultiSource").getHierarchy().findElementForHandle(
"=MultiSource/src\\/java\\/tests<pkg");
IProgramElement srcThreePackage = getModelFor("MultiSource").getHierarchy().findElementForHandle(
"=MultiSource/src\\/java\\/testssrc3<pkg");
assertNotNull(srcOne);
assertNotNull(CodeOneClass);
assertNotNull(srcTwoPackage);
assertNotNull(srcThreePackage);
if (srcTwoPackage.equals(srcThreePackage)) {
throw new RuntimeException(
"Should not have found these package nodes to be the same, they are in different source folders");
}
// dumptree(AsmManager.getDefault().getHierarchy().getRoot(), 0);
}
public void testIncrementalItdsWithMultipleAspects_pr173729() {
initialiseProject("PR173729");
build("PR173729");
checkWasFullBuild();
alter("PR173729", "inc1");
build("PR173729");
checkWasntFullBuild();
}
// Compile a single simple project
public void testTheBasics() {
initialiseProject("P1");
build("P1"); // This first build will be batch
build("P1");
checkWasntFullBuild();
checkCompileWeaveCount("P1", 0, 0);
}
// source code doesnt matter, we are checking invalid path handling
public void testInvalidAspectpath_pr121395() {
initialiseProject("P1");
File f = new File("foo.jar");
Set<File> s = new HashSet<File>();
s.add(f);
configureAspectPath("P1", s);
build("P1"); // This first build will be batch
checkForError("P1", "invalid aspectpath entry");
}
// incorrect use of '?' when it should be '*'
public void testAspectPath_pr242797_c46() {
String bug = "pr242797_1";
String bug2 = "pr242797_2";
initialiseProject(bug);
initialiseProject(bug2);
configureAspectPath(bug2, getProjectRelativePath(bug, "bin"));
build(bug);
build(bug2);
}
public void testAspectPath_pr247742_c16() throws IOException {
String bug = "AspectPathOne";
String bug2 = "AspectPathTwo";
addSourceFolderForSourceFile(bug2, getProjectRelativePath(bug2, "src/C.java"), "src");
initialiseProject(bug);
initialiseProject(bug2);
configureAspectPath(bug2, getProjectRelativePath(bug, "bin"));
build(bug);
build(bug2);
dumptree(getModelFor(bug2).getHierarchy().getRoot(), 0);
PrintWriter pw = new PrintWriter(System.out);
getModelFor(bug2).dumprels(pw);
pw.flush();
IProgramElement root = getModelFor(bug2).getHierarchy().getRoot();
assertEquals("=AspectPathTwo/binaries<pkg(Asp.class'Asp&before", findElementAtLine(root, 5).getHandleIdentifier());
assertEquals("=AspectPathTwo/binaries<(Asp2.class'Asp2&before", findElementAtLine(root, 16).getHandleIdentifier());
}
public void testAspectPath_pr274558() throws Exception {
String base = "bug274558depending";
String depending = "bug274558base";
// addSourceFolderForSourceFile(bug2, getProjectRelativePath(bug2, "src/C.java"), "src");
initialiseProject(base);
initialiseProject(depending);
configureAspectPath(depending, getProjectRelativePath(base, "bin"));
build(base);
build(depending);
printModel(depending);
IProgramElement root = getModelFor(depending).getHierarchy().getRoot();
assertEquals("=bug274558base/binaries<r(DeclaresITD.class'DeclaresITD,InterfaceForITD.x", findElementAtLine(root, 5)
.getHandleIdentifier());
// assertEquals("=AspectPathTwo/binaries<(Asp2.class}Asp2&before", findElementAtLine(root, 16).getHandleIdentifier());
}
public void testAspectPath_pr265693() throws IOException {
String bug = "AspectPath3";
String bug2 = "AspectPath4";
addSourceFolderForSourceFile(bug2, getProjectRelativePath(bug2, "src/C.java"), "src");
initialiseProject(bug);
initialiseProject(bug2);
configureAspectPath(bug2, getProjectRelativePath(bug, "bin"));
build(bug);
build(bug2);
// dumptree(getModelFor(bug2).getHierarchy().getRoot(), 0);
// PrintWriter pw = new PrintWriter(System.out);
// getModelFor(bug2).dumprels(pw);
// pw.flush();
IProgramElement root = getModelFor(bug2).getHierarchy().getRoot();
IProgramElement binariesNode = getChild(root, "binaries");
assertNotNull(binariesNode);
IProgramElement packageNode = binariesNode.getChildren().get(0);
assertEquals("a.b.c", packageNode.getName());
IProgramElement fileNode = packageNode.getChildren().get(0);
assertEquals(IProgramElement.Kind.FILE, fileNode.getKind());
}
private IProgramElement getChild(IProgramElement start, String name) {
if (start.getName().equals(name)) {
return start;
}
List<IProgramElement> kids = start.getChildren();
if (kids != null) {
for (int i = 0; i < kids.size(); i++) {
IProgramElement found = getChild((IProgramElement) kids.get(i), name);
if (found != null) {
return found;
}
}
}
return null;
}
public void testHandleQualification_pr265993() throws IOException {
String p = "pr265993";
initialiseProject(p);
configureNonStandardCompileOptions(p, "-Xset:minimalModel=false");
build(p);
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
// dumptree(getModelFor(p).getHierarchy().getRoot(), 0);
// PrintWriter pw = new PrintWriter(System.out);
// getModelFor(p).dumprels(pw);
// pw.flush();
assertEquals("=pr265993<{A.java[A~m~QString;~Qjava.lang.String;", findElementAtLine(root, 3).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m2~QList;", findElementAtLine(root, 5).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m3~Qjava.util.ArrayList;", findElementAtLine(root, 6).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m4~QMap\\<Qjava.lang.String;QList;>;", findElementAtLine(root, 8).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m5~Qjava.util.Map\\<Qjava.lang.String;QList;>;", findElementAtLine(root, 9)
.getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m6~QMap\\<\\[IQList;>;", findElementAtLine(root, 10).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m7~\\[I", findElementAtLine(root, 11).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m8~\\[Qjava.lang.String;", findElementAtLine(root, 12).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m9~\\[QString;", findElementAtLine(root, 13).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m10~\\[\\[QList\\<QString;>;", findElementAtLine(root, 14).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m11~Qjava.util.List\\<QT;>;", findElementAtLine(root, 15).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m12~\\[QT;", findElementAtLine(root, 16).getHandleIdentifier());
assertEquals("=pr265993<{A.java[A~m13~QClass\\<QT;>;~QObject;~QString;", findElementAtLine(root, 17).getHandleIdentifier());
}
public void testHandlesForAnnotationStyle_pr269286() throws IOException {
String p = "pr269286";
initialiseProject(p);
build(p);
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
dumptree(getModelFor(p).getHierarchy().getRoot(), 0);
PrintWriter pw = new PrintWriter(System.out);
getModelFor(p).dumprels(pw);
pw.flush();
assertEquals("=pr269286<{Logger.java[Logger", findElementAtLine(root, 4).getHandleIdentifier()); // type
assertEquals("=pr269286<{Logger.java[Logger~boo", findElementAtLine(root, 7).getHandleIdentifier()); // before
assertEquals("=pr269286<{Logger.java[Logger~aoo", findElementAtLine(root, 11).getHandleIdentifier()); // after
assertEquals("=pr269286<{Logger.java[Logger~aroo", findElementAtLine(root, 15).getHandleIdentifier()); // around
// pointcuts are not fixed - seems to buggy handling of them internally
assertEquals("=pr269286<{Logger.java[Logger\"ooo", findElementAtLine(root, 20).getHandleIdentifier());
// DeclareWarning
assertEquals("=pr269286<{Logger.java[Logger^message", findElementAtLine(root, 24).getHandleIdentifier());
// DeclareError
assertEquals("=pr269286<{Logger.java[Logger^message2", findElementAtLine(root, 27).getHandleIdentifier());
}
public void testHandleCountersForAdvice() throws IOException {
String p = "prx";
initialiseProject(p);
build(p);
// System.out.println("Handle Counters For Advice Output");
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
// dumptree(getModelFor(p).getHierarchy().getRoot(), 0);
// PrintWriter pw = new PrintWriter(System.out);
// getModelFor(p).dumprels(pw);
// pw.flush();
IProgramElement ff = findFile(root, "ProcessAspect.aj");
assertEquals("=prx<com.kronos.aspects*ProcessAspect.aj'ProcessAspect&after&QMyProcessor;", findElementAtLine(root, 22)
.getHandleIdentifier());
assertEquals("=prx<com.kronos.aspects*ProcessAspect.aj'ProcessAspect&after&QMyProcessor;!2", findElementAtLine(root, 68)
.getHandleIdentifier());
}
/**
* A change is made to an aspect on the aspectpath (staticinitialization() advice is added) for another project.
* <p>
* Managing the aspectpath is hard. We want to do a minimal build of this project which means recognizing what kind of changes
* have occurred on the aspectpath. Was it a regular class or an aspect? Was it a structural change to that aspect?
* <p>
* The filenames for .class files created that contain aspects is stored in the AjState.aspectClassFiles field. When a change is
* detected we can see who was managing the location where the change occurred and ask them if the .class file contained an
* aspect. Right now a change detected like this will cause a full build. We might improve the detection logic here but it isn't
* trivial:
* <ul>
* <li>Around advice is inlined. Changing the body of an around advice would not normally be thought of as a structural change
* (as it does not change the signature of the class) but due to inlining it is a change we would need to pay attention to as it
* will affect types previously woven with that advice.
* <li>Annotation style aspects include pointcuts in strings. Changes to these are considered non-structural but clearly they do
* affect what might be woven.
* </ul>
*/
public void testAspectPath_pr249212_c1() throws IOException {
String p1 = "AspectPathOne";
String p2 = "AspectPathTwo";
addSourceFolderForSourceFile(p2, getProjectRelativePath(p2, "src/C.java"), "src");
initialiseProject(p1);
initialiseProject(p2);
configureAspectPath(p2, getProjectRelativePath(p1, "bin"));
build(p1);
build(p2);
alter(p1, "inc1");
build(p1); // Modify the aspect Asp2 to include staticinitialization()
// advice
checkWasFullBuild();
Set s = getModelFor(p1).getModelChangesOnLastBuild();
assertTrue("Should be empty as was full build:" + s, s.isEmpty());
// prod the build of the second project with some extra info to tell it
// more precisely about the change:
addClasspathEntryChanged(p2, getProjectRelativePath(p1, "bin").toString());
configureAspectPath(p2, getProjectRelativePath(p1, "bin"));
build(p2);
checkWasFullBuild();
// dumptree(AsmManager.getDefault().getHierarchy().getRoot(), 0);
// PrintWriter pw = new PrintWriter(System.out);
// AsmManager.getDefault().dumprels(pw);
// pw.flush();
// Not incremental
assertTrue("Should be empty as was full build:" + s, s.isEmpty());
// Set s = AsmManager.getDefault().getModelChangesOnLastBuild();
// checkIfContainsFile(AsmManager.getDefault().getModelChangesOnLastBuild
// (), "C.java", true);
}
// public void testAspectPath_pr242797_c41() {
// String bug = "pr242797_3";
// String bug2 = "pr242797_4";
// initialiseProject(bug);
// initialiseProject(bug2);
// configureAspectPath(bug2, getProjectRelativePath(bug, "bin"));
// build(bug);
// build(bug2);
// }
/**
* Build a project containing a resource - then mark the resource readOnly(), then do an inc-compile, it will report an error
* about write access to the resource in the output folder being denied
*/
/*
* public void testProblemCopyingResources_pr138171() { initialiseProject("PR138171");
*
* File f=getProjectRelativePath("PR138171","res.txt"); Map m = new HashMap(); m.put("res.txt",f);
* AjdeInteractionTestbed.MyProjectPropertiesAdapter .getInstance().setSourcePathResources(m); build("PR138171"); File f2 =
* getProjectOutputRelativePath("PR138171","res.txt"); boolean successful = f2.setReadOnly();
*
* alter("PR138171","inc1"); AjdeInteractionTestbed.MyProjectPropertiesAdapter .getInstance().setSourcePathResources(m);
* build("PR138171"); List msgs = MyTaskListManager.getErrorMessages(); assertTrue("there should be one message but there are "
* +(msgs==null?0:msgs.size())+":\n"+msgs,msgs!=null && msgs.size()==1); IMessage msg = (IMessage)msgs.get(0); String exp =
* "unable to copy resource to output folder: 'res.txt'"; assertTrue("Expected message to include this text ["
* +exp+"] but it does not: "+msg,msg.toString().indexOf(exp)!=-1); }
*/
// Make simple changes to a project, adding a class
public void testSimpleChanges() {
initialiseProject("P1");
build("P1"); // This first build will be batch
alter("P1", "inc1"); // adds a single class
build("P1");
checkCompileWeaveCount("P1", 1, -1);
build("P1");
checkCompileWeaveCount("P1", 0, -1);
}
// Make simple changes to a project, adding a class and an aspect
public void testAddingAnAspect() {
initialiseProject("P1");
build("P1"); // build 1, weave 1
alter("P1", "inc1"); // adds a class
alter("P1", "inc2"); // adds an aspect
build("P1"); // build 1,
long timeTakenForFullBuildAndWeave = getTimeTakenForBuild("P1");
checkWasFullBuild(); // it *will* be a full build under the new
// "back-to-the-source strategy
checkCompileWeaveCount("P1", 5, 3); // we compile X and A (the delta)
// find out that
// an aspect has changed, go back to the source
// and compile X,A,C, then weave them all.
build("P1");
long timeTakenForSimpleIncBuild = getTimeTakenForBuild("P1");
// I don't think this test will have timing issues as the times should
// be *RADICALLY* different
// On my config, first build time is 2093ms and the second is 30ms
assertTrue("Should not take longer for the trivial incremental build! first=" + timeTakenForFullBuildAndWeave
+ "ms second=" + timeTakenForSimpleIncBuild + "ms", timeTakenForSimpleIncBuild < timeTakenForFullBuildAndWeave);
}
public void testBuildingTwoProjectsInTurns() {
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
}
public void testBuildingBrokenCode_pr240360() {
initialiseProject("pr240360");
// configureNonStandardCompileOptions("pr240360","-proceedOnError");
build("pr240360");
checkWasFullBuild();
checkCompileWeaveCount("pr240360", 5, 4);
assertTrue("There should be an error:\n" + getErrorMessages("pr240360"), !getErrorMessages("pr240360").isEmpty());
Set s = getModelFor("pr240360").getRelationshipMap().getEntries();
int relmapLength = s.size();
// Delete the erroneous type
String f = getWorkingDir().getAbsolutePath() + File.separatorChar + "pr240360" + File.separatorChar + "src"
+ File.separatorChar + "test" + File.separatorChar + "Error.java";
(new File(f)).delete();
build("pr240360");
checkWasntFullBuild();
checkCompileWeaveCount("pr240360", 0, 0);
assertEquals(relmapLength, getModelFor("pr240360").getRelationshipMap().getEntries().size());
// Readd the erroneous type
alter("pr240360", "inc1");
build("pr240360");
checkWasntFullBuild();
checkCompileWeaveCount("pr240360", 1, 0);
assertEquals(relmapLength, getModelFor("pr240360").getRelationshipMap().getEntries().size());
// Change the advice
alter("pr240360", "inc2");
build("pr240360");
checkWasFullBuild();
checkCompileWeaveCount("pr240360", 6, 4);
assertEquals(relmapLength, getModelFor("pr240360").getRelationshipMap().getEntries().size());
}
public void testBrokenCodeCompilation() {
initialiseProject("pr102733_1");
// configureNonStandardCompileOptions("pr102733_1","-proceedOnError");
build("pr102733_1");
checkWasFullBuild();
checkCompileWeaveCount("pr102733_1", 1, 0);
assertTrue("There should be an error:\n" + getErrorMessages("pr102733_1"), !getErrorMessages("pr102733_1").isEmpty());
build("pr102733_1"); // incremental
checkCompileWeaveCount("pr102733_1", 0, 0);
checkWasntFullBuild();
alter("pr102733_1", "inc1"); // fix the error
build("pr102733_1");
checkWasntFullBuild();
checkCompileWeaveCount("pr102733_1", 1, 1);
assertTrue("There should be no errors:\n" + getErrorMessages("pr102733_1"), getErrorMessages("pr102733_1").isEmpty());
alter("pr102733_1", "inc2"); // break it again
build("pr102733_1");
checkWasntFullBuild();
checkCompileWeaveCount("pr102733_1", 1, 0);
assertTrue("There should be an error:\n" + getErrorMessages("pr102733_1"), !getErrorMessages("pr102733_1").isEmpty());
}
// public void testDeclareAtType_pr149293() {
// configureBuildStructureModel(true);
// initialiseProject("PR149293_1");
// build("PR149293_1");
// checkCompileWeaveCount(4,5);
// assertNoErrors();
// alter("PR149293_1","inc1");
// build("PR149293_1");
// assertNoErrors();
// }
public void testRefactoring_pr148285() {
// configureBuildStructureModel(true);
initialiseProject("PR148285");
build("PR148285");
alter("PR148285", "inc1");
build("PR148285");
}
/**
* In order for this next test to run, I had to move the weaver/world pair we keep in the AjBuildManager instance down into the
* state object - this makes perfect sense - otherwise when reusing the state for another project we'd not be switching to the
* right weaver/world for that project.
*/
public void testBuildingTwoProjectsMakingSmallChanges() {
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
alter("P1", "inc1"); // adds a class
alter("P1", "inc2"); // adds an aspect
build("P1");
checkWasFullBuild(); // adding an aspect makes us go back to the source
}
public void testPr134371() {
initialiseProject("PR134371");
build("PR134371");
alter("PR134371", "inc1");
build("PR134371");
assertTrue("There should be no exceptions handled:\n" + getErrorMessages("PR134371"), getErrorMessages("PR134371")
.isEmpty());
}
/**
* This test is verifying the behaviour of the code that iterates through the type hierarchy for some type. There are two ways
* to do it - an approach that grabs all the information up front or an approach that works through iterators and only processes
* as much data as necessary to satisfy the caller. The latter approach could be much faster - especially if the matching
* process typically looks for a method in the declaring type.
*/
public void xtestOptimizedMemberLookup() {
String p = "oml";
initialiseProject(p);
build(p);
AjdeCoreBuildManager buildManager = getCompilerForProjectWithName(p).getBuildManager();
AjBuildManager ajBuildManager = buildManager.getAjBuildManager();
World w = ajBuildManager.getWorld();
// Type A has no hierarchy (well, Object) and defines 3 methods
checkType(w, "com.foo.A");
// Type B extends B2. Two methods in B2, three in B
checkType(w, "com.foo.B");
// Type C implements an interface
checkType(w, "com.foo.C");
// Type CC extends a class that implements an interface
checkType(w, "com.foo.CC");
// Type CCC implements an interface that extends another interface
checkType(w, "com.foo.CCC");
// Type CCC implements an interface that extends another interface
checkType(w, "com.foo.CCC");
checkType(w, "GenericMethodInterface");
checkType(w, "GenericInterfaceChain");
// Some random classes from rt.jar that did reveal some problems:
checkType(w, "java.lang.StringBuffer");
checkType(w, "com.sun.corba.se.impl.encoding.CDRInputObject");
checkTypeHierarchy(w, "com.sun.corba.se.impl.interceptors.PIHandlerImpl$RequestInfoStack", true);
checkType(w, "com.sun.corba.se.impl.interceptors.PIHandlerImpl$RequestInfoStack");
checkType(w, "DeclareWarningAndInterfaceMethodCW");
checkType(w, "ICanGetSomething");
checkType(w, "B");
checkType(w, "C");
// checkRtJar(w); // only works if the JDK path is setup ok in checkRtJar
// speedCheck(w);
}
// private void checkRtJar(World w) {
// System.out.println("Processing everything in rt.jar: ~16000 classes");
// try {
// ZipFile zf = new ZipFile("c:/jvms/jdk1.6.0_06/jre/lib/rt.jar");
// Enumeration e = zf.entries();
// int count = 1;
// while (e.hasMoreElements()) {
// ZipEntry ze = (ZipEntry) e.nextElement();
// String n = ze.getName();
// if (n.endsWith(".class")) {
// n = n.replace('/', '.');
// n = n.substring(0, n.length() - 6);
// if ((count % 100) == 0) {
// System.out.print(count + " ");
// }
// if ((count % 1000) == 0) {
// System.out.println();
// }
// checkType(w, n);
// count++;
// }
// }
// zf.close();
// } catch (IOException t) {
// t.printStackTrace();
// fail(t.toString());
// }
// System.out.println();
// }
/**
* Compare time taken to grab them all and look at them and iterator through them all.
*/
private void speedCheck(World w) {
long stime = System.currentTimeMillis();
try {
ZipFile zf = new ZipFile("c:/jvms/jdk1.6.0_06/jre/lib/rt.jar");
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
String n = ze.getName();
if (n.endsWith(".class")) {
n = n.replace('/', '.');
n = n.substring(0, n.length() - 6);
ResolvedType typeA = w.resolve(n);
assertFalse(typeA.isMissing());
List<ResolvedMember> viaIteratorList = getThemAll(typeA.getMethods(true, true));
viaIteratorList = getThemAll(typeA.getMethods(false, true));
}
}
zf.close();
} catch (IOException t) {
t.printStackTrace();
fail(t.toString());
}
long etime = System.currentTimeMillis();
System.out.println("Time taken for 'iterator' approach: " + (etime - stime) + "ms");
stime = System.currentTimeMillis();
try {
ZipFile zf = new ZipFile("c:/jvms/jdk1.6.0_06/jre/lib/rt.jar");
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
String n = ze.getName();
if (n.endsWith(".class")) {
n = n.replace('/', '.');
n = n.substring(0, n.length() - 6);
ResolvedType typeA = w.resolve(n);
assertFalse(typeA.isMissing());
List<ResolvedMember> viaIteratorList = typeA.getMethodsWithoutIterator(false, true, true);
viaIteratorList = typeA.getMethodsWithoutIterator(false, true, false);
}
}
zf.close();
} catch (IOException t) {
t.printStackTrace();
fail(t.toString());
}
etime = System.currentTimeMillis();
System.out.println("Time taken for 'grab all up front' approach: " + (etime - stime) + "ms");
}
private void checkType(World w, String name) {
checkTypeHierarchy(w, name, true);
checkTypeHierarchy(w, name, false);
checkMethods(w, name, true);
checkMethods(w, name, false);
}
private void checkMethods(World w, String name, boolean wantGenerics) {
ResolvedType typeA = w.resolve(name);
assertFalse(typeA.isMissing());
List<ResolvedMember> viaIteratorList = getThemAll(typeA.getMethods(wantGenerics, true));
List<ResolvedMember> directlyList = typeA.getMethodsWithoutIterator(true, true, wantGenerics);
Collections.sort(viaIteratorList, new ResolvedMemberComparator());
Collections.sort(directlyList, new ResolvedMemberComparator());
compare(viaIteratorList, directlyList, name);
// System.out.println(toString(viaIteratorList, directlyList, genericsAware));
}
private static class ResolvedMemberComparator implements Comparator<ResolvedMember> {
public int compare(ResolvedMember o1, ResolvedMember o2) {
return o1.toString().compareTo(o2.toString());
}
}
private void checkTypeHierarchy(World w, String name, boolean wantGenerics) {
ResolvedType typeA = w.resolve(name);
assertFalse(typeA.isMissing());
List<String> viaIteratorList = exhaustTypeIterator(typeA.getHierarchy(wantGenerics, false));
List<ResolvedType> typeDirectlyList = typeA.getHierarchyWithoutIterator(true, true, wantGenerics);
assertFalse(viaIteratorList.isEmpty());
List<String> directlyList = new ArrayList<String>();
for (ResolvedType type : typeDirectlyList) {
String n = type.getName();
if (!directlyList.contains(n)) {
directlyList.add(n);
}
}
Collections.sort(viaIteratorList);
Collections.sort(directlyList);
compareTypeLists(viaIteratorList, directlyList);
// System.out.println("ShouldBeGenerics?" + wantGenerics + "\n" + typeListsToString(viaIteratorList, directlyList));
}
private void compare(List<ResolvedMember> viaIteratorList, List<ResolvedMember> directlyList, String typename) {
assertEquals(typename + "\n" + toString(directlyList), typename + "\n" + toString(viaIteratorList));
}
private void compareTypeLists(List<String> viaIteratorList, List<String> directlyList) {
assertEquals(typeListToString(directlyList), typeListToString(viaIteratorList));
}
private String toString(List<ResolvedMember> list) {
StringBuffer sb = new StringBuffer();
for (ResolvedMember m : list) {
sb.append(m).append("\n");
}
return sb.toString();
}
private String typeListToString(List<String> list) {
StringBuffer sb = new StringBuffer();
for (String m : list) {
sb.append(m).append("\n");
}
return sb.toString();
}
private String toString(List<ResolvedMember> one, List<ResolvedMember> two, boolean shouldIncludeGenerics) {
StringBuffer sb = new StringBuffer();
sb.append("Through iterator\n");
for (ResolvedMember m : one) {
sb.append(m).append("\n");
}
sb.append("Directly retrieved\n");
for (ResolvedMember m : one) {
sb.append(m).append("\n");
}
return sb.toString();
}
private String typeListsToString(List<String> one, List<String> two) {
StringBuffer sb = new StringBuffer();
sb.append("Through iterator\n");
for (String m : one) {
sb.append(">" + m).append("\n");
}
sb.append("Directly retrieved\n");
for (String m : one) {
sb.append(">" + m).append("\n");
}
return sb.toString();
}
private List<ResolvedMember> getThemAll(Iterator<ResolvedMember> methods) {
List<ResolvedMember> allOfThem = new ArrayList<ResolvedMember>();
while (methods.hasNext()) {
allOfThem.add(methods.next());
}
return allOfThem;
}
private List<String> exhaustTypeIterator(Iterator<ResolvedType> types) {
List<String> allOfThem = new ArrayList<String>();
while (types.hasNext()) {
allOfThem.add(types.next().getName());
}
return allOfThem;
}
/**
* Setup up two simple projects and build them in turn - check the structure model is right after each build
*/
public void testBuildingTwoProjectsAndVerifyingModel() {
initialiseProject("P1");
initialiseProject("P2");
configureNonStandardCompileOptions("P1", "-Xset:minimalModel=false");
configureNonStandardCompileOptions("P2", "-Xset:minimalModel=false");
build("P1");
checkForNode(getModelFor("P1"), "pkg", "C", true);
build("P2");
checkForNode(getModelFor("P2"), "pkg", "C", false);
build("P1");
checkForNode(getModelFor("P1"), "pkg", "C", true);
build("P2");
checkForNode(getModelFor("P2"), "pkg", "C", false);
}
// Setup up two simple projects and build them in turn - check the
// structure model is right after each build
public void testBuildingTwoProjectsAndVerifyingStuff() {
initialiseProject("P1");
initialiseProject("P2");
configureNonStandardCompileOptions("P1", "-Xset:minimalModel=false");
configureNonStandardCompileOptions("P2", "-Xset:minimalModel=false");
build("P1");
checkForNode(getModelFor("P1"), "pkg", "C", true);
build("P2");
checkForNode(getModelFor("P2"), "pkg", "C", false);
build("P1");
checkForNode(getModelFor("P1"), "pkg", "C", true);
build("P2");
checkForNode(getModelFor("P2"), "pkg", "C", false);
}
/**
* Complex. Here we are testing that a state object records structural changes since the last full build correctly. We build a
* simple project from scratch - this will be a full build and so the structural changes since last build count should be 0. We
* then alter a class, adding a new method and check structural changes is 1.
*/
public void testStateManagement1() {
File binDirectoryForP1 = new File(getFile("P1", "bin"));
initialiseProject("P1");
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be a state object for project P1", ajs != null);
assertTrue(
"Should be no structural changes as it was a full build but found: "
+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0);
alter("P1", "inc3"); // adds a method to the class C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1", "bin")));
assertTrue("There should be state for project P1", ajs != null);
checkWasntFullBuild();
assertTrue(
"Should be one structural changes as it was a full build but found: "
+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 1);
}
/**
* Complex. Here we are testing that a state object records structural changes since the last full build correctly. We build a
* simple project from scratch - this will be a full build and so the structural changes since last build count should be 0. We
* then alter a class, changing body of a method, not the structure and check struc changes is still 0.
*/
public void testStateManagement2() {
File binDirectoryForP1 = new File(getFile("P1", "bin"));
initialiseProject("P1");
alter("P1", "inc3"); // need this change in here so 'inc4' can be
// applied without making
// it a structural change
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be state for project P1", ajs != null);
assertTrue("Should be no struc changes as its a full build: " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0);
alter("P1", "inc4"); // changes body of main() method but does *not*
// change the structure of C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1", "bin")));
assertTrue("There should be state for project P1", ajs != null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0);
}
/**
* The C.java file modified in this test has an inner class - this means the inner class has a this$0 field and <init>(C) ctor
* to watch out for when checking for structural changes
*
*/
public void testStateManagement3() {
File binDirForInterproject1 = new File(getFile("interprojectdeps1", "bin"));
initialiseProject("interprojectdeps1");
build("interprojectdeps1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject1);
assertTrue("There should be state for project P1", ajs != null);
assertTrue("Should be no struc changes as its a full build: " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0);
alter("interprojectdeps1", "inc1"); // adds a space to C.java
build("interprojectdeps1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps1", "bin")));
assertTrue("There should be state for project interprojectdeps1", ajs != null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0);
}
/**
* The C.java file modified in this test has an inner class - which has two ctors - this checks how they are mangled with an
* instance of C.
*
*/
public void testStateManagement4() {
File binDirForInterproject2 = new File(getFile("interprojectdeps2", "bin"));
initialiseProject("interprojectdeps2");
build("interprojectdeps2"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject2);
assertTrue("There should be state for project interprojectdeps2", ajs != null);
assertTrue("Should be no struc changes as its a full build: " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0);
alter("interprojectdeps2", "inc1"); // minor change to C.java
build("interprojectdeps2");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps2", "bin")));
assertTrue("There should be state for project interprojectdeps1", ajs != null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0);
}
/**
* The C.java file modified in this test has an inner class - it has two ctors but also a reference to C.this in it - which will
* give rise to an accessor being created in C
*
*/
public void testStateManagement5() {
File binDirForInterproject3 = new File(getFile("interprojectdeps3", "bin"));
initialiseProject("interprojectdeps3");
build("interprojectdeps3"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject3);
assertTrue("There should be state for project interprojectdeps3", ajs != null);
assertTrue("Should be no struc changes as its a full build: " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0);
alter("interprojectdeps3", "inc1"); // minor change to C.java
build("interprojectdeps3");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps3", "bin")));
assertTrue("There should be state for project interprojectdeps1", ajs != null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were " + ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild() == 0);
}
/**
* Now the most complex test. Create a dependancy between two projects. Building one may affect whether the other does an
* incremental or full build. The structural information recorded in the state object should be getting used to control whether
* a full build is necessary...
*/
public void testBuildingDependantProjects() {
initialiseProject("P1");
initialiseProject("P2");
configureNewProjectDependency("P2", "P1");
build("P1");
build("P2"); // now everything is consistent and compiled
alter("P1", "inc1"); // adds a second class
build("P1");
build("P2"); // although a second class was added - P2 can't be using
// it, so we don't full build here :)
checkWasntFullBuild();
alter("P1", "inc3"); // structurally changes one of the classes
build("P1");
build("P2"); // build notices the structural change, but is incremental
// of I and J as they depend on C
checkWasntFullBuild();
alter("P1", "inc4");
build("P1");
build("P2"); // build sees a change but works out its not structural
checkWasntFullBuild();
}
public void testPr85132() {
initialiseProject("PR85132");
build("PR85132");
alter("PR85132", "inc1");
build("PR85132");
}
// parameterization of generic aspects
public void testPr125405() {
initialiseProject("PR125405");
build("PR125405");
checkCompileWeaveCount("PR125405", 1, 1);
alter("PR125405", "inc1");
build("PR125405");
// "only abstract aspects can have type parameters"
checkForError("PR125405", "only abstract aspects can have type parameters");
alter("PR125405", "inc2");
build("PR125405");
checkCompileWeaveCount("PR125405", 1, 1);
assertTrue("Should be no errors, but got " + getErrorMessages("PR125405"), getErrorMessages("PR125405").size() == 0);
}
public void testPr128618() {
initialiseProject("PR128618_1");
initialiseProject("PR128618_2");
configureNewProjectDependency("PR128618_2", "PR128618_1");
assertTrue("there should be no warning messages before we start", getWarningMessages("PR128618_1").isEmpty());
assertTrue("there should be no warning messages before we start", getWarningMessages("PR128618_2").isEmpty());
build("PR128618_1");
build("PR128618_2");
List<IMessage> l = getWarningMessages("PR128618_2");
// there should be one warning against "PR128618_2"
List<IMessage> warnings = getWarningMessages("PR128618_2");
assertTrue("Should be one warning, but there are #" + warnings.size(), warnings.size() == 1);
IMessage msg = (getWarningMessages("PR128618_2").get(0));
assertEquals("warning should be against the FFDC.aj resource", "FFDC.aj", msg.getSourceLocation().getSourceFile().getName());
alter("PR128618_2", "inc1");
build("PR128618_2");
checkWasntFullBuild();
IMessage msg2 = (getWarningMessages("PR128618_2").get(0));
assertEquals("warning should be against the FFDC.aj resource", "FFDC.aj", msg2.getSourceLocation().getSourceFile()
.getName());
assertFalse("a new warning message should have been generated", msg.equals(msg2));
}
public void testPr92837() {
initialiseProject("PR92837");
build("PR92837");
alter("PR92837", "inc1");
build("PR92837");
}
// See open generic itd bug mentioning 119570
// public void testPr119570() {
// initialiseProject("PR119570");
// build("PR119570");
// assertNoErrors("PR119570");
// }
// public void testPr119570_212783_2() {
// initialiseProject("PR119570_2");
// build("PR119570_2");
// List l = getWarningMessages("PR119570_2");
// assertTrue("Should be no warnings, but got "+l,l.size()==0);
// assertNoErrors("PR119570_2");
// }
//
// public void testPr119570_212783_3() {
// initialiseProject("pr119570_3");
// build("pr119570_3");
// List l = getWarningMessages("pr119570_3");
// assertTrue("Should be no warnings, but got "+l,l.size()==0);
// assertNoErrors("pr119570_3");
// }
// If you fiddle with the compiler options - you must manually reset the
// options at the end of the test
public void testPr117209() {
try {
initialiseProject("pr117209");
configureNonStandardCompileOptions("pr117209", "-proceedOnError");
build("pr117209");
checkCompileWeaveCount("pr117209", 6, 5);
} finally {
// MyBuildOptionsAdapter.reset();
}
}
public void testPr114875() {
// temporary problem with this on linux, think it is a filesystem
// lastmodtime issue
if (System.getProperty("os.name", "").toLowerCase().equals("linux")) {
return;
}
initialiseProject("pr114875");
build("pr114875");
alter("pr114875", "inc1");
build("pr114875");
checkWasFullBuild();
alter("pr114875", "inc2");
build("pr114875");
checkWasFullBuild(); // back to the source for an aspect change
}
public void testPr117882() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882");
build("PR117882");
checkWasFullBuild();
alter("PR117882", "inc1");
build("PR117882");
// This should be an incremental build now - because of the changes
// under 259649
checkWasntFullBuild(); // back to the source for an aspect
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr117882_2() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882_2");
build("PR117882_2");
checkWasFullBuild();
alter("PR117882_2", "inc1");
build("PR117882_2");
checkWasFullBuild(); // back to the source...
// checkCompileWeaveCount(1,4);
// fullBuild("PR117882_2");
// checkWasFullBuild();
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr115251() {
// AjdeInteractionTestbed.VERBOSE=true;
initialiseProject("PR115251");
build("PR115251");
checkWasFullBuild();
alter("PR115251", "inc1");
build("PR115251");
checkWasFullBuild(); // back to the source
}
public void testPr220255_InfiniteBuildHasMember() {
initialiseProject("pr220255");
configureNonStandardCompileOptions("pr220255", "-XhasMember");
build("pr220255");
checkWasFullBuild();
alter("pr220255", "inc1");
build("pr220255");
checkWasntFullBuild();
}
public void testPr157054() {
initialiseProject("PR157054");
configureNonStandardCompileOptions("PR157054", "-showWeaveInfo");
configureShowWeaveInfoMessages("PR157054", true);
build("PR157054");
checkWasFullBuild();
List weaveMessages = getWeavingMessages("PR157054");
assertTrue("Should be two weaving messages but there are " + weaveMessages.size(), weaveMessages.size() == 2);
alter("PR157054", "inc1");
build("PR157054");
weaveMessages = getWeavingMessages("PR157054");
assertTrue("Should be three weaving messages but there are " + weaveMessages.size(), weaveMessages.size() == 3);
checkWasntFullBuild();
fullBuild("PR157054");
weaveMessages = getWeavingMessages("PR157054");
assertTrue("Should be three weaving messages but there are " + weaveMessages.size(), weaveMessages.size() == 3);
}
/**
* Checks we aren't leaking mungers across compiles (accumulating multiple instances of the same one that all do the same
* thing). On the first compile the munger is added late on - so at the time we set the count it is still zero. On the
* subsequent compiles we know about this extra one.
*/
public void testPr141956_IncrementallyCompilingAtAj() {
initialiseProject("PR141956");
build("PR141956");
assertTrue("Should be zero but reports " + EclipseFactory.debug_mungerCount, EclipseFactory.debug_mungerCount == 0);
alter("PR141956", "inc1");
build("PR141956");
assertTrue("Should be two but reports " + EclipseFactory.debug_mungerCount, EclipseFactory.debug_mungerCount == 2);
alter("PR141956", "inc1");
build("PR141956");
assertTrue("Should be two but reports " + EclipseFactory.debug_mungerCount, EclipseFactory.debug_mungerCount == 2);
alter("PR141956", "inc1");
build("PR141956");
assertTrue("Should be two but reports " + EclipseFactory.debug_mungerCount, EclipseFactory.debug_mungerCount == 2);
alter("PR141956", "inc1");
build("PR141956");
assertTrue("Should be two but reports " + EclipseFactory.debug_mungerCount, EclipseFactory.debug_mungerCount == 2);
}
// public void testPr124399() {
// AjdeInteractionTestbed.VERBOSE=true;
// configureBuildStructureModel(true);
// initialiseProject("PR124399");
// build("PR124399");
// checkWasFullBuild();
// alter("PR124399","inc1");
// build("PR124399");
// checkWasntFullBuild();
// }
public void testPr121384() {
// AjdeInteractionTestbed.VERBOSE=true;
// AsmManager.setReporting("c:/foo.txt",true,true,true,false);
initialiseProject("pr121384");
configureNonStandardCompileOptions("pr121384", "-showWeaveInfo");
build("pr121384");
checkWasFullBuild();
alter("pr121384", "inc1");
build("pr121384");
checkWasntFullBuild();
}
/*
* public void testPr111779() { super.VERBOSE=true; initialiseProject("PR111779"); build("PR111779"); alter("PR111779","inc1");
* build("PR111779"); }
*/
public void testPr93310_1() {
initialiseProject("PR93310_1");
build("PR93310_1");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src"
+ File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_1", "inc1");
build("PR93310_1");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: " + l, l == 1);
String name = (String) AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is " + name, name.endsWith("C2.java"));
}
public void testPr93310_2() {
initialiseProject("PR93310_2");
build("PR93310_2");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src"
+ File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_2", "inc1");
build("PR93310_2");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: " + l, l == 1);
String name = (String) AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is " + name, name.endsWith("C2.java"));
}
// Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field
// in A.
// Stage2: make the field private in class A > gives compile error
// Stage3: Add a new aspect whilst there is a compile error !
public void testPr113531() {
initialiseProject("PR113531");
build("PR113531");
assertTrue("build should have compiled ok", getErrorMessages("PR113531").isEmpty());
alter("PR113531", "inc1");
build("PR113531");
assertEquals("error message should be 'foo cannot be resolved to a variable' ", "foo cannot be resolved to a variable",
(getErrorMessages("PR113531").get(0)).getMessage());
alter("PR113531", "inc2");
build("PR113531");
assertTrue("There should be no exceptions handled:\n" + getCompilerErrorMessages("PR113531"),
getCompilerErrorMessages("PR113531").isEmpty());
assertEquals("error message should be 'foo cannot be resolved to a variable' ", "foo cannot be resolved to a variable",
(getErrorMessages("PR113531").get(0)).getMessage());
}
// Stage 1: Compile the 4 files, pack.A2 extends pack.A1 (aspects) where
// A2 uses a protected field in A1 and pack.C2 extends pack.C1 (classes)
// where C2 uses a protected field in C1
// Stage 2: make the field private in class C1 ==> compile errors in C2
// Stage 3: make the field private in aspect A1 whilst there's the compile
// error.
// There shouldn't be a BCException saying can't find delegate for pack.C2
public void testPr119882() {
initialiseProject("PR119882");
build("PR119882");
assertTrue("build should have compiled ok", getErrorMessages("PR119882").isEmpty());
alter("PR119882", "inc1");
build("PR119882");
// fullBuild("PR119882");
List<IMessage> errors = getErrorMessages("PR119882");
assertTrue("Should be at least one error, but got none", errors.size() == 1);
assertEquals("error message should be 'i cannot be resolved to a variable' ", "i cannot be resolved to a variable",
((IMessage) errors.get(0)).getMessage());
alter("PR119882", "inc2");
build("PR119882");
assertTrue("There should be no exceptions handled:\n" + getCompilerErrorMessages("PR119882"),
getCompilerErrorMessages("PR119882").isEmpty());
assertEquals("error message should be 'i cannot be resolved to a variable' ", "i cannot be resolved to a variable",
((IMessage) errors.get(0)).getMessage());
}
public void testPr112736() {
initialiseProject("PR112736");
build("PR112736");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src"
+ File.separatorChar + "pack" + File.separatorChar + "A.java";
(new File(fileC2)).delete();
alter("PR112736", "inc1");
build("PR112736");
checkWasFullBuild();
}
/**
* We have problems with multiple rewrites of a pointcut across incremental builds.
*/
public void testPr113257() {
initialiseProject("PR113257");
build("PR113257");
alter("PR113257", "inc1");
build("PR113257");
checkWasFullBuild(); // back to the source
alter("PR113257", "inc1");
build("PR113257");
}
public void testPr123612() {
initialiseProject("PR123612");
build("PR123612");
alter("PR123612", "inc1");
build("PR123612");
checkWasFullBuild(); // back to the source
}
// Bugzilla Bug 152257 - Incremental compiler doesn't handle exception
// declaration correctly
public void testPr152257() {
initialiseProject("PR152257");
configureNonStandardCompileOptions("PR152257", "-XnoInline");
build("PR152257");
List errors = getErrorMessages("PR152257");
assertTrue("Should be no warnings, but there are #" + errors.size(), errors.size() == 0);
checkWasFullBuild();
alter("PR152257", "inc1");
build("PR152257");
errors = getErrorMessages("PR152257");
assertTrue("Should be no warnings, but there are #" + errors.size(), errors.size() == 0);
checkWasntFullBuild();
}
public void testPr128655() {
initialiseProject("pr128655");
configureNonStandardCompileOptions("pr128655", "-showWeaveInfo");
configureShowWeaveInfoMessages("pr128655", true);
build("pr128655");
List<IMessage> firstBuildMessages = getWeavingMessages("pr128655");
assertTrue("Should be at least one message about the dec @type, but there were none", firstBuildMessages.size() > 0);
alter("pr128655", "inc1");
build("pr128655");
checkWasntFullBuild(); // back to the source
List<IMessage> secondBuildMessages = getWeavingMessages("pr128655");
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage) firstBuildMessages.get(i);
IMessage m2 = (IMessage) secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: " + m1);
System.err.println("Message during second build was: " + m1);
fail("The two messages should be the same, but are not: \n" + m1 + "!=" + m2);
}
}
}
// Similar to above, but now the annotation is in the default package
public void testPr128655_2() {
initialiseProject("pr128655_2");
configureNonStandardCompileOptions("pr128655_2", "-showWeaveInfo");
configureShowWeaveInfoMessages("pr128655_2", true);
build("pr128655_2");
List<IMessage> firstBuildMessages = getWeavingMessages("pr128655_2");
assertTrue("Should be at least one message about the dec @type, but there were none", firstBuildMessages.size() > 0);
alter("pr128655_2", "inc1");
build("pr128655_2");
checkWasntFullBuild(); // back to the source
List<IMessage> secondBuildMessages = getWeavingMessages("pr128655_2");
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage) firstBuildMessages.get(i);
IMessage m2 = (IMessage) secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: " + m1);
System.err.println("Message during second build was: " + m1);
fail("The two messages should be the same, but are not: \n" + m1 + "!=" + m2);
}
}
}
// test for comment #31 - NPE
public void testPr129163() {
initialiseProject("PR129613");
build("PR129613");
alter("PR129613", "inc1");
build("PR129613");
assertTrue("There should be no exceptions handled:\n" + getCompilerErrorMessages("PR129613"),
getCompilerErrorMessages("PR129613").isEmpty());
assertEquals("warning message should be 'no match for this type name: File [Xlint:invalidAbsoluteTypeName]' ",
"no match for this type name: File [Xlint:invalidAbsoluteTypeName]",
(getWarningMessages("PR129613").get(0)).getMessage());
}
// test for comment #0 - adding a comment to a class file shouldn't
// cause us to go back to source and recompile everything. To force this
// to behave like AJDT we need to include the aspect in 'inc1' so that
// when AjState looks at its timestamp it thinks the aspect has been
// modified.
// The logic within CrosscuttingMembers should then work out correctly
// that there haven't really been any changes within the aspect and so
// we shouldn't go back to source.
public void testPr129163_2() {
// want to behave like AJDT
initialiseProject("pr129163_2");
build("pr129163_2");
checkWasFullBuild();
alter("pr129163_2", "inc1");
build("pr129163_2");
checkWasntFullBuild(); // shouldn't be a full build because the
// aspect hasn't changed
}
public void testIncrementalIntelligence_Scenario01() {
AjdeInteractionTestbed.VERBOSE = true;
initialiseProject("Project1");
initialiseProject("Project2");
configureNewProjectDependency("Project2", "Project1");
build("Project1");
build("Project2");
alter("Project1", "inc1"); // white space change to ClassA - no impact
build("Project1");
build("Project2");
checkWasntFullBuild(); // not a structural change so ignored
alter("Project1", "inc2"); // structural change to ClassB - new method!
build("Project1");
build("Project2");
checkWasntFullBuild(); // not a type that Project2 depends on so ignored
alter("Project1", "inc3"); // structural change to ClassA
build("Project1");
setNextChangeResponse("Project2", ICompilerConfiguration.EVERYTHING); // See
// pr245566
// comment
// 3
build("Project2");
checkWasntFullBuild(); // Just need to recompile ClassAExtender
checkCompileWeaveCount("Project2", 1, 1);
checkCompiled("Project2", "ClassAExtender");
alter("Project2", "inc1"); // New type that depends on ClassAExtender
build("Project1");
build("Project2");
checkWasntFullBuild(); // Just build ClassAExtenderExtender
alter("Project1", "inc4"); // another structural change to ClassA
build("Project1");
setNextChangeResponse("Project2", ICompilerConfiguration.EVERYTHING); // See
// pr245566
// comment
// 3
build("Project2");
checkWasntFullBuild(); // Should rebuild ClassAExtender and
// ClassAExtenderExtender
checkCompileWeaveCount("Project2", 2, 2);
checkCompiled("Project2", "ClassAExtenderExtender");
}
private void checkCompiled(String projectName, String typeNameSubstring) {
List files = getCompiledFiles(projectName);
boolean found = false;
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
String object = (String) iterator.next();
if (object.indexOf(typeNameSubstring) != -1) {
found = true;
}
}
assertTrue("Did not find '" + typeNameSubstring + "' in list of compiled files", found);
}
// Case001: renaming a private field in a type
/*
* public void testPrReducingDependentBuilds_001_221427() { AjdeInteractionTestbed.VERBOSE=true;
* IncrementalStateManager.debugIncrementalStates=true; initialiseProject("P221427_1"); initialiseProject("P221427_2");
* configureNewProjectDependency("P221427_2","P221427_1");
*
* build("P221427_1"); build("P221427_2"); alter("P221427_1","inc1"); // rename private class in super project
* MyStateListener.reset(); build("P221427_1"); build("P221427_2");
*
* AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P221427_1","bin")));
* assertTrue("There should be state for project P221427_1",ajs!=null);
* //System.out.println(MyStateListener.getInstance().getDecisions()); checkWasntFullBuild();
* assertTrue("Should be one structural change but there were "+ ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
* ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1);
*
* }
*
* // Case002: changing a class to final that is extended in a dependent project public void
* testPrReducingDependentBuilds_002_221427() { AjdeInteractionTestbed.VERBOSE=true;
* IncrementalStateManager.debugIncrementalStates=true; initialiseProject("P221427_3"); initialiseProject("P221427_4");
* configureNewProjectDependency("P221427_4","P221427_3");
*
* build("P221427_3"); build("P221427_4"); // build OK, type in super project is non-final alter("P221427_3","inc1"); // change
* class declaration in super-project to final MyStateListener.reset(); build("P221427_3"); build("P221427_4"); // build FAIL,
* type in super project is now final
*
* AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P221427_3","bin")));
* assertTrue("There should be state for project P221427_3",ajs!=null);
* System.out.println(MyStateListener.getInstance().getDecisions());
*
* List errors = getErrorMessages("P221427_4"); if (errors.size()!=1) { if (errors.size()==0)
* fail("Expected error about not being able to extend final class"); for (Iterator iterator = errors.iterator();
* iterator.hasNext();) { Object object = (Object) iterator.next(); System.out.println(object); }
* fail("Expected 1 error but got "+errors.size()); } // assertTrue("Shouldn't be one structural change but there were "+ //
* ajs.getNumberOfStructuralChangesSinceLastFullBuild(), // ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1);
*
* }
*/
// test for comment #6 - simulates AJDT core builder test testBug99133a -
// changing the contents of a method within a class shouldn't force a
// full build of a dependant project. To force this to behave like AJDT
// 'inc1' of the dependant project should just be a copy of 'base' so that
// AjState thinks somethings changed within the dependant project and
// we do a build. Similarly, 'inc1' of the project depended on should
// include the aspect even though nothing's changed within it. This causes
// AjState to think that the aspect has changed. Together its then up to
// logic within CrosscuttingMembers and various equals methods to decide
// correctly that we don't have to go back to source.
public void testPr129163_3() {
initialiseProject("PR129163_4");
build("PR129163_4");
checkWasFullBuild(); // should be a full build because initializing
// project
initialiseProject("PR129163_3");
configureNewProjectDependency("PR129163_3", "PR129163_4");
build("PR129163_3");
checkWasFullBuild(); // should be a full build because initializing
// project
alter("PR129163_4", "inc1");
build("PR129163_4");
checkWasntFullBuild(); // should be an incremental build because
// although
// "inc1" includes the aspect A1.aj, it actually hasn't
// changed so we shouldn't go back to source
alter("PR129163_3", "inc1");
build("PR129163_3");
checkWasntFullBuild(); // should be an incremental build because nothing
// has
// changed within the class and no aspects have changed
// within the running of the test
}
public void testPr133117() {
// System.gc();
// System.exit();
initialiseProject("PR133117");
configureNonStandardCompileOptions("PR133117", "-Xlint:warning");
build("PR133117");
assertTrue("There should only be one xlint warning message reported:\n" + getWarningMessages("PR133117"),
getWarningMessages("PR133117").size() == 1);
alter("PR133117", "inc1");
build("PR133117");
List warnings = getWarningMessages("PR133117");
List noGuardWarnings = new ArrayList();
for (Iterator iter = warnings.iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
if (element.getMessage().indexOf("Xlint:noGuardForLazyTjp") != -1) {
noGuardWarnings.add(element);
}
}
assertTrue("There should only be two Xlint:noGuardForLazyTjp warning message reported:\n" + noGuardWarnings,
noGuardWarnings.size() == 2);
}
public void testPr131505() {
initialiseProject("PR131505");
configureNonStandardCompileOptions("PR131505", "-outxml");
build("PR131505");
checkWasFullBuild();
String outputDir = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR131505" + File.separatorChar + "bin";
// aop.xml file shouldn't contain any aspects
checkXMLAspectCount("PR131505", "", 0, outputDir);
// add a new aspect A which should be included in the aop.xml file
alter("PR131505", "inc1");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505", "", 1, outputDir);
checkXMLAspectCount("PR131505", "A", 1, outputDir);
// make changes to the class file which shouldn't affect the contents
// of the aop.xml file
alter("PR131505", "inc2");
build("PR131505");
checkWasntFullBuild();
checkXMLAspectCount("PR131505", "", 1, outputDir);
checkXMLAspectCount("PR131505", "A", 1, outputDir);
// add another new aspect A1 which should also be included in the
// aop.xml file
// ...there should be no duplicate entries in the file
alter("PR131505", "inc3");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505", "", 2, outputDir);
checkXMLAspectCount("PR131505", "A1", 1, outputDir);
checkXMLAspectCount("PR131505", "A", 1, outputDir);
// delete aspect A1 which meanss that aop.xml file should only contain A
File a1 = new File(getWorkingDir().getAbsolutePath() + File.separatorChar + "PR131505" + File.separatorChar + "A1.aj");
a1.delete();
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505", "", 1, outputDir);
checkXMLAspectCount("PR131505", "A1", 0, outputDir);
checkXMLAspectCount("PR131505", "A", 1, outputDir);
// add another aspect called A which is in a different package, both A
// and pkg.A should be included in the aop.xml file
alter("PR131505", "inc4");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505", "", 2, outputDir);
checkXMLAspectCount("PR131505", "A", 1, outputDir);
checkXMLAspectCount("PR131505", "pkg.A", 1, outputDir);
}
public void testPr136585() {
initialiseProject("PR136585");
build("PR136585");
alter("PR136585", "inc1");
build("PR136585");
assertTrue("There should be no errors reported:\n" + getErrorMessages("PR136585"), getErrorMessages("PR136585").isEmpty());
}
public void testPr133532() {
initialiseProject("PR133532");
build("PR133532");
alter("PR133532", "inc1");
build("PR133532");
alter("PR133532", "inc2");
build("PR133532");
assertTrue("There should be no errors reported:\n" + getErrorMessages("PR133532"), getErrorMessages("PR133532").isEmpty());
}
public void testPr133532_2() {
initialiseProject("pr133532_2");
build("pr133532_2");
alter("pr133532_2", "inc2");
build("pr133532_2");
assertTrue("There should be no errors reported:\n" + getErrorMessages("pr133532_2"), getErrorMessages("pr133532_2")
.isEmpty());
String decisions = AjdeInteractionTestbed.MyStateListener.getDecisions();
String expect = "Need to recompile 'A.aj'";
assertTrue("Couldn't find build decision: '" + expect + "' in the list of decisions made:\n" + decisions,
decisions.indexOf(expect) != -1);
}
public void testPr133532_3() {
initialiseProject("PR133532_3");
build("PR133532_3");
alter("PR133532_3", "inc1");
build("PR133532_3");
assertTrue("There should be no errors reported:\n" + getErrorMessages("PR133532_3"), getErrorMessages("PR133532_3")
.isEmpty());
}
public void testPr134541() {
initialiseProject("PR134541");
build("PR134541");
assertEquals("[Xlint:adviceDidNotMatch] should be associated with line 5", 5, (getWarningMessages("PR134541").get(0))
.getSourceLocation().getLine());
alter("PR134541", "inc1");
build("PR134541");
// if (getModelFor("PR134541").getHandleProvider().dependsOnLocation())
// checkWasFullBuild(); // the line number has changed... but nothing
// // structural about the code
// else
checkWasntFullBuild(); // the line number has changed... but nothing
// structural about the code
assertEquals("[Xlint:adviceDidNotMatch] should now be associated with line 7", 7, (getWarningMessages("PR134541").get(0))
.getSourceLocation().getLine());
}
public void testJDTLikeHandleProviderWithLstFile_pr141730() {
// IElementHandleProvider handleProvider =
// AsmManager.getDefault().getHandleProvider();
// AsmManager.getDefault().setHandleProvider(new
// JDTLikeHandleProvider());
// try {
// The JDTLike-handles should start with the name
// of the buildconfig file
initialiseProject("JDTLikeHandleProvider");
build("JDTLikeHandleProvider");
IHierarchy top = getModelFor("JDTLikeHandleProvider").getHierarchy();
IProgramElement pe = top.findElementForType("pkg", "A");
String expectedHandle = "=JDTLikeHandleProvider<pkg*A.aj'A";
assertEquals("expected handle to be " + expectedHandle + ", but found " + pe.getHandleIdentifier(), expectedHandle,
pe.getHandleIdentifier());
// } finally {
// AsmManager.getDefault().setHandleProvider(handleProvider);
// }
}
public void testMovingAdviceDoesntChangeHandles_pr141730() {
// IElementHandleProvider handleProvider =
// AsmManager.getDefault().getHandleProvider();
// AsmManager.getDefault().setHandleProvider(new
// JDTLikeHandleProvider());
// try {
initialiseProject("JDTLikeHandleProvider");
build("JDTLikeHandleProvider");
checkWasFullBuild();
IHierarchy top = getModelFor("JDTLikeHandleProvider").getHierarchy();
IProgramElement pe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE, "before(): <anonymous pointcut>");
// add a line which shouldn't change the handle
alter("JDTLikeHandleProvider", "inc1");
build("JDTLikeHandleProvider");
checkWasntFullBuild();
IHierarchy top2 = getModelFor("JDTLikeHandleProvider").getHierarchy();
IProgramElement pe2 = top
.findElementForLabel(top2.getRoot(), IProgramElement.Kind.ADVICE, "before(): <anonymous pointcut>");
assertEquals("expected advice to be on line " + pe.getSourceLocation().getLine() + 1 + " but was on "
+ pe2.getSourceLocation().getLine(), pe.getSourceLocation().getLine() + 1, pe2.getSourceLocation().getLine());
assertEquals(
"expected advice to have handle " + pe.getHandleIdentifier() + " but found handle " + pe2.getHandleIdentifier(),
pe.getHandleIdentifier(), pe2.getHandleIdentifier());
// } finally {
// AsmManager.getDefault().setHandleProvider(handleProvider);
// }
}
public void testSwappingAdviceAndHandles_pr141730() {
// IElementHandleProvider handleProvider =
// AsmManager.getDefault().getHandleProvider();
// AsmManager.getDefault().setHandleProvider(new
// JDTLikeHandleProvider());
// try {
initialiseProject("JDTLikeHandleProvider");
build("JDTLikeHandleProvider");
IHierarchy top = getModelFor("JDTLikeHandleProvider").getHierarchy();
IProgramElement call = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE, "after(): callPCD..");
IProgramElement exec = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.ADVICE, "after(): execPCD..");
// swap the two after advice statements over. This forces
// a full build which means 'after(): callPCD..' will now
// be the second after advice in the file and have the same
// handle as 'after(): execPCD..' originally did.
alter("JDTLikeHandleProvider", "inc2");
build("JDTLikeHandleProvider");
checkWasFullBuild();
IHierarchy top2 = getModelFor("JDTLikeHandleProvider").getHierarchy();
IProgramElement newCall = top2.findElementForLabel(top2.getRoot(), IProgramElement.Kind.ADVICE, "after(): callPCD..");
IProgramElement newExec = top2.findElementForLabel(top2.getRoot(), IProgramElement.Kind.ADVICE, "after(): execPCD..");
assertEquals("after swapping places, expected 'after(): callPCD..' " + "to be on line "
+ newExec.getSourceLocation().getLine() + " but was on line " + call.getSourceLocation().getLine(), newExec
.getSourceLocation().getLine(), call.getSourceLocation().getLine());
assertEquals("after swapping places, expected 'after(): callPCD..' " + "to have handle " + exec.getHandleIdentifier()
+ " (because was full build) but had " + newCall.getHandleIdentifier(), exec.getHandleIdentifier(),
newCall.getHandleIdentifier());
// } finally {
// AsmManager.getDefault().setHandleProvider(handleProvider);
// }
}
public void testInitializerCountForJDTLikeHandleProvider_pr141730() {
// IElementHandleProvider handleProvider =
// AsmManager.getDefault().getHandleProvider();
// AsmManager.getDefault().setHandleProvider(new
// JDTLikeHandleProvider());
// try {
initialiseProject("JDTLikeHandleProvider");
build("JDTLikeHandleProvider");
String expected = "=JDTLikeHandleProvider<pkg*A.aj[C|1";
IHierarchy top = getModelFor("JDTLikeHandleProvider").getHierarchy();
IProgramElement init = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.INITIALIZER, "...");
assertEquals("expected initializers handle to be " + expected + "," + " but found " + init.getHandleIdentifier(true),
expected, init.getHandleIdentifier(true));
alter("JDTLikeHandleProvider", "inc2");
build("JDTLikeHandleProvider");
checkWasFullBuild();
IHierarchy top2 = getModelFor("JDTLikeHandleProvider").getHierarchy();
IProgramElement init2 = top2.findElementForLabel(top2.getRoot(), IProgramElement.Kind.INITIALIZER, "...");
assertEquals(
"expected initializers handle to still be " + expected + "," + " but found " + init2.getHandleIdentifier(true),
expected, init2.getHandleIdentifier(true));
// } finally {
// AsmManager.getDefault().setHandleProvider(handleProvider);
// }
}
// 134471 related tests perform incremental compilation and verify features
// of the structure model post compile
public void testPr134471_IncrementalCompilationAndModelUpdates() {
try {
// see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=false;
// Step1. Build the code, simple advice from aspect A onto class C
initialiseProject("PR134471");
configureNonStandardCompileOptions("PR134471", "-showWeaveInfo -emacssym");
configureShowWeaveInfoMessages("PR134471", true);
build("PR134471");
AsmManager model = getModelFor("PR134471");
// Step2. Quick check that the advice points to something...
IProgramElement nodeForTypeA = checkForNode(model, "pkg", "A", true);
IProgramElement nodeForAdvice = findAdvice(nodeForTypeA);
List relatedElements = getRelatedElements(model, nodeForAdvice, 1);
// Step3. Check the advice applying at the first 'code' join point
// in pkg.C is from aspect pkg.A, line 7
IProgramElement programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true)));
int line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line " + line, line == 7);
// Step4. Simulate the aspect being saved but with no change at all
// in it
alter("PR134471", "inc1");
build("PR134471");
model = getModelFor("PR134471");
// Step5. Quick check that the advice points to something...
nodeForTypeA = checkForNode(model, "pkg", "A", true);
nodeForAdvice = findAdvice(nodeForTypeA);
relatedElements = getRelatedElements(model, nodeForAdvice, 1);
// Step6. Check the advice applying at the first 'code' join point
// in pkg.C is from aspect pkg.A, line 7
programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true)));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line " + line, line == 7);
} finally {
// see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=true;
}
}
// now the advice moves down a few lines - hopefully the model will
// notice... see discussion in 134471
public void testPr134471_MovingAdvice() {
// Step1. build the project
initialiseProject("PR134471_2");
configureNonStandardCompileOptions("PR134471_2", "-showWeaveInfo -emacssym");
configureShowWeaveInfoMessages("PR134471_2", true);
build("PR134471_2");
AsmManager model = getModelFor("PR134471_2");
// Step2. confirm advice is from correct location
IProgramElement programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true)));
int line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line " + line, line == 7);
// Step3. No structural change to the aspect but the advice has moved
// down a few lines... (change in source location)
alter("PR134471_2", "inc1");
build("PR134471_2");
model = getModelFor("PR134471_2");
checkWasntFullBuild(); // the line number has changed... but nothing
// structural about the code
// checkWasFullBuild(); // this is true whilst we consider
// sourcelocation in the type/shadow munger equals() method - have
// to until the handles are independent of location
// Step4. Check we have correctly realised the advice moved to line 11
programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true)));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 11 - but is at line " + line, line == 11);
}
public void testAddingAndRemovingDecwWithStructureModel() {
initialiseProject("P3");
build("P3");
alter("P3", "inc1");
build("P3");
assertTrue("There should be no exceptions handled:\n" + getCompilerErrorMessages("P3"), getCompilerErrorMessages("P3")
.isEmpty());
alter("P3", "inc2");
build("P3");
assertTrue("There should be no exceptions handled:\n" + getCompilerErrorMessages("P3"), getCompilerErrorMessages("P3")
.isEmpty());
}
// same as first test with an extra stage that asks for C to be recompiled,
// it should still be advised...
public void testPr134471_IncrementallyRecompilingTheAffectedClass() {
try {
// see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=false;
// Step1. build the project
initialiseProject("PR134471");
configureNonStandardCompileOptions("PR134471", "-showWeaveInfo -emacssym");
configureShowWeaveInfoMessages("PR134471", true);
build("PR134471");
AsmManager model = getModelFor("PR134471");
// Step2. confirm advice is from correct location
IProgramElement programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true)));
int line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line " + line, line == 7);
// Step3. No change to the aspect at all
alter("PR134471", "inc1");
build("PR134471");
model = getModelFor("PR134471");
// Step4. Quick check that the advice points to something...
IProgramElement nodeForTypeA = checkForNode(model, "pkg", "A", true);
IProgramElement nodeForAdvice = findAdvice(nodeForTypeA);
List<String> relatedElements = getRelatedElements(model, nodeForAdvice, 1);
// Step5. No change to the file C but it should still be advised
// afterwards
alter("PR134471", "inc2");
build("PR134471");
checkWasntFullBuild();
model = getModelFor("PR134471");
// Step6. confirm advice is from correct location
programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true)));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line " + line, line == 7);
} finally {
// see pr148027 AsmHierarchyBuilder.shouldAddUsesPointcut=true;
}
}
// similar to previous test but with 'declare warning' as well as advice
public void testPr134471_IncrementallyRecompilingAspectContainingDeclare() {
// Step1. build the project
initialiseProject("PR134471_3");
configureNonStandardCompileOptions("PR134471_3", "-showWeaveInfo -emacssym");
configureShowWeaveInfoMessages("PR134471_3", true);
build("PR134471_3");
checkWasFullBuild();
AsmManager model = getModelFor("PR134471_3");
// Step2. confirm declare warning is from correct location, decw matches
// line 7 in pkg.C
IProgramElement programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true), 7));
int line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 10 - but is at line " + line, line == 10);
// Step3. confirm advice is from correct location, advice matches line 6
// in pkg.C
programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true), 6));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line " + line, line == 7);
// Step4. Move declare warning in the aspect
alter("PR134471_3", "inc1");
build("PR134471_3");
model = getModelFor("PR134471_3");
checkWasntFullBuild(); // the line number has changed... but nothing
// structural about the code
// checkWasFullBuild();
// Step5. confirm declare warning is from correct location, decw (now at
// line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true), 7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line " + line, line == 12);
// Step6. Now just simulate 'resave' of the aspect, nothing has changed
alter("PR134471_3", "inc2");
build("PR134471_3");
checkWasntFullBuild();
model = getModelFor("PR134471_3");
// Step7. confirm declare warning is from correct location, decw (now at
// line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true), 7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line " + line, line == 12);
}
// similar to previous test but with 'declare warning' as well as advice
public void testPr134471_IncrementallyRecompilingTheClassAffectedByDeclare() {
// Step1. build the project
initialiseProject("PR134471_3");
configureNonStandardCompileOptions("PR134471_3", "-showWeaveInfo -emacssym");
configureShowWeaveInfoMessages("PR134471_3", true);
build("PR134471_3");
checkWasFullBuild();
AsmManager model = getModelFor("PR134471_3");
// Step2. confirm declare warning is from correct location, decw matches
// line 7 in pkg.C
IProgramElement programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true), 7));
int line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 10 - but is at line " + line, line == 10);
// Step3. confirm advice is from correct location, advice matches line 6
// in pkg.C
programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true), 6));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line " + line, line == 7);
// Step4. Move declare warning in the aspect
alter("PR134471_3", "inc1");
build("PR134471_3");
model = getModelFor("PR134471_3");
checkWasntFullBuild(); // the line number has changed... but nothing
// structural about the code
// checkWasFullBuild();
// Step5. confirm declare warning is from correct location, decw (now at
// line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true), 7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line " + line, line == 12);
// Step6. Now just simulate 'resave' of the aspect, nothing has changed
alter("PR134471_3", "inc2");
build("PR134471_3");
checkWasntFullBuild();
model = getModelFor("PR134471_3");
// Step7. confirm declare warning is from correct location, decw (now at
// line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true), 7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line " + line, line == 12);
// Step8. Now just simulate resave of the pkg.C type - no change at
// all... are relationships gonna be repaired OK?
alter("PR134471_3", "inc3");
build("PR134471_3");
checkWasntFullBuild();
// Step9. confirm declare warning is from correct location, decw (now at
// line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(model, findCode(checkForNode(model, "pkg", "C", true), 7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line " + line, line == 12);
}
public void testDontLoseXlintWarnings_pr141556() {
initialiseProject("PR141556");
configureNonStandardCompileOptions("PR141556", "-Xlint:warning");
build("PR141556");
checkWasFullBuild();
String warningMessage = "can not build thisJoinPoint " + "lazily for this advice since it has no suitable guard "
+ "[Xlint:noGuardForLazyTjp]";
assertEquals("warning message should be '" + warningMessage + "'", warningMessage,
(getWarningMessages("PR141556").get(0)).getMessage());
// add a space to the Aspect but dont do a build
alter("PR141556", "inc1");
// remove the space so that the Aspect is exactly as it was
alter("PR141556", "inc2");
// build the project and we should not have lost the xlint warning
build("PR141556");
checkWasntFullBuild();
assertTrue("there should still be a warning message ", !getWarningMessages("PR141556").isEmpty());
assertEquals("warning message should be '" + warningMessage + "'", warningMessage,
(getWarningMessages("PR141556").get(0)).getMessage());
}
public void testAdviceDidNotMatch_pr152589() {
initialiseProject("PR152589");
build("PR152589");
List warnings = getWarningMessages("PR152589");
assertTrue("There should be no warnings:\n" + warnings, warnings.isEmpty());
alter("PR152589", "inc1");
build("PR152589");
checkWasntFullBuild(); // the line number has changed... but nothing
// structural about the code
// checkWasFullBuild();
warnings = getWarningMessages("PR152589");
assertTrue("There should be no warnings after adding a whitespace:\n" + warnings, warnings.isEmpty());
}
// see comment #11 of bug 154054
public void testNoFullBuildOnChangeInSysOutInAdviceBody_pr154054() {
initialiseProject("PR154054");
build("PR154054");
alter("PR154054", "inc1");
build("PR154054");
checkWasntFullBuild();
}
// change exception type in around advice, does it notice?
public void testShouldFullBuildOnExceptionChange_pr154054() {
initialiseProject("PR154054_2");
build("PR154054_2");
alter("PR154054_2", "inc1");
build("PR154054_2");
checkWasFullBuild();
}
public void testPR158573() {
// IElementHandleProvider handleProvider =
// AsmManager.getDefault().getHandleProvider();
// AsmManager.getDefault().setHandleProvider(new
// JDTLikeHandleProvider());
initialiseProject("PR158573");
build("PR158573");
List warnings = getWarningMessages("PR158573");
assertTrue("There should be no warnings:\n" + warnings, warnings.isEmpty());
alter("PR158573", "inc1");
build("PR158573");
checkWasntFullBuild();
warnings = getWarningMessages("PR158573");
assertTrue("There should be no warnings after changing the value of a " + "variable:\n" + warnings, warnings.isEmpty());
// AsmManager.getDefault().setHandleProvider(handleProvider);
}
/**
* If the user has specified that they want Java 6 compliance and kept the default classfile and source file level settings
* (also 6.0) then expect an error saying that we don't support java 6.
*/
public void testPR164384_1() {
initialiseProject("PR164384");
Hashtable<String, String> javaOptions = new Hashtable<String, String>();
javaOptions.put("org.eclipse.jdt.core.compiler.compliance", "1.6");
javaOptions.put("org.eclipse.jdt.core.compiler.codegen.targetPlatform", "1.6");
javaOptions.put("org.eclipse.jdt.core.compiler.source", "1.6");
configureJavaOptionsMap("PR164384", javaOptions);
build("PR164384");
List<IMessage> errors = getErrorMessages("PR164384");
if (getCompilerForProjectWithName("PR164384").isJava6Compatible()) {
assertTrue("There should be no errors:\n" + errors, errors.isEmpty());
} else {
String expectedError = "Java 6.0 compliance level is unsupported";
String found = ((IMessage) errors.get(0)).getMessage();
assertEquals("Expected 'Java 6.0 compliance level is unsupported'" + " error message but found " + found,
expectedError, found);
// This is because the 'Java 6.0 compliance' error is an 'error'
// rather than an 'abort'. Aborts are really for compiler
// exceptions.
assertTrue("expected there to be more than the one compliance level" + " error but only found that one",
errors.size() > 1);
}
}
/**
* If the user has specified that they want Java 6 compliance and selected classfile and source file level settings to be 5.0
* then expect an error saying that we don't support java 6.
*/
public void testPR164384_2() {
initialiseProject("PR164384");
Hashtable<String, String> javaOptions = new Hashtable<String, String>();
javaOptions.put("org.eclipse.jdt.core.compiler.compliance", "1.6");
javaOptions.put("org.eclipse.jdt.core.compiler.codegen.targetPlatform", "1.5");
javaOptions.put("org.eclipse.jdt.core.compiler.source", "1.5");
configureJavaOptionsMap("PR164384", javaOptions);
build("PR164384");
List<IMessage> errors = getErrorMessages("PR164384");
if (getCompilerForProjectWithName("PR164384").isJava6Compatible()) {
assertTrue("There should be no errors:\n" + errors, errors.isEmpty());
} else {
String expectedError = "Java 6.0 compliance level is unsupported";
String found = ((IMessage) errors.get(0)).getMessage();
assertEquals("Expected 'Java 6.0 compliance level is unsupported'" + " error message but found " + found,
expectedError, found);
// This is because the 'Java 6.0 compliance' error is an 'error'
// rather than an 'abort'. Aborts are really for compiler
// exceptions.
assertTrue("expected there to be more than the one compliance level" + " error but only found that one",
errors.size() > 1);
}
}
/**
* If the user has specified that they want Java 6 compliance and set the classfile level to be 6.0 and source file level to be
* 5.0 then expect an error saying that we don't support java 6.
*/
public void testPR164384_3() {
initialiseProject("PR164384");
Hashtable<String, String> javaOptions = new Hashtable<String, String>();
javaOptions.put("org.eclipse.jdt.core.compiler.compliance", "1.6");
javaOptions.put("org.eclipse.jdt.core.compiler.codegen.targetPlatform", "1.6");
javaOptions.put("org.eclipse.jdt.core.compiler.source", "1.5");
configureJavaOptionsMap("PR164384", javaOptions);
build("PR164384");
List errors = getErrorMessages("PR164384");
if (getCompilerForProjectWithName("PR164384").isJava6Compatible()) {
assertTrue("There should be no errros:\n" + errors, errors.isEmpty());
} else {
String expectedError = "Java 6.0 compliance level is unsupported";
String found = ((IMessage) errors.get(0)).getMessage();
assertEquals("Expected 'Java 6.0 compliance level is unsupported'" + " error message but found " + found,
expectedError, found);
// This is because the 'Java 6.0 compliance' error is an 'error'
// rather than an 'abort'. Aborts are really for compiler
// exceptions.
assertTrue("expected there to be more than the one compliance level" + " error but only found that one",
errors.size() > 1);
}
}
public void testPr168840() throws Exception {
initialiseProject("inpathTesting");
String inpathTestingDir = getWorkingDir() + File.separator + "inpathTesting";
String inpathDir = inpathTestingDir + File.separator + "injarBin" + File.separator + "pkg";
String expectedOutputDir = inpathTestingDir + File.separator + "bin";
// set up the inpath to have the directory on it's path
File f = new File(inpathDir);
Set<File> s = new HashSet<File>();
s.add(f);
configureInPath("inpathTesting", s);
build("inpathTesting");
// the declare warning matches one place so expect one warning message
List<IMessage> warnings = getWarningMessages("inpathTesting");
assertTrue("Expected there to be one warning message but found " + warnings.size() + ": " + warnings, warnings.size() == 1);
// copy over the updated version of the inpath class file
File from = new File(testdataSrcDir + File.separatorChar + "inpathTesting" + File.separatorChar + "newInpathClass"
+ File.separatorChar + "InpathClass.class");
File destination = new File(inpathDir + File.separatorChar + "InpathClass.class");
FileUtil.copyFile(from, destination);
build("inpathTesting");
checkWasntFullBuild();
// the newly copied inpath class means the declare warning now matches
// two
// places, therefore expect two warning messages
warnings = getWarningMessages("inpathTesting");
assertTrue("Expected there to be two warning message but found " + warnings.size() + ": " + warnings, warnings.size() == 2);
}
// warning about cant change parents of Object is fine
public void testInpathHandles_271201() throws Exception {
AjdeInteractionTestbed.VERBOSE = true;
String p = "inpathHandles";
initialiseProject(p);
String inpathTestingDir = getWorkingDir() + File.separator + "inpathHandles";
String inpathDir = inpathTestingDir + File.separator + "binpath";
// set up the inpath to have the directory on it's path
System.out.println(inpathDir);
File f = new File(inpathDir);
Set<File> s = new HashSet<File>();
s.add(f);
configureInPath(p, s);
build(p);
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
// alter(p,"inc1");
// build(p);
dumptree(root, 0);
PrintWriter pw = new PrintWriter(System.out);
try {
getModelFor(p).dumprels(pw);
pw.flush();
} catch (Exception e) {
}
List<IRelationship> l = getModelFor(p).getRelationshipMap().get("=inpathHandles/;<codep(Code.class[Code");
assertNotNull(l);
}
// warning about cant change parents of Object is fine
public void testInpathHandles_IncrementalCompilation_271201() throws Exception {
AjdeInteractionTestbed.VERBOSE = true;
String p = "inpathHandles";
initialiseProject(p);
String inpathTestingDir = getWorkingDir() + File.separator + "inpathHandles";
String inpathDir = inpathTestingDir + File.separator + "binpath";
// set up the inpath to have the directory on it's path
File f = new File(inpathDir);
Set<File> s = new HashSet<File>();
s.add(f);
configureInPath(p, s);
// This build will weave a declare parents into the inpath class codep.Code
build(p);
assertNotNull(getModelFor(p).getRelationshipMap().get("=inpathHandles/;<codep(Code.class[Code"));
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
// This alteration introduces a new source file B.java, the build should not
// damage phantom handle based relationships
alter(p, "inc1");
build(p);
assertNotNull(getModelFor(p).getRelationshipMap().get("=inpathHandles/;<codep(Code.class[Code"));
assertNotNull(getModelFor(p).getRelationshipMap().get("=inpathHandles<p{B.java[B"));
// This alteration removes B.java, the build should not damage phantom handle based relationships
String fileB = getWorkingDir().getAbsolutePath() + File.separatorChar + "inpathHandles" + File.separatorChar + "src"
+ File.separatorChar + "p" + File.separatorChar + "B.java";
(new File(fileB)).delete();
build(p);
assertNotNull(getModelFor(p).getRelationshipMap().get("=inpathHandles/;<codep(Code.class[Code"));
assertNull(getModelFor(p).getRelationshipMap().get("=inpathHandles<p{B.java[B"));
}
public void testInpathHandles_WithInpathMap_271201() throws Exception {
AjdeInteractionTestbed.VERBOSE = true;
String p = "inpathHandles";
initialiseProject(p);
String inpathTestingDir = getWorkingDir() + File.separator + "inpathHandles";
String inpathDir = inpathTestingDir + File.separator + "binpath";// + File.separator+ "codep";
// String expectedOutputDir = inpathTestingDir + File.separator + "bin";
// set up the inpath to have the directory on it's path
System.out.println(inpathDir);
File f = new File(inpathDir);
Set<File> s = new HashSet<File>();
s.add(f);
Map<File, String> m = new HashMap<File, String>();
m.put(f, "wibble");
configureOutputLocationManager(p, new TestOutputLocationManager(getProjectRelativePath(p, ".").toString(), m));
configureInPath(p, s);
build(p);
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
// alter(p,"inc1");
// build(p);
dumptree(root, 0);
PrintWriter pw = new PrintWriter(System.out);
try {
getModelFor(p).dumprels(pw);
pw.flush();
} catch (Exception e) {
}
List<IRelationship> l = getModelFor(p).getRelationshipMap().get("=inpathHandles/;wibble<codep(Code.class[Code");
assertNotNull(l);
}
private void printModelAndRelationships(String p) {
IProgramElement root = getModelFor(p).getHierarchy().getRoot();
dumptree(root, 0);
PrintWriter pw = new PrintWriter(System.out);
try {
getModelFor(p).dumprels(pw);
pw.flush();
} catch (Exception e) {
}
}
public void testInpathHandles_IncrementalCompilation_RemovingInpathEntries_271201() throws Exception {
AjdeInteractionTestbed.VERBOSE = true;
String p = "inpathHandles2";
initialiseProject(p);
String inpathDir = getWorkingDir() + File.separator + "inpathHandles2" + File.separator + "binpath";
// set up the inpath to have the directory on it's path
File f = new File(inpathDir);
configureInPath(p, f);
// This build will weave a declare parents into the inpath class codep.A and codep.B
build(p);
assertNotNull(getModelFor(p).getRelationshipMap().get("=inpathHandles2/;<codep(A.class[A"));
// Not let us delete one of the inpath .class files
assertTrue(new File(inpathDir, "codep" + File.separator + "A.class").delete());
setNextChangeResponse(p, ICompilerConfiguration.EVERYTHING);
build(p);
// printModelAndRelationships(p);
}
// warning about cant change parents of Object is fine
// public void testInpathJars_271201() throws Exception {
// AjdeInteractionTestbed.VERBOSE = true;
// String p = "inpathJars";
// initialiseProject(p);
//
// String inpathTestingDir = getWorkingDir() + File.separator + "inpathJars";
// String inpathDir = inpathTestingDir + File.separator + "code.jar";
// // String expectedOutputDir = inpathTestingDir + File.separator + "bin";
//
// // set up the inpath to have the directory on it's path
// File f = new File(inpathDir);
// Set s = new HashSet();
// s.add(f);
// Map m = new HashMap();
// m.put(f, "Gibble");
// configureOutputLocationManager(p, new TestOutputLocationManager(getProjectRelativePath(p, ".").toString(), m));
// configureInPath(p, s);
// build(p);
//
// // alter(p,"inc1");
// // build(p);
// List l = getModelFor(p).getRelationshipMap().get("=inpathJars/,Gibble<codep(Code.class[Code");
// assertNotNull(l);
// }
// --- helper code ---
/**
* Retrieve program elements related to this one regardless of the relationship. A JUnit assertion is made that the number that
* the 'expected' number are found.
*
* @param programElement Program element whose related elements are to be found
* @param expected the number of expected related elements
*/
private List<String> getRelatedElements(AsmManager model, IProgramElement programElement, int expected) {
List<String> relatedElements = getRelatedElements(model, programElement);
StringBuffer debugString = new StringBuffer();
if (relatedElements != null) {
for (String element : relatedElements) {
debugString.append(model.getHierarchy().findElementForHandle(element).toLabelString()).append("\n");
}
}
assertTrue("Should be " + expected + " element" + (expected > 1 ? "s" : "") + " related to this one '" + programElement
+ "' but found :\n " + debugString, relatedElements != null && relatedElements.size() == 1);
return relatedElements;
}
private IProgramElement getFirstRelatedElement(AsmManager model, IProgramElement programElement) {
List<String> rels = getRelatedElements(model, programElement, 1);
return model.getHierarchy().findElementForHandle((String) rels.get(0));
}
private List<String> getRelatedElements(AsmManager model, IProgramElement advice) {
List<String> output = null;
IRelationshipMap map = model.getRelationshipMap();
List<IRelationship> rels = map.get(advice);
if (rels == null) {
fail("Did not find any related elements!");
}
for (Iterator<IRelationship> iter = rels.iterator(); iter.hasNext();) {
IRelationship element = iter.next();
List<String> targets = element.getTargets();
if (output == null) {
output = new ArrayList<String>();
}
output.addAll(targets);
}
return output;
}
private IProgramElement findAdvice(IProgramElement ipe) {
return findAdvice(ipe, 1);
}
private IProgramElement findAdvice(IProgramElement ipe, int whichOne) {
if (ipe.getKind() == IProgramElement.Kind.ADVICE) {
whichOne = whichOne - 1;
if (whichOne == 0) {
return ipe;
}
}
List kids = ipe.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement kid = (IProgramElement) iter.next();
IProgramElement found = findAdvice(kid, whichOne);
if (found != null) {
return found;
}
}
return null;
}
/**
* Finds the first 'code' program element below the element supplied - will return null if there aren't any
*/
private IProgramElement findCode(IProgramElement ipe) {
return findCode(ipe, -1);
}
/**
* Searches a hierarchy of program elements for a 'code' element at the specified line number, a line number of -1 means just
* return the first one you find
*/
private IProgramElement findCode(IProgramElement ipe, int linenumber) {
if (ipe.getKind() == IProgramElement.Kind.CODE) {
if (linenumber == -1 || ipe.getSourceLocation().getLine() == linenumber) {
return ipe;
}
}
List<IProgramElement> kids = ipe.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement kid = (IProgramElement) iter.next();
IProgramElement found = findCode(kid, linenumber);
if (found != null) {
return found;
}
}
return null;
}
// other possible tests:
// - memory usage (freemem calls?)
// - relationship map
// --------------------------------------------------------------------------
// -------------------------
private IProgramElement checkForNode(AsmManager model, String packageName, String typeName, boolean shouldBeFound) {
IProgramElement ipe = model.getHierarchy().findElementForType(packageName, typeName);
if (shouldBeFound) {
if (ipe == null) {
printModel(model);
}
assertTrue("Should have been able to find '" + packageName + "." + typeName + "' in the asm", ipe != null);
} else {
if (ipe != null) {
printModel(model);
}
assertTrue("Should have NOT been able to find '" + packageName + "." + typeName + "' in the asm", ipe == null);
}
return ipe;
}
private void printModel(AsmManager model) {
try {
AsmManager.dumptree(model.getHierarchy().getRoot(), 0);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void log(String msg) {
if (VERBOSE) {
System.out.println(msg);
}
}
protected File getProjectOutputRelativePath(String p, String filename) {
File projDir = new File(getWorkingDir(), p);
return new File(projDir, "bin" + File.separator + filename);
}
} |
423,257 | Bug 423257 LTW - java.lang.VerifyError: Bad return type with generics and local variables | null | resolved fixed | dd88d21 | AspectJ | https://github.com/eclipse/org.aspectj | eclipse/org.aspectj | java | null | null | null | "2013-12-06T18:33:48Z" | "2013-12-04T23:33:20Z" | weaver/src/org/aspectj/weaver/bcel/asm/StackMapAdder.java | /* *******************************************************************
* Copyright (c) 2008 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement
* ******************************************************************/
package org.aspectj.weaver.bcel.asm;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import aj.org.objectweb.asm.*;
/**
* Uses asm to add the stack map attribute to methods in a class. The class is passed in as pure byte data and then a reader/writer
* process it. The writer is wired into the world so that types can be resolved and getCommonSuperClass() can be implemented without
* class loading using the context class loader.
*
* It is important that the constant pool is preserved here and asm does not try to remove unused entries. That is because some
* entries are refered to from classfile attributes. Asm cannot see into these attributes so does not realise the constant pool
* entries are in use. In order to ensure the copying of cp occurs, we use the variant super constructor call in AspectJConnectClassWriter
* that passes in the classreader. However, ordinarily that change causes a further optimization: that if a classreader sees
* a methodvisitor that has been created by a ClassWriter then it just copies the data across without changing it (and so it
* fails to attach the stackmapattribute). In order to avoid this further optimization we use our own minimal MethodVisitor.
*
* @author Andy Clement
*/
public class StackMapAdder {
public static byte[] addStackMaps(World world, byte[] data) {
try {
ClassReader cr = new ClassReader(data);
ClassWriter cw = new AspectJConnectClassWriter(cr, world);
ClassVisitor cv = new AspectJClassVisitor(cw);
cr.accept(cv, 0);
return cw.toByteArray();
} catch (Throwable t) {
System.err.println("AspectJ Internal Error: unable to add stackmap attributes. " + t.getMessage());
AsmDetector.isAsmAround = false;
return data;
}
}
private static class AspectJClassVisitor extends ClassVisitor {
public AspectJClassVisitor(ClassVisitor classwriter) {
super(Opcodes.ASM4, classwriter);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
return new AJMethodVisitor(mv);
}
// Minimal pass through MethodVisitor just so that the ClassReader doesn't see one that has been directly
// created by a ClassWriter (see top level class comment)
static class AJMethodVisitor extends MethodVisitor {
public AJMethodVisitor(MethodVisitor mv) {
super(Opcodes.ASM4,mv);
}
}
}
private static class AspectJConnectClassWriter extends ClassWriter {
private final World world;
public AspectJConnectClassWriter(ClassReader cr, World w) {
super(cr, ClassWriter.COMPUTE_FRAMES); // passing in cr is necessary so cpool isnt modified (see 2.2.4 of asm doc)
this.world = w;
}
// Implementation of getCommonSuperClass() that avoids Class.forName()
protected String getCommonSuperClass(final String type1, final String type2) {
ResolvedType resolvedType1 = world.resolve(UnresolvedType.forName(type1.replace('/', '.')));
ResolvedType resolvedType2 = world.resolve(UnresolvedType.forName(type2.replace('/', '.')));
if (resolvedType1.isAssignableFrom(resolvedType2)) {
return type1;
}
if (resolvedType2.isAssignableFrom(resolvedType1)) {
return type2;
}
if (resolvedType1.isInterface() || resolvedType2.isInterface()) {
return "java/lang/Object";
} else {
do {
resolvedType1 = resolvedType1.getSuperclass();
} while (!resolvedType1.isAssignableFrom(resolvedType2));
return resolvedType1.getRawName().replace('.', '/');
}
}
}
}
|
Subsets and Splits